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

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

added mesh instance support
improved support for occlusion queries + other extensions

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