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

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