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

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