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

Revision 735, 90.5 KB checked in by mattausch, 19 years ago (diff)

added histogram functionality

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