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

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