source: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp @ 610

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