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

Revision 1074, 96.8 KB checked in by mattausch, 18 years ago (diff)

wked on view space object space partition

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