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

Revision 652, 77.4 KB checked in by mattausch, 19 years ago (diff)

started to implement split plane queue

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