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

Revision 1012, 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
2391        Vector3 entp = ray.Extrap(mint);
2392        Vector3 extp = ray.Extrap(maxt);
2393
2394        BspNode *node = mRoot;
2395        BspNode *farChild = NULL;
2396
2397        while (1)
2398        {
2399                if (!node->IsLeaf())
2400                {
2401                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2402
2403                        Plane3 splitPlane = in->GetPlane();
2404                        const int entSide = splitPlane.Side(entp);
2405                        const int extSide = splitPlane.Side(extp);
2406
2407                        if (entSide < 0)
2408                        {
2409                                node = in->GetBack();
2410
2411                                if(extSide <= 0) // plane does not split ray => no far child
2412                                        continue;
2413
2414                                farChild = in->GetFront(); // plane splits ray
2415
2416                        } else if (entSide > 0)
2417                        {
2418                                node = in->GetFront();
2419
2420                                if (extSide >= 0) // plane does not split ray => no far child
2421                                        continue;
2422
2423                                farChild = in->GetBack(); // plane splits ray
2424                        }
2425                        else // ray and plane are coincident
2426                        {
2427                                // matt: WHAT TO DO IN THIS CASE ?
2428                                //break;
2429                                node = in->GetFront();
2430                                continue;
2431                        }
2432
2433                        // push data for far child
2434                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
2435
2436                        // find intersection of ray segment with plane
2437                        float t;
2438                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
2439                        maxt *= t;
2440
2441                } else // reached leaf => intersection with view cell
2442                {
2443                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2444
2445                        if (!leaf->GetViewCell()->Mailed())
2446                        {
2447                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
2448                                leaf->GetViewCell()->Mail();
2449                                ++ hits;
2450                        }
2451
2452                        //-- fetch the next far child from the stack
2453                        if (tQueue.empty())
2454                                break;
2455
2456                        entp = extp;
2457                        mint = maxt; // NOTE: need this?
2458
2459                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
2460                                break;
2461
2462                        BspRayTraversalData &s = tQueue.top();
2463
2464                        node = s.mNode;
2465                        extp = s.mExitPoint;
2466                        maxt = s.mMaxT;
2467
2468                        tQueue.pop();
2469                }
2470        }
2471
2472        return hits;
2473}
2474
2475
2476void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
2477{
2478        ViewCell::NewMail();
2479       
2480        CollectViewCells(mRoot, onlyValid, viewCells, true);
2481}
2482
2483
2484void VspBspTree::CollapseViewCells()
2485{
2486// TODO
2487#if HAS_TO_BE_REDONE
2488        stack<BspNode *> nodeStack;
2489
2490        if (!mRoot)
2491                return;
2492
2493        nodeStack.push(mRoot);
2494       
2495        while (!nodeStack.empty())
2496        {
2497                BspNode *node = nodeStack.top();
2498                nodeStack.pop();
2499               
2500                if (node->IsLeaf())
2501        {
2502                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2503
2504                        if (!viewCell->GetValid())
2505                        {
2506                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2507       
2508                                ViewCellContainer leaves;
2509                                mViewCellsTree->CollectLeaves(viewCell, leaves);
2510
2511                                ViewCellContainer::const_iterator it, it_end = leaves.end();
2512
2513                                for (it = leaves.begin(); it != it_end; ++ it)
2514                                {
2515                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2516                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
2517                                        ++ mBspStats.invalidLeaves;
2518                                }
2519
2520                                // add to unbounded view cell
2521                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
2522                                DEL_PTR(viewCell);
2523                        }
2524                }
2525                else
2526                {
2527                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2528               
2529                        nodeStack.push(interior->GetFront());
2530                        nodeStack.push(interior->GetBack());
2531                }
2532        }
2533
2534        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2535#endif
2536}
2537
2538
2539void VspBspTree::CollectRays(VssRayContainer &rays)
2540{
2541        vector<BspLeaf *> leaves;
2542
2543        vector<BspLeaf *>::const_iterator lit, lit_end = leaves.end();
2544
2545        for (lit = leaves.begin(); lit != lit_end; ++ lit)
2546        {
2547                BspLeaf *leaf = *lit;
2548                VssRayContainer::const_iterator rit, rit_end = leaf->mVssRays.end();
2549
2550                for (rit = leaf->mVssRays.begin(); rit != rit_end; ++ rit)
2551                        rays.push_back(*rit);
2552        }
2553}
2554
2555
2556void VspBspTree::ValidateTree()
2557{
2558        stack<BspNode *> nodeStack;
2559
2560        if (!mRoot)
2561                return;
2562
2563        nodeStack.push(mRoot);
2564       
2565        mBspStats.invalidLeaves = 0;
2566        while (!nodeStack.empty())
2567        {
2568                BspNode *node = nodeStack.top();
2569                nodeStack.pop();
2570               
2571                if (node->IsLeaf())
2572                {
2573                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2574
2575                        if (!leaf->GetViewCell()->GetValid())
2576                                ++ mBspStats.invalidLeaves;
2577
2578                        // validity flags don't match => repair
2579                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
2580                        {
2581                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
2582                                PropagateUpValidity(leaf);
2583                        }
2584                }
2585                else
2586                {
2587                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2588               
2589                        nodeStack.push(interior->GetFront());
2590                        nodeStack.push(interior->GetBack());
2591                }
2592        }
2593
2594        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
2595}
2596
2597
2598
2599void VspBspTree::CollectViewCells(BspNode *root,
2600                                                                  bool onlyValid,
2601                                                                  ViewCellContainer &viewCells,
2602                                                                  bool onlyUnmailed) const
2603{
2604        stack<BspNode *> nodeStack;
2605
2606        if (!root)
2607                return;
2608
2609        nodeStack.push(root);
2610       
2611        while (!nodeStack.empty())
2612        {
2613                BspNode *node = nodeStack.top();
2614                nodeStack.pop();
2615               
2616                if (node->IsLeaf())
2617                {
2618                        if (!onlyValid || node->TreeValid())
2619                        {
2620                                ViewCellLeaf *leafVc = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2621
2622                                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leafVc);
2623                                               
2624                                if (!onlyUnmailed || !viewCell->Mailed())
2625                                {
2626                                        viewCell->Mail();
2627                                        viewCells.push_back(viewCell);
2628                                }
2629                        }
2630                }
2631                else
2632                {
2633                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2634               
2635                        nodeStack.push(interior->GetFront());
2636                        nodeStack.push(interior->GetBack());
2637                }
2638        }
2639
2640}
2641
2642
2643void VspBspTree::PreprocessPolygons(PolygonContainer &polys)
2644{
2645        // preprocess: throw out polygons coincident to the view space box (not needed)
2646        PolygonContainer boxPolys;
2647        /*mBox.ExtractPolys(boxPolys);
2648        vector<Plane3> boxPlanes;
2649
2650        PolygonContainer::iterator pit, pit_end = boxPolys.end();
2651
2652        // extract planes of box
2653        // TODO: can be done more elegantly than first extracting polygons
2654        // and take their planes
2655        for (pit = boxPolys.begin(); pit != pit_end; ++ pit)
2656        {
2657                boxPlanes.push_back((*pit)->GetSupportingPlane());
2658        }
2659
2660        pit_end = polys.end();
2661
2662        for (pit = polys.begin(); pit != pit_end; ++ pit)
2663        {
2664                vector<Plane3>::const_iterator bit, bit_end = boxPlanes.end();
2665               
2666                for (bit = boxPlanes.begin(); (bit != bit_end) && (*pit); ++ bit)
2667                {
2668                        const int cf = (*pit)->ClassifyPlane(*bit, mEpsilon);
2669
2670                        if (cf == Polygon3::COINCIDENT)
2671                        {
2672                                DEL_PTR(*pit);
2673                                //Debug << "coincident!!" << endl;
2674                        }
2675                }
2676        }
2677
2678        // remove deleted entries after swapping them to end of vector
2679        for (int i = 0; i < (int)polys.size(); ++ i)
2680        {
2681                while (!polys[i] && (i < (int)polys.size()))
2682                {
2683                        swap(polys[i], polys.back());
2684                        polys.pop_back();
2685                }
2686        }*/
2687}
2688
2689
2690float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
2691{
2692        float len = 0;
2693
2694        RayInfoContainer::const_iterator it, it_end = rays.end();
2695
2696        for (it = rays.begin(); it != it_end; ++ it)
2697                len += (*it).SegmentLength();
2698
2699        return len;
2700}
2701
2702
2703int VspBspTree::SplitRays(const Plane3 &plane,
2704                                                  RayInfoContainer &rays,
2705                                                  RayInfoContainer &frontRays,
2706                                                  RayInfoContainer &backRays) const
2707{
2708        int splits = 0;
2709
2710        RayInfoContainer::const_iterator it, it_end = rays.end();
2711
2712        for (it = rays.begin(); it != it_end; ++ it)
2713        {
2714                RayInfo bRay = *it;
2715               
2716                VssRay *ray = bRay.mRay;
2717                float t;
2718
2719                // get classification and receive new t
2720                const int cf = bRay.ComputeRayIntersection(plane, t);
2721
2722                switch (cf)
2723                {
2724                case -1:
2725                        backRays.push_back(bRay);
2726                        break;
2727                case 1:
2728                        frontRays.push_back(bRay);
2729                        break;
2730                case 0:
2731                        {
2732                                //-- split ray
2733                                //   test if start point behind or in front of plane
2734                                const int side = plane.Side(bRay.ExtrapOrigin());
2735
2736                                ++ splits;
2737
2738                                if (side <= 0)
2739                                {
2740                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2741                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2742                                }
2743                                else
2744                                {
2745                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
2746                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
2747                                }
2748                        }
2749                        break;
2750                default:
2751                        Debug << "Should not come here" << endl;
2752                        break;
2753                }
2754        }
2755
2756        return splits;
2757}
2758
2759
2760void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
2761{
2762        BspNode *lastNode;
2763
2764        do
2765        {
2766                lastNode = n;
2767
2768                // want to get planes defining geometry of this node => don't take
2769                // split plane of node itself
2770                n = n->GetParent();
2771
2772                if (n)
2773                {
2774                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
2775                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2776
2777            if (interior->GetBack() != lastNode)
2778                                halfSpace.ReverseOrientation();
2779
2780                        halfSpaces.push_back(halfSpace);
2781                }
2782        }
2783        while (n);
2784}
2785
2786
2787void VspBspTree::ConstructGeometry(BspNode *n,
2788                                                                   BspNodeGeometry &geom) const
2789{
2790        vector<Plane3> halfSpaces;
2791        ExtractHalfSpaces(n, halfSpaces);
2792
2793        PolygonContainer candidatePolys;
2794        vector<Plane3> candidatePlanes;
2795
2796        vector<Plane3>::const_iterator pit, pit_end = halfSpaces.end();
2797
2798        // bounded planes are added to the polygons
2799        for (pit = halfSpaces.begin(); pit != pit_end; ++ pit)
2800        {
2801                Polygon3 *p = GetBoundingBox().CrossSection(*pit);
2802
2803                if (p->Valid(mEpsilon))
2804                {
2805                        candidatePolys.push_back(p);
2806                        candidatePlanes.push_back(*pit);
2807                }
2808        }
2809
2810        // add faces of bounding box (also could be faces of the cell)
2811        for (int i = 0; i < 6; ++ i)
2812        {
2813                VertexContainer vertices;
2814
2815                for (int j = 0; j < 4; ++ j)
2816                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2817
2818                Polygon3 *poly = new Polygon3(vertices);
2819
2820                candidatePolys.push_back(poly);
2821                candidatePlanes.push_back(poly->GetSupportingPlane());
2822        }
2823
2824        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2825        {
2826                // polygon is split by all other planes
2827                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2828                {
2829                        if (i == j) // polygon and plane are coincident
2830                                continue;
2831
2832                        VertexContainer splitPts;
2833                        Polygon3 *frontPoly, *backPoly;
2834
2835                        const int cf =
2836                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2837                                                                                                 mEpsilon);
2838
2839                        switch (cf)
2840                        {
2841                                case Polygon3::SPLIT:
2842                                        frontPoly = new Polygon3();
2843                                        backPoly = new Polygon3();
2844
2845                                        candidatePolys[i]->Split(halfSpaces[j],
2846                                                                                         *frontPoly,
2847                                                                                         *backPoly,
2848                                                                                         mEpsilon);
2849
2850                                        DEL_PTR(candidatePolys[i]);
2851
2852                                        if (backPoly->Valid(mEpsilon))
2853                                                candidatePolys[i] = backPoly;
2854                                        else
2855                                                DEL_PTR(backPoly);
2856
2857                                        // outside, don't need this
2858                                        DEL_PTR(frontPoly);
2859                                        break;
2860                                // polygon outside of halfspace
2861                                case Polygon3::FRONT_SIDE:
2862                                        DEL_PTR(candidatePolys[i]);
2863                                        break;
2864                                // just take polygon as it is
2865                                case Polygon3::BACK_SIDE:
2866                                case Polygon3::COINCIDENT:
2867                                default:
2868                                        break;
2869                        }
2870                }
2871
2872                if (candidatePolys[i])
2873                {
2874                        geom.Add(candidatePolys[i], candidatePlanes[i]);
2875                        //      geom.mPolys.push_back(candidates[i]);
2876                }
2877        }
2878}
2879
2880
2881void VspBspTree::ConstructGeometry(ViewCell *vc,
2882                                                                   BspNodeGeometry &vcGeom) const
2883{
2884        ViewCellContainer leaves;
2885       
2886        mViewCellsTree->CollectLeaves(vc, leaves);
2887
2888        ViewCellContainer::const_iterator it, it_end = leaves.end();
2889
2890        for (it = leaves.begin(); it != it_end; ++ it)
2891        {
2892                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2893               
2894                ConstructGeometry(l, vcGeom);
2895        }
2896}
2897
2898
2899int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2900                                                          const bool onlyUnmailed) const
2901{
2902        stack<bspNodePair> nodeStack;
2903       
2904        BspNodeGeometry nodeGeom;
2905        ConstructGeometry(n, nodeGeom);
2906//      const float eps = 0.5f;
2907        const float eps = 0.01f;
2908        // split planes from the root to this node
2909        // needed to verify that we found neighbor leaf
2910        // TODO: really needed?
2911        vector<Plane3> halfSpaces;
2912        ExtractHalfSpaces(n, halfSpaces);
2913
2914
2915        BspNodeGeometry *rgeom = new BspNodeGeometry();
2916        ConstructGeometry(mRoot, *rgeom);
2917
2918        nodeStack.push(bspNodePair(mRoot, rgeom));
2919
2920        while (!nodeStack.empty())
2921        {
2922                BspNode *node = nodeStack.top().first;
2923                BspNodeGeometry *geom = nodeStack.top().second;
2924       
2925                nodeStack.pop();
2926
2927                if (node->IsLeaf())
2928                {
2929                        // test if this leaf is in valid view space
2930                        if (node->TreeValid() &&
2931                                (node != n) &&
2932                                (!onlyUnmailed || !node->Mailed()))
2933                        {
2934                                bool isAdjacent = true;
2935
2936                                if (1)
2937                                {
2938                                        // test all planes of current node if still adjacent
2939                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2940                                        {
2941                                                const int cf =
2942                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2943                                                                                                        halfSpaces[i],
2944                                                                                                        eps);
2945
2946                                                if (cf == Polygon3::FRONT_SIDE)
2947                                                {
2948                                                        isAdjacent = false;
2949                                                }
2950                                        }
2951                                }
2952                                else
2953                                {
2954                                        // TODO: why is this wrong??
2955                                        // test all planes of current node if still adjacent
2956                                        for (int i = 0; (i < nodeGeom.Size()) && isAdjacent; ++ i)
2957                                        {
2958                                                Polygon3 *poly = nodeGeom.GetPolys()[i];
2959
2960                                                const int cf =
2961                                                        Polygon3::ClassifyPlane(geom->GetPolys(),
2962                                                                                                        poly->GetSupportingPlane(),
2963                                                                                                        eps);
2964
2965                                                if (cf == Polygon3::FRONT_SIDE)
2966                                                {
2967                                                        isAdjacent = false;
2968                                                }
2969                                        }
2970                                }
2971                                // neighbor was found
2972                                if (isAdjacent)
2973                                {       
2974                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2975                                }
2976                        }
2977                }
2978                else
2979                {
2980                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2981
2982                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
2983                                                                                                   interior->GetPlane(),
2984                                                                                                   eps);
2985                       
2986                        BspNode *front = interior->GetFront();
2987                        BspNode *back = interior->GetBack();
2988           
2989                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2990                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2991
2992                        geom->SplitGeometry(*fGeom,
2993                                                                *bGeom,
2994                                                                interior->GetPlane(),
2995                                                                mBox,
2996                                                                //0.0000001f);
2997                                                                eps);
2998               
2999                        if (cf == Polygon3::BACK_SIDE)
3000                        {
3001                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3002                                DEL_PTR(fGeom);
3003                        }
3004                        else
3005                        {
3006                                if (cf == Polygon3::FRONT_SIDE)
3007                                {
3008                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3009                                        DEL_PTR(bGeom);
3010                                }
3011                                else
3012                                {       // random decision
3013                                        nodeStack.push(bspNodePair(front, fGeom));
3014                                        nodeStack.push(bspNodePair(back, bGeom));
3015                                }
3016                        }
3017                }
3018       
3019                DEL_PTR(geom);
3020        }
3021
3022        return (int)neighbors.size();
3023}
3024
3025
3026
3027int VspBspTree::FindApproximateNeighbors(BspNode *n,
3028                                                                                 vector<BspLeaf *> &neighbors,
3029                                                                                 const bool onlyUnmailed) const
3030{
3031        stack<bspNodePair> nodeStack;
3032       
3033        BspNodeGeometry nodeGeom;
3034        ConstructGeometry(n, nodeGeom);
3035       
3036        float eps = 0.01f;
3037        // split planes from the root to this node
3038        // needed to verify that we found neighbor leaf
3039        // TODO: really needed?
3040        vector<Plane3> halfSpaces;
3041        ExtractHalfSpaces(n, halfSpaces);
3042
3043
3044        BspNodeGeometry *rgeom = new BspNodeGeometry();
3045        ConstructGeometry(mRoot, *rgeom);
3046
3047        nodeStack.push(bspNodePair(mRoot, rgeom));
3048
3049        while (!nodeStack.empty())
3050        {
3051                BspNode *node = nodeStack.top().first;
3052                BspNodeGeometry *geom = nodeStack.top().second;
3053       
3054                nodeStack.pop();
3055
3056                if (node->IsLeaf())
3057                {
3058                        // test if this leaf is in valid view space
3059                        if (node->TreeValid() &&
3060                                (node != n) &&
3061                                (!onlyUnmailed || !node->Mailed()))
3062                        {
3063                                bool isAdjacent = true;
3064
3065                                // neighbor was found
3066                                if (isAdjacent)
3067                                {       
3068                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
3069                                }
3070                        }
3071                }
3072                else
3073                {
3074                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3075
3076                        const int cf = Polygon3::ClassifyPlane(nodeGeom.GetPolys(),
3077                                                                                                   interior->GetPlane(),
3078                                                                                                   eps);
3079                       
3080                        BspNode *front = interior->GetFront();
3081                        BspNode *back = interior->GetBack();
3082           
3083                        BspNodeGeometry *fGeom = new BspNodeGeometry();
3084                        BspNodeGeometry *bGeom = new BspNodeGeometry();
3085
3086                        geom->SplitGeometry(*fGeom,
3087                                                                *bGeom,
3088                                                                interior->GetPlane(),
3089                                                                mBox,
3090                                                                //0.0000001f);
3091                                                                eps);
3092               
3093                        if (cf == Polygon3::BACK_SIDE)
3094                        {
3095                                nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
3096                                DEL_PTR(fGeom);
3097                                }
3098                        else
3099                        {
3100                                if (cf == Polygon3::FRONT_SIDE)
3101                                {
3102                                        nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
3103                                        DEL_PTR(bGeom);
3104                                }
3105                                else
3106                                {       // random decision
3107                                        nodeStack.push(bspNodePair(front, fGeom));
3108                                        nodeStack.push(bspNodePair(back, bGeom));
3109                                }
3110                        }
3111                }
3112       
3113                DEL_PTR(geom);
3114        }
3115
3116        return (int)neighbors.size();
3117}
3118
3119
3120
3121BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
3122{
3123    stack<BspNode *> nodeStack;
3124        nodeStack.push(mRoot);
3125
3126        int mask = rand();
3127
3128        while (!nodeStack.empty())
3129        {
3130                BspNode *node = nodeStack.top();
3131                nodeStack.pop();
3132
3133                if (node->IsLeaf())
3134                {
3135                        return dynamic_cast<BspLeaf *>(node);
3136                }
3137                else
3138                {
3139                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3140                        BspNode *next;
3141                        BspNodeGeometry geom;
3142
3143                        // todo: not very efficient: constructs full cell everytime
3144                        ConstructGeometry(interior, geom);
3145
3146                        const int cf =
3147                                Polygon3::ClassifyPlane(geom.GetPolys(), halfspace, mEpsilon);
3148
3149                        if (cf == Polygon3::BACK_SIDE)
3150                                next = interior->GetFront();
3151                        else
3152                                if (cf == Polygon3::FRONT_SIDE)
3153                                        next = interior->GetFront();
3154                        else
3155                        {
3156                                // random decision
3157                                if (mask & 1)
3158                                        next = interior->GetBack();
3159                                else
3160                                        next = interior->GetFront();
3161                                mask = mask >> 1;
3162                        }
3163
3164                        nodeStack.push(next);
3165                }
3166        }
3167
3168        return NULL;
3169}
3170
3171
3172BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
3173{
3174        stack<BspNode *> nodeStack;
3175
3176        nodeStack.push(mRoot);
3177
3178        int mask = rand();
3179
3180        while (!nodeStack.empty())
3181        {
3182                BspNode *node = nodeStack.top();
3183                nodeStack.pop();
3184
3185                if (node->IsLeaf())
3186                {
3187                        if ( (!onlyUnmailed || !node->Mailed()) )
3188                                return dynamic_cast<BspLeaf *>(node);
3189                }
3190                else
3191                {
3192                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3193
3194                        // random decision
3195                        if (mask & 1)
3196                                nodeStack.push(interior->GetBack());
3197                        else
3198                                nodeStack.push(interior->GetFront());
3199
3200                        mask = mask >> 1;
3201                }
3202        }
3203
3204        return NULL;
3205}
3206
3207
3208int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
3209{
3210        int pvsSize = 0;
3211
3212        RayInfoContainer::const_iterator rit, rit_end = rays.end();
3213
3214        Intersectable::NewMail();
3215
3216        for (rit = rays.begin(); rit != rays.end(); ++ rit)
3217        {
3218                VssRay *ray = (*rit).mRay;
3219
3220                if (ray->mOriginObject)
3221                {
3222                        if (!ray->mOriginObject->Mailed())
3223                        {
3224                                ray->mOriginObject->Mail();
3225                                ++ pvsSize;
3226                        }
3227                }
3228                if (ray->mTerminationObject)
3229                {
3230                        if (!ray->mTerminationObject->Mailed())
3231                        {
3232                                ray->mTerminationObject->Mail();
3233                                ++ pvsSize;
3234                        }
3235                }
3236        }
3237
3238        return pvsSize;
3239}
3240
3241
3242float VspBspTree::GetEpsilon() const
3243{
3244        return mEpsilon;
3245}
3246
3247
3248int VspBspTree::SplitPolygons(const Plane3 &plane,
3249                                                          PolygonContainer &polys,
3250                                                          PolygonContainer &frontPolys,
3251                                                          PolygonContainer &backPolys,
3252                                                          PolygonContainer &coincident) const
3253{
3254        int splits = 0;
3255
3256        PolygonContainer::const_iterator it, it_end = polys.end();
3257
3258        for (it = polys.begin(); it != polys.end(); ++ it)     
3259        {
3260                Polygon3 *poly = *it;
3261
3262                // classify polygon
3263                const int cf = poly->ClassifyPlane(plane, mEpsilon);
3264
3265                switch (cf)
3266                {
3267                        case Polygon3::COINCIDENT:
3268                                coincident.push_back(poly);
3269                                break;
3270                        case Polygon3::FRONT_SIDE:
3271                                frontPolys.push_back(poly);
3272                                break;
3273                        case Polygon3::BACK_SIDE:
3274                                backPolys.push_back(poly);
3275                                break;
3276                        case Polygon3::SPLIT:
3277                                backPolys.push_back(poly);
3278                                frontPolys.push_back(poly);
3279                                ++ splits;
3280                                break;
3281                        default:
3282                Debug << "SHOULD NEVER COME HERE\n";
3283                                break;
3284                }
3285        }
3286
3287        return splits;
3288}
3289
3290
3291int VspBspTree::CastLineSegment(const Vector3 &origin,
3292                                                                const Vector3 &termination,
3293                                                                ViewCellContainer &viewcells)
3294{
3295        int hits = 0;
3296        stack<BspRayTraversalData> tStack;
3297
3298        float mint = 0.0f, maxt = 1.0f;
3299
3300        Intersectable::NewMail();
3301        ViewCell::NewMail();
3302
3303        Vector3 entp = origin;
3304        Vector3 extp = termination;
3305
3306        BspNode *node = mRoot;
3307        BspNode *farChild = NULL;
3308
3309        float t;
3310        const float thresh = 1e-6f; // matt: change this to adjustable value
3311       
3312        while (1)
3313        {
3314                if (!node->IsLeaf())
3315                {
3316                        BspInterior *in = dynamic_cast<BspInterior *>(node);
3317
3318                        Plane3 splitPlane = in->GetPlane();
3319                       
3320                        const int entSide = splitPlane.Side(entp, thresh);
3321                        const int extSide = splitPlane.Side(extp, thresh);
3322
3323                        if (entSide < 0)
3324                        {
3325                                node = in->GetBack();
3326                               
3327                                // plane does not split ray => no far child
3328                                if (extSide <= 0)
3329                                        continue;
3330 
3331                                farChild = in->GetFront(); // plane splits ray
3332                        }
3333                        else if (entSide > 0)
3334                        {
3335                                node = in->GetFront();
3336
3337                                if (extSide >= 0) // plane does not split ray => no far child
3338                                        continue;
3339
3340                                farChild = in->GetBack(); // plane splits ray
3341                        }
3342                        else // one of the ray end points is on the plane
3343                        {       // NOTE: what to do if ray is coincident with plane?
3344                                if (extSide < 0)
3345                                        node = in->GetBack();
3346                                else //if (extSide > 0)
3347                                        node = in->GetFront();
3348                                //else break; // coincident => count no intersections
3349
3350                                continue; // no far child
3351                        }
3352
3353                        // push data for far child
3354                        tStack.push(BspRayTraversalData(farChild, extp));
3355
3356                        // find intersection of ray segment with plane
3357                        extp = splitPlane.FindIntersection(origin, extp, &t);
3358                }
3359                else
3360                {
3361                        // reached leaf => intersection with view cell
3362                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3363                        ViewCell *viewCell;
3364                       
3365                        if (0)
3366                                viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3367                        else
3368                                viewCell = leaf->GetViewCell();
3369
3370                        if (!viewCell->Mailed())
3371                        {
3372                                viewcells.push_back(viewCell);
3373                                viewCell->Mail();
3374                                ++ hits;
3375                        }
3376
3377                        //-- fetch the next far child from the stack
3378                        if (tStack.empty())
3379                                break;
3380
3381                        entp = extp;
3382                       
3383                        const BspRayTraversalData &s = tStack.top();
3384
3385                        node = s.mNode;
3386                        extp = s.mExitPoint;
3387
3388                        tStack.pop();
3389                }
3390        }
3391
3392        return hits;
3393}
3394
3395
3396
3397
3398int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
3399{
3400        std::deque<BspNode *> path1;
3401        BspNode *p1 = n1;
3402
3403        // create path from node 1 to root
3404        while (p1)
3405        {
3406                if (p1 == n2) // second node on path
3407                        return (int)path1.size();
3408
3409                path1.push_front(p1);
3410                p1 = p1->GetParent();
3411        }
3412
3413        int depth = n2->GetDepth();
3414        int d = depth;
3415
3416        BspNode *p2 = n2;
3417
3418        // compare with same depth
3419        while (1)
3420        {
3421                if ((d < (int)path1.size()) && (p2 == path1[d]))
3422                        return (depth - d) + ((int)path1.size() - 1 - d);
3423
3424                -- d;
3425                p2 = p2->GetParent();
3426        }
3427
3428        return 0; // never come here
3429}
3430
3431
3432BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
3433{
3434// TODO
3435#if HAS_TO_BE_REDONE
3436        if (node->IsLeaf())
3437                return node;
3438
3439        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3440
3441        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
3442        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
3443
3444        if (front->IsLeaf() && back->IsLeaf())
3445        {
3446                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
3447                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
3448
3449                //-- collapse tree
3450                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
3451                {
3452                        BspViewCell *vc = frontLeaf->GetViewCell();
3453
3454                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
3455                        leaf->SetTreeValid(frontLeaf->TreeValid());
3456
3457                        // replace a link from node's parent
3458                        if (leaf->GetParent())
3459                                leaf->GetParent()->ReplaceChildLink(node, leaf);
3460                        else
3461                                mRoot = leaf;
3462
3463                        ++ collapsed;
3464                        delete interior;
3465
3466                        return leaf;
3467                }
3468        }
3469#endif
3470        return node;
3471}
3472
3473
3474int VspBspTree::CollapseTree()
3475{
3476        int collapsed = 0;
3477        //TODO
3478#if HAS_TO_BE_REDONE
3479        (void)CollapseTree(mRoot, collapsed);
3480
3481        // revalidate leaves
3482        RepairViewCellsLeafLists();
3483#endif
3484        return collapsed;
3485}
3486
3487
3488void VspBspTree::RepairViewCellsLeafLists()
3489{
3490// TODO
3491#if HAS_TO_BE_REDONE
3492        // list not valid anymore => clear
3493        stack<BspNode *> nodeStack;
3494        nodeStack.push(mRoot);
3495
3496        ViewCell::NewMail();
3497
3498        while (!nodeStack.empty())
3499        {
3500                BspNode *node = nodeStack.top();
3501                nodeStack.pop();
3502
3503                if (node->IsLeaf())
3504                {
3505                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3506
3507                        BspViewCell *viewCell = leaf->GetViewCell();
3508
3509                        if (!viewCell->Mailed())
3510                        {
3511                                viewCell->mLeaves.clear();
3512                                viewCell->Mail();
3513                        }
3514       
3515                        viewCell->mLeaves.push_back(leaf);
3516
3517                }
3518                else
3519                {
3520                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3521
3522                        nodeStack.push(interior->GetFront());
3523                        nodeStack.push(interior->GetBack());
3524                }
3525        }
3526// TODO
3527#endif
3528}
3529
3530
3531int VspBspTree::CastBeam(Beam &beam)
3532{
3533    stack<bspNodePair> nodeStack;
3534        BspNodeGeometry *rgeom = new BspNodeGeometry();
3535        ConstructGeometry(mRoot, *rgeom);
3536
3537        nodeStack.push(bspNodePair(mRoot, rgeom));
3538 
3539        ViewCell::NewMail();
3540
3541        while (!nodeStack.empty())
3542        {
3543                BspNode *node = nodeStack.top().first;
3544                BspNodeGeometry *geom = nodeStack.top().second;
3545                nodeStack.pop();
3546               
3547                AxisAlignedBox3 box;
3548                geom->GetBoundingBox(box);
3549
3550                const int side = beam.ComputeIntersection(box);
3551               
3552                switch (side)
3553                {
3554                case -1:
3555                        CollectViewCells(node, true, beam.mViewCells, true);
3556                        break;
3557                case 0:
3558                       
3559                        if (node->IsLeaf())
3560                        {
3561                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3562                       
3563                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
3564                                {
3565                                        leaf->GetViewCell()->Mail();
3566                                        beam.mViewCells.push_back(leaf->GetViewCell());
3567                                }
3568                        }
3569                        else
3570                        {
3571                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3572                       
3573                                BspNode *first = interior->GetFront();
3574                                BspNode *second = interior->GetBack();
3575           
3576                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
3577                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
3578
3579                                geom->SplitGeometry(*firstGeom,
3580                                                                        *secondGeom,
3581                                                                        interior->GetPlane(),
3582                                                                        mBox,
3583                                                                        //0.0000001f);
3584                                                                        mEpsilon);
3585
3586                                // decide on the order of the nodes
3587                                if (DotProd(beam.mPlanes[0].mNormal,
3588                                        interior->GetPlane().mNormal) > 0)
3589                                {
3590                                        swap(first, second);
3591                                        swap(firstGeom, secondGeom);
3592                                }
3593
3594                                nodeStack.push(bspNodePair(first, firstGeom));
3595                                nodeStack.push(bspNodePair(second, secondGeom));
3596                        }
3597                       
3598                        break;
3599                default:
3600                        // default: cull
3601                        break;
3602                }
3603               
3604                DEL_PTR(geom);
3605               
3606        }
3607
3608        return (int)beam.mViewCells.size();
3609}
3610
3611
3612void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
3613{
3614        mViewCellsManager = vcm;
3615}
3616
3617
3618int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
3619                                                                           vector<MergeCandidate> &candidates)
3620{
3621        BspLeaf::NewMail();
3622       
3623        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
3624
3625        int numCandidates = 0;
3626
3627        // find merge candidates and push them into queue
3628        for (it = leaves.begin(); it != it_end; ++ it)
3629        {
3630                BspLeaf *leaf = *it;
3631               
3632                // the same leaves must not be part of two merge candidates
3633                leaf->Mail();
3634               
3635                vector<BspLeaf *> neighbors;
3636               
3637                // appoximate neighbor search has slightl relaxed constraints
3638                if (1)
3639                        FindNeighbors(leaf, neighbors, true);
3640                else
3641                        FindApproximateNeighbors(leaf, neighbors, true);
3642
3643                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
3644
3645                // TODO: test if at least one ray goes from one leaf to the other
3646                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
3647                {
3648                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
3649                        {
3650                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
3651
3652                                if (!leaf->GetViewCell()->GetPvs().Empty() ||
3653                                        !(*nit)->GetViewCell()->GetPvs().Empty() ||
3654                    leaf->IsSibling(*nit))
3655                                {
3656                                        candidates.push_back(mc);
3657                                }
3658
3659                                ++ numCandidates;
3660                                if ((numCandidates % 1000) == 0)
3661                                {
3662                                        cout << "collected " << numCandidates << " merge candidates" << endl;
3663                                }
3664                        }
3665                }
3666        }
3667
3668        Debug << "merge queue: " << (int)candidates.size() << endl;
3669        Debug << "leaves in queue: " << numCandidates << endl;
3670       
3671
3672        return (int)leaves.size();
3673}
3674
3675
3676int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
3677                                                                           vector<MergeCandidate> &candidates)
3678{
3679        ViewCell::NewMail();
3680        long startTime = GetTime();
3681       
3682        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
3683        ViewCellContainer::const_iterator iit;
3684
3685        int numLeaves = 0;
3686       
3687        BspLeaf::NewMail();
3688
3689        for (int i = 0; i < (int)rays.size(); ++ i)
3690        { 
3691                VssRay *ray = rays[i];
3692       
3693                // traverse leaves stored in the rays and compare and
3694                // merge consecutive leaves (i.e., the neighbors in the tree)
3695                if (ray->mViewCells.size() < 2)
3696                        continue;
3697//TODO viewcellhierarchy
3698                iit = ray->mViewCells.begin();
3699                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
3700                BspLeaf *leaf = bspVc->mLeaf;
3701               
3702                // traverse intersections
3703                // consecutive leaves are neighbors => add them to queue
3704                for (; iit != ray->mViewCells.end(); ++ iit)
3705                {
3706                        // next pair
3707                        BspLeaf *prevLeaf = leaf;
3708                        bspVc = dynamic_cast<BspViewCell *>(*iit);
3709            leaf = bspVc->mLeaf;
3710
3711                        // view space not valid or same view cell
3712                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
3713                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
3714                                continue;
3715
3716                vector<BspLeaf *> &neighbors = neighborMap[leaf];
3717                       
3718                        bool found = false;
3719
3720                        // both leaves inserted in queue already =>
3721                        // look if double pair already exists
3722                        if (leaf->Mailed() && prevLeaf->Mailed())
3723                        {
3724                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
3725                               
3726                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
3727                                        if (*it == prevLeaf)
3728                                                found = true; // already in queue
3729                        }
3730               
3731                        if (!found)
3732                        {
3733                                // this pair is not in map yet
3734                                // => insert into the neighbor map and the queue
3735                                neighbors.push_back(prevLeaf);
3736                                neighborMap[prevLeaf].push_back(leaf);
3737
3738                                leaf->Mail();
3739                                prevLeaf->Mail();
3740               
3741                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
3742                               
3743                                candidates.push_back(mc);
3744
3745                                if (((int)candidates.size() % 1000) == 0)
3746                                {
3747                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
3748                                }
3749                        }
3750        }
3751        }
3752
3753        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
3754        Debug << "merge queue: " << (int)candidates.size() << endl;
3755        Debug << "leaves in queue: " << numLeaves << endl;
3756
3757
3758        //-- collect the leaves which haven't been found by ray casting
3759        if (0)
3760        {
3761                cout << "finding additional merge candidates using geometry" << endl;
3762                vector<BspLeaf *> leaves;
3763                CollectLeaves(leaves, true);
3764                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
3765                CollectMergeCandidates(leaves, candidates);
3766        }
3767
3768        return numLeaves;
3769}
3770
3771
3772
3773
3774ViewCell *VspBspTree::GetViewCell(const Vector3 &point, const bool active)
3775{
3776        if (mRoot == NULL)
3777                return NULL;
3778
3779        stack<BspNode *> nodeStack;
3780        nodeStack.push(mRoot);
3781 
3782        ViewCellLeaf *viewcell = NULL;
3783 
3784        while (!nodeStack.empty()) 
3785        {
3786                BspNode *node = nodeStack.top();
3787                nodeStack.pop();
3788       
3789                if (node->IsLeaf())
3790                {
3791                        viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
3792                        break;
3793                }
3794                else   
3795                {       
3796                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3797       
3798                        // random decision
3799                        if (interior->GetPlane().Side(point) < 0)
3800                                nodeStack.push(interior->GetBack());
3801                        else
3802                                nodeStack.push(interior->GetFront());
3803                }
3804        }
3805 
3806        if (active)
3807                return mViewCellsTree->GetActiveViewCell(viewcell);
3808        else
3809                return viewcell;
3810}
3811
3812
3813bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
3814{
3815        BspNode *node = mRoot;
3816
3817        while (1)
3818        {
3819                // early exit
3820                if (node->TreeValid())
3821                        return true;
3822
3823                if (node->IsLeaf())
3824                        return false;
3825                       
3826                BspInterior *in = dynamic_cast<BspInterior *>(node);
3827                                       
3828                if (in->GetPlane().Side(viewPoint) <= 0)
3829                {
3830                        node = in->GetBack();
3831                }
3832                else
3833                {
3834                        node = in->GetFront();
3835                }
3836        }
3837
3838        // should never come here
3839        return false;
3840}
3841
3842
3843void VspBspTree::PropagateUpValidity(BspNode *node)
3844{
3845        const bool isValid = node->TreeValid();
3846
3847        // propagative up invalid flag until only invalid nodes exist over this node
3848        if (!isValid)
3849        {
3850                while (!node->IsRoot() && node->GetParent()->TreeValid())
3851                {
3852                        node = node->GetParent();
3853                        node->SetTreeValid(false);
3854                }
3855        }
3856        else
3857        {
3858                // propagative up valid flag until one of the subtrees is invalid
3859                while (!node->IsRoot() && !node->TreeValid())
3860                {
3861            node = node->GetParent();
3862                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3863                       
3864                        // the parent is valid iff both leaves are valid
3865                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3866                                                           interior->GetFront()->TreeValid());
3867                }
3868        }
3869}
3870
3871#if ZIPPED_VIEWCELLS
3872bool VspBspTree::Export(ogzstream &stream)
3873#else
3874bool VspBspTree::Export(ofstream &stream)
3875#endif
3876{
3877        ExportNode(mRoot, stream);
3878
3879        return true;
3880}
3881
3882#if ZIPPED_VIEWCELLS
3883void VspBspTree::ExportNode(BspNode *node, ogzstream &stream)
3884#else
3885void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3886#endif
3887{
3888        if (node->IsLeaf())
3889        {
3890                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3891                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3892
3893                int id = -1;
3894                if (viewCell != mOutOfBoundsCell)
3895                        id = viewCell->GetId();
3896
3897                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3898        }
3899        else
3900        {
3901                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3902       
3903                Plane3 plane = interior->GetPlane();
3904                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3905                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3906                           << plane.mD << "\">" << endl;
3907
3908                ExportNode(interior->GetBack(), stream);
3909                ExportNode(interior->GetFront(), stream);
3910
3911                stream << "</Interior>" << endl;
3912        }
3913}
3914
3915}
Note: See TracBrowser for help on using the repository browser.