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

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