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

Revision 666, 85.1 KB checked in by mattausch, 19 years ago (diff)

debug version for testing subdivision quality

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