source: GTP/trunk/Lib/Vis/Preprocessing/src/FromPointVisibilityTree.cpp @ 840

Revision 840, 96.3 KB checked in by mattausch, 18 years ago (diff)

implementing bounding box hack

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