source: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp @ 1006

Revision 1006, 95.2 KB checked in by mattausch, 18 years ago (diff)

started viewspace-objectspace subdivision
removed memory leaks

Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18#include "Beam.h"
19
20namespace GtpVisibilityPreprocessor {
21
22#define USE_FIXEDPOINT_T 0
23
24
25//-- static members
26
27
28int VspBspTree::sFrontId = 0;
29int VspBspTree::sBackId = 0;
30int VspBspTree::sFrontAndBackId = 0;
31
32typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
33
34
35// pvs penalty can be different from pvs size
36inline static float EvalPvsPenalty(const int pvs,
37                                                                   const int lower,
38                                                                   const int upper)
39{
40        // clamp to minmax values
41        if (pvs < lower)
42                return (float)lower;
43        if (pvs > upper)
44                return (float)upper;
45
46        return (float)pvs;
47}
48
49
50
51
52/******************************************************************************/
53/*                       class VspBspTree implementation                      */
54/******************************************************************************/
55
56
57VspBspTree::VspBspTree():
58mRoot(NULL),
59mUseAreaForPvs(false),
60mCostNormalizer(Limits::Small),
61mViewCellsManager(NULL),
62mOutOfBoundsCell(NULL),
63mStoreRays(false),
64mRenderCostWeight(0.5),
65mUseRandomAxis(false),
66mTimeStamp(1)
67{
68        bool randomize = false;
69        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.randomize", randomize);
70        if (randomize)
71                Randomize(); // initialise random generator for heuristics
72
73        //-- termination criteria for autopartition
74        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
75        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
76        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
77        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
78        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
79        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
80        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
81        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
82        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
83
84        //-- max cost ratio for early tree termination
85        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
86
87        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.minGlobalCostRatio", mTermMinGlobalCostRatio);
88        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.globalCostMissTolerance", mTermGlobalCostMissTolerance);
89
90        // HACK//mTermMinPolygons = 25;
91
92        //-- factors for bsp tree split plane heuristics
93        Environment::GetSingleton()->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
94        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
95
96
97        //-- partition criteria
98        Environment::GetSingleton()->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
99        Environment::GetSingleton()->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
100        Environment::GetSingleton()->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
101
102        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
103        Environment::GetSingleton()->GetIntValue("VspBspTree.maxTests", mMaxTests);
104
105        // if only the driving axis is used for axis aligned split
106        Environment::GetSingleton()->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
107       
108        //-- termination criteria for axis aligned split
109        Environment::GetSingleton()->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
110                                                                mTermMaxRayContriForAxisAligned);
111        Environment::GetSingleton()->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
112                                                         mTermMinRaysForAxisAligned);
113
114        //Environment::GetSingleton()->GetFloatValue("VspBspTree.maxTotalMemory", mMaxTotalMemory);
115        Environment::GetSingleton()->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
116
117        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
118        Environment::GetSingleton()->GetBoolValue("VspBspTree.usePolygonSplitIfAvailable", mUsePolygonSplitIfAvailable);
119
120        Environment::GetSingleton()->GetBoolValue("VspBspTree.useCostHeuristics", mUseCostHeuristics);
121        Environment::GetSingleton()->GetBoolValue("VspBspTree.useSplitCostQueue", mUseSplitCostQueue);
122        Environment::GetSingleton()->GetBoolValue("VspBspTree.simulateOctree", mCirculatingAxis);
123        Environment::GetSingleton()->GetBoolValue("VspBspTree.useRandomAxis", mUseRandomAxis);
124        Environment::GetSingleton()->GetIntValue("VspBspTree.nodePriorityQueueType", mNodePriorityQueueType);
125
126       
127        char subdivisionStatsLog[100];
128        Environment::GetSingleton()->GetStringValue("VspBspTree.subdivisionStats", subdivisionStatsLog);
129        mSubdivisionStats.open(subdivisionStatsLog);
130
131        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.minBand", mMinBand);
132        Environment::GetSingleton()->GetFloatValue("VspBspTree.Construction.maxBand", mMaxBand);
133        Environment::GetSingleton()->GetBoolValue("VspBspTree.Construction.useDrivingAxisForMaxCost", mUseDrivingAxisIfMaxCostViolated);
134
135        //-- debug output
136
137        Debug << "******* VSP BSP options ******** " << endl;
138    Debug << "max depth: " << mTermMaxDepth << endl;
139        Debug << "min PVS: " << mTermMinPvs << endl;
140        Debug << "min probabiliy: " << mTermMinProbability << endl;
141        Debug << "min rays: " << mTermMinRays << endl;
142        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
143        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
144        Debug << "miss tolerance: " << mTermMissTolerance << endl;
145        Debug << "max view cells: " << mMaxViewCells << endl;
146        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
147        //Debug << "max plane candidates: " << mMaxRayCandidates << endl;
148        Debug << "randomize: " << randomize << endl;
149
150        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
151        Debug << "render cost weight: " << mRenderCostWeight << endl;
152        Debug << "min global cost ratio: " << mTermMinGlobalCostRatio << endl;
153        Debug << "global cost miss tolerance: " << mTermGlobalCostMissTolerance << endl;
154        Debug << "only driving axis: " << mOnlyDrivingAxis << endl;
155        Debug << "max memory: " << mMaxMemory << endl;
156        Debug << "use poly split if available: " << mUsePolygonSplitIfAvailable << endl;
157        Debug << "use cost heuristics: " << mUseCostHeuristics << endl;
158        Debug << "use split cost queue: " << mUseSplitCostQueue << endl;
159        Debug << "subdivision stats log: " << subdivisionStatsLog << endl;
160        Debug << "use random axis: " << mUseRandomAxis << endl;
161        Debug << "priority queue type: " << mNodePriorityQueueType << endl;
162        Debug << "circulating axis: " << mCirculatingAxis << endl;
163        Debug << "minband: " << mMinBand << endl;
164        Debug << "maxband: " << mMaxBand << endl;
165        Debug << "use driving axis for max cost: " << mUseDrivingAxisIfMaxCostViolated << endl;
166
167        Debug << "Split plane strategy: ";
168
169        if (mSplitPlaneStrategy & RANDOM_POLYGON)
170        {
171                Debug << "random polygon ";
172        }
173        if (mSplitPlaneStrategy & AXIS_ALIGNED)
174        {
175                Debug << "axis aligned ";
176        }
177        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
178        {
179                mCostNormalizer += mLeastRaySplitsFactor;
180                Debug << "least ray splits ";
181        }
182        if (mSplitPlaneStrategy & BALANCED_RAYS)
183        {
184                mCostNormalizer += mBalancedRaysFactor;
185                Debug << "balanced rays ";
186        }
187        if (mSplitPlaneStrategy & PVS)
188        {
189                mCostNormalizer += mPvsFactor;
190                Debug << "pvs";
191        }
192
193
194        mSplitCandidates = new vector<SortableEntry>;
195
196        Debug << endl;
197}
198/*
199VspBspTree::VspBspTree():
200mRoot(NULL),
201mUseAreaForPvs(false),
202mCostNormalizer(Limits::Small),
203mViewCellsManager(NULL),
204mOutOfBoundsCell(NULL),
205mStoreRays(false),
206mRenderCostWeight(0.5),
207mUseRandomAxis(false),
208mTimeStamp(1),
209mEpsilon(1e-6f)
210{
211}*/
212
213BspViewCell *VspBspTree::GetOutOfBoundsCell()
214{
215        return mOutOfBoundsCell;
216}
217
218
219BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
220{
221        if (!mOutOfBoundsCell)
222        {
223                mOutOfBoundsCell = new BspViewCell();
224                mOutOfBoundsCell->SetId(-1);
225                mOutOfBoundsCell->SetValid(false);
226        }
227
228        return mOutOfBoundsCell;
229}
230
231
232const BspTreeStatistics &VspBspTree::GetStatistics() const
233{
234        return mBspStats;
235}
236
237
238VspBspTree::~VspBspTree()
239{
240        DEL_PTR(mRoot);
241        DEL_PTR(mSplitCandidates);
242}
243
244
245int VspBspTree::AddMeshToPolygons(Mesh *mesh,
246                                                                  PolygonContainer &polys,
247                                                                  MeshInstance *parent)
248{
249        FaceContainer::const_iterator fi;
250
251        // copy the face data to polygons
252        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
253        {
254                Polygon3 *poly = new Polygon3((*fi), mesh);
255
256                if (poly->Valid(mEpsilon))
257                {
258                        poly->mParent = parent; // set parent intersectable
259                        polys.push_back(poly);
260                }
261                else
262                        DEL_PTR(poly);
263        }
264        return (int)mesh->mFaces.size();
265}
266
267
268int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
269                                                                 PolygonContainer &polys,
270                                                                 int maxObjects)
271{
272        int limit = (maxObjects > 0) ?
273                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
274
275        int polysSize = 0;
276
277        for (int i = 0; i < limit; ++ i)
278        {
279                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
280                {
281                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
282                        polysSize +=
283                                AddMeshToPolygons(viewCells[i]->GetMesh(),
284                                                                  polys,
285                                                                  viewCells[i]);
286                }
287        }
288
289        return polysSize;
290}
291
292
293int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
294                                                                 PolygonContainer &polys,
295                                                                 int maxObjects)
296{
297        int limit = (maxObjects > 0) ?
298                Min((int)objects.size(), maxObjects) : (int)objects.size();
299
300        for (int i = 0; i < limit; ++i)
301        {
302                Intersectable *object = objects[i];//*it;
303                Mesh *mesh = NULL;
304
305                switch (object->Type()) // extract the meshes
306                {
307                case Intersectable::MESH_INSTANCE:
308                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
309                        break;
310                case Intersectable::VIEW_CELL:
311                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
312                        break;
313                case Intersectable::TRANSFORMED_MESH_INSTANCE:
314                        {
315                                TransformedMeshInstance *mi = dynamic_cast<TransformedMeshInstance *>(object);
316
317                                if (!mi->GetMesh())     
318                                        break;
319                                mesh = new Mesh();
320                                mi->GetTransformedMesh(*mesh);
321                               
322                break;
323                        }
324                default:
325                        Debug << "intersectable type not supported" << endl;
326                        break;
327                }
328
329        if (mesh) // copy the mesh data to polygons
330                {
331                        mBox.Include(object->GetBox()); // add to BSP tree aabb
332                        AddMeshToPolygons(mesh, polys, NULL);
333
334                        // cleanup
335                        if (object->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
336                                DEL_PTR(mesh);
337                }
338        }
339
340        return (int)polys.size();
341}
342
343
344void VspBspTree::Construct(const VssRayContainer &sampleRays,
345                                                   AxisAlignedBox3 *forcedBoundingBox)
346{
347        mBspStats.nodes = 1;
348        mBox.Initialize();      // initialise BSP tree bounding box
349
350        if (forcedBoundingBox)
351                mBox = *forcedBoundingBox;
352       
353        PolygonContainer polys;
354        RayInfoContainer *rays = new RayInfoContainer();
355
356        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
357
358        long startTime = GetTime();
359
360        cout << "Extracting polygons from rays ... ";
361
362        Intersectable::NewMail();
363
364        int numObj = 0;
365
366        //-- extract polygons intersected by the rays
367        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
368        {
369                VssRay *ray = *rit;
370                Intersectable *obj = ray->mTerminationObject;
371
372                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
373                        obj && !obj->Mailed())
374                {
375                        obj->Mail();
376
377                        // transformed mesh instance and mesh instance handle mesh differently
378                        if (obj->Type() == Intersectable::TRANSFORMED_MESH_INSTANCE)
379                        {
380                                Mesh mesh;
381                               
382                                TransformedMeshInstance *tmobj =
383                                        dynamic_cast<TransformedMeshInstance *>(obj);
384                               
385                                tmobj->GetTransformedMesh(mesh);
386                                AddMeshToPolygons(&mesh, polys, tmobj);
387                        }
388                        else // MeshInstance
389                        {
390                                MeshInstance *mobj = dynamic_cast<MeshInstance *>(obj);
391                                AddMeshToPolygons(mobj->GetMesh(), polys, mobj);
392                        }
393
394                        ++ numObj;
395
396                        //-- compute bounding box
397                        if (!forcedBoundingBox)
398                                mBox.Include(ray->mTermination);
399                }
400
401                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
402                        ray->mOriginObject &&
403                        !ray->mOriginObject->Mailed())
404                {
405                        ray->mOriginObject->Mail();
406                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
407                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
408                        ++ numObj;
409
410                        //-- compute bounding box
411                        if (!forcedBoundingBox)
412                                mBox.Include(ray->mOrigin);
413                }
414        }
415       
416        Debug << "maximal pvs (i.e., pvs still considered as valid) : "
417                  << mViewCellsManager->GetMaxPvsSize() << endl;
418
419        //-- store rays
420        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
421        {
422                VssRay *ray = *rit;
423
424                float minT, maxT;
425
426                static Ray hray;
427                hray.Init(*ray);
428
429                // TODO: not very efficient to implictly cast between rays types
430                if (mBox.GetRaySegment(hray, minT, maxT))
431                {
432                        float len = ray->Length();
433
434                        if (!len)
435                                len = Limits::Small;
436
437                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
438                }
439        }
440
441        // normalize
442        if (mUseAreaForPvs)
443                mTermMinProbability *= mBox.SurfaceArea();
444        else
445                mTermMinProbability *= mBox.GetVolume();
446
447        // throw out unnecessary polygons
448        PreprocessPolygons(polys);
449
450        mBspStats.polys = (int)polys.size();
451        mGlobalCostMisses = 0;
452
453        cout << "finished" << endl;
454
455        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
456                  << (int)sampleRays.size() << " rays in "
457                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
458
459        // use split cost priority queue
460        if (mUseSplitCostQueue)
461        {
462                ConstructWithSplitQueue(polys, rays);
463        }
464        else
465        {
466                Construct(polys, rays);
467        }
468
469        // clean up polygons
470        CLEAR_CONTAINER(polys);
471}
472
473
474// TODO: return memory usage in MB
475float VspBspTree::GetMemUsage() const
476{
477        return (float)
478                 (sizeof(VspBspTree) +
479                  mBspStats.Leaves() * sizeof(BspLeaf) +
480                  mCreatedViewCells * sizeof(BspViewCell) +
481                  mBspStats.pvs * sizeof(ObjectPvsData) +
482                  mBspStats.Interior() * sizeof(BspInterior) +
483                  mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
484}
485
486
487
488void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
489{
490        VspBspTraversalQueue tQueue;
491
492        mRoot = new BspLeaf();
493
494        // constrruct root node geometry
495        BspNodeGeometry *geom = new BspNodeGeometry();
496        ConstructGeometry(mRoot, *geom);
497
498        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
499
500        VspBspTraversalData tData(mRoot,
501                                                          new PolygonContainer(polys),
502                                                          0,
503                                                          rays,
504                              ComputePvsSize(*rays),
505                                                          prop,
506                                                          geom);
507
508        EvalPriority(tData);
509
510
511        // first node is kd node, i.e. an axis aligned box
512        if (1)
513        tData.mIsKdNode = true;
514        else
515                tData.mIsKdNode = false;
516
517        tQueue.push(tData);
518
519
520        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
521        mTotalPvsSize = tData.mPvs;
522       
523        mSubdivisionStats
524                        << "#ViewCells\n1" <<  endl
525                        << "#RenderCostDecrease\n0" << endl
526                        << "#TotalRenderCost\n" << mTotalCost << endl
527                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
528
529        Debug << "total cost: " << mTotalCost << endl;
530       
531       
532        mBspStats.Start();
533        cout << "Constructing vsp bsp tree ... \n";
534
535        long startTime = GetTime();     
536        int nLeaves = 500;
537        int nViewCells = 500;
538
539        // used for intermediate time measurements and progress
540        long interTime = GetTime();     
541
542        mOutOfMemory = false;
543
544        mCreatedViewCells = 0;
545       
546        while (!tQueue.empty())
547        {
548                tData = tQueue.top();
549            tQueue.pop();               
550
551                if (0 && !mOutOfMemory)
552                {
553                        float mem = GetMemUsage();
554
555                        if (mem > mMaxMemory)
556                        {
557                                mOutOfMemory = true;
558                                Debug << "memory limit reached: " << mem << endl;
559                        }
560                }
561
562                // subdivide leaf node
563                BspNode *r = Subdivide(tQueue, tData);
564
565                if (r == mRoot)
566                        Debug << "VSP BSP tree construction time spent at root: "
567                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
568
569                if (mBspStats.Leaves() >= nLeaves)
570                {
571                        nLeaves += 500;
572
573                        cout << "leaves=" << mBspStats.Leaves() << endl;
574                        Debug << "needed "
575                                  << TimeDiff(interTime, GetTime())*1e-3
576                                  << " secs to create 500 view cells" << endl;
577                        interTime = GetTime();
578                }
579
580                if (mCreatedViewCells >= nViewCells)
581                {
582                        nViewCells += 500;
583
584                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
585                }
586        }
587
588        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
589        cout << "finished\n";
590
591        mBspStats.Stop();
592}
593
594
595
596void VspBspTree::ConstructWithSplitQueue(const PolygonContainer &polys,
597                                                                                          RayInfoContainer *rays)
598{
599        VspBspSplitQueue tQueue;
600
601        mRoot = new BspLeaf();
602
603        // constrruct root node geometry
604        BspNodeGeometry *geom = new BspNodeGeometry();
605        ConstructGeometry(mRoot, *geom);
606
607        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
608
609        VspBspTraversalData tData(mRoot,
610                                                          new PolygonContainer(polys),
611                                                          0,
612                                                          rays,
613                              ComputePvsSize(*rays),
614                                                          prop,
615                                                          geom);
616
617
618        // compute first split candidate
619        VspBspSplitCandidate splitCandidate;
620        EvalSplitCandidate(tData, splitCandidate);
621
622        tQueue.push(splitCandidate);
623
624        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
625        mTotalPvsSize = tData.mPvs;
626       
627        mSubdivisionStats
628                        << "#ViewCells\n1\n" <<  endl
629                        << "#RenderCostDecrease\n0\n" << endl
630                        << "#SplitCandidateCost\n0\n" << endl
631                        << "#TotalRenderCost\n" << mTotalCost << endl
632                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
633
634        Debug << "total cost: " << mTotalCost << endl;
635       
636       
637        mBspStats.Start();
638        cout << "Constructing vsp bsp tree ... \n";
639
640        long startTime = GetTime();     
641        int nLeaves = 500;
642        int nViewCells = 500;
643
644        // used for intermediate time measurements and progress
645        long interTime = GetTime();     
646
647        mOutOfMemory = false;
648
649        mCreatedViewCells = 0;
650       
651        while (!tQueue.empty())
652        {
653                splitCandidate = tQueue.top();
654            tQueue.pop();               
655
656                // cost ratio of cost decrease / totalCost
657                float costRatio = splitCandidate.GetCost() / mTotalCost;
658
659                //Debug << "cost ratio: " << costRatio << endl;
660
661                if (costRatio < mTermMinGlobalCostRatio)
662                        ++ mGlobalCostMisses;
663               
664                if (0 && !mOutOfMemory)
665                {
666                        float mem = GetMemUsage();
667
668                        if (mem > mMaxMemory)
669                        {
670                                mOutOfMemory = true;
671                                Debug << "memory limit reached: " << mem << endl;
672                        }
673                }
674
675                // subdivide leaf node
676                BspNode *r = Subdivide(tQueue, splitCandidate);
677
678                if (r == mRoot)
679                        Debug << "VSP BSP tree construction time spent at root: "
680                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
681
682                if (mBspStats.Leaves() >= nLeaves)
683                {
684                        nLeaves += 500;
685
686                        cout << "leaves=" << mBspStats.Leaves() << endl;
687                        Debug << "needed "
688                                  << TimeDiff(interTime, GetTime())*1e-3
689                                  << " secs to create 500 view cells" << endl;
690                        interTime = GetTime();
691                }
692
693                if (mCreatedViewCells == nViewCells)
694                {
695                        nViewCells += 500;
696
697                        cout << "generated " << mCreatedViewCells << " viewcells" << endl;
698                }
699        }
700
701        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
702        cout << "finished\n";
703
704        mBspStats.Stop();
705}
706
707
708bool VspBspTree::LocalTerminationCriteriaMet(const VspBspTraversalData &data) const
709{
710        return
711                (((int)data.mRays->size() <= mTermMinRays) ||
712                 (data.mPvs <= mTermMinPvs)   ||
713                 (data.mProbability <= mTermMinProbability) ||
714                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
715                 (data.mDepth >= mTermMaxDepth));
716}
717
718
719bool VspBspTree::GlobalTerminationCriteriaMet(const VspBspTraversalData &data) const
720{
721        return
722                (mOutOfMemory
723                || (mBspStats.Leaves() >= mMaxViewCells)
724                || (mGlobalCostMisses >= mTermGlobalCostMissTolerance)
725                 );
726}
727
728
729
730BspNode *VspBspTree::Subdivide(VspBspTraversalQueue &tQueue,
731                                                           VspBspTraversalData &tData)
732{
733        BspNode *newNode = tData.mNode;
734
735        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
736        {
737                PolygonContainer coincident;
738
739                VspBspTraversalData tFrontData;
740                VspBspTraversalData tBackData;
741
742                // create new interior node and two leaf nodes
743                // or return leaf as it is (if maxCostRatio missed)
744                int splitAxis;
745                bool splitFurther = true;
746                int maxCostMisses = tData.mMaxCostMisses;
747               
748                Plane3 splitPlane;
749                BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
750               
751                // choose next split plane
752                if (!SelectPlane(splitPlane, leaf, tData, tFrontData, tBackData, splitAxis))
753                {
754                        ++ maxCostMisses;
755
756                        if (maxCostMisses > mTermMissTolerance)
757                        {
758                                // terminate branch because of max cost
759                                ++ mBspStats.maxCostNodes;
760                                splitFurther = false;
761                        }
762                }
763       
764                // if this a valid split => subdivide this node further
765                if (splitFurther) //-- continue subdivision
766                {
767                        newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
768
769                        if (splitAxis < 3)
770                                ++ mBspStats.splits[splitAxis];
771                        else
772                                ++ mBspStats.polySplits;
773
774                        // if it was a kd node (i.e., a box) and the split axis is axis aligned, it is still a kd node
775                        tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
776                        tFrontData.mAxis = tBackData.mAxis = splitAxis;
777
778                        // how often was max cost ratio missed in this branch?
779                        tFrontData.mMaxCostMisses = maxCostMisses;
780                        tBackData.mMaxCostMisses = maxCostMisses;
781
782                        EvalPriority(tFrontData);
783                        EvalPriority(tBackData);
784
785                        // evaluate subdivision stats
786                        if (1)
787                        {
788                                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
789                                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
790                                float cData = (float)tData.mPvs * tData.mProbability;;
791
792                float costDecr = (cFront + cBack - cData) / mBox.GetVolume();
793
794                                mTotalCost += costDecr;
795                                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
796
797                                mSubdivisionStats
798                                                << "#ViewCells\n" << mBspStats.Leaves() << endl
799                                                << "#RenderCostDecrease\n" << -costDecr << endl
800                                                << "#TotalRenderCost\n" << mTotalCost << endl
801                                                << "#AvgRenderCost\n" << (float)mTotalPvsSize / (float)mBspStats.Leaves() << endl;
802                        }
803
804                        // push the children on the stack
805                        tQueue.push(tFrontData);
806                        tQueue.push(tBackData);
807
808                        // delete old leaf node
809                        DEL_PTR(tData.mNode);
810                }
811        }
812
813        //-- terminate traversal and create new view cell
814        if (newNode->IsLeaf())
815        {
816                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
817                BspViewCell *viewCell = new BspViewCell();
818               
819                leaf->SetViewCell(viewCell);
820       
821                //-- update pvs
822                int conSamp = 0;
823                float sampCon = 0.0f;
824                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
825
826                // update scalar pvs size lookup
827                mViewCellsManager->SetScalarPvsSize(viewCell, viewCell->GetPvs().GetSize());
828       
829
830                mBspStats.contributingSamples += conSamp;
831                mBspStats.sampleContributions +=(int) sampCon;
832
833                //-- store additional info
834                if (mStoreRays)
835                {
836                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
837                        for (it = tData.mRays->begin(); it != it_end; ++ it)
838                        {
839                                (*it).mRay->Ref();                     
840                                leaf->mVssRays.push_back((*it).mRay);
841                        }
842                }
843
844                // should I check here?
845                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0, mViewCellsManager->GetMaxPvsSize()))
846                {
847                        viewCell->SetValid(false);
848                        leaf->SetTreeValid(false);
849                        PropagateUpValidity(leaf);
850
851                        ++ mBspStats.invalidLeaves;
852                }
853               
854        viewCell->mLeaf = leaf;
855
856                if (mUseAreaForPvs)
857                        viewCell->SetArea(tData.mProbability);
858                else
859                        viewCell->SetVolume(tData.mProbability);
860
861                leaf->mProbability = tData.mProbability;
862
863                EvaluateLeafStats(tData);               
864        }
865
866        //-- cleanup
867        tData.Clear();
868
869        return newNode;
870}
871
872// subdivide using a split plane queue
873BspNode *VspBspTree::Subdivide(VspBspSplitQueue &tQueue,
874                                                           VspBspSplitCandidate &splitCandidate)
875{
876        VspBspTraversalData &tData = splitCandidate.mParentData;
877
878        BspNode *newNode = tData.mNode;
879
880        if (!LocalTerminationCriteriaMet(tData) && !GlobalTerminationCriteriaMet(tData))
881        {       
882                PolygonContainer coincident;
883
884                VspBspTraversalData tFrontData;
885                VspBspTraversalData tBackData;
886
887                //-- continue subdivision
888               
889                // create new interior node and two leaf node
890                const Plane3 splitPlane = splitCandidate.mSplitPlane;
891                               
892                newNode = SubdivideNode(splitPlane, tData, tFrontData, tBackData, coincident);
893       
894                const int splitAxis = splitCandidate.mSplitAxis;
895                const int maxCostMisses = splitCandidate.mMaxCostMisses;
896
897                if (splitAxis < 3)
898                        ++ mBspStats.splits[splitAxis];
899                else
900                        ++ mBspStats.polySplits;
901
902                tFrontData.mIsKdNode = tBackData.mIsKdNode = (tData.mIsKdNode && (splitAxis < 3));
903                tFrontData.mAxis = tBackData.mAxis = splitAxis;
904
905                // how often was max cost ratio missed in this branch?
906                tFrontData.mMaxCostMisses = maxCostMisses;
907                tBackData.mMaxCostMisses = maxCostMisses;
908                       
909               
910                if (1)
911                {
912                        float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
913                        float cBack = (float)tBackData.mPvs * tBackData.mProbability;
914                        float cData = (float)tData.mPvs * tData.mProbability;
915
916                       
917                        float costDecr =
918                                (cFront + cBack - cData) / mBox.GetVolume();
919
920                        mTotalCost += costDecr;
921                        mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
922
923                        mSubdivisionStats
924                                        << "#ViewCells\n" << mBspStats.Leaves() << endl
925                                        << "#RenderCostDecrease\n" << -costDecr << endl
926                                        << "#SplitCandidateCost\n" << splitCandidate.GetCost() << endl
927                                        << "#TotalRenderCost\n" << mTotalCost << endl
928                                        << "#AvgRenderCost\n" << (float)mTotalPvsSize / (float)mBspStats.Leaves() << endl;
929                }
930
931       
932                //-- push the new split candidates on the stack
933                VspBspSplitCandidate frontCandidate;
934                VspBspSplitCandidate backCandidate;
935
936                EvalSplitCandidate(tFrontData, frontCandidate);
937                EvalSplitCandidate(tBackData, backCandidate);
938       
939                tQueue.push(frontCandidate);
940                tQueue.push(backCandidate);
941       
942                // delete old leaf node
943                DEL_PTR(tData.mNode);
944        }
945
946
947        //-- terminate traversal and create new view cell
948        if (newNode->IsLeaf())
949        {
950                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
951                BspViewCell *viewCell = new BspViewCell();
952
953        leaf->SetViewCell(viewCell);
954               
955                //-- update pvs
956                int conSamp = 0;
957                float sampCon = 0.0f;
958                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
959
960                // update scalar pvs size value
961                mViewCellsManager->SetScalarPvsSize(viewCell, viewCell->GetPvs().GetSize());
962
963                mBspStats.contributingSamples += conSamp;
964                mBspStats.sampleContributions +=(int) sampCon;
965
966                //-- store additional info
967                if (mStoreRays)
968                {
969                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
970                        for (it = tData.mRays->begin(); it != it_end; ++ it)
971                        {
972                                (*it).mRay->Ref();                     
973                                leaf->mVssRays.push_back((*it).mRay);
974                        }
975                }
976
977                // should I check here?
978                viewCell->mLeaf = leaf;
979
980                if (mUseAreaForPvs)
981                        viewCell->SetArea(tData.mProbability);
982                else
983                        viewCell->SetVolume(tData.mProbability);
984
985        leaf->mProbability = tData.mProbability;
986
987                EvaluateLeafStats(tData);               
988        }
989
990        //-- cleanup
991        tData.Clear();
992
993        return newNode;
994}
995
996
997void VspBspTree::EvalPriority(VspBspTraversalData &tData) const
998{
999    switch (mNodePriorityQueueType)
1000        {
1001        case BREATH_FIRST:
1002                tData.mPriority = (float)-tData.mDepth;
1003                break;
1004        case DEPTH_FIRST:
1005                tData.mPriority = (float)tData.mDepth;
1006                break;
1007        default:
1008                tData.mPriority = tData.mPvs * tData.mProbability;
1009                //Debug << "priority: " << tData.mPriority << endl;
1010                break;
1011        }
1012}
1013
1014
1015void VspBspTree::EvalSplitCandidate(VspBspTraversalData &tData,
1016                                                                        VspBspSplitCandidate &splitData)
1017{
1018        VspBspTraversalData frontData;
1019        VspBspTraversalData backData;
1020
1021        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1022
1023        // compute locally best split plane
1024    bool success = SelectPlane(splitData.mSplitPlane, leaf, tData,
1025                                                           frontData, backData, splitData.mSplitAxis);
1026
1027        // TODO: reuse
1028        DEL_PTR(frontData.mGeometry);
1029        DEL_PTR(backData.mGeometry);
1030       
1031        // compute global decrease in render cost
1032        splitData.mRenderCost = EvalRenderCostDecrease(splitData.mSplitPlane, tData);
1033        splitData.mParentData = tData;
1034        splitData.mMaxCostMisses = success ? tData.mMaxCostMisses : tData.mMaxCostMisses + 1;
1035}
1036
1037
1038BspInterior *VspBspTree::SubdivideNode(const Plane3 &splitPlane,
1039                                                                           VspBspTraversalData &tData,
1040                                                                           VspBspTraversalData &frontData,
1041                                                                           VspBspTraversalData &backData,
1042                                                                           PolygonContainer &coincident)
1043{
1044        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
1045       
1046        //-- the front and back traversal data is filled with the new values
1047        frontData.mDepth = tData.mDepth + 1;
1048        frontData.mPolygons = new PolygonContainer();
1049        frontData.mRays = new RayInfoContainer();
1050       
1051        backData.mDepth = tData.mDepth + 1;
1052        backData.mPolygons = new PolygonContainer();
1053        backData.mRays = new RayInfoContainer();
1054       
1055
1056        //-- subdivide rays
1057        SplitRays(splitPlane,
1058                          *tData.mRays,
1059                          *frontData.mRays,
1060                          *backData.mRays);
1061
1062
1063        // compute pvs
1064        frontData.mPvs = ComputePvsSize(*frontData.mRays);
1065        backData.mPvs = ComputePvsSize(*backData.mRays);
1066
1067        // split front and back node geometry and compute area
1068       
1069        // if geometry was not already computed
1070        if (!frontData.mGeometry && !backData.mGeometry)
1071        {
1072                frontData.mGeometry = new BspNodeGeometry();
1073                backData.mGeometry = new BspNodeGeometry();
1074
1075                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
1076                                                                           *backData.mGeometry,
1077                                                                           splitPlane,
1078                                                                           mBox,
1079                                                                           //0.0f);
1080                                                                           mEpsilon);
1081               
1082                if (mUseAreaForPvs)
1083                {
1084                        frontData.mProbability = frontData.mGeometry->GetArea();
1085                        backData.mProbability = backData.mGeometry->GetArea();
1086                }
1087                else
1088                {
1089                        frontData.mProbability = frontData.mGeometry->GetVolume();
1090                        backData.mProbability = tData.mProbability - frontData.mProbability;
1091
1092                        // should never come here: wrong volume !!!
1093                        if (0)
1094                        {
1095                                if (frontData.mProbability < -0.00001)
1096                                        Debug << "fatal error f: " << frontData.mProbability << endl;
1097                                if (backData.mProbability < -0.00001)
1098                                        Debug << "fatal error b: " << backData.mProbability << endl;
1099
1100                                // clamp because of precision issues
1101                                if (frontData.mProbability < 0) frontData.mProbability = 0;
1102                                if (backData.mProbability < 0) backData.mProbability = 0;
1103                        }
1104                }
1105        }
1106
1107       
1108    // subdivide polygons
1109        SplitPolygons(splitPlane,
1110                                  *tData.mPolygons,
1111                      *frontData.mPolygons,
1112                                  *backData.mPolygons,
1113                                  coincident);
1114
1115
1116
1117        ///////////////////////////////////////
1118        // subdivide further
1119
1120        // store maximal and minimal depth
1121        if (tData.mDepth > mBspStats.maxDepth)
1122        {
1123                Debug << "max depth increases to " << tData.mDepth << " at " << mBspStats.Leaves() << " leaves" << endl;
1124                mBspStats.maxDepth = tData.mDepth;
1125        }
1126
1127        mBspStats.nodes += 2;
1128
1129   
1130        BspInterior *interior = new BspInterior(splitPlane);
1131
1132#ifdef _DEBUG
1133        Debug << interior << endl;
1134#endif
1135
1136
1137        //-- create front and back leaf
1138
1139        BspInterior *parent = leaf->GetParent();
1140
1141        // replace a link from node's parent
1142        if (parent)
1143        {
1144                parent->ReplaceChildLink(leaf, interior);
1145                interior->SetParent(parent);
1146        }
1147        else // new root
1148        {
1149                mRoot = interior;
1150        }
1151
1152        // and setup child links
1153        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
1154
1155        frontData.mNode = interior->GetFront();
1156        backData.mNode = interior->GetBack();
1157
1158        interior->mTimeStamp = mTimeStamp ++;
1159       
1160
1161        //DEL_PTR(leaf);
1162        return interior;
1163}
1164
1165
1166void VspBspTree::AddToPvs(BspLeaf *leaf,
1167                                                  const RayInfoContainer &rays,
1168                                                  float &sampleContributions,
1169                                                  int &contributingSamples)
1170{
1171        sampleContributions = 0;
1172        contributingSamples = 0;
1173 
1174        RayInfoContainer::const_iterator it, it_end = rays.end();
1175 
1176        ViewCellLeaf *vc = leaf->GetViewCell();
1177 
1178        // add contributions from samples to the PVS
1179        for (it = rays.begin(); it != it_end; ++ it)
1180        {
1181                float sc = 0.0f;
1182                VssRay *ray = (*it).mRay;
1183
1184                bool madeContrib = false;
1185                float contribution;
1186
1187                if (ray->mTerminationObject)
1188                {
1189                        if (vc->AddPvsSample(ray->mTerminationObject, ray->mPdf, contribution))
1190                                madeContrib = true;
1191                        sc += contribution;
1192                }
1193         
1194                // only count termination objects?
1195                if (1 && ray->mOriginObject)
1196                {
1197                        if (vc->AddPvsSample(ray->mOriginObject, ray->mPdf, contribution))
1198                                madeContrib = true;
1199                        sc += contribution;
1200                }
1201         
1202          sampleContributions += sc;
1203
1204          if (madeContrib)
1205                  ++ contributingSamples;
1206               
1207          //leaf->mVssRays.push_back(ray);
1208        }
1209}
1210
1211
1212void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays,
1213                                                                         const int axis,
1214                                                                         float minBand,
1215                                                                         float maxBand)
1216{
1217        mSplitCandidates->clear();
1218
1219        int requestedSize = 2 * (int)(rays.size());
1220        // creates a sorted split candidates array
1221        if (mSplitCandidates->capacity() > 500000 &&
1222                requestedSize < (int)(mSplitCandidates->capacity() / 10) )
1223        {
1224        delete mSplitCandidates;
1225                mSplitCandidates = new vector<SortableEntry>;
1226        }
1227
1228        mSplitCandidates->reserve(requestedSize);
1229
1230        float pos;
1231
1232        // float values => don't compare with exact values
1233        if (0)
1234        {
1235                minBand += Limits::Small;
1236                maxBand -= Limits::Small;
1237        }
1238
1239        // insert all queries
1240        for (RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
1241        {
1242                const bool positive = (*ri).mRay->HasPosDir(axis);
1243                               
1244                pos = (*ri).ExtrapOrigin(axis);
1245                // clamp to min / max band
1246                if (0) ClipValue(pos, minBand, maxBand);
1247               
1248                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
1249                                                                        pos, (*ri).mRay));
1250
1251                pos = (*ri).ExtrapTermination(axis);
1252                // clamp to min / max band
1253                if (0) ClipValue(pos, minBand, maxBand);
1254
1255                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
1256                                                                        pos, (*ri).mRay));
1257        }
1258
1259        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
1260}
1261
1262
1263float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
1264                                                                                  const AxisAlignedBox3 &box,
1265                                                                                  const int pvsSize,
1266                                                                                  const int axis,
1267                                          float &position)
1268{
1269        const float minBox = box.Min(axis);
1270        const float maxBox = box.Max(axis);
1271
1272        const float sizeBox = maxBox - minBox;
1273
1274        const float minBand = minBox + mMinBand * sizeBox;
1275        const float maxBand = minBox + mMaxBand * sizeBox;
1276
1277        SortSplitCandidates(rays, axis, minBand, maxBand);
1278
1279        // go through the lists, count the number of objects left and right
1280        // and evaluate the following cost funcion:
1281        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
1282
1283        int pvsl = 0;
1284        int pvsr = pvsSize;
1285
1286        int pvsBack = pvsl;
1287        int pvsFront = pvsr;
1288
1289        float sum = (float)pvsSize * sizeBox;
1290        float minSum = 1e20f;
1291
1292       
1293        // if no border can be found, take mid split
1294        position = minBox + 0.5f * sizeBox;
1295       
1296        // the relative cost ratio
1297        float ratio = /*Limits::Infinity;*/99999999.0f;
1298        bool splitPlaneFound = false;
1299
1300        Intersectable::NewMail();
1301
1302        RayInfoContainer::const_iterator ri, ri_end = rays.end();
1303
1304        // set all object as belonging to the front pvs
1305        for(ri = rays.begin(); ri != ri_end; ++ ri)
1306        {
1307                Intersectable *oObject = (*ri).mRay->mOriginObject;
1308                Intersectable *tObject = (*ri).mRay->mTerminationObject;
1309
1310                if (oObject)
1311                {
1312                        if (!oObject->Mailed())
1313                        {
1314                                oObject->Mail();
1315                                oObject->mCounter = 1;
1316                        }
1317                        else
1318                        {
1319                                ++ oObject->mCounter;
1320                        }
1321                }
1322                if (tObject)
1323                {
1324                        if (!tObject->Mailed())
1325                        {
1326                                tObject->Mail();
1327                                tObject->mCounter = 1;
1328                        }
1329                        else
1330                        {
1331                                ++ tObject->mCounter;
1332                        }
1333                }
1334        }
1335
1336        Intersectable::NewMail();
1337
1338        vector<SortableEntry>::const_iterator ci, ci_end = mSplitCandidates->end();
1339
1340        for (ci = mSplitCandidates->begin(); ci != ci_end; ++ ci)
1341        {
1342                VssRay *ray;
1343                ray = (*ci).ray;
1344               
1345                Intersectable *oObject = ray->mOriginObject;
1346                Intersectable *tObject = ray->mTerminationObject;
1347               
1348
1349                switch ((*ci).type)
1350                {
1351                        case SortableEntry::ERayMin:
1352                                {
1353                                        if (oObject && !oObject->Mailed())
1354                                        {
1355                                                oObject->Mail();
1356                                                ++ pvsl;
1357                                        }
1358                                        if (tObject && !tObject->Mailed())
1359                                        {
1360                                                tObject->Mail();
1361                                                ++ pvsl;
1362                                        }
1363                                        break;
1364                                }
1365                        case SortableEntry::ERayMax:
1366                                {
1367                                        if (oObject)
1368                                        {
1369                                                if (-- oObject->mCounter == 0)
1370                                                        -- pvsr;
1371                                        }
1372
1373                                        if (tObject)
1374                                        {
1375                                                if (-- tObject->mCounter == 0)
1376                                                        -- pvsr;
1377                                        }
1378
1379                                        break;
1380                                }
1381                }
1382
1383               
1384               
1385                // Note: sufficient to compare size of bounding boxes of front and back side?
1386                if (((*ci).value >= minBand) && ((*ci).value <= maxBand))
1387                {
1388                        sum = pvsl * ((*ci).value - minBox) + pvsr * (maxBox - (*ci).value);
1389
1390                        //Debug  << "pos=" << (*ci).value << "\t pvs=(" <<  pvsl << "," << pvsr << ")" << endl;
1391                        //Debug << "cost= " << sum << endl;
1392
1393                        if (sum < minSum)
1394                        {
1395                                splitPlaneFound = true;
1396
1397                                minSum = sum;
1398                                position = (*ci).value;
1399                               
1400                                pvsBack = pvsl;
1401                                pvsFront = pvsr;
1402                        }
1403                }
1404        }
1405       
1406       
1407        // -- compute cost
1408        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1409        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1410
1411        const float pOverall = sizeBox;
1412
1413        const float pBack = position - minBox;
1414        const float pFront = maxBox - position;
1415       
1416        const float penaltyOld = EvalPvsPenalty(pvsSize, lowerPvsLimit, upperPvsLimit);
1417    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1418        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1419       
1420        const float oldRenderCost = penaltyOld * pOverall;
1421        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1422
1423        if (splitPlaneFound)
1424        {
1425                ratio = mPvsFactor * newRenderCost / (oldRenderCost + Limits::Small);
1426        }
1427        //if (axis != 1)
1428        //Debug << "axis=" << axis << " costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
1429         //    <<"\t pb=(" << pvsBack << ")\t pf=(" << pvsFront << ")" << endl;
1430
1431        return ratio;
1432}
1433
1434
1435float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
1436                                                                                 const VspBspTraversalData &tData,
1437                                                                                 int &axis,
1438                                                                                 BspNodeGeometry **frontGeom,
1439                                                                                 BspNodeGeometry **backGeom,
1440                                                                                 float &pFront,
1441                                                                                 float &pBack,
1442                                                                                 const bool isKdNode)
1443{
1444        float nPosition[3];
1445        float nCostRatio[3];
1446        float nProbFront[3];
1447        float nProbBack[3];
1448
1449        BspNodeGeometry *nFrontGeom[3];
1450        BspNodeGeometry *nBackGeom[3];
1451
1452        // set to NULL, so I can find out which gemetry was stored
1453        for (int i = 0; i < 3; ++ i)
1454        {
1455                nFrontGeom[i] = NULL;
1456                nBackGeom[i] = NULL;
1457        }
1458
1459        // create bounding box of node geometry
1460        AxisAlignedBox3 box;
1461               
1462        //TODO: for kd split geometry already is box => only take minmax vertices
1463        if (1)
1464        {
1465                // get bounding box from geometry
1466                tData.mGeometry->GetBoundingBox(box);
1467        }
1468        else
1469        {
1470                box.Initialize();
1471                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
1472
1473                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
1474                        box.Include((*ri).ExtrapTermination());
1475        }
1476
1477        int sAxis = 0;
1478        int bestAxis;
1479
1480        // if max cost ratio is exceeded, take split along longest axis instead
1481        const float maxCostRatioForArbitraryAxis = 0.9f;
1482
1483        if (mUseDrivingAxisIfMaxCostViolated)
1484                bestAxis = box.Size().DrivingAxis();
1485        else
1486                bestAxis = -1;
1487
1488#if 0
1489        // maximum cost ratio for axis to be valid:
1490        // if exceeded, spatial mid split is used instead
1491        const maxCostRatioForHeur = 0.99f;
1492#endif
1493
1494        // if we use some kind of specialised fixed axis
1495    const bool useSpecialAxis =
1496                mOnlyDrivingAxis || mUseRandomAxis || mCirculatingAxis;
1497
1498        if (mUseRandomAxis)
1499                sAxis = Random(3);
1500        else if (mCirculatingAxis)
1501                sAxis = (tData.mAxis + 1) % 3;
1502        else if (mOnlyDrivingAxis)
1503                sAxis = box.Size().DrivingAxis();
1504
1505               
1506        //Debug << "use special axis: " << useSpecialAxis << endl;
1507        //Debug << "axis: " << sAxis << " drivingaxis: " << box.Size().DrivingAxis();
1508
1509        for (axis = 0; axis < 3 ; ++ axis)
1510        {
1511                if (!useSpecialAxis || (axis == sAxis))
1512                {
1513                        //-- place split plane using heuristics
1514
1515                        if (mUseCostHeuristics)
1516                        {
1517                                nCostRatio[axis] =
1518                                        BestCostRatioHeuristics(*tData.mRays,
1519                                                                                    box,
1520                                                                                        tData.mPvs,
1521                                                                                        axis,
1522                                                                                        nPosition[axis]);                       
1523                        }
1524                        else //-- split plane position is spatial median
1525                        {
1526
1527                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1528                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
1529
1530                                // allows faster split because we have axis aligned kd tree boxes
1531                                if (isKdNode)
1532                                {
1533                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1534                                                                                                                                box,
1535                                                                                                                                axis,
1536                                                                                                                                nPosition[axis],
1537                                                                                                                                nProbFront[axis],
1538                                                                                                                                nProbBack[axis]);
1539                                       
1540                                        Vector3 pos;
1541                                       
1542                                        // create back geometry from box
1543                                        // NOTE: the geometry is saved when possible
1544                                        pos = box.Max(); pos[axis] = nPosition[axis];
1545                                        AxisAlignedBox3 bBox(box.Min(), pos);
1546                                        PolygonContainer fPolys;
1547                                        bBox.ExtractPolys(fPolys);
1548
1549                                        nBackGeom[axis] = new BspNodeGeometry(fPolys);
1550       
1551                                        //-- create front geometry from box
1552                                        pos = box.Min(); pos[axis] = nPosition[axis];
1553                                        AxisAlignedBox3 fBox(pos, box.Max());
1554
1555                                        PolygonContainer bPolys;
1556                                        fBox.ExtractPolys(bPolys);
1557                                        nFrontGeom[axis] = new BspNodeGeometry(bPolys);
1558                                }
1559                                else
1560                                {
1561                                        nFrontGeom[axis] = new BspNodeGeometry();
1562                                        nBackGeom[axis] = new BspNodeGeometry();
1563
1564                                        nCostRatio[axis] =
1565                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1566                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1567                                                                                   nProbFront[axis], nProbBack[axis]);
1568                                }
1569                        }
1570                                               
1571                       
1572                        if (mUseDrivingAxisIfMaxCostViolated)
1573                        {
1574                                // we take longest axis split if cost ratio exceeds threshold
1575                                if (nCostRatio[axis] < min(maxCostRatioForArbitraryAxis, nCostRatio[bestAxis]))
1576                                {
1577                                        bestAxis = axis;
1578                                }
1579                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1580                                        Debug << "taking split along longest axis (" << bestAxis << ") instead of  (" << axis << ")" << endl;
1581                               
1582                        }
1583                        else
1584                        {
1585                                if (bestAxis == -1)
1586                                {
1587                                        bestAxis = axis;
1588                                }
1589                                else if (nCostRatio[axis] < nCostRatio[bestAxis])
1590                                {
1591                                        bestAxis = axis;
1592                                }
1593                        }
1594                }
1595        }
1596
1597        //-- assign values
1598        axis = bestAxis;
1599        pFront = nProbFront[bestAxis];
1600        pBack = nProbBack[bestAxis];
1601
1602        // assign best split nodes geometry
1603        *frontGeom = nFrontGeom[bestAxis];
1604        *backGeom = nBackGeom[bestAxis];
1605
1606        // and delete other geometry
1607        DEL_PTR(nFrontGeom[(bestAxis + 1) % 3]);
1608        DEL_PTR(nBackGeom[(bestAxis + 2) % 3]);
1609
1610        //-- split plane
1611    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1612        plane = Plane3(normal, nPosition[bestAxis]);
1613
1614        //Debug << "best axis: " << bestAxis << " pos " << nPosition[bestAxis] << endl;
1615        //Debug << "!!!!!!!!!!!!!!" << endl;
1616        return nCostRatio[bestAxis];
1617}
1618
1619
1620bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1621                                                         BspLeaf *leaf,
1622                                                         VspBspTraversalData &data,                                                     
1623                                                         VspBspTraversalData &frontData,
1624                                                         VspBspTraversalData &backData,
1625                                                         int &splitAxis)
1626{
1627        // HACK matt: subdivide regularily to certain depth
1628        if (data.mDepth < 0)   
1629        {
1630                cout << "d: " << data.mDepth << endl;
1631                // return axis aligned split
1632                AxisAlignedBox3 box;
1633                box.Initialize();
1634       
1635                // create bounding box of region
1636                data.mGeometry->GetBoundingBox(box);
1637       
1638                const int axis = box.Size().DrivingAxis();
1639                const Vector3 position = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1640
1641                Vector3 norm(0,0,0); norm[axis] = 1.0f;
1642                bestPlane = Plane3(norm, position);
1643                splitAxis = axis;
1644                return true;
1645        }
1646
1647        // simplest strategy: just take next polygon
1648        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1649        {
1650        if (!data.mPolygons->empty())
1651                {
1652                        const int randIdx =
1653                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1654                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1655
1656                        bestPlane = nextPoly->GetSupportingPlane();
1657                        return true;
1658                }
1659        }
1660
1661        //-- use heuristics to find appropriate plane
1662
1663        // intermediate plane
1664        Plane3 plane;
1665        float lowestCost = MAX_FLOAT;
1666       
1667        // decides if the first few splits should be only axisAligned
1668        const bool onlyAxisAligned  =
1669                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1670                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1671                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1672       
1673        const int limit = onlyAxisAligned ? 0 :
1674                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1675
1676        float candidateCost;
1677
1678        int maxIdx = (int)data.mPolygons->size();
1679
1680        for (int i = 0; i < limit; ++ i)
1681        {
1682                // the already taken candidates are stored behind maxIdx
1683                // => assure that no index is taken twice
1684                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1685                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1686
1687                // swap candidate to the end to avoid testing same plane
1688                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1689                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1690
1691                // evaluate current candidate
1692                BspNodeGeometry fGeom, bGeom;
1693                float fArea, bArea;
1694                plane = poly->GetSupportingPlane();
1695                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1696               
1697                if (candidateCost < lowestCost)
1698                {
1699                        bestPlane = plane;
1700                        lowestCost = candidateCost;
1701                }
1702        }
1703
1704
1705        //-- evaluate axis aligned splits
1706       
1707        int axis;
1708        BspNodeGeometry *fGeom, *bGeom;
1709        float pFront, pBack;
1710
1711        candidateCost = 99999999.0f;
1712
1713        // as a variant, we take axis aligned split only if there is
1714        // more polygon available to guide the split
1715        if (!mUsePolygonSplitIfAvailable || data.mPolygons->empty())
1716        {
1717                candidateCost = SelectAxisAlignedPlane(plane,
1718                                                                                           data,
1719                                                                                           axis,
1720                                                                                           &fGeom,
1721                                                                                           &bGeom,
1722                                                                                           pFront,
1723                                                                                           pBack,
1724                                                                                           data.mIsKdNode);     
1725        }
1726
1727        splitAxis = 3;
1728
1729        if (candidateCost < lowestCost)
1730        {       
1731                bestPlane = plane;
1732                lowestCost = candidateCost;
1733                splitAxis = axis;
1734       
1735                // assign already computed values
1736                // we can do this because we always save the
1737                // computed values from the axis aligned splits         
1738
1739                if (fGeom && bGeom)
1740                {
1741                        frontData.mGeometry = fGeom;
1742                        backData.mGeometry = bGeom;
1743       
1744                        frontData.mProbability = pFront;
1745                        backData.mProbability = pBack;
1746                }
1747        }
1748        else
1749        {
1750                DEL_PTR(fGeom);
1751                DEL_PTR(bGeom);
1752        }
1753   
1754#ifdef _DEBUG
1755        Debug << "plane lowest cost: " << lowestCost << endl;
1756#endif
1757
1758        // exeeded relative max cost ratio
1759        if (lowestCost > mTermMaxCostRatio)
1760        {
1761                return false;
1762        }
1763
1764        return true;
1765}
1766
1767
1768Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1769{
1770        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1771
1772        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1773        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1774
1775        const Vector3 pt = (maxPt + minPt) * 0.5;
1776        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1777
1778        return Plane3(normal, pt);
1779}
1780
1781
1782Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1783{
1784        Vector3 pt[3];
1785
1786        int idx[3];
1787        int cmaxT = 0;
1788        int cminT = 0;
1789        bool chooseMin = false;
1790
1791        for (int j = 0; j < 3; ++ j)
1792        {
1793                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1794
1795                if (idx[j] >= (int)rays.size())
1796                {
1797                        idx[j] -= (int)rays.size();
1798
1799                        chooseMin = (cminT < 2);
1800                }
1801                else
1802                        chooseMin = (cmaxT < 2);
1803
1804                RayInfo rayInf = rays[idx[j]];
1805                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1806        }
1807
1808        return Plane3(pt[0], pt[1], pt[2]);
1809}
1810
1811
1812Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1813{
1814        Vector3 pt[3];
1815
1816        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1817        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1818
1819        // check if rays different
1820        if (idx1 == idx2)
1821                idx2 = (idx2 + 1) % (int)rays.size();
1822
1823        const RayInfo ray1 = rays[idx1];
1824        const RayInfo ray2 = rays[idx2];
1825
1826        // normal vector of the plane parallel to both lines
1827        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1828
1829        // vector from line 1 to line 2
1830        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1831
1832        // project vector on normal to get distance
1833        const float dist = DotProd(vd, norm);
1834
1835        // point on plane lies halfway between the two planes
1836        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1837
1838        return Plane3(norm, planePt);
1839}
1840
1841
1842inline void VspBspTree::GenerateUniqueIdsForPvs()
1843{
1844        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1845        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1846        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1847}
1848
1849
1850float VspBspTree::EvalRenderCostDecrease(const Plane3 &candidatePlane,
1851                                                                                 const VspBspTraversalData &data) const
1852{
1853        float pvsFront = 0;
1854        float pvsBack = 0;
1855        float totalPvs = 0;
1856
1857        // probability that view point lies in back / front node
1858        float pOverall = data.mProbability;
1859        float pFront = 0;
1860        float pBack = 0;
1861
1862
1863        // create unique ids for pvs heuristics
1864        GenerateUniqueIdsForPvs();
1865       
1866        for (int i = 0; i < data.mRays->size(); ++ i)
1867        {
1868                RayInfo rayInf = (*data.mRays)[i];
1869
1870                float t;
1871                VssRay *ray = rayInf.mRay;
1872                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1873
1874                // find front and back pvs for origing and termination object
1875                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1876                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1877        }
1878
1879
1880        BspNodeGeometry geomFront;
1881        BspNodeGeometry geomBack;
1882
1883        // construct child geometry with regard to the candidate split plane
1884        data.mGeometry->SplitGeometry(geomFront,
1885                                                                  geomBack,
1886                                                                  candidatePlane,
1887                                                                  mBox,
1888                                                                  //0.0f);
1889                                                                  mEpsilon);
1890
1891        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1892        {
1893                pFront = geomFront.GetVolume();
1894                pBack = pOverall - pFront;
1895
1896                // something is wrong with the volume
1897                if ((pFront < 0.0) || (pBack < 0.0))
1898                {
1899                        Debug << "ERROR in volume:\n"
1900                                  << "volume f :" << pFront << " b: " << pBack << " p: " << pOverall
1901                                  << ", real volume f: " << pFront << " b: " << geomBack.GetVolume()
1902                                  << ", #polygons f: " << geomFront.Size() << " b: " << geomBack.Size() << " p: " << data.mGeometry->Size() << endl;
1903                }
1904        }
1905        else
1906        {
1907                pFront = geomFront.GetArea();
1908                pBack = geomBack.GetArea();
1909        }
1910       
1911
1912        // -- pvs rendering heuristics
1913        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1914        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1915
1916        // only render cost heuristics or combined with standard deviation
1917        const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1918    const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1919        const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1920                       
1921        const float oldRenderCost = pOverall * penaltyOld;
1922        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1923
1924        //Debug << "decrease: " << oldRenderCost - newRenderCost << endl;
1925        const float renderCostDecrease = (oldRenderCost - newRenderCost) / mBox.GetVolume();
1926       
1927
1928#if 1
1929        // take render cost of node into account to avoid being stuck in a local minimum
1930        const float normalizedOldRenderCost = oldRenderCost / mBox.GetVolume();
1931       
1932        //Debug << "rendercostdecr: " << 0.99f * renderCostDecrease << " old render cost: " << 0.01f * normalizedOldRenderCost << endl;
1933        return 0.99f * renderCostDecrease + 0.01f * normalizedOldRenderCost;
1934#else
1935        return renderCostDecrease;
1936#endif
1937}
1938
1939
1940float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1941                                                                         const VspBspTraversalData &data,
1942                                                                         BspNodeGeometry &geomFront,
1943                                                                         BspNodeGeometry &geomBack,
1944                                                                         float &pFront,
1945                                                                         float &pBack) const
1946{
1947        float cost = 0;
1948
1949        float totalPvs = 0;
1950        float pvsFront = 0;
1951        float pvsBack = 0;
1952       
1953        // overall probability is used as normalizer
1954        float pOverall = 0;
1955
1956        // probability that view point lies in back / front node
1957        pFront = 0;
1958        pBack = 0;
1959
1960
1961        int limit;
1962        bool useRand;
1963
1964        // create unique ids for pvs heuristics
1965        GenerateUniqueIdsForPvs();
1966
1967        // choose test rays randomly if too much
1968        if ((int)data.mRays->size() > mMaxTests)
1969        {
1970                useRand = true;
1971                limit = mMaxTests;
1972        }
1973        else
1974        {
1975                useRand = false;
1976                limit = (int)data.mRays->size();
1977        }
1978       
1979        for (int i = 0; i < limit; ++ i)
1980        {
1981                const int testIdx = useRand ?
1982                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
1983                RayInfo rayInf = (*data.mRays)[testIdx];
1984
1985                float t;
1986                VssRay *ray = rayInf.mRay;
1987                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1988
1989                // find front and back pvs for origing and termination object
1990                AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1991                AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1992        }
1993
1994        // construct child geometry with regard to the candidate split plane
1995        bool splitSuccessFull = data.mGeometry->SplitGeometry(geomFront,
1996                                                                                                                  geomBack,
1997                                                                                                                  candidatePlane,
1998                                                                                                                  mBox,
1999                                                                                                                  //0.0f);
2000                                                                                                                  mEpsilon);
2001
2002        pOverall = data.mProbability;
2003
2004        if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
2005        {
2006                pFront = geomFront.GetVolume();
2007                pBack = pOverall - pFront;
2008               
2009                // HACK: precision issues possible for unbalanced split => don't take this split!
2010                if (1 &&
2011                        (!splitSuccessFull || (pFront <= 0) || (pBack <= 0) ||
2012                        !geomFront.Valid() || !geomBack.Valid()))
2013                {
2014                        //Debug << "error f: " << pFront << " b: " << pBack << endl;
2015                        // high penalty for this split
2016                        return 99999.9f;
2017                }
2018        }
2019        else
2020        {
2021                pFront = geomFront.GetArea();
2022                pBack = geomBack.GetArea();
2023        }
2024       
2025
2026        // -- pvs rendering heuristics
2027        const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
2028        const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
2029
2030        // only render cost heuristics or combined with standard deviation
2031        const float penaltyOld = EvalPvsPenalty((int)totalPvs, lowerPvsLimit, upperPvsLimit);
2032    const float penaltyFront = EvalPvsPenalty((int)pvsFront, lowerPvsLimit, upperPvsLimit);
2033        const float penaltyBack = EvalPvsPenalty((int)pvsBack, lowerPvsLimit, upperPvsLimit);
2034                       
2035        const float oldRenderCost = pOverall * penaltyOld;
2036        const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
2037
2038        float oldCost, newCost;
2039
2040        // only render cost
2041        if (1)
2042        {
2043                oldCost = oldRenderCost;
2044                newCost = newRenderCost;
2045        }
2046        else // also considering standard deviation
2047        {
2048                // standard deviation is difference of back and front pvs
2049                const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
2050
2051                const float newDeviation = 0.5f *
2052                        fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
2053
2054                const float oldDeviation = penaltyOld;
2055
2056                newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
2057                oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
2058        }
2059
2060        cost += mPvsFactor * newCost / (oldCost + Limits::Small);
2061               
2062
2063#ifdef _DEBUG
2064        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
2065                  << " frontpvs: " << pvsFront << " pFront: " << pFront
2066                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
2067        Debug << "cost: " << cost << endl;
2068#endif
2069
2070        return cost;
2071}
2072
2073
2074int VspBspTree::ComputeBoxIntersections(const AxisAlignedBox3 &box,
2075                                                                                ViewCellContainer &viewCells) const
2076{
2077        stack<bspNodePair> nodeStack;
2078        BspNodeGeometry *rgeom = new BspNodeGeometry();
2079
2080        ConstructGeometry(mRoot, *rgeom);
2081
2082        nodeStack.push(bspNodePair(mRoot, rgeom));
2083 
2084        ViewCell::NewMail();
2085
2086        while (!nodeStack.empty())
2087        {
2088                BspNode *node = nodeStack.top().first;
2089                BspNodeGeometry *geom = nodeStack.top().second;
2090                nodeStack.pop();
2091
2092                const int side = geom->ComputeIntersection(box);
2093               
2094                switch (side)
2095                {
2096                case -1:
2097                        // node geometry is contained in box
2098                        CollectViewCells(node, true, viewCells, true);
2099                        break;
2100
2101                case 0:
2102                        if (node->IsLeaf())
2103                        {
2104                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2105                       
2106                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2107                                {
2108                                        leaf->GetViewCell()->Mail();
2109                                        viewCells.push_back(leaf->GetViewCell());
2110                                }
2111                        }
2112                        else
2113                        {
2114                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2115                       
2116                                BspNode *first = interior->GetFront();
2117                                BspNode *second = interior->GetBack();
2118           
2119                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2120                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2121
2122                                geom->SplitGeometry(*firstGeom,
2123                                                                        *secondGeom,
2124                                                                        interior->GetPlane(),
2125                                                                        mBox,
2126                                                                        //0.0000001f);
2127                                                                        mEpsilon);
2128
2129                                nodeStack.push(bspNodePair(first, firstGeom));
2130                                nodeStack.push(bspNodePair(second, secondGeom));
2131                        }
2132                       
2133                        break;
2134                default:
2135                        // default: cull
2136                        break;
2137                }
2138               
2139                DEL_PTR(geom);
2140               
2141        }
2142
2143        return (int)viewCells.size();
2144}
2145
2146
2147float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
2148                                                                                   const AxisAlignedBox3 &box,
2149                                                                                   const int axis,
2150                                                                                   const float &position,                                                                                 
2151                                                                                   float &pFront,
2152                                                                                   float &pBack) const
2153{
2154        float pvsTotal = 0;
2155        float pvsFront = 0;
2156        float pvsBack = 0;
2157       
2158        // create unique ids for pvs heuristics
2159        GenerateUniqueIdsForPvs();
2160
2161        const int pvsSize = data.mPvs;
2162
2163        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
2164
2165        // this is the main ray classification loop!
2166        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
2167        {
2168                //if (!(*rit).mRay->IsActive()) continue;
2169
2170                // determine the side of this ray with respect to the plane
2171                float t;
2172                const int side = (*rit).ComputeRayIntersection(axis, position, t);
2173       
2174                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
2175                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
2176        }
2177
2178        //-- pvs heuristics
2179        float pOverall;
2180
2181        //-- compute heurstics
2182        //-- we take simplified computation for mid split
2183               
2184        pOverall = data.mProbability;
2185
2186        if (!mUseAreaForPvs)
2187        {   // volume
2188                pBack = pFront = pOverall * 0.5f;
2189               
2190#if 0
2191                // box length substitute for probability
2192                const float minBox = box.Min(axis);
2193                const float maxBox = box.Max(axis);
2194
2195                pBack = position - minBox;
2196                pFront = maxBox - position;
2197                pOverall = maxBox - minBox;
2198#endif
2199        }
2200        else //-- area substitute for probability
2201        {
2202                const int axis2 = (axis + 1) % 3;
2203                const int axis3 = (axis + 2) % 3;
2204
2205                const float faceArea =
2206                        (box.Max(axis2) - box.Min(axis2)) *
2207                        (box.Max(axis3) - box.Min(axis3));
2208
2209                pBack = pFront = pOverall * 0.5f + faceArea;
2210        }
2211
2212#ifdef _DEBUG
2213        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
2214        Debug << pFront << " " << pBack << " " << pOverall << endl;
2215#endif
2216
2217       
2218        const float newCost = pvsBack * pBack + pvsFront * pFront;
2219        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
2220
2221        return  (mCtDivCi + newCost) / oldCost;
2222}
2223
2224
2225void VspBspTree::AddObjToPvs(Intersectable *obj,
2226                                                         const int cf,
2227                                                         float &frontPvs,
2228                                                         float &backPvs,
2229                                                         float &totalPvs) const
2230{
2231        if (!obj)
2232                return;
2233
2234        const float renderCost = mViewCellsManager->EvalRenderCost(obj);
2235
2236        // new object
2237        if ((obj->mMailbox != sFrontId) &&
2238                (obj->mMailbox != sBackId) &&
2239                (obj->mMailbox != sFrontAndBackId))
2240        {
2241                totalPvs += renderCost;
2242        }
2243
2244        // TODO: does this really belong to no pvs?
2245        //if (cf == Ray::COINCIDENT) return;
2246
2247        // object belongs to both PVS
2248        if (cf >= 0)
2249        {
2250                if ((obj->mMailbox != sFrontId) &&
2251                        (obj->mMailbox != sFrontAndBackId))
2252                {
2253                        frontPvs += renderCost;
2254               
2255                        if (obj->mMailbox == sBackId)
2256                                obj->mMailbox = sFrontAndBackId;
2257                        else
2258                                obj->mMailbox = sFrontId;
2259                }
2260        }
2261
2262        if (cf <= 0)
2263        {
2264                if ((obj->mMailbox != sBackId) &&
2265                        (obj->mMailbox != sFrontAndBackId))
2266                {
2267                        backPvs += renderCost;
2268               
2269                        if (obj->mMailbox == sFrontId)
2270                                obj->mMailbox = sFrontAndBackId;
2271                        else
2272                                obj->mMailbox = sBackId;
2273                }
2274        }
2275}
2276
2277
2278void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
2279                                                           const bool onlyUnmailed,
2280                                                           const int maxPvsSize) const
2281{
2282        stack<BspNode *> nodeStack;
2283        nodeStack.push(mRoot);
2284
2285        while (!nodeStack.empty())
2286        {
2287                BspNode *node = nodeStack.top();
2288                nodeStack.pop();
2289               
2290                if (node->IsLeaf())
2291                {
2292                        // test if this leaf is in valid view space
2293                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2294                        if (leaf->TreeValid() &&
2295                                (!onlyUnmailed || !leaf->Mailed()) &&
2296                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
2297                        {
2298                                leaves.push_back(leaf);
2299                        }
2300                }
2301                else
2302                {
2303                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2304
2305                        nodeStack.push(interior->GetBack());
2306                        nodeStack.push(interior->GetFront());
2307                }
2308        }
2309}
2310
2311
2312AxisAlignedBox3 VspBspTree::GetBoundingBox() const
2313{
2314        return mBox;
2315}
2316
2317
2318BspNode *VspBspTree::GetRoot() const
2319{
2320        return mRoot;
2321}
2322
2323
2324void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
2325{
2326        // the node became a leaf -> evaluate stats for leafs
2327        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
2328
2329
2330        if (data.mPvs > mBspStats.maxPvs)
2331        {
2332                mBspStats.maxPvs = data.mPvs;
2333        }
2334
2335        mBspStats.pvs += data.mPvs;
2336
2337        if (data.mDepth < mBspStats.minDepth)
2338        {
2339                mBspStats.minDepth = data.mDepth;
2340        }
2341       
2342        if (data.mDepth >= mTermMaxDepth)
2343        {
2344        ++ mBspStats.maxDepthNodes;
2345                //Debug << "new max depth: " << mBspStats.maxDepthNodes << endl;
2346        }
2347
2348        // accumulate rays to compute rays /  leaf
2349        mBspStats.accumRays += (int)data.mRays->size();
2350
2351        if (data.mPvs < mTermMinPvs)
2352                ++ mBspStats.minPvsNodes;
2353
2354        if ((int)data.mRays->size() < mTermMinRays)
2355                ++ mBspStats.minRaysNodes;
2356
2357        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
2358                ++ mBspStats.maxRayContribNodes;
2359
2360        if (data.mProbability <= mTermMinProbability)
2361                ++ mBspStats.minProbabilityNodes;
2362       
2363        // accumulate depth to compute average depth
2364        mBspStats.accumDepth += data.mDepth;
2365
2366        ++ mCreatedViewCells;
2367
2368#ifdef _DEBUG
2369        Debug << "BSP stats: "
2370                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
2371                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
2372          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
2373                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
2374                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
2375                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
2376#endif
2377}
2378
2379
2380int VspBspTree::CastRay(Ray &ray)
2381{
2382        int hits = 0;
2383
2384        stack<BspRayTraversalData> tQueue;
2385
2386        float maxt, mint;
2387
2388        if (!mBox.GetRaySegment(ray, mint, maxt))
2389                return 0;
2390
2391        Intersectable::NewMail();
2392        ViewCell::NewMail();
2393        Vector3 entp = ray.Extrap(mint);
2394        Vector3 extp = ray.Extrap(maxt);
2395
2396        BspNode *node = mRoot;
2397        BspNode *farChild = NULL;
2398
2399        while (1)
2400        {
2401                if (!node->IsLeaf())
2402                {
2403                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2404
2405                        Plane3 splitPlane = in->GetPlane();
2406                        const int entSide = splitPlane.Side(entp);
2407                        const int extSide = splitPlane.Side(extp);
2408
2409                        if (entSide < 0)
2410                        {
2411                                node = in->GetBack();
2412
2413                                if(extSide <= 0) // plane does not split ray => no far child
2414                                        continue;
2415
2416                                farChild = in->GetFront(); // plane splits ray
2417
2418                        } else if (entSide > 0)
2419                        {
2420                                node = in->GetFront();
2421
2422                                if (extSide >= 0) // plane does not split ray => no far child
2423                                        continue;
2424
2425                                farChild = in->GetBack(); // plane splits ray
2426                        }
2427                        else // ray and plane are coincident
2428                        {
2429                                // WHAT TO DO IN THIS CASE ?
2430                                //break;
2431                                node = in->GetFront();
2432                                continue;
2433                        }
2434
2435                        // push data for far child
2436                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
2437
2438                        // find intersection of ray segment with plane
2439                        float t;
2440                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2441                        maxt *= t;
2442
2443                } else // reached leaf => intersection with view cell
2444                {
2445                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2446
2447                        if (!leaf->GetViewCell()->Mailed())
2448                        {
2449                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2450                                leaf->GetViewCell()->Mail();
2451                                ++ hits;
2452                        }
2453
2454                        //-- fetch the next far child from the stack
2455                        if (tQueue.empty())
2456                                break;
2457
2458                        entp = extp;
2459                        mint = maxt; // NOTE: need this?
2460
2461                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2462                                break;
2463
2464                        BspRayTraversalData &s = tQueue.top();
2465
2466                        node = s.mNode;
2467                        extp = s.mExitPoint;
2468                        maxt = s.mMaxT;
2469
2470                        tQueue.pop();
2471                }
2472        }
2473
2474        return hits;
2475}
2476
2477
2478void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
2479{
2480        ViewCell::NewMail();
2481       
2482        CollectViewCells(mRoot, onlyValid, viewCells, true);
2483}
2484
2485
2486void VspBspTree::CollapseViewCells()
2487{
2488// TODO
2489#if HAS_TO_BE_REDONE
2490        stack<BspNode *> nodeStack;
2491
2492        if (!mRoot)
2493                return;
2494
2495        nodeStack.push(mRoot);
2496       
2497        while (!nodeStack.empty())
2498        {
2499                BspNode *node = nodeStack.top();
2500                nodeStack.pop();
2501               
2502                if (node->IsLeaf())
2503        {
2504                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2505
2506                        if (!viewCell->GetValid())
2507                        {
2508                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2509       
2510                                ViewCellContainer leaves;
2511                                mViewCellsTree->CollectLeaves(viewCell, leaves);
2512
2513                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2514
2515                                for (it = leaves.begin(); it != it_end; ++ it)
2516                                {
2517                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2518                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2519                                        ++ mBspStats.invalidLeaves;
2520                                }
2521
2522                                // add to unbounded view cell
2523                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2524                                DEL_PTR(viewCell);
2525                        }
2526                }
2527                else
2528                {
2529                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2530               
2531                        nodeStack.push(interior->GetFront());
2532                        nodeStack.push(interior->GetBack());
2533                }
2534        }
2535
2536        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2537#endif
2538}
2539
2540
2541void VspBspTree::CollectRays(VssRayContainer &rays)
2542{
2543        vector<BspLeaf *> leaves;
2544
2545        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2546
2547        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2548        {
2549                BspLeaf *leaf = *lit;
2550                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2551
2552                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2553                        rays.push_back(*rit);
2554        }
2555}
2556
2557
2558void VspBspTree::ValidateTree()
2559{
2560        stack<BspNode *> nodeStack;
2561
2562        if (!mRoot)
2563                return;
2564
2565        nodeStack.push(mRoot);
2566       
2567        mBspStats.invalidLeaves = 0;
2568        while (!nodeStack.empty())
2569        {
2570                BspNode *node = nodeStack.top();
2571                nodeStack.pop();
2572               
2573                if (node->IsLeaf())
2574                {
2575                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2576
2577                        if (!leaf->GetViewCell()->GetValid())
2578                                ++ mBspStats.invalidLeaves;
2579
2580                        // validity flags don't match => repair
2581                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2582                        {
2583                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2584                                PropagateUpValidity(leaf);
2585                        }
2586                }
2587                else
2588                {
2589                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2590               
2591                        nodeStack.push(interior->GetFront());
2592                        nodeStack.push(interior->GetBack());
2593                }
2594        }
2595
2596        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2597}
2598
2599
2600
2601void VspBspTree::CollectViewCells(BspNode *root,
2602                                                                  bool onlyValid,
2603                                                                  ViewCellContainer &viewCells,
2604                                                                  bool onlyUnmailed) const
2605{
2606        stack<BspNode *> nodeStack;
2607
2608        if (!root)
2609                return;
2610
2611        nodeStack.push(root);
2612       
2613        while (!nodeStack.empty())
2614        {
2615                BspNode *node = nodeStack.top();
2616                nodeStack.pop();
2617               
2618                if (node->IsLeaf())
2619                {
2620                        if (!onlyValid || node->TreeValid())
2621                        {
2622                                ViewCellLeaf *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2623
2624                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2625                                               
2626                                if (!onlyUnmailed || !viewCell->Mailed())
2627                                {
2628                                        viewCell->Mail();
2629                                        viewCells.push_back(viewCell);
2630                                }
2631                        }
2632                }
2633                else
2634                {
2635                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2636               
2637                        nodeStack.push(interior->GetFront());
2638                        nodeStack.push(interior->GetBack());
2639                }
2640        }
2641
2642}
2643
2644
2645void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2646{
2647        // preprocess: throw out polygons coincident to the view space box (not needed)
2648        PolygonContainer boxPolys;
2649        /*mBox.ExtractPolys(boxPolys);
2650        vector<Plane3> boxPlanes;
2651
2652        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2653
2654        // extract planes of box
2655        // TODO: can be done more elegantly than first extracting polygons
2656        // and take their planes
2657        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2658        {
2659                boxPlanes.push_back((*pit)->GetSupportingPlane());
2660        }
2661
2662        pit_end = polys.end();
2663
2664        for (pit = polys.begin(); pit != pit_end; ++ pit)
2665        {
2666                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2667               
2668                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2669                {
2670                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2671
2672                        if (cf == Polygon3::COINCIDENT)
2673                        {
2674                                DEL_PTR(*pit);
2675                                //Debug << "coincident!!" << endl;
2676                        }
2677                }
2678        }
2679
2680        // remove deleted entries after swapping them to end of vector
2681        for (int i = 0; i < (int)polys.size(); ++ i)
2682        {
2683                while (!polys[i] && (i < (int)polys.size()))
2684                {
2685                        swap(polys[i], polys.back());
2686                        polys.pop_back();
2687                }
2688        }*/
2689}
2690
2691
2692float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2693{
2694        float len = 0;
2695
2696        RayInfoContainer::const_iterator it, it_end = rays.end();
2697
2698        for (it = rays.begin(); it != it_end; ++ it)
2699                len += (*it).SegmentLength();
2700
2701        return len;
2702}
2703
2704
2705int VspBspTree::SplitRays(const Plane3 &plane,
2706                                                  RayInfoContainer &rays,
2707                                                  RayInfoContainer &frontRays,
2708                                                  RayInfoContainer &backRays) const
2709{
2710        int splits = 0;
2711
2712        RayInfoContainer::const_iterator it, it_end = rays.end();
2713
2714        for (it = rays.begin(); it != it_end; ++ it)
2715        {
2716                RayInfo bRay = *it;
2717               
2718                VssRay *ray = bRay.mRay;
2719                float t;
2720
2721                // get classification and receive new t
2722                const int cf = bRay.ComputeRayIntersection(plane, t);
2723
2724                switch (cf)
2725                {
2726                case -1:
2727                        backRays.push_back(bRay);
2728                        break;
2729                case 1:
2730                        frontRays.push_back(bRay);
2731                        break;
2732                case 0:
2733                        {
2734                                //-- split ray
2735                                //   test if start point behind or in front of plane
2736                                const int side = plane.Side(bRay.ExtrapOrigin());
2737
2738                                if (side <= 0)
2739                                {
2740                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2741                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2742                                }
2743                                else
2744                                {
2745                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2746                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2747                                }
2748                        }
2749                        break;
2750                default:
2751                        Debug << "Should not come here" << endl;
2752                        break;
2753                }
2754        }
2755
2756        return splits;
2757}
2758
2759
2760void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2761{
2762        BspNode *lastNode;
2763
2764        do
2765        {
2766                lastNode = n;
2767
2768                // want to get planes defining geometry of this node => don't take
2769                // split plane of node itself
2770                n = n->GetParent();
2771
2772                if (n)
2773                {
2774                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2775                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2776
2777            if (interior->GetBack() != lastNode)
2778                                halfSpace.ReverseOrientation();
2779
2780                        halfSpaces.push_back(halfSpace);
2781                }
2782        }
2783        while (n);
2784}
2785
2786
2787void VspBspTree::ConstructGeometry(BspNode *n,
2788                                                                   BspNodeGeometry &geom) const
2789{
2790        vector<Plane3> halfSpaces;
2791        ExtractHalfSpaces(n, halfSpaces);
2792
2793        PolygonContainer candidatePolys;
2794        vector<Plane3> candidatePlanes;
2795
2796        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2797
2798        // bounded planes are added to the polygons
2799        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
2800        {
2801                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
2802
2803                if (p->Valid(mEpsilon))
2804                {
2805                        candidatePolys.push_back(p);
2806                        candidatePlanes.push_back(*pit);
2807                }
2808        }
2809
2810        // add faces of bounding box (also could be faces of the cell)
2811        for (int i = 0; i < 6; ++ i)
2812        {
2813                VertexContainer vertices;
2814
2815                for (int j = 0; j < 4; ++ j)
2816                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2817
2818                Polygon3 *poly = new Polygon3(vertices);
2819
2820                candidatePolys.push_back(poly);
2821                candidatePlanes.push_back(poly->GetSupportingPlane());
2822        }
2823
2824        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2825        {
2826                // polygon is split by all other planes
2827                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2828                {
2829                        if (i == j) // polygon and plane are coincident
2830                                continue;
2831
2832                        VertexContainer splitPts;
2833                        Polygon3 *frontPoly, *backPoly;
2834
2835                        const int cf =
2836                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2837                                                                                                 mEpsilon);
2838
2839                        switch (cf)
2840                        {
2841                                case Polygon3::SPLIT:
2842                                        frontPoly = new Polygon3();
2843                                        backPoly = new Polygon3();
2844
2845                                        candidatePolys[i]->Split(halfSpaces[j],
2846                                                                                         *frontPoly,
2847                                                                                         *backPoly,
2848                                                                                         mEpsilon);
2849
2850                                        DEL_PTR(candidatePolys[i]);
2851
2852                                        if (backPoly->Valid(mEpsilon))
2853                                                candidatePolys[i] = backPoly;
2854                                        else
2855                                                DEL_PTR(backPoly);
2856
2857                                        // outside, don't need this
2858                                        DEL_PTR(frontPoly);
2859                                        break;
2860                                // polygon outside of halfspace
2861                                case Polygon3::FRONT_SIDE:
2862                                        DEL_PTR(candidatePolys[i]);
2863                                        break;
2864                                // just take polygon as it is
2865                                case Polygon3::BACK_SIDE:
2866                                case Polygon3::COINCIDENT:
2867                                default:
2868                                        break;
2869                        }
2870                }
2871
2872                if (candidatePolys[i])
2873                {
2874                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2875                        //      geom.mPolys.push_back(candidates[i]);
2876                }
2877        }
2878}
2879
2880
2881void VspBspTree::ConstructGeometry(ViewCell *vc,
2882                                                                   BspNodeGeometry &vcGeom) const
2883{
2884        ViewCellContainer leaves;
2885       
2886        mViewCellsTree->CollectLeaves(vc, leaves);
2887
2888        ViewCellContainer::const_iterator it, it_end = leaves.end();
2889
2890        for (it = leaves.begin(); it != it_end; ++ it)
2891        {
2892                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2893               
2894                ConstructGeometry(l, vcGeom);
2895        }
2896}
2897
2898
2899int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2900                                                          const bool onlyUnmailed) const
2901{
2902        stack<bspNodePair> nodeStack;
2903       
2904        BspNodeGeometry nodeGeom;
2905        ConstructGeometry(n, nodeGeom);
2906//      const float eps = 0.5f;
2907        const float eps = 0.01f;
2908        // split planes from the root to this node
2909        // needed to verify that we found neighbor leaf
2910        // TODO: really needed?
2911        vector<Plane3> halfSpaces;
2912        ExtractHalfSpaces(n, halfSpaces);
2913
2914
2915        BspNodeGeometry *rgeom = new BspNodeGeometry();
2916        ConstructGeometry(mRoot, *rgeom);
2917
2918        nodeStack.push(bspNodePair(mRoot, rgeom));
2919
2920        while (!nodeStack.empty())
2921        {
2922                BspNode *node = nodeStack.top().first;
2923                BspNodeGeometry *geom = nodeStack.top().second;
2924       
2925                nodeStack.pop();
2926
2927                if (node->IsLeaf())
2928                {
2929                        // test if this leaf is in valid view space
2930                        if (node->TreeValid() &&
2931                                (node != n) &&
2932                                (!onlyUnmailed || !node->Mailed()))
2933                        {
2934                                bool isAdjacent = true;
2935
2936                                if (1)
2937                                {
2938                                        // test all planes of current node if still adjacent
2939                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2940                                        {
2941                                                const int cf =
2942                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2943                                                                                                        halfSpaces[i],
2944                                                                                                        eps);
2945
2946                                                if (cf == Polygon3::FRONT_SIDE)
2947                                                {
2948                                                        isAdjacent = false;
2949                                                }
2950                                        }
2951                                }
2952                                else
2953                                {
2954                                        // TODO: why is this wrong??
2955                                        // test all planes of current node if still adjacent
2956                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2957                                        {
2958                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2959
2960                                                const int cf =
2961                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2962                                                                                                        poly->GetSupportingPlane(),
2963                                                                                                        eps);
2964
2965                                                if (cf == Polygon3::FRONT_SIDE)
2966                                                {
2967                                                        isAdjacent = false;
2968                                                }
2969                                        }
2970                                }
2971                                // neighbor was found
2972                                if (isAdjacent)
2973                                {       
2974                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2975                                }
2976                        }
2977                }
2978                else
2979                {
2980                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2981
2982                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2983                                                                                                   interior->GetPlane(),
2984                                                                                                   eps);
2985                       
2986                        BspNode *front = interior->GetFront();
2987                        BspNode *back = interior->GetBack();
2988           
2989                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2990                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2991
2992                        geom->SplitGeometry(*fGeom,
2993                                                                *bGeom,
2994                                                                interior->GetPlane(),
2995                                                                mBox,
2996                                                                //0.0000001f);
2997                                                                eps);
2998               
2999                        if (cf == Polygon3::BACK_SIDE)
3000                        {
3001                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3002                                DEL_PTR(fGeom);
3003                        }
3004                        else
3005                        {
3006                                if (cf == Polygon3::FRONT_SIDE)
3007                                {
3008                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3009                                        DEL_PTR(bGeom);
3010                                }
3011                                else
3012                                {       // random decision
3013                                        nodeStack.push(bspNodePair(front, fGeom));
3014                                        nodeStack.push(bspNodePair(back, bGeom));
3015                                }
3016                        }
3017                }
3018       
3019                DEL_PTR(geom);
3020        }
3021
3022        return (int)neighbors.size();
3023}
3024
3025
3026
3027int VspBspTree::FindApproximateNeighbors(BspNode *n,
3028                                                                                 vector<BspLeaf *> &neighbors,
3029                                                                                 const bool onlyUnmailed) const
3030{
3031        stack<bspNodePair> nodeStack;
3032       
3033        BspNodeGeometry nodeGeom;
3034        ConstructGeometry(n, nodeGeom);
3035       
3036        float eps = 0.01f;
3037        // split planes from the root to this node
3038        // needed to verify that we found neighbor leaf
3039        // TODO: really needed?
3040        vector<Plane3> halfSpaces;
3041        ExtractHalfSpaces(n, halfSpaces);
3042
3043
3044        BspNodeGeometry *rgeom = new BspNodeGeometry();
3045        ConstructGeometry(mRoot, *rgeom);
3046
3047        nodeStack.push(bspNodePair(mRoot, rgeom));
3048
3049        while (!nodeStack.empty())
3050        {
3051                BspNode *node = nodeStack.top().first;
3052                BspNodeGeometry *geom = nodeStack.top().second;
3053       
3054                nodeStack.pop();
3055
3056                if (node->IsLeaf())
3057                {
3058                        // test if this leaf is in valid view space
3059                        if (node->TreeValid() &&
3060                                (node != n) &&
3061                                (!onlyUnmailed || !node->Mailed()))
3062                        {
3063                                bool isAdjacent = true;
3064
3065                                // neighbor was found
3066                                if (isAdjacent)
3067                                {       
3068                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3069                                }
3070                        }
3071                }
3072                else
3073                {
3074                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3075
3076                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
3077                                                                                                   interior->GetPlane(),
3078                                                                                                   eps);
3079                       
3080                        BspNode *front = interior->GetFront();
3081                        BspNode *back = interior->GetBack();
3082           
3083                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3084                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3085
3086                        geom->SplitGeometry(*fGeom,
3087                                                                *bGeom,
3088                                                                interior->GetPlane(),
3089                                                                mBox,
3090                                                                //0.0000001f);
3091                                                                eps);
3092               
3093                        if (cf == Polygon3::BACK_SIDE)
3094                        {
3095                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3096                                DEL_PTR(fGeom);
3097                                }
3098                        else
3099                        {
3100                                if (cf == Polygon3::FRONT_SIDE)
3101                                {
3102                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3103                                        DEL_PTR(bGeom);
3104                                }
3105                                else
3106                                {       // random decision
3107                                        nodeStack.push(bspNodePair(front, fGeom));
3108                                        nodeStack.push(bspNodePair(back, bGeom));
3109                                }
3110                        }
3111                }
3112       
3113                DEL_PTR(geom);
3114        }
3115
3116        return (int)neighbors.size();
3117}
3118
3119
3120
3121BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3122{
3123    stack<BspNode *> nodeStack;
3124        nodeStack.push(mRoot);
3125
3126        int mask = rand();
3127
3128        while (!nodeStack.empty())
3129        {
3130                BspNode *node = nodeStack.top();
3131                nodeStack.pop();
3132
3133                if (node->IsLeaf())
3134                {
3135                        return dynamic_cast<BspLeaf *>(node);
3136                }
3137                else
3138                {
3139                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3140                        BspNode *next;
3141                        BspNodeGeometry geom;
3142
3143                        // todo: not very efficient: constructs full cell everytime
3144                        ConstructGeometry(interior, geom);
3145
3146                        const int cf =
3147                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
3148
3149                        if (cf == Polygon3::BACK_SIDE)
3150                                next = interior->GetFront();
3151                        else
3152                                if (cf == Polygon3::FRONT_SIDE)
3153                                        next = interior->GetFront();
3154                        else
3155                        {
3156                                // random decision
3157                                if (mask & 1)
3158                                        next = interior->GetBack();
3159                                else
3160                                        next = interior->GetFront();
3161                                mask = mask >> 1;
3162                        }
3163
3164                        nodeStack.push(next);
3165                }
3166        }
3167
3168        return NULL;
3169}
3170
3171
3172BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3173{
3174        stack<BspNode *> nodeStack;
3175
3176        nodeStack.push(mRoot);
3177
3178        int mask = rand();
3179
3180        while (!nodeStack.empty())
3181        {
3182                BspNode *node = nodeStack.top();
3183                nodeStack.pop();
3184
3185                if (node->IsLeaf())
3186                {
3187                        if ( (!onlyUnmailed || !node->Mailed()) )
3188                                return dynamic_cast<BspLeaf *>(node);
3189                }
3190                else
3191                {
3192                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3193
3194                        // random decision
3195                        if (mask & 1)
3196                                nodeStack.push(interior->GetBack());
3197                        else
3198                                nodeStack.push(interior->GetFront());
3199
3200                        mask = mask >> 1;
3201                }
3202        }
3203
3204        return NULL;
3205}
3206
3207
3208int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3209{
3210        int pvsSize = 0;
3211
3212        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3213
3214        Intersectable::NewMail();
3215
3216        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3217        {
3218                VssRay *ray = (*rit).mRay;
3219
3220                if (ray->mOriginObject)
3221                {
3222                        if (!ray->mOriginObject->Mailed())
3223                        {
3224                                ray->mOriginObject->Mail();
3225                                ++ pvsSize;
3226                        }
3227                }
3228                if (ray->mTerminationObject)
3229                {
3230                        if (!ray->mTerminationObject->Mailed())
3231                        {
3232                                ray->mTerminationObject->Mail();
3233                                ++ pvsSize;
3234                        }
3235                }
3236        }
3237
3238        return pvsSize;
3239}
3240
3241
3242float VspBspTree::GetEpsilon() const
3243{
3244        return mEpsilon;
3245}
3246
3247
3248int VspBspTree::SplitPolygons(const Plane3 &plane,
3249                                                          PolygonContainer &polys,
3250                                                          PolygonContainer &frontPolys,
3251                                                          PolygonContainer &backPolys,
3252                                                          PolygonContainer &coincident) const
3253{
3254        int splits = 0;
3255
3256        PolygonContainer::const_iterator it, it_end = polys.end();
3257
3258        for (it = polys.begin(); it != polys.end(); ++ it)     
3259        {
3260                Polygon3 *poly = *it;
3261
3262                // classify polygon
3263                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3264
3265                switch (cf)
3266                {
3267                        case Polygon3::COINCIDENT:
3268                                coincident.push_back(poly);
3269                                break;
3270                        case Polygon3::FRONT_SIDE:
3271                                frontPolys.push_back(poly);
3272                                break;
3273                        case Polygon3::BACK_SIDE:
3274                                backPolys.push_back(poly);
3275                                break;
3276                        case Polygon3::SPLIT:
3277                                backPolys.push_back(poly);
3278                                frontPolys.push_back(poly);
3279                                ++ splits;
3280                                break;
3281                        default:
3282                Debug << "SHOULD NEVER COME HERE\n";
3283                                break;
3284                }
3285        }
3286
3287        return splits;
3288}
3289
3290
3291int VspBspTree::CastLineSegment(const Vector3 &origin,
3292                                                                const Vector3 &termination,
3293                                                                ViewCellContainer &viewcells)
3294{
3295        int hits = 0;
3296        stack<BspRayTraversalData> tStack;
3297
3298        float mint = 0.0f, maxt = 1.0f;
3299
3300        Intersectable::NewMail();
3301        ViewCell::NewMail();
3302
3303        Vector3 entp = origin;
3304        Vector3 extp = termination;
3305
3306        BspNode *node = mRoot;
3307        BspNode *farChild = NULL;
3308
3309        float t;
3310        const float thresh = 1e-6f; // matt: change this to adjustable value
3311       
3312        while (1)
3313        {
3314                if (!node->IsLeaf())
3315                {
3316                        BspInterior *in = dynamic_cast<BspInterior *>(node);
3317
3318                        Plane3 splitPlane = in->GetPlane();
3319                       
3320                        const int entSide = splitPlane.Side(entp, thresh);
3321                        const int extSide = splitPlane.Side(extp, thresh);
3322
3323                        if (entSide < 0)
3324                        {
3325                                node = in->GetBack();
3326                               
3327                                // plane does not split ray => no far child
3328                                if (extSide <= 0)
3329                                        continue;
3330 
3331                                farChild = in->GetFront(); // plane splits ray
3332                        }
3333                        else if (entSide > 0)
3334                        {
3335                                node = in->GetFront();
3336
3337                                if (extSide >= 0) // plane does not split ray => no far child
3338                                        continue;
3339
3340                                farChild = in->GetBack(); // plane splits ray
3341                        }
3342                        else // one of the ray end points is on the plane
3343                        {       // NOTE: what to do if ray is coincident with plane?
3344                                if (extSide < 0)
3345                                        node = in->GetBack();
3346                                else //if (extSide > 0)
3347                                        node = in->GetFront();
3348                                //else break; // coincident => count no intersections
3349
3350                                continue; // no far child
3351                        }
3352
3353                        // push data for far child
3354                        tStack.push(BspRayTraversalData(farChild, extp));
3355
3356                        // find intersection of ray segment with plane
3357                        extp = splitPlane.FindIntersection(origin, extp, &t);
3358                }
3359                else
3360                {
3361                        // reached leaf => intersection with view cell
3362                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3363                        ViewCell *viewCell;
3364                       
3365                        if (0)
3366                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3367                        else
3368                                viewCell = leaf->GetViewCell();
3369
3370                        if (!viewCell->Mailed())
3371                        {
3372                                viewcells.push_back(viewCell);
3373                                viewCell->Mail();
3374                                ++ hits;
3375                        }
3376
3377                        //-- fetch the next far child from the stack
3378                        if (tStack.empty())
3379                                break;
3380
3381                        entp = extp;
3382                       
3383                        const BspRayTraversalData &s = tStack.top();
3384
3385                        node = s.mNode;
3386                        extp = s.mExitPoint;
3387
3388                        tStack.pop();
3389                }
3390        }
3391
3392        return hits;
3393}
3394
3395
3396
3397
3398int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
3399{
3400        std::deque<BspNode *> path1;
3401        BspNode *p1 = n1;
3402
3403        // create path from node 1 to root
3404        while (p1)
3405        {
3406                if (p1 == n2) // second node on path
3407                        return (int)path1.size();
3408
3409                path1.push_front(p1);
3410                p1 = p1->GetParent();
3411        }
3412
3413        int depth = n2->GetDepth();
3414        int d = depth;
3415
3416        BspNode *p2 = n2;
3417
3418        // compare with same depth
3419        while (1)
3420        {
3421                if ((d < (int)path1.size()) && (p2 == path1[d]))
3422                        return (depth - d) + ((int)path1.size() - 1 - d);
3423
3424                -- d;
3425                p2 = p2->GetParent();
3426        }
3427
3428        return 0; // never come here
3429}
3430
3431
3432BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
3433{
3434// TODO
3435#if HAS_TO_BE_REDONE
3436        if (node->IsLeaf())
3437                return node;
3438
3439        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3440
3441        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3442        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
3443
3444        if (front->IsLeaf() && back->IsLeaf())
3445        {
3446                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3447                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3448
3449                //-- collapse tree
3450                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3451                {
3452                        BspViewCell *vc = frontLeaf->GetViewCell();
3453
3454                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
3455                        leaf->SetTreeValid(frontLeaf->TreeValid());
3456
3457                        // replace a link from node's parent
3458                        if (leaf->GetParent())
3459                                leaf->GetParent()->ReplaceChildLink(node, leaf);
3460                        else
3461                                mRoot = leaf;
3462
3463                        ++ collapsed;
3464                        delete interior;
3465
3466                        return leaf;
3467                }
3468        }
3469#endif
3470        return node;
3471}
3472
3473
3474int VspBspTree::CollapseTree()
3475{
3476        int collapsed = 0;
3477        //TODO
3478#if HAS_TO_BE_REDONE
3479        (void)CollapseTree(mRoot, collapsed);
3480
3481        // revalidate leaves
3482        RepairViewCellsLeafLists();
3483#endif
3484        return collapsed;
3485}
3486
3487
3488void VspBspTree::RepairViewCellsLeafLists()
3489{
3490// TODO
3491#if HAS_TO_BE_REDONE
3492        // list not valid anymore => clear
3493        stack<BspNode *> nodeStack;
3494        nodeStack.push(mRoot);
3495
3496        ViewCell::NewMail();
3497
3498        while (!nodeStack.empty())
3499        {
3500                BspNode *node = nodeStack.top();
3501                nodeStack.pop();
3502
3503                if (node->IsLeaf())
3504                {
3505                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3506
3507                        BspViewCell *viewCell = leaf->GetViewCell();
3508
3509                        if (!viewCell->Mailed())
3510                        {
3511                                viewCell->mLeaves.clear();
3512                                viewCell->Mail();
3513                        }
3514       
3515                        viewCell->mLeaves.push_back(leaf);
3516
3517                }
3518                else
3519                {
3520                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3521
3522                        nodeStack.push(interior->GetFront());
3523                        nodeStack.push(interior->GetBack());
3524                }
3525        }
3526// TODO
3527#endif
3528}
3529
3530
3531int VspBspTree::CastBeam(Beam &beam)
3532{
3533    stack<bspNodePair> nodeStack;
3534        BspNodeGeometry *rgeom = new BspNodeGeometry();
3535        ConstructGeometry(mRoot, *rgeom);
3536
3537        nodeStack.push(bspNodePair(mRoot, rgeom));
3538 
3539        ViewCell::NewMail();
3540
3541        while (!nodeStack.empty())
3542        {
3543                BspNode *node = nodeStack.top().first;
3544                BspNodeGeometry *geom = nodeStack.top().second;
3545                nodeStack.pop();
3546               
3547                AxisAlignedBox3 box;
3548                geom->GetBoundingBox(box);
3549
3550                const int side = beam.ComputeIntersection(box);
3551               
3552                switch (side)
3553                {
3554                case -1:
3555                        CollectViewCells(node, true, beam.mViewCells, true);
3556                        break;
3557                case 0:
3558                       
3559                        if (node->IsLeaf())
3560                        {
3561                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3562                       
3563                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
3564                                {
3565                                        leaf->GetViewCell()->Mail();
3566                                        beam.mViewCells.push_back(leaf->GetViewCell());
3567                                }
3568                        }
3569                        else
3570                        {
3571                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3572                       
3573                                BspNode *first = interior->GetFront();
3574                                BspNode *second = interior->GetBack();
3575           
3576                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3577                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3578
3579                                geom->SplitGeometry(*firstGeom,
3580                                                                        *secondGeom,
3581                                                                        interior->GetPlane(),
3582                                                                        mBox,
3583                                                                        //0.0000001f);
3584                                                                        mEpsilon);
3585
3586                                // decide on the order of the nodes
3587                                if (DotProd(beam.mPlanes[0].mNormal,
3588                                        interior->GetPlane().mNormal) > 0)
3589                                {
3590                                        swap(first, second);
3591                                        swap(firstGeom, secondGeom);
3592                                }
3593
3594                                nodeStack.push(bspNodePair(first, firstGeom));
3595                                nodeStack.push(bspNodePair(second, secondGeom));
3596                        }
3597                       
3598                        break;
3599                default:
3600                        // default: cull
3601                        break;
3602                }
3603               
3604                DEL_PTR(geom);
3605               
3606        }
3607
3608        return (int)beam.mViewCells.size();
3609}
3610
3611
3612void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
3613{
3614        mViewCellsManager = vcm;
3615}
3616
3617
3618int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3619                                                                           vector<MergeCandidate> &candidates)
3620{
3621        BspLeaf::NewMail();
3622       
3623        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3624
3625        int numCandidates = 0;
3626
3627        // find merge candidates and push them into queue
3628        for (it = leaves.begin(); it != it_end; ++ it)
3629        {
3630                BspLeaf *leaf = *it;
3631               
3632                // the same leaves must not be part of two merge candidates
3633                leaf->Mail();
3634               
3635                vector<BspLeaf *> neighbors;
3636               
3637                // appoximate neighbor search has slightl relaxed constraints
3638                if (1)
3639                        FindNeighbors(leaf, neighbors, true);
3640                else
3641                        FindApproximateNeighbors(leaf, neighbors, true);
3642
3643                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3644
3645                // TODO: test if at least one ray goes from one leaf to the other
3646                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
3647                {
3648                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
3649                        {
3650                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
3651
3652                                if (!leaf->GetViewCell()->GetPvs().Empty() ||
3653                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
3654                    leaf->IsSibling(*nit))
3655                                {
3656                                        candidates.push_back(mc);
3657                                }
3658
3659                                ++ numCandidates;
3660                                if ((numCandidates % 1000) == 0)
3661                                {
3662                                        cout << "collected " << numCandidates << " merge candidates" << endl;
3663                                }
3664                        }
3665                }
3666        }
3667
3668        Debug << "merge queue: " << (int)candidates.size() << endl;
3669        Debug << "leaves in queue: " << numCandidates << endl;
3670       
3671
3672        return (int)leaves.size();
3673}
3674
3675
3676int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3677                                                                           vector<MergeCandidate> &candidates)
3678{
3679        ViewCell::NewMail();
3680        long startTime = GetTime();
3681       
3682        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
3683        ViewCellContainer::const_iterator iit;
3684
3685        int numLeaves = 0;
3686       
3687        BspLeaf::NewMail();
3688
3689        for (int i = 0; i < (int)rays.size(); ++ i)
3690        { 
3691                VssRay *ray = rays[i];
3692       
3693                // traverse leaves stored in the rays and compare and
3694                // merge consecutive leaves (i.e., the neighbors in the tree)
3695                if (ray->mViewCells.size() < 2)
3696                        continue;
3697//TODO viewcellhierarchy
3698                iit = ray->mViewCells.begin();
3699                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
3700                BspLeaf *leaf = bspVc->mLeaf;
3701               
3702                // traverse intersections
3703                // consecutive leaves are neighbors => add them to queue
3704                for (; iit != ray->mViewCells.end(); ++ iit)
3705                {
3706                        // next pair
3707                        BspLeaf *prevLeaf = leaf;
3708                        bspVc = dynamic_cast<BspViewCell *>(*iit);
3709            leaf = bspVc->mLeaf;
3710
3711                        // view space not valid or same view cell
3712                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3713                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
3714                                continue;
3715
3716                vector<BspLeaf *> &neighbors = neighborMap[leaf];
3717                       
3718                        bool found = false;
3719
3720                        // both leaves inserted in queue already =>
3721                        // look if double pair already exists
3722                        if (leaf->Mailed() && prevLeaf->Mailed())
3723                        {
3724                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3725                               
3726                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3727                                        if (*it == prevLeaf)
3728                                                found = true; // already in queue
3729                        }
3730               
3731                        if (!found)
3732                        {
3733                                // this pair is not in map yet
3734                                // => insert into the neighbor map and the queue
3735                                neighbors.push_back(prevLeaf);
3736                                neighborMap[prevLeaf].push_back(leaf);
3737
3738                                leaf->Mail();
3739                                prevLeaf->Mail();
3740               
3741                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3742                               
3743                                candidates.push_back(mc);
3744
3745                                if (((int)candidates.size() % 1000) == 0)
3746                                {
3747                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
3748                                }
3749                        }
3750        }
3751        }
3752
3753        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
3754        Debug << "merge queue: " << (int)candidates.size() << endl;
3755        Debug << "leaves in queue: " << numLeaves << endl;
3756
3757
3758        //-- collect the leaves which haven't been found by ray casting
3759        if (0)
3760        {
3761                cout << "finding additional merge candidates using geometry" << endl;
3762                vector<BspLeaf *> leaves;
3763                CollectLeaves(leaves, true);
3764                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
3765                CollectMergeCandidates(leaves, candidates);
3766        }
3767
3768        return numLeaves;
3769}
3770
3771
3772
3773
3774ViewCell *VspBspTree::GetViewCell(const Vector3 &point, const bool active)
3775{
3776        if (mRoot == NULL)
3777                return NULL;
3778
3779        stack<BspNode *> nodeStack;
3780        nodeStack.push(mRoot);
3781 
3782        ViewCellLeaf *viewcell = NULL;
3783 
3784        while (!nodeStack.empty()) 
3785        {
3786                BspNode *node = nodeStack.top();
3787                nodeStack.pop();
3788       
3789                if (node->IsLeaf())
3790                {
3791                        viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3792                        break;
3793                }
3794                else   
3795                {       
3796                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3797       
3798                        // random decision
3799                        if (interior->GetPlane().Side(point) < 0)
3800                                nodeStack.push(interior->GetBack());
3801                        else
3802                                nodeStack.push(interior->GetFront());
3803                }
3804        }
3805 
3806        if (active)
3807                return mViewCellsTree->GetActiveViewCell(viewcell);
3808        else
3809                return viewcell;
3810}
3811
3812
3813bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3814{
3815        BspNode *node = mRoot;
3816
3817        while (1)
3818        {
3819                // early exit
3820                if (node->TreeValid())
3821                        return true;
3822
3823                if (node->IsLeaf())
3824                        return false;
3825                       
3826                BspInterior *in = dynamic_cast<BspInterior *>(node);
3827                                       
3828                if (in->GetPlane().Side(viewPoint) <= 0)
3829                {
3830                        node = in->GetBack();
3831                }
3832                else
3833                {
3834                        node = in->GetFront();
3835                }
3836        }
3837
3838        // should never come here
3839        return false;
3840}
3841
3842
3843void VspBspTree::PropagateUpValidity(BspNode *node)
3844{
3845        const bool isValid = node->TreeValid();
3846
3847        // propagative up invalid flag until only invalid nodes exist over this node
3848        if (!isValid)
3849        {
3850                while (!node->IsRoot() && node->GetParent()->TreeValid())
3851                {
3852                        node = node->GetParent();
3853                        node->SetTreeValid(false);
3854                }
3855        }
3856        else
3857        {
3858                // propagative up valid flag until one of the subtrees is invalid
3859                while (!node->IsRoot() && !node->TreeValid())
3860                {
3861            node = node->GetParent();
3862                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3863                       
3864                        // the parent is valid iff both leaves are valid
3865                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3866                                                           interior->GetFront()->TreeValid());
3867                }
3868        }
3869}
3870
3871#if ZIPPED_VIEWCELLS
3872bool VspBspTree::Export(ogzstream &stream)
3873#else
3874bool VspBspTree::Export(ofstream &stream)
3875#endif
3876{
3877        ExportNode(mRoot, stream);
3878
3879        return true;
3880}
3881
3882#if ZIPPED_VIEWCELLS
3883void VspBspTree::ExportNode(BspNode *node, ogzstream &stream)
3884#else
3885void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3886#endif
3887{
3888        if (node->IsLeaf())
3889        {
3890                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3891                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3892
3893                int id = -1;
3894                if (viewCell != mOutOfBoundsCell)
3895                        id = viewCell->GetId();
3896
3897                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3898        }
3899        else
3900        {
3901                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3902       
3903                Plane3 plane = interior->GetPlane();
3904                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3905                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3906                           << plane.mD << "\">" << endl;
3907
3908                ExportNode(interior->GetBack(), stream);
3909                ExportNode(interior->GetFront(), stream);
3910
3911                stream << "</Interior>" << endl;
3912        }
3913}
3914
3915}
Note: See TracBrowser for help on using the repository browser.