source: trunk/VUT/GtpVisibilityPreprocessor/src/VspBspTree.cpp @ 611

Revision 611, 72.8 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include <stack>
2#include <time.h>
3#include <iomanip>
4
5#include "Plane3.h"
6#include "VspBspTree.h"
7#include "Mesh.h"
8#include "common.h"
9#include "ViewCell.h"
10#include "Environment.h"
11#include "Polygon3.h"
12#include "Ray.h"
13#include "AxisAlignedBox3.h"
14#include "Exporter.h"
15#include "Plane3.h"
16#include "ViewCellBsp.h"
17#include "ViewCellsManager.h"
18#include "Beam.h"
19
20
21//-- static members
22
23/** Evaluates split plane classification with respect to the plane's
24        contribution for a minimum number of ray splits.
25*/
26const float VspBspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
27/** Evaluates split plane classification with respect to the plane's
28        contribution for  balanced rays.
29*/
30const float VspBspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
31
32
33int VspBspTree::sFrontId = 0;
34int VspBspTree::sBackId = 0;
35int VspBspTree::sFrontAndBackId = 0;
36
37
38
39
40// pvs penalty can be different from pvs size
41inline float EvalPvsPenalty(const int pvs,
42                                                        const int lower,
43                                                        const int upper)
44{
45        // clamp to minmax values
46        if (pvs < lower)
47                return (float)lower;
48        if (pvs > upper)
49                return (float)upper;
50
51        return (float)pvs;
52}
53
54
55
56
57/******************************************************************************/
58/*                       class VspBspTree implementation                      */
59/******************************************************************************/
60
61
62VspBspTree::VspBspTree():
63mRoot(NULL),
64mUseAreaForPvs(false),
65mCostNormalizer(Limits::Small),
66mViewCellsManager(NULL),
67mOutOfBoundsCell(NULL),
68mStoreRays(false),
69mRenderCostWeight(0.5),
70mUseRandomAxis(false),
71mTimeStamp(0)
72{
73        bool randomize = false;
74        environment->GetBoolValue("VspBspTree.Construction.randomize", randomize);
75        if (randomize)
76                Randomize(); // initialise random generator for heuristics
77
78        //-- termination criteria for autopartition
79        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
80        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
81        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
82        environment->GetFloatValue("VspBspTree.Termination.minProbability", mTermMinProbability);
83        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
84        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
85        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
86        environment->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
87        environment->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
88        //-- max cost ratio for early tree termination
89        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
90
91        // HACK
92        mTermMinPolygons = 25;
93
94        //-- factors for bsp tree split plane heuristics
95        environment->GetFloatValue("VspBspTree.Factor.balancedRays", mBalancedRaysFactor);
96        environment->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
97        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
98
99
100        //-- partition criteria
101        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
102        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
103        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
104
105        environment->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
106        environment->GetIntValue("VspBspTree.maxTests", mMaxTests);
107
108        // if only the driving axis is used for axis aligned split
109        environment->GetBoolValue("VspBspTree.splitUseOnlyDrivingAxis", mOnlyDrivingAxis);
110       
111        //-- termination criteria for axis aligned split
112        environment->GetFloatValue("VspBspTree.Termination.AxisAligned.maxRayContribution",
113                mTermMaxRayContriForAxisAligned);
114        environment->GetIntValue("VspBspTree.Termination.AxisAligned.minRays",
115                mTermMinRaysForAxisAligned);
116
117        //environment->GetFloatValue("VspBspTree.maxTotalMemory", mMaxTotalMemory);
118        environment->GetFloatValue("VspBspTree.maxStaticMemory", mMaxMemory);
119
120        environment->GetFloatValue("VspBspTree.Construction.renderCostWeight", mRenderCostWeight);
121
122        environment->GetBoolValue("VspBspTree.usePolygonSplitIfAvailable", mUsePolygonSplitIfAvailable);
123
124        mSubdivisionStats.open("subdivisionStats.log");
125
126
127        //-- debug output
128
129        Debug << "******* VSP BSP options ******** " << endl;
130    Debug << "max depth: " << mTermMaxDepth << endl;
131        Debug << "min PVS: " << mTermMinPvs << endl;
132        Debug << "min probabiliy: " << mTermMinProbability << endl;
133        Debug << "min rays: " << mTermMinRays << endl;
134        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
135        //Debug << "VSP BSP mininam accumulated ray lenght: ", mTermMinAccRayLength) << endl;
136        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
137        Debug << "miss tolerance: " << mTermMissTolerance << endl;
138        Debug << "max view cells: " << mMaxViewCells << endl;
139        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
140        Debug << "max plane candidates: " << mMaxRayCandidates << endl;
141        Debug << "randomize: " << randomize << endl;
142
143        Debug << "using area for pvs: " << mUseAreaForPvs << endl;
144        Debug << "render cost weight: " << mRenderCostWeight << endl;
145        Debug << "Split plane strategy: ";
146
147        if (mSplitPlaneStrategy & RANDOM_POLYGON)
148        {
149                Debug << "random polygon ";
150        }
151        if (mSplitPlaneStrategy & AXIS_ALIGNED)
152        {
153                Debug << "axis aligned ";
154        }
155        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
156        {
157                mCostNormalizer += mLeastRaySplitsFactor;
158                Debug << "least ray splits ";
159        }
160        if (mSplitPlaneStrategy & BALANCED_RAYS)
161        {
162                mCostNormalizer += mBalancedRaysFactor;
163                Debug << "balanced rays ";
164        }
165        if (mSplitPlaneStrategy & PVS)
166        {
167                mCostNormalizer += mPvsFactor;
168                Debug << "pvs";
169        }
170
171
172        mSplitCandidates = new vector<SortableEntry>;
173
174        Debug << endl;
175}
176
177
178BspViewCell *VspBspTree::GetOutOfBoundsCell()
179{
180        return mOutOfBoundsCell;
181}
182
183
184BspViewCell *VspBspTree::GetOrCreateOutOfBoundsCell()
185{
186        if (!mOutOfBoundsCell)
187        {
188                mOutOfBoundsCell = new BspViewCell();
189                mOutOfBoundsCell->SetId(-1);
190                mOutOfBoundsCell->SetValid(false);
191        }
192
193        return mOutOfBoundsCell;
194}
195
196
197const BspTreeStatistics &VspBspTree::GetStatistics() const
198{
199        return mBspStats;
200}
201
202
203VspBspTree::~VspBspTree()
204{
205        DEL_PTR(mRoot);
206        DEL_PTR(mSplitCandidates);
207}
208
209
210int VspBspTree::AddMeshToPolygons(Mesh *mesh,
211                                                                  PolygonContainer &polys,
212                                                                  MeshInstance *parent)
213{
214        FaceContainer::const_iterator fi;
215
216        // copy the face data to polygons
217        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
218        {
219                Polygon3 *poly = new Polygon3((*fi), mesh);
220
221                if (poly->Valid(mEpsilon))
222                {
223                        poly->mParent = parent; // set parent intersectable
224                        polys.push_back(poly);
225                }
226                else
227                        DEL_PTR(poly);
228        }
229        return (int)mesh->mFaces.size();
230}
231
232
233int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
234                                                          PolygonContainer &polys,
235                                                          int maxObjects)
236{
237        int limit = (maxObjects > 0) ?
238                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
239
240        int polysSize = 0;
241
242        for (int i = 0; i < limit; ++ i)
243        {
244                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
245                {
246                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
247                        polysSize +=
248                                AddMeshToPolygons(viewCells[i]->GetMesh(),
249                                                                  polys,
250                                                                  viewCells[i]);
251                }
252        }
253
254        return polysSize;
255}
256
257
258int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
259                                                                 PolygonContainer &polys,
260                                                                 int maxObjects)
261{
262        int limit = (maxObjects > 0) ?
263                Min((int)objects.size(), maxObjects) : (int)objects.size();
264
265        for (int i = 0; i < limit; ++i)
266        {
267                Intersectable *object = objects[i];//*it;
268                Mesh *mesh = NULL;
269
270                switch (object->Type()) // extract the meshes
271                {
272                case Intersectable::MESH_INSTANCE:
273                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
274                        break;
275                case Intersectable::VIEW_CELL:
276                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
277                        break;
278                        // TODO: handle transformed mesh instances
279                default:
280                        Debug << "intersectable type not supported" << endl;
281                        break;
282                }
283
284        if (mesh) // copy the mesh data to polygons
285                {
286                        mBox.Include(object->GetBox()); // add to BSP tree aabb
287                        AddMeshToPolygons(mesh, polys, NULL);
288                }
289        }
290
291        return (int)polys.size();
292}
293
294
295void VspBspTree::Construct(const VssRayContainer &sampleRays,
296                                                   AxisAlignedBox3 *forcedBoundingBox)
297{
298        mBspStats.nodes = 1;
299        mBox.Initialize();      // initialise BSP tree bounding box
300
301        if (forcedBoundingBox)
302                mBox = *forcedBoundingBox;
303       
304        PolygonContainer polys;
305        RayInfoContainer *rays = new RayInfoContainer();
306
307        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
308
309        long startTime = GetTime();
310
311        cout << "Extracting polygons from rays ... ";
312
313        Intersectable::NewMail();
314
315        int numObj = 0;
316
317        //-- extract polygons intersected by the rays
318        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
319        {
320                VssRay *ray = *rit;
321
322                if ((mBox.IsInside(ray->mTermination) || !forcedBoundingBox) &&
323                        ray->mTerminationObject &&
324                        !ray->mTerminationObject->Mailed())
325                {
326                        ray->mTerminationObject->Mail();
327                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
328                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
329                        ++ numObj;
330                        //-- compute bounding box
331                        if (!forcedBoundingBox)
332                                mBox.Include(ray->mTermination);
333                }
334
335                if ((mBox.IsInside(ray->mOrigin) || !forcedBoundingBox) &&
336                        ray->mOriginObject &&
337                        !ray->mOriginObject->Mailed())
338                {
339                        ray->mOriginObject->Mail();
340                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
341                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
342                        ++ numObj;
343
344                        //-- compute bounding box
345                        if (!forcedBoundingBox)
346                                mBox.Include(ray->mOrigin);
347                }
348        }
349       
350        Debug << "maximal pvs (i.e., pvs still considered as valid) : " << mViewCellsManager->GetMaxPvsSize() << endl;
351
352        //-- store rays
353        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
354        {
355                VssRay *ray = *rit;
356
357                float minT, maxT;
358
359                static Ray hray;
360                hray.Init(*ray);
361
362                // TODO: not very efficient to implictly cast between rays types
363                if (mBox.GetRaySegment(hray, minT, maxT))
364                {
365                        float len = ray->Length();
366
367                        if (!len)
368                                len = Limits::Small;
369
370                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
371                }
372        }
373
374        // normalize
375        if (mUseAreaForPvs)
376                mTermMinProbability *= mBox.SurfaceArea();
377        else
378                mTermMinProbability *= mBox.GetVolume();
379
380        mBspStats.polys = (int)polys.size();
381
382        cout << "finished" << endl;
383
384        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
385                  << (int)sampleRays.size() << " rays in "
386                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
387
388        Construct(polys, rays);
389
390        // clean up polygons
391        CLEAR_CONTAINER(polys);
392}
393
394
395// return memory usage in MB
396float VspBspTree::GetMemUsage(/*const VspBspTraversalQueue &tstack*/) const
397{
398        return
399                (sizeof(VspBspTree) +
400                 (float)mBspStats.Leaves() * sizeof(BspLeaf) +
401                 // the nodes in the stack is the minimal additional number of leaves
402                 //(float)tstack.size() * sizeof(BspLeaf) +
403                 mBspStats.Interior() * sizeof(BspInterior) +
404                 mBspStats.accumRays * sizeof(RayInfo)) / (1024.0f * 1024.0f);
405}
406
407
408
409void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
410{
411        VspBspTraversalQueue tQueue;
412
413        mRoot = new BspLeaf();
414
415        // constrruct root node geometry
416        BspNodeGeometry *geom = new BspNodeGeometry();
417        ConstructGeometry(mRoot, *geom);
418
419        const float prop = mUseAreaForPvs ? geom->GetArea() : geom->GetVolume();
420
421        VspBspTraversalData tData(mRoot,
422                                                          new PolygonContainer(polys),
423                                                          0,
424                                                          rays,
425                              ComputePvsSize(*rays),
426                                                          prop,
427                                                          geom);
428#if OCTREE_HACK
429tData.mAxis = 0;
430#endif
431        // first node is kd node, i.e. an axis aligned box
432        if (1)
433        tData.mIsKdNode = true;
434        else
435                tData.mIsKdNode = false;
436
437        tQueue.push(tData);
438
439
440        mTotalCost = tData.mPvs * tData.mProbability / mBox.GetVolume();
441        mTotalPvsSize = tData.mPvs;
442       
443        mSubdivisionStats
444                        << "#ViewCells\n1\n" <<  endl
445                        << "#RenderCostDecrease\n0\n" << endl
446                        << "#TotalRenderCost\n" << mTotalCost << endl
447                        << "#AvgRenderCost\n" << mTotalPvsSize << endl;
448
449        Debug << "total cost: " << mTotalCost << endl;
450       
451       
452        mBspStats.Start();
453        cout << "Contructing vsp bsp tree ... \n";
454
455        long startTime = GetTime();     
456
457        // used for intermediate time measurements and progress
458        long interTime = GetTime();     
459
460        mOutOfMemory = false;
461
462        int nleaves = 500;
463
464        while (!tQueue.empty())
465        {
466                tData = tQueue.top();
467            tQueue.pop();               
468
469                if (0 && !mOutOfMemory)
470                {
471                        float mem = GetMemUsage();
472
473                        if (mem > mMaxMemory)
474                        {
475                                mOutOfMemory = true;
476                                Debug << "memory limit reached: " << mem << endl;
477                        }
478                }
479
480                // subdivide leaf node
481                BspNode *r = Subdivide(tQueue, tData);
482
483                if (r == mRoot)
484                        Debug << "VSP BSP tree construction time spent at root: "
485                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl;
486
487                if (mBspStats.Leaves() >= nleaves)
488                {
489                        nleaves += 500;
490                               
491                        cout << "leaves=" << mBspStats.Leaves() << endl;
492                        Debug << "needed "
493                                  << TimeDiff(interTime, GetTime())*1e-3
494                                  << " secs to create 500 leaves" << endl;
495                        interTime = GetTime();
496                }
497        }
498
499        Debug << "Used Memory: " << GetMemUsage() << " MB" << endl << endl;
500        cout << "finished\n";
501
502        mBspStats.Stop();
503}
504
505
506bool VspBspTree::TerminationCriteriaMet(const VspBspTraversalData &data) const
507{
508        return
509                (((int)data.mRays->size() <= mTermMinRays) ||
510                 (data.mPvs <= mTermMinPvs)   ||
511                 (data.mProbability <= mTermMinProbability) ||
512                 (mBspStats.Leaves() >= mMaxViewCells) ||
513#if 0
514                 (((int)data.mPolygons->size() <= mTermMinPolygons) && !data.mPolygons->empty())||
515#endif
516                 (data.GetAvgRayContribution() > mTermMaxRayContribution) ||
517                 (data.mDepth >= mTermMaxDepth));
518}
519
520
521BspNode *VspBspTree::Subdivide(VspBspTraversalQueue &tQueue,
522                                                           VspBspTraversalData &tData)
523{
524        BspNode *newNode = tData.mNode;
525
526        if (!mOutOfMemory && !TerminationCriteriaMet(tData))
527        {
528                PolygonContainer coincident;
529
530                VspBspTraversalData tFrontData;
531                VspBspTraversalData tBackData;
532#if OCTREE_HACK
533                //Debug << "new axis:" << (tData.mAxis + 1) % 3 << endl;
534
535                tFrontData.mAxis = (tData.mAxis + 1) % 3;
536                tBackData.mAxis = (tData.mAxis + 1) % 3;
537#endif
538                // create new interior node and two leaf nodes
539                // or return leaf as it is (if maxCostRatio missed)
540                newNode = SubdivideNode(tData, tFrontData, tBackData, coincident);
541
542                if (!newNode->IsLeaf()) //-- continue subdivision
543                {
544                        if (1)
545                        {
546                                float cFront = (float)tFrontData.mPvs * tFrontData.mProbability;
547                                float cBack = (float)tBackData.mPvs * tBackData.mProbability;
548                                float cData = (float)tData.mPvs * tData.mProbability;;
549
550                float costDecr =
551                                        (cFront + cBack - cData) / mBox.GetVolume();
552
553                                mTotalCost += costDecr;
554                                mTotalPvsSize += tFrontData.mPvs + tBackData.mPvs - tData.mPvs;
555
556                                mSubdivisionStats
557                                                << "#ViewCells\n" << mBspStats.Leaves() << endl
558                                                << "#RenderCostDecrease\n" << -costDecr << endl
559                                                << "#TotalRenderCost\n" << mTotalCost << endl
560                                                << "#AvgRenderCost\n" << mTotalPvsSize / mBspStats.Leaves() << endl;
561                        }
562
563                        // push the children on the stack
564                        tQueue.push(tFrontData);
565                        tQueue.push(tBackData);
566
567                        // delete old leaf node
568                        DEL_PTR(tData.mNode);
569                }
570        }
571
572        //-- terminate traversal and create new view cell
573        if (newNode->IsLeaf())
574        {
575                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
576                BspViewCell *viewCell = new BspViewCell();
577               
578                leaf->SetViewCell(viewCell);
579       
580                //-- update pvs
581                int conSamp = 0;
582                float sampCon = 0.0f;
583                AddToPvs(leaf, *tData.mRays, sampCon, conSamp);
584
585                mBspStats.contributingSamples += conSamp;
586                mBspStats.sampleContributions +=(int) sampCon;
587
588                //-- store additional info
589                if (mStoreRays)
590                {
591                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
592                        for (it = tData.mRays->begin(); it != it_end; ++ it)
593                                leaf->mVssRays.push_back((*it).mRay);
594                }
595                // should I check here?
596                if (0 && !mViewCellsManager->CheckValidity(viewCell, 0, mViewCellsManager->GetMaxPvsSize()))
597                {
598                        viewCell->SetValid(false);
599                        leaf->SetTreeValid(false);
600                        PropagateUpValidity(leaf);
601
602                        ++ mBspStats.invalidLeaves;
603                }
604               
605        viewCell->mLeaf = leaf;
606
607                if (mUseAreaForPvs)
608                        viewCell->SetArea(tData.mProbability);
609                else
610                        viewCell->SetVolume(tData.mProbability);
611
612                leaf->mProbability = tData.mProbability;
613
614                EvaluateLeafStats(tData);               
615        }
616
617        //-- cleanup
618        tData.Clear();
619
620        return newNode;
621}
622
623
624BspNode *VspBspTree::SubdivideNode(VspBspTraversalData &tData,
625                                                                   VspBspTraversalData &frontData,
626                                                                   VspBspTraversalData &backData,
627                                                                   PolygonContainer &coincident)
628{
629        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
630       
631        // select subdivision plane
632        Plane3 splitPlane;
633       
634        int maxCostMisses = tData.mMaxCostMisses;
635
636        const bool success =
637                SelectPlane(splitPlane, leaf, tData, frontData, backData);
638
639        if (!success)
640        {
641                ++ maxCostMisses;
642
643                if (maxCostMisses > mTermMissTolerance)
644                {
645                        // terminate branch because of max cost
646                        ++ mBspStats.maxCostNodes;
647            return leaf;
648                }
649        }
650
651        mBspStats.nodes += 2;
652
653        //-- subdivide further
654        BspInterior *interior = new BspInterior(splitPlane);
655
656#ifdef _DEBUG
657        Debug << interior << endl;
658#endif
659
660        //-- the front and back traversal data is filled with the new values
661        frontData.mDepth = tData.mDepth + 1;
662        frontData.mPolygons = new PolygonContainer();
663        frontData.mRays = new RayInfoContainer();
664       
665        backData.mDepth = tData.mDepth + 1;
666        backData.mPolygons = new PolygonContainer();
667        backData.mRays = new RayInfoContainer();
668       
669        // subdivide rays
670        SplitRays(interior->GetPlane(),
671                          *tData.mRays,
672                          *frontData.mRays,
673                          *backData.mRays);
674
675        // subdivide polygons
676        SplitPolygons(interior->GetPlane(),
677                                  *tData.mPolygons,
678                      *frontData.mPolygons,
679                                  *backData.mPolygons,
680                                  coincident);
681
682
683        // how often was max cost ratio missed in this branch?
684        frontData.mMaxCostMisses = maxCostMisses;
685        backData.mMaxCostMisses = maxCostMisses;
686
687        // compute pvs
688        frontData.mPvs = ComputePvsSize(*frontData.mRays);
689        backData.mPvs = ComputePvsSize(*backData.mRays);
690
691        // split front and back node geometry and compute area
692       
693        // if geometry was not already computed
694        if (!frontData.mGeometry && !backData.mGeometry)
695        {
696                frontData.mGeometry = new BspNodeGeometry();
697                backData.mGeometry = new BspNodeGeometry();
698
699                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
700                                                                           *backData.mGeometry,
701                                                                           interior->GetPlane(),
702                                                                           mBox,
703                                                                           mEpsilon);
704               
705                if (mUseAreaForPvs)
706                {
707                        frontData.mProbability = frontData.mGeometry->GetArea();
708                        backData.mProbability = backData.mGeometry->GetArea();
709                }
710                else
711                {
712                        frontData.mProbability = frontData.mGeometry->GetVolume();
713                        backData.mProbability =  tData.mProbability - frontData.mProbability;
714                }
715        }
716       
717
718        //-- create front and back leaf
719
720        BspInterior *parent = leaf->GetParent();
721
722        // replace a link from node's parent
723        if (parent)
724        {
725                parent->ReplaceChildLink(leaf, interior);
726                interior->SetParent(parent);
727        }
728        else // new root
729        {
730                mRoot = interior;
731        }
732
733        // and setup child links
734        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
735
736        frontData.mNode = interior->GetFront();
737        backData.mNode = interior->GetBack();
738
739        frontData.mNode->mTimeStamp = mTimeStamp;
740        backData.mNode->mTimeStamp = mTimeStamp ++;
741
742        //DEL_PTR(leaf);
743        return interior;
744}
745
746
747void VspBspTree::AddToPvs(BspLeaf *leaf,
748                                                  const RayInfoContainer &rays,
749                                                  float &sampleContributions,
750                                                  int &contributingSamples)
751{
752  sampleContributions = 0;
753  contributingSamples = 0;
754 
755  RayInfoContainer::const_iterator it, it_end = rays.end();
756 
757  ViewCell *vc = leaf->GetViewCell();
758 
759  // add contributions from samples to the PVS
760  for (it = rays.begin(); it != it_end; ++ it)
761        {
762          float sc = 0.0f;
763          VssRay *ray = (*it).mRay;
764          bool madeContrib = false;
765          float contribution;
766          if (ray->mTerminationObject) {
767                if (vc->GetPvs().AddSample(ray->mTerminationObject, ray->mPdf, contribution))
768                  madeContrib = true;
769                sc += contribution;
770          }
771         
772          if (ray->mOriginObject) {
773                if (vc->GetPvs().AddSample(ray->mOriginObject, ray->mPdf, contribution))
774                  madeContrib = true;
775                sc += contribution;
776          }
777         
778          sampleContributions += sc;
779          if (madeContrib)
780                  ++ contributingSamples;
781               
782          //leaf->mVssRays.push_back(ray);
783        }
784}
785
786
787void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays, const int axis)
788{
789        mSplitCandidates->clear();
790
791        int requestedSize = 2 * (int)(rays.size());
792        // creates a sorted split candidates array
793        if (mSplitCandidates->capacity() > 500000 &&
794                requestedSize < (int)(mSplitCandidates->capacity()/10) )
795        {
796        delete mSplitCandidates;
797                mSplitCandidates = new vector<SortableEntry>;
798        }
799
800        mSplitCandidates->reserve(requestedSize);
801
802        // insert all queries
803        for(RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
804        {
805                bool positive = (*ri).mRay->HasPosDir(axis);
806                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
807                                                                                                  (*ri).ExtrapOrigin(axis), (*ri).mRay));
808
809                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
810                                                                                                  (*ri).ExtrapTermination(axis), (*ri).mRay));
811        }
812
813        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
814}
815
816
817float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
818                                                                                  const AxisAlignedBox3 &box,
819                                                                                  const int pvsSize,
820                                                                                  const int &axis,
821                                          float &position)
822{
823        int raysBack;
824        int raysFront;
825        int pvsBack;
826        int pvsFront;
827
828        SortSplitCandidates(rays, axis);
829
830        // go through the lists, count the number of objects left and right
831        // and evaluate the following cost funcion:
832        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
833
834        int rl = 0, rr = (int)rays.size();
835        int pl = 0, pr = pvsSize;
836
837        float minBox = box.Min(axis);
838        float maxBox = box.Max(axis);
839        float sizeBox = maxBox - minBox;
840
841        float minBand = minBox + 0.1f*(maxBox - minBox);
842        float maxBand = minBox + 0.9f*(maxBox - minBox);
843
844        float sum = rr*sizeBox;
845        float minSum = 1e20f;
846
847        Intersectable::NewMail();
848
849        // set all object as belonging to the fron pvs
850        for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ++ ri)
851        {
852                if ((*ri).mRay->IsActive())
853                {
854                        Intersectable *object = (*ri).mRay->mTerminationObject;
855
856                        if (object)
857                        {
858                                if (!object->Mailed())
859                                {
860                                        object->Mail();
861                                        object->mCounter = 1;
862                                }
863                                else
864                                        ++ object->mCounter;
865                        }
866                }
867        }
868
869        Intersectable::NewMail();
870
871        for (vector<SortableEntry>::const_iterator ci = mSplitCandidates->begin();
872                ci < mSplitCandidates->end(); ++ ci)
873        {
874                VssRay *ray;
875
876                switch ((*ci).type)
877                {
878                        case SortableEntry::ERayMin:
879                                {
880                                        ++ rl;
881                                        ray = (VssRay *) (*ci).ray;
882
883                                        Intersectable *object = ray->mTerminationObject;
884
885                                        if (object && !object->Mailed())
886                                        {
887                                                object->Mail();
888                                                ++ pl;
889                                        }
890                                        break;
891                                }
892                        case SortableEntry::ERayMax:
893                                {
894                                        -- rr;
895                                        ray = (VssRay *) (*ci).ray;
896
897                                        Intersectable *object = ray->mTerminationObject;
898
899                                        if (object)
900                                        {
901                                                if (-- object->mCounter == 0)
902                                                        -- pr;
903                                        }
904
905                                        break;
906                                }
907                }
908
909                // Note: sufficient to compare size of bounding boxes of front and back side?
910                if ((*ci).value > minBand && (*ci).value < maxBand)
911                {
912                        sum = pl*((*ci).value - minBox) + pr*(maxBox - (*ci).value);
913
914                        //  cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
915                        // cout<<"cost= "<<sum<<endl;
916
917                        if (sum < minSum)
918                        {
919                                minSum = sum;
920                                position = (*ci).value;
921
922                                raysBack = rl;
923                                raysFront = rr;
924
925                                pvsBack = pl;
926                                pvsFront = pr;
927
928                        }
929                }
930        }
931
932        float oldCost = (float)pvsSize;
933        float newCost = mCtDivCi + minSum / sizeBox;
934        float ratio = newCost / oldCost;
935
936        //Debug << "costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
937        //     <<"\t q=(" << queriesBack << "," << queriesFront << ")\t r=(" << raysBack << "," << raysFront << ")" << endl;
938
939        return ratio;
940}
941
942
943float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
944                                                                                 const VspBspTraversalData &tData,
945                                                                                 int &axis,
946                                                                                 BspNodeGeometry **frontGeom,
947                                                                                 BspNodeGeometry **backGeom,
948                                                                                 float &pFront,
949                                                                                 float &pBack,
950                                                                                 const bool useKdSplit)
951{
952        const bool useCostHeuristics = false;
953
954        //-- regular split
955        float nPosition[3];
956        float nCostRatio[3];
957        float nProbFront[3];
958        float nProbBack[3];
959
960        BspNodeGeometry *nFrontGeom[3];
961        BspNodeGeometry *nBackGeom[3];
962
963        int bestAxis = -1;
964
965        // create bounding box of node geometry
966        AxisAlignedBox3 box;
967        box.Initialize();
968       
969        //TODO: for kd split geometry already is box => only take minmax vertices
970        if (1)
971        {
972                PolygonContainer::const_iterator it, it_end = tData.mGeometry->mPolys.end();
973
974                for(it = tData.mGeometry->mPolys.begin(); it < it_end; ++ it)
975                        box.Include(*(*it));
976        }
977        else
978        {
979                RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
980
981                for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
982                        box.Include((*ri).ExtrapTermination());
983        }
984#if OCTREE_HACK
985        //Debug << "choosing axis:" << tData.mAxis << endl;
986        const int sAxis = tData.mAxis;
987#else
988        const int sAxis = mUseRandomAxis ? Random(3) : box.Size().DrivingAxis();
989#endif
990        for (axis = 0; axis < 3; ++ axis)
991        {
992                nFrontGeom[axis] = new BspNodeGeometry();
993                nBackGeom[axis] = new BspNodeGeometry();
994
995                if (!mOnlyDrivingAxis || (axis == sAxis))
996                {
997                        if (!useCostHeuristics)
998                        {
999                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
1000                                Vector3 normal(0,0,0); normal[axis] = 1.0f;
1001
1002                                // allows faster split because we have axis aligned kd tree boxes
1003                                if (useKdSplit)
1004                                {
1005                                        nCostRatio[axis] = EvalAxisAlignedSplitCost(tData,
1006                                                                                                                                box,
1007                                                                                                                                axis,
1008                                                                                                                                nPosition[axis],
1009                                                                                                                                nProbFront[axis],
1010                                                                                                                                nProbBack[axis]);
1011                                       
1012                                        Vector3 pos;
1013                                       
1014                                        pos = box.Max(); pos[axis] = nPosition[axis];
1015                                        AxisAlignedBox3 bBox(box.Min(), pos);
1016                                        bBox.ExtractPolys(nBackGeom[axis]->mPolys);
1017                                       
1018                                        pos = box.Min(); pos[axis] = nPosition[axis];
1019                                        AxisAlignedBox3 fBox(pos, box.Max());
1020                                        fBox.ExtractPolys(nFrontGeom[axis]->mPolys);
1021                                }
1022                                else
1023                                {
1024                                        nCostRatio[axis] =
1025                                                EvalSplitPlaneCost(Plane3(normal, nPosition[axis]),
1026                                                                                   tData, *nFrontGeom[axis], *nBackGeom[axis],
1027                                                                                   nProbFront[axis], nProbBack[axis]);
1028                                }
1029                        }
1030                        else
1031                        {
1032                                nCostRatio[axis] =
1033                                        BestCostRatioHeuristics(*tData.mRays,
1034                                                                                    box,
1035                                                                                        tData.mPvs,
1036                                                                                        axis,
1037                                                                                        nPosition[axis]);
1038                        }
1039
1040                        if (bestAxis == -1)
1041                        {
1042                                bestAxis = axis;
1043                        }
1044
1045                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
1046                        {
1047                                bestAxis = axis;
1048                        }
1049
1050                }
1051        }
1052
1053        //-- assign values
1054        axis = bestAxis;
1055        pFront = nProbFront[bestAxis];
1056        pBack = nProbBack[bestAxis];
1057
1058        // assign best split nodes geometry
1059        *frontGeom = nFrontGeom[bestAxis];
1060        *backGeom = nBackGeom[bestAxis];
1061
1062        // and delete other geometry
1063        delete nFrontGeom[(bestAxis + 1) % 3];
1064        delete nBackGeom[(bestAxis + 2) % 3];
1065
1066        //-- split plane
1067    Vector3 normal(0,0,0); normal[bestAxis] = 1;
1068        plane = Plane3(normal, nPosition[bestAxis]);
1069
1070        return nCostRatio[bestAxis];
1071}
1072
1073
1074bool VspBspTree::SelectPlane(Plane3 &bestPlane,
1075                                                         BspLeaf *leaf,
1076                                                         VspBspTraversalData &data,
1077                                                         VspBspTraversalData &frontData,
1078                                                         VspBspTraversalData &backData)
1079{
1080        // simplest strategy: just take next polygon
1081        if (mSplitPlaneStrategy & RANDOM_POLYGON)
1082        {
1083        if (!data.mPolygons->empty())
1084                {
1085                        const int randIdx =
1086                                (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
1087                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
1088
1089                        bestPlane = nextPoly->GetSupportingPlane();
1090                        return true;
1091                }
1092        }
1093
1094        //-- use heuristics to find appropriate plane
1095
1096        // intermediate plane
1097        Plane3 plane;
1098        float lowestCost = MAX_FLOAT;
1099       
1100        // decides if the first few splits should be only axisAligned
1101        const bool onlyAxisAligned  =
1102                (mSplitPlaneStrategy & AXIS_ALIGNED) &&
1103                ((int)data.mRays->size() > mTermMinRaysForAxisAligned) &&
1104                ((int)data.GetAvgRayContribution() < mTermMaxRayContriForAxisAligned);
1105       
1106        const int limit = onlyAxisAligned ? 0 :
1107                Min((int)data.mPolygons->size(), mMaxPolyCandidates);
1108
1109        float candidateCost;
1110
1111        int maxIdx = (int)data.mPolygons->size();
1112
1113        for (int i = 0; i < limit; ++ i)
1114        {
1115                // the already taken candidates are stored behind maxIdx
1116                // => assure that no index is taken twice
1117                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
1118                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
1119
1120                // swap candidate to the end to avoid testing same plane
1121                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
1122                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
1123
1124                // evaluate current candidate
1125                BspNodeGeometry fGeom, bGeom;
1126                float fArea, bArea;
1127                plane = poly->GetSupportingPlane();
1128                candidateCost = EvalSplitPlaneCost(plane, data, fGeom, bGeom, fArea, bArea);
1129               
1130                if (candidateCost < lowestCost)
1131                {
1132                        bestPlane = plane;
1133                        lowestCost = candidateCost;
1134                }
1135        }
1136
1137        // cost ratio miss
1138        if (mUsePolygonSplitIfAvailable && !data.mPolygons->empty())
1139        {
1140                frontData.mIsKdNode = backData.mIsKdNode = false;
1141                if (lowestCost > mTermMaxCostRatio)
1142                        return false;
1143
1144                return true;
1145        }
1146
1147        //-- evaluate axis aligned splits
1148        int axis;
1149        BspNodeGeometry *fGeom, *bGeom;
1150        float pFront, pBack;
1151
1152        candidateCost = SelectAxisAlignedPlane(plane, data, axis,
1153                                                                                   &fGeom, &bGeom,
1154                                                                                   pFront, pBack,
1155                                                                                   data.mIsKdNode);     
1156
1157        bool isAxisAlignedSplit = false;
1158
1159        if (candidateCost < lowestCost)
1160        {       
1161                bestPlane = plane;
1162                lowestCost = candidateCost;
1163
1164                // assign already computed values
1165                // we can do this because we always save the
1166                // computed values from the axis aligned splits         
1167                frontData.mGeometry = fGeom;
1168                backData.mGeometry = bGeom;
1169       
1170                frontData.mProbability = pFront;
1171                backData.mProbability = pBack;
1172               
1173                //! error also computed if cost ratio is missed
1174                ++ mBspStats.splits[axis];
1175                isAxisAlignedSplit = true;
1176        }
1177        else
1178        {
1179                DEL_PTR(fGeom);
1180                DEL_PTR(bGeom);
1181        }
1182
1183        frontData.mIsKdNode = backData.mIsKdNode = (data.mIsKdNode && isAxisAlignedSplit);
1184
1185#ifdef _DEBUG
1186        Debug << "plane lowest cost: " << lowestCost << endl;
1187#endif
1188
1189        // cost ratio miss
1190        if (lowestCost > mTermMaxCostRatio)
1191        {
1192                return false;
1193        }
1194
1195        return true;
1196}
1197
1198
1199Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
1200{
1201        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1202
1203        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
1204        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
1205
1206        const Vector3 pt = (maxPt + minPt) * 0.5;
1207        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
1208
1209        return Plane3(normal, pt);
1210}
1211
1212
1213Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
1214{
1215        Vector3 pt[3];
1216
1217        int idx[3];
1218        int cmaxT = 0;
1219        int cminT = 0;
1220        bool chooseMin = false;
1221
1222        for (int j = 0; j < 3; ++ j)
1223        {
1224                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
1225
1226                if (idx[j] >= (int)rays.size())
1227                {
1228                        idx[j] -= (int)rays.size();
1229
1230                        chooseMin = (cminT < 2);
1231                }
1232                else
1233                        chooseMin = (cmaxT < 2);
1234
1235                RayInfo rayInf = rays[idx[j]];
1236                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
1237        }
1238
1239        return Plane3(pt[0], pt[1], pt[2]);
1240}
1241
1242
1243Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
1244{
1245        Vector3 pt[3];
1246
1247        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1248        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
1249
1250        // check if rays different
1251        if (idx1 == idx2)
1252                idx2 = (idx2 + 1) % (int)rays.size();
1253
1254        const RayInfo ray1 = rays[idx1];
1255        const RayInfo ray2 = rays[idx2];
1256
1257        // normal vector of the plane parallel to both lines
1258        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
1259
1260        // vector from line 1 to line 2
1261        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
1262
1263        // project vector on normal to get distance
1264        const float dist = DotProd(vd, norm);
1265
1266        // point on plane lies halfway between the two planes
1267        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
1268
1269        return Plane3(norm, planePt);
1270}
1271
1272
1273inline void VspBspTree::GenerateUniqueIdsForPvs()
1274{
1275        Intersectable::NewMail(); sBackId = Intersectable::sMailId;
1276        Intersectable::NewMail(); sFrontId = Intersectable::sMailId;
1277        Intersectable::NewMail(); sFrontAndBackId = Intersectable::sMailId;
1278}
1279
1280
1281float VspBspTree::EvalSplitPlaneCost(const Plane3 &candidatePlane,
1282                                                                         const VspBspTraversalData &data,
1283                                                                         BspNodeGeometry &geomFront,
1284                                                                         BspNodeGeometry &geomBack,
1285                                                                         float &pFront,
1286                                                                         float &pBack) const
1287{
1288        float cost = 0;
1289
1290        float sumBalancedRays = 0;
1291        float sumRaySplits = 0;
1292
1293        int pvsFront = 0;
1294        int pvsBack = 0;
1295
1296        // probability that view point lies in back / front node
1297        float pOverall = 0;
1298        pFront = 0;
1299        pBack = 0;
1300
1301        int raysFront = 0;
1302        int raysBack = 0;
1303        int totalPvs = 0;
1304
1305        int limit;
1306        bool useRand;
1307
1308        // choose test rays randomly if too much
1309        if ((int)data.mRays->size() > mMaxTests)
1310        {
1311                useRand = true;
1312                limit = mMaxTests;
1313        }
1314        else
1315        {
1316                useRand = false;
1317                limit = (int)data.mRays->size();
1318        }
1319       
1320        for (int i = 0; i < limit; ++ i)
1321        {
1322                const int testIdx = useRand ?
1323                        (int)RandomValue(0, (Real)((int)data.mRays->size() - 1)) : i;
1324                RayInfo rayInf = (*data.mRays)[testIdx];
1325
1326                float t;
1327                VssRay *ray = rayInf.mRay;
1328                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1329
1330        if (0)
1331                {
1332                        if (cf >= 0)
1333                                ++ raysFront;
1334                        if (cf <= 0)
1335                                ++ raysBack;
1336                }
1337
1338                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1339                {
1340                        sumBalancedRays += cf;
1341                }
1342
1343                if (mSplitPlaneStrategy & BALANCED_RAYS)
1344                {
1345                        if (cf == 0)
1346                                ++ sumRaySplits;
1347                }
1348
1349                if (mSplitPlaneStrategy & PVS)
1350                {
1351                        // find front and back pvs for origing and termination object
1352                        AddObjToPvs(ray->mTerminationObject, cf, pvsFront, pvsBack, totalPvs);
1353                        AddObjToPvs(ray->mOriginObject, cf, pvsFront, pvsBack, totalPvs);
1354                }
1355        }
1356
1357        const float raysSize = (float)data.mRays->size() + Limits::Small;
1358
1359        if (mSplitPlaneStrategy & PVS)
1360        {
1361                // create unique ids for pvs heuristics
1362                GenerateUniqueIdsForPvs();
1363
1364                // construct child geometry with regard to the candidate split plane
1365                data.mGeometry->SplitGeometry(geomFront,
1366                                                                          geomBack,
1367                                                                          candidatePlane,
1368                                                                          mBox,
1369                                                                          mEpsilon);
1370
1371                pOverall = data.mProbability;
1372
1373                if (!mUseAreaForPvs) // use front and back cell areas to approximate volume
1374                {
1375                        pFront = geomFront.GetVolume();
1376                        pBack = pOverall - pFront;
1377                }
1378                else
1379                {
1380                        pFront = geomFront.GetArea();
1381                        pBack = geomBack.GetArea();
1382                }
1383        }
1384
1385
1386        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1387                cost += mLeastRaySplitsFactor * sumRaySplits / raysSize;
1388
1389        if (mSplitPlaneStrategy & BALANCED_RAYS)
1390                cost += mBalancedRaysFactor * fabs(sumBalancedRays) / raysSize;
1391
1392        // -- pvs rendering heuristics
1393        if (mSplitPlaneStrategy & PVS)
1394        {
1395                const int lowerPvsLimit = mViewCellsManager->GetMinPvsSize();
1396                const int upperPvsLimit = mViewCellsManager->GetMaxPvsSize();
1397
1398                // only render cost heuristics or combined with standard deviation
1399                const float penaltyOld = EvalPvsPenalty(totalPvs, lowerPvsLimit, upperPvsLimit);
1400        const float penaltyFront = EvalPvsPenalty(pvsFront, lowerPvsLimit, upperPvsLimit);
1401                const float penaltyBack = EvalPvsPenalty(pvsBack, lowerPvsLimit, upperPvsLimit);
1402                       
1403                const float oldRenderCost = pOverall * (float)penaltyOld + Limits::Small;
1404                const float newRenderCost = penaltyFront * pFront + penaltyBack * pBack;
1405
1406                float oldCost, newCost;
1407
1408                // only render cost
1409                if (1)
1410                {
1411                        oldCost = oldRenderCost;
1412                        newCost = newRenderCost;
1413                }
1414                else // also considering standard deviation
1415                {
1416                        // standard deviation is difference of back and front pvs
1417                        const float expectedCost = 0.5f * (penaltyFront + penaltyBack);
1418
1419                        const float newDeviation = 0.5f *
1420                                fabs(penaltyFront - expectedCost) + fabs(penaltyBack - expectedCost);
1421
1422                        const float oldDeviation = penaltyOld + Limits::Small;
1423
1424                        newCost = mRenderCostWeight * newRenderCost + (1.0f - mRenderCostWeight) * newDeviation;
1425                        oldCost = mRenderCostWeight * oldRenderCost + (1.0f - mRenderCostWeight) * oldDeviation;
1426                }
1427
1428                cost += mPvsFactor * newCost / oldCost;
1429               
1430        }
1431
1432#ifdef _DEBUG
1433        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
1434                  << " frontpvs: " << pvsFront << " pFront: " << pFront
1435                  << " backpvs: " << pvsBack << " pBack: " << pBack << endl << endl;
1436        Debug << "cost: " << cost << endl;
1437#endif
1438
1439       
1440        // normalize cost by sum of linear factors
1441        if(0)
1442                return cost / (float)mCostNormalizer;
1443        else
1444                return cost;
1445}
1446
1447
1448float VspBspTree::EvalAxisAlignedSplitCost(const VspBspTraversalData &data,
1449                                                                                   const AxisAlignedBox3 &box,
1450                                                                                   const int axis,
1451                                                                                   const float &position,                                                                                 
1452                                                                                   float &pFront,
1453                                                                                   float &pBack) const
1454{
1455        int pvsTotal = 0;
1456        int pvsFront = 0;
1457        int pvsBack = 0;
1458       
1459        // create unique ids for pvs heuristics
1460        GenerateUniqueIdsForPvs();
1461
1462        const int pvsSize = data.mPvs;
1463
1464        RayInfoContainer::const_iterator rit, rit_end = data.mRays->end();
1465
1466        // this is the main ray classification loop!
1467        for(rit = data.mRays->begin(); rit != rit_end; ++ rit)
1468        {
1469                //if (!(*rit).mRay->IsActive()) continue;
1470
1471                // determine the side of this ray with respect to the plane
1472                float t;
1473                const int side = (*rit).ComputeRayIntersection(axis, position, t);
1474       
1475                AddObjToPvs((*rit).mRay->mTerminationObject, side, pvsFront, pvsBack, pvsTotal);
1476                AddObjToPvs((*rit).mRay->mOriginObject, side, pvsFront, pvsBack, pvsTotal);
1477        }
1478
1479        //-- pvs heuristics
1480        float pOverall;
1481
1482        //-- compute heurstics
1483        //   we take simplified computation for mid split
1484               
1485        pOverall = data.mProbability;
1486
1487        if (!mUseAreaForPvs)
1488        {   // volume
1489                pBack = pFront = pOverall * 0.5f;
1490               
1491#if 0
1492                // box length substitute for probability
1493                const float minBox = box.Min(axis);
1494                const float maxBox = box.Max(axis);
1495
1496                pBack = position - minBox;
1497                pFront = maxBox - position;
1498                pOverall = maxBox - minBox;
1499#endif
1500        }
1501        else //-- area substitute for probability
1502        {
1503                const int axis2 = (axis + 1) % 3;
1504                const int axis3 = (axis + 2) % 3;
1505
1506                const float faceArea =
1507                        (box.Max(axis2) - box.Min(axis2)) *
1508                        (box.Max(axis3) - box.Min(axis3));
1509
1510                pBack = pFront = pOverall * 0.5f + faceArea;
1511        }
1512
1513#ifdef _DEBUG
1514        Debug << axis << " " << pvsSize << " " << pvsBack << " " << pvsFront << endl;
1515        Debug << pFront << " " << pBack << " " << pOverall << endl;
1516#endif
1517
1518       
1519        const float newCost = pvsBack * pBack + pvsFront * pFront;
1520        const float oldCost = (float)pvsSize * pOverall + Limits::Small;
1521
1522        return  (mCtDivCi + newCost) / oldCost;
1523}
1524
1525
1526void VspBspTree::AddObjToPvs(Intersectable *obj,
1527                                                         const int cf,
1528                                                         int &frontPvs,
1529                                                         int &backPvs,
1530                                                         int &totalPvs) const
1531{
1532        if (!obj)
1533                return;
1534       
1535        if ((obj->mMailbox != sFrontId) &&
1536                (obj->mMailbox != sBackId) &&
1537                (obj->mMailbox != sFrontAndBackId))
1538        {
1539                ++ totalPvs;
1540        }
1541
1542        // TODO: does this really belong to no pvs?
1543        //if (cf == Ray::COINCIDENT) return;
1544
1545        // object belongs to both PVS
1546        if (cf >= 0)
1547        {
1548                if ((obj->mMailbox != sFrontId) &&
1549                        (obj->mMailbox != sFrontAndBackId))
1550                {
1551                        ++ frontPvs;
1552               
1553                        if (obj->mMailbox == sBackId)
1554                                obj->mMailbox = sFrontAndBackId;
1555                        else
1556                                obj->mMailbox = sFrontId;
1557                }
1558        }
1559
1560        if (cf <= 0)
1561        {
1562                if ((obj->mMailbox != sBackId) &&
1563                        (obj->mMailbox != sFrontAndBackId))
1564                {
1565                        ++ backPvs;
1566               
1567                        if (obj->mMailbox == sFrontId)
1568                                obj->mMailbox = sFrontAndBackId;
1569                        else
1570                                obj->mMailbox = sBackId;
1571                }
1572        }
1573}
1574
1575
1576void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves,
1577                                                           const bool onlyUnmailed,
1578                                                           const int maxPvsSize) const
1579{
1580        stack<BspNode *> nodeStack;
1581        nodeStack.push(mRoot);
1582
1583        while (!nodeStack.empty())
1584        {
1585                BspNode *node = nodeStack.top();
1586                nodeStack.pop();
1587               
1588                if (node->IsLeaf())
1589                {
1590                        // test if this leaf is in valid view space
1591                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1592                        if (leaf->TreeValid() &&
1593                                (!onlyUnmailed || !leaf->Mailed()) &&
1594                                ((maxPvsSize < 0) || (leaf->GetViewCell()->GetPvs().GetSize() <= maxPvsSize)))
1595                        {
1596                                leaves.push_back(leaf);
1597                        }
1598                }
1599                else
1600                {
1601                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1602
1603                        nodeStack.push(interior->GetBack());
1604                        nodeStack.push(interior->GetFront());
1605                }
1606        }
1607}
1608
1609
1610AxisAlignedBox3 VspBspTree::GetBoundingBox() const
1611{
1612        return mBox;
1613}
1614
1615
1616BspNode *VspBspTree::GetRoot() const
1617{
1618        return mRoot;
1619}
1620
1621
1622void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
1623{
1624        // the node became a leaf -> evaluate stats for leafs
1625        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1626
1627        // store maximal and minimal depth
1628        if (data.mDepth > mBspStats.maxDepth)
1629                mBspStats.maxDepth = data.mDepth;
1630
1631        if (data.mPvs > mBspStats.maxPvs)
1632                mBspStats.maxPvs = data.mPvs;
1633       
1634        if (data.mDepth < mBspStats.minDepth)
1635                mBspStats.minDepth = data.mDepth;
1636
1637        if (data.mDepth >= mTermMaxDepth)
1638                ++ mBspStats.maxDepthNodes;
1639
1640        // accumulate rays to compute rays /  leaf
1641        mBspStats.accumRays += (int)data.mRays->size();
1642
1643        if (data.mPvs < mTermMinPvs)
1644                ++ mBspStats.minPvsNodes;
1645
1646        if ((int)data.mRays->size() < mTermMinRays)
1647                ++ mBspStats.minRaysNodes;
1648
1649        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1650                ++ mBspStats.maxRayContribNodes;
1651
1652        if (data.mProbability <= mTermMinProbability)
1653                ++ mBspStats.minProbabilityNodes;
1654       
1655        // accumulate depth to compute average depth
1656        mBspStats.accumDepth += data.mDepth;
1657
1658#ifdef _DEBUG
1659        Debug << "BSP stats: "
1660                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1661                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1662          //              << "Area: " << data.mProbability << " (min: " << mTermMinProbability << "), "
1663                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
1664                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1665                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1666#endif
1667}
1668
1669int VspBspTree::CastRay(Ray &ray)
1670{
1671        int hits = 0;
1672
1673        stack<BspRayTraversalData> tQueue;
1674
1675        float maxt, mint;
1676
1677        if (!mBox.GetRaySegment(ray, mint, maxt))
1678                return 0;
1679
1680        Intersectable::NewMail();
1681        ViewCell::NewMail();
1682        Vector3 entp = ray.Extrap(mint);
1683        Vector3 extp = ray.Extrap(maxt);
1684
1685        BspNode *node = mRoot;
1686        BspNode *farChild = NULL;
1687
1688        while (1)
1689        {
1690                if (!node->IsLeaf())
1691                {
1692                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1693
1694                        Plane3 splitPlane = in->GetPlane();
1695                        const int entSide = splitPlane.Side(entp);
1696                        const int extSide = splitPlane.Side(extp);
1697
1698                        if (entSide < 0)
1699                        {
1700                                node = in->GetBack();
1701
1702                                if(extSide <= 0) // plane does not split ray => no far child
1703                                        continue;
1704
1705                                farChild = in->GetFront(); // plane splits ray
1706
1707                        } else if (entSide > 0)
1708                        {
1709                                node = in->GetFront();
1710
1711                                if (extSide >= 0) // plane does not split ray => no far child
1712                                        continue;
1713
1714                                farChild = in->GetBack(); // plane splits ray
1715                        }
1716                        else // ray and plane are coincident
1717                        {
1718                                // WHAT TO DO IN THIS CASE ?
1719                                //break;
1720                                node = in->GetFront();
1721                                continue;
1722                        }
1723
1724                        // push data for far child
1725                        tQueue.push(BspRayTraversalData(farChild, extp, maxt));
1726
1727                        // find intersection of ray segment with plane
1728                        float t;
1729                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
1730                        maxt *= t;
1731
1732                } else // reached leaf => intersection with view cell
1733                {
1734                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1735
1736                        if (!leaf->GetViewCell()->Mailed())
1737                        {
1738                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
1739                                leaf->GetViewCell()->Mail();
1740                                ++ hits;
1741                        }
1742
1743                        //-- fetch the next far child from the stack
1744                        if (tQueue.empty())
1745                                break;
1746
1747                        entp = extp;
1748                        mint = maxt; // NOTE: need this?
1749
1750                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1751                                break;
1752
1753                        BspRayTraversalData &s = tQueue.top();
1754
1755                        node = s.mNode;
1756                        extp = s.mExitPoint;
1757                        maxt = s.mMaxT;
1758
1759                        tQueue.pop();
1760                }
1761        }
1762
1763        return hits;
1764}
1765
1766
1767void VspBspTree::CollectViewCells(ViewCellContainer &viewCells, bool onlyValid) const
1768{
1769        ViewCell::NewMail();
1770       
1771        CollectViewCells(mRoot, onlyValid, viewCells, true);
1772}
1773
1774
1775void VspBspTree::CollapseViewCells()
1776{
1777// TODO
1778#if VC_HISTORY
1779        stack<BspNode *> nodeStack;
1780
1781        if (!mRoot)
1782                return;
1783
1784        nodeStack.push(mRoot);
1785       
1786        while (!nodeStack.empty())
1787        {
1788                BspNode *node = nodeStack.top();
1789                nodeStack.pop();
1790               
1791                if (node->IsLeaf())
1792        {
1793                        BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1794
1795                        if (!viewCell->GetValid())
1796                        {
1797                                BspViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1798       
1799                                ViewCellContainer leaves;
1800                                mViewCellsTree->CollectLeaves(viewCell, leaves);
1801
1802                                ViewCellContainer::const_iterator it, it_end = leaves.end();
1803
1804                                for (it = leaves.begin(); it != it_end; ++ it)
1805                                {
1806                                        BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
1807                                        l->SetViewCell(GetOrCreateOutOfBoundsCell());
1808                                        ++ mBspStats.invalidLeaves;
1809                                }
1810
1811                                // add to unbounded view cell
1812                                GetOrCreateOutOfBoundsCell()->GetPvs().AddPvs(viewCell->GetPvs());
1813                                DEL_PTR(viewCell);
1814                        }
1815                }
1816                else
1817                {
1818                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1819               
1820                        nodeStack.push(interior->GetFront());
1821                        nodeStack.push(interior->GetBack());
1822                }
1823        }
1824
1825        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
1826#endif
1827}
1828
1829
1830void VspBspTree::ValidateTree()
1831{
1832        stack<BspNode *> nodeStack;
1833
1834        if (!mRoot)
1835                return;
1836
1837        nodeStack.push(mRoot);
1838       
1839        mBspStats.invalidLeaves = 0;
1840        while (!nodeStack.empty())
1841        {
1842                BspNode *node = nodeStack.top();
1843                nodeStack.pop();
1844               
1845                if (node->IsLeaf())
1846                {
1847                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
1848
1849                        if (!leaf->GetViewCell()->GetValid())
1850                                ++ mBspStats.invalidLeaves;
1851
1852                        // validity flags don't match => repair
1853                        if (leaf->GetViewCell()->GetValid() != leaf->TreeValid())
1854                        {
1855                                leaf->SetTreeValid(leaf->GetViewCell()->GetValid());
1856                                PropagateUpValidity(leaf);
1857                        }
1858                }
1859                else
1860                {
1861                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1862               
1863                        nodeStack.push(interior->GetFront());
1864                        nodeStack.push(interior->GetBack());
1865                }
1866        }
1867
1868        Debug << "invalid leaves: " << mBspStats.invalidLeaves << endl;
1869}
1870
1871
1872
1873void VspBspTree::CollectViewCells(BspNode *root,
1874                                                                  bool onlyValid,
1875                                                                  ViewCellContainer &viewCells,
1876                                                                  bool onlyUnmailed) const
1877{
1878        stack<BspNode *> nodeStack;
1879
1880        if (!root)
1881                return;
1882
1883        nodeStack.push(root);
1884       
1885        while (!nodeStack.empty())
1886        {
1887                BspNode *node = nodeStack.top();
1888                nodeStack.pop();
1889               
1890                if (node->IsLeaf())
1891                {
1892                        if (!onlyValid || node->TreeValid())
1893                        {
1894                                ViewCell *viewCell =
1895                                        mViewCellsTree->GetActiveViewCell(dynamic_cast<BspLeaf *>(node)->GetViewCell());
1896                                               
1897                                if (!onlyUnmailed || !viewCell->Mailed())
1898                                {
1899                                        viewCell->Mail();
1900                                        viewCells.push_back(viewCell);
1901                                }
1902                        }
1903                }
1904                else
1905                {
1906                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1907               
1908                        nodeStack.push(interior->GetFront());
1909                        nodeStack.push(interior->GetBack());
1910                }
1911        }
1912
1913}
1914
1915
1916float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1917{
1918        float len = 0;
1919
1920        RayInfoContainer::const_iterator it, it_end = rays.end();
1921
1922        for (it = rays.begin(); it != it_end; ++ it)
1923                len += (*it).SegmentLength();
1924
1925        return len;
1926}
1927
1928
1929int VspBspTree::SplitRays(const Plane3 &plane,
1930                                                  RayInfoContainer &rays,
1931                                                  RayInfoContainer &frontRays,
1932                                                  RayInfoContainer &backRays)
1933{
1934        int splits = 0;
1935
1936        RayInfoContainer::const_iterator it, it_end = rays.end();
1937
1938        for (it = rays.begin(); it != it_end; ++ it)
1939        {
1940                RayInfo bRay = *it;
1941               
1942                VssRay *ray = bRay.mRay;
1943                float t;
1944
1945                // get classification and receive new t
1946                const int cf = bRay.ComputeRayIntersection(plane, t);
1947
1948                switch (cf)
1949                {
1950                case -1:
1951                        backRays.push_back(bRay);
1952                        break;
1953                case 1:
1954                        frontRays.push_back(bRay);
1955                        break;
1956                case 0:
1957                        {
1958                                //-- split ray
1959                                //-- test if start point behind or in front of plane
1960                                const int side = plane.Side(bRay.ExtrapOrigin());
1961
1962                                if (side <= 0)
1963                                {
1964                                        backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1965                                        frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1966                                }
1967                                else
1968                                {
1969                                        frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1970                                        backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1971                                }
1972                        }
1973                        break;
1974                default:
1975                        Debug << "Should not come here" << endl;
1976                        break;
1977                }
1978        }
1979
1980        return splits;
1981}
1982
1983
1984void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
1985{
1986        BspNode *lastNode;
1987
1988        do
1989        {
1990                lastNode = n;
1991
1992                // want to get planes defining geometry of this node => don't take
1993                // split plane of node itself
1994                n = n->GetParent();
1995
1996                if (n)
1997                {
1998                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
1999                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
2000
2001            if (interior->GetFront() != lastNode)
2002                                halfSpace.ReverseOrientation();
2003
2004                        halfSpaces.push_back(halfSpace);
2005                }
2006        }
2007        while (n);
2008}
2009
2010
2011void VspBspTree::ConstructGeometry(BspNode *n,
2012                                                                   BspNodeGeometry &geom) const
2013{
2014        vector<Plane3> halfSpaces;
2015        ExtractHalfSpaces(n, halfSpaces);
2016
2017        PolygonContainer candidatePolys;
2018
2019        // bounded planes are added to the polygons (reverse polygons
2020        // as they have to be outfacing
2021        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
2022        {
2023                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
2024
2025                if (p->Valid(mEpsilon))
2026                {
2027                        candidatePolys.push_back(p->CreateReversePolygon());
2028                        DEL_PTR(p);
2029                }
2030        }
2031
2032        // add faces of bounding box (also could be faces of the cell)
2033        for (int i = 0; i < 6; ++ i)
2034        {
2035                VertexContainer vertices;
2036
2037                for (int j = 0; j < 4; ++ j)
2038                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
2039
2040                candidatePolys.push_back(new Polygon3(vertices));
2041        }
2042
2043        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
2044        {
2045                // polygon is split by all other planes
2046                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
2047                {
2048                        if (i == j) // polygon and plane are coincident
2049                                continue;
2050
2051                        VertexContainer splitPts;
2052                        Polygon3 *frontPoly, *backPoly;
2053
2054                        const int cf =
2055                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
2056                                                                                                 mEpsilon);
2057
2058                        switch (cf)
2059                        {
2060                                case Polygon3::SPLIT:
2061                                        frontPoly = new Polygon3();
2062                                        backPoly = new Polygon3();
2063
2064                                        candidatePolys[i]->Split(halfSpaces[j],
2065                                                                                         *frontPoly,
2066                                                                                         *backPoly,
2067                                                                                         mEpsilon);
2068
2069                                        DEL_PTR(candidatePolys[i]);
2070
2071                                        if (frontPoly->Valid(mEpsilon))
2072                                                candidatePolys[i] = frontPoly;
2073                                        else
2074                                                DEL_PTR(frontPoly);
2075
2076                                        DEL_PTR(backPoly);
2077                                        break;
2078                                case Polygon3::BACK_SIDE:
2079                                        DEL_PTR(candidatePolys[i]);
2080                                        break;
2081                                // just take polygon as it is
2082                                case Polygon3::FRONT_SIDE:
2083                                case Polygon3::COINCIDENT:
2084                                default:
2085                                        break;
2086                        }
2087                }
2088
2089                if (candidatePolys[i])
2090                        geom.mPolys.push_back(candidatePolys[i]);
2091        }
2092}
2093
2094
2095void VspBspTree::ConstructGeometry(ViewCell *vc,
2096                                                                   BspNodeGeometry &vcGeom) const
2097{
2098        ViewCellContainer leaves;
2099       
2100        mViewCellsTree->CollectLeaves(vc, leaves);
2101
2102        ViewCellContainer::const_iterator it, it_end = leaves.end();
2103
2104        for (it = leaves.begin(); it != it_end; ++ it)
2105        {
2106                BspLeaf *l = dynamic_cast<BspViewCell *>(*it)->mLeaf;
2107               
2108                ConstructGeometry(l, vcGeom);
2109        }
2110}
2111
2112
2113typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2114
2115
2116int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2117                                                          const bool onlyUnmailed) const
2118{
2119        stack<bspNodePair> nodeStack;
2120       
2121        BspNodeGeometry nodeGeom;
2122        ConstructGeometry(n, nodeGeom);
2123       
2124        // split planes from the root to this node
2125        // needed to verify that we found neighbor leaf
2126        // TODO: really needed?
2127        vector<Plane3> halfSpaces;
2128        ExtractHalfSpaces(n, halfSpaces);
2129
2130
2131        BspNodeGeometry *rgeom = new BspNodeGeometry();
2132        ConstructGeometry(mRoot, *rgeom);
2133
2134        nodeStack.push(bspNodePair(mRoot, rgeom));
2135
2136        while (!nodeStack.empty())
2137        {
2138                BspNode *node = nodeStack.top().first;
2139                BspNodeGeometry *geom = nodeStack.top().second;
2140       
2141                nodeStack.pop();
2142
2143                if (node->IsLeaf())
2144                {
2145                        // test if this leaf is in valid view space
2146                        if (node->TreeValid() &&
2147                                (node != n) &&
2148                                (!onlyUnmailed || !node->Mailed()))
2149                        {
2150                                bool isAdjacent = true;
2151
2152                                if (1)
2153                                {
2154                                        // test all planes of current node if still adjacent
2155                                        for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
2156                                        {
2157                                                const int cf =
2158                                                        Polygon3::ClassifyPlane(geom->mPolys,
2159                                                                                                        halfSpaces[i],
2160                                                                                                        mEpsilon);
2161
2162                                                if (cf == Polygon3::BACK_SIDE)
2163                                                {
2164                                                        isAdjacent = false;
2165                                                }
2166                                        }
2167                                }
2168                                else
2169                                {
2170                                        // TODO: why is this wrong??
2171                                        // test all planes of current node if still adjacent
2172                                        for (int i = 0; (i < (int)nodeGeom.mPolys.size()) && isAdjacent; ++ i)
2173                                        {
2174                                                Polygon3 *poly = nodeGeom.mPolys[i];
2175
2176                                                const int cf =
2177                                                        Polygon3::ClassifyPlane(geom->mPolys,
2178                                                                                                        poly->GetSupportingPlane(),
2179                                                                                                        mEpsilon);
2180
2181                                                if (cf == Polygon3::BACK_SIDE)
2182                                                {
2183                                                        isAdjacent = false;
2184                                                }
2185                                        }
2186                                }
2187                                // neighbor was found
2188                                if (isAdjacent)
2189                                {       
2190                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2191                                }
2192                        }
2193                }
2194                else
2195                {
2196                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2197
2198                        const int cf = Polygon3::ClassifyPlane(nodeGeom.mPolys,
2199                                                                                                   interior->GetPlane(),
2200                                                                                                   mEpsilon);
2201                       
2202                        BspNode *front = interior->GetFront();
2203                        BspNode *back = interior->GetBack();
2204           
2205                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2206                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2207
2208                        geom->SplitGeometry(*fGeom,
2209                                                                *bGeom,
2210                                                                interior->GetPlane(),
2211                                                                mBox,
2212                                                                mEpsilon);
2213               
2214                        if (cf == Polygon3::FRONT_SIDE)
2215                        {
2216                                nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2217                                DEL_PTR(bGeom);
2218                        }
2219                        else
2220                        {
2221                                if (cf == Polygon3::BACK_SIDE)
2222                                {
2223                                        nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2224                                        DEL_PTR(fGeom);
2225                                }
2226                                else
2227                                {       // random decision
2228                                        nodeStack.push(bspNodePair(front, fGeom));
2229                                        nodeStack.push(bspNodePair(back, bGeom));
2230                                }
2231                        }
2232                }
2233       
2234                DEL_PTR(geom);
2235        }
2236
2237        return (int)neighbors.size();
2238}
2239
2240
2241
2242int VspBspTree::FindApproximateNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
2243                                                                                 const bool onlyUnmailed) const
2244{
2245        stack<bspNodePair> nodeStack;
2246       
2247        BspNodeGeometry nodeGeom;
2248        ConstructGeometry(n, nodeGeom);
2249       
2250        // split planes from the root to this node
2251        // needed to verify that we found neighbor leaf
2252        // TODO: really needed?
2253        vector<Plane3> halfSpaces;
2254        ExtractHalfSpaces(n, halfSpaces);
2255
2256
2257        BspNodeGeometry *rgeom = new BspNodeGeometry();
2258        ConstructGeometry(mRoot, *rgeom);
2259
2260        nodeStack.push(bspNodePair(mRoot, rgeom));
2261
2262        while (!nodeStack.empty())
2263        {
2264                BspNode *node = nodeStack.top().first;
2265                BspNodeGeometry *geom = nodeStack.top().second;
2266       
2267                nodeStack.pop();
2268
2269                if (node->IsLeaf())
2270                {
2271                        // test if this leaf is in valid view space
2272                        if (node->TreeValid() &&
2273                                (node != n) &&
2274                                (!onlyUnmailed || !node->Mailed()))
2275                        {
2276                                bool isAdjacent = true;
2277
2278                                // neighbor was found
2279                                if (isAdjacent)
2280                                {       
2281                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
2282                                }
2283                        }
2284                }
2285                else
2286                {
2287                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2288
2289                        const int cf = Polygon3::ClassifyPlane(nodeGeom.mPolys,
2290                                                                                                   interior->GetPlane(),
2291                                                                                                   mEpsilon);
2292                       
2293                        BspNode *front = interior->GetFront();
2294                        BspNode *back = interior->GetBack();
2295           
2296                        BspNodeGeometry *fGeom = new BspNodeGeometry();
2297                        BspNodeGeometry *bGeom = new BspNodeGeometry();
2298
2299                        geom->SplitGeometry(*fGeom,
2300                                                                *bGeom,
2301                                                                interior->GetPlane(),
2302                                                                mBox,
2303                                                                mEpsilon);
2304               
2305                        if (cf == Polygon3::FRONT_SIDE)
2306                        {
2307                                nodeStack.push(bspNodePair(interior->GetFront(), fGeom));
2308                                DEL_PTR(bGeom);
2309                        }
2310                        else
2311                        {
2312                                if (cf == Polygon3::BACK_SIDE)
2313                                {
2314                                        nodeStack.push(bspNodePair(interior->GetBack(), bGeom));
2315                                        DEL_PTR(fGeom);
2316                                }
2317                                else
2318                                {       // random decision
2319                                        nodeStack.push(bspNodePair(front, fGeom));
2320                                        nodeStack.push(bspNodePair(back, bGeom));
2321                                }
2322                        }
2323                }
2324       
2325                DEL_PTR(geom);
2326        }
2327
2328        return (int)neighbors.size();
2329}
2330
2331
2332
2333BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
2334{
2335    stack<BspNode *> nodeStack;
2336        nodeStack.push(mRoot);
2337
2338        int mask = rand();
2339
2340        while (!nodeStack.empty())
2341        {
2342                BspNode *node = nodeStack.top();
2343                nodeStack.pop();
2344
2345                if (node->IsLeaf())
2346                {
2347                        return dynamic_cast<BspLeaf *>(node);
2348                }
2349                else
2350                {
2351                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2352                        BspNode *next;
2353                        BspNodeGeometry geom;
2354
2355                        // todo: not very efficient: constructs full cell everytime
2356                        ConstructGeometry(interior, geom);
2357
2358                        const int cf =
2359                                Polygon3::ClassifyPlane(geom.mPolys, halfspace, mEpsilon);
2360
2361                        if (cf == Polygon3::BACK_SIDE)
2362                                next = interior->GetFront();
2363                        else
2364                                if (cf == Polygon3::FRONT_SIDE)
2365                                        next = interior->GetFront();
2366                        else
2367                        {
2368                                // random decision
2369                                if (mask & 1)
2370                                        next = interior->GetBack();
2371                                else
2372                                        next = interior->GetFront();
2373                                mask = mask >> 1;
2374                        }
2375
2376                        nodeStack.push(next);
2377                }
2378        }
2379
2380        return NULL;
2381}
2382
2383BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
2384{
2385        stack<BspNode *> nodeStack;
2386
2387        nodeStack.push(mRoot);
2388
2389        int mask = rand();
2390
2391        while (!nodeStack.empty())
2392        {
2393                BspNode *node = nodeStack.top();
2394                nodeStack.pop();
2395
2396                if (node->IsLeaf())
2397                {
2398                        if ( (!onlyUnmailed || !node->Mailed()) )
2399                                return dynamic_cast<BspLeaf *>(node);
2400                }
2401                else
2402                {
2403                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2404
2405                        // random decision
2406                        if (mask & 1)
2407                                nodeStack.push(interior->GetBack());
2408                        else
2409                                nodeStack.push(interior->GetFront());
2410
2411                        mask = mask >> 1;
2412                }
2413        }
2414
2415        return NULL;
2416}
2417
2418int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
2419{
2420        int pvsSize = 0;
2421
2422        RayInfoContainer::const_iterator rit, rit_end = rays.end();
2423
2424        Intersectable::NewMail();
2425
2426        for (rit = rays.begin(); rit != rays.end(); ++ rit)
2427        {
2428                VssRay *ray = (*rit).mRay;
2429
2430                if (ray->mOriginObject)
2431                {
2432                        if (!ray->mOriginObject->Mailed())
2433                        {
2434                                ray->mOriginObject->Mail();
2435                                ++ pvsSize;
2436                        }
2437                }
2438                if (ray->mTerminationObject)
2439                {
2440                        if (!ray->mTerminationObject->Mailed())
2441                        {
2442                                ray->mTerminationObject->Mail();
2443                                ++ pvsSize;
2444                        }
2445                }
2446        }
2447
2448        return pvsSize;
2449}
2450
2451float VspBspTree::GetEpsilon() const
2452{
2453        return mEpsilon;
2454}
2455
2456
2457int VspBspTree::SplitPolygons(const Plane3 &plane,
2458                                                          PolygonContainer &polys,
2459                                                          PolygonContainer &frontPolys,
2460                                                          PolygonContainer &backPolys,
2461                                                          PolygonContainer &coincident) const
2462{
2463        int splits = 0;
2464
2465        PolygonContainer::const_iterator it, it_end = polys.end();
2466
2467        for (it = polys.begin(); it != polys.end(); ++ it)     
2468        {
2469                Polygon3 *poly = *it;
2470
2471                // classify polygon
2472                const int cf = poly->ClassifyPlane(plane, mEpsilon);
2473
2474                switch (cf)
2475                {
2476                        case Polygon3::COINCIDENT:
2477                                coincident.push_back(poly);
2478                                break;
2479                        case Polygon3::FRONT_SIDE:
2480                                frontPolys.push_back(poly);
2481                                break;
2482                        case Polygon3::BACK_SIDE:
2483                                backPolys.push_back(poly);
2484                                break;
2485                        case Polygon3::SPLIT:
2486                                backPolys.push_back(poly);
2487                                frontPolys.push_back(poly);
2488                                ++ splits;
2489                                break;
2490                        default:
2491                Debug << "SHOULD NEVER COME HERE\n";
2492                                break;
2493                }
2494        }
2495
2496        return splits;
2497}
2498
2499
2500int VspBspTree::CastLineSegment(const Vector3 &origin,
2501                                                                const Vector3 &termination,
2502                                                                vector<ViewCell *> &viewcells)
2503{
2504        int hits = 0;
2505        stack<BspRayTraversalData> tQueue;
2506
2507        float mint = 0.0f, maxt = 1.0f;
2508
2509        Intersectable::NewMail();
2510        ViewCell::NewMail();
2511
2512        Vector3 entp = origin;
2513        Vector3 extp = termination;
2514
2515        BspNode *node = mRoot;
2516        BspNode *farChild = NULL;
2517
2518        float t;
2519        while (1)
2520        {
2521                if (!node->IsLeaf())
2522                {
2523                        BspInterior *in = dynamic_cast<BspInterior *>(node);
2524
2525                        Plane3 splitPlane = in->GetPlane();
2526                       
2527                        const int entSide = splitPlane.Side(entp);
2528                        const int extSide = splitPlane.Side(extp);
2529
2530                        if (entSide < 0)
2531                        {
2532                          node = in->GetBack();
2533                          // plane does not split ray => no far child
2534                          if (extSide <= 0)
2535                                continue;
2536                         
2537                          farChild = in->GetFront(); // plane splits ray
2538                        }
2539                        else if (entSide > 0)
2540                        {
2541                          node = in->GetFront();
2542
2543                          if (extSide >= 0) // plane does not split ray => no far child
2544                                continue;
2545
2546                                farChild = in->GetBack(); // plane splits ray
2547                        }
2548                        else // ray end point on plane
2549                        {       // NOTE: what to do if ray is coincident with plane?
2550                                if (extSide < 0)
2551                                        node = in->GetBack();
2552                                else
2553                                        node = in->GetFront();
2554                                                               
2555                                continue; // no far child
2556                        }
2557
2558                        // push data for far child
2559                        tQueue.push(BspRayTraversalData(farChild, extp));
2560
2561                        // find intersection of ray segment with plane
2562                        extp = splitPlane.FindIntersection(origin, extp, &t);
2563                }
2564                else
2565                {
2566                        // reached leaf => intersection with view cell
2567                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2568
2569                        ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
2570                        if (!viewCell->Mailed())
2571                        {
2572                                viewcells.push_back(viewCell);
2573                                viewCell->Mail();
2574                                ++ hits;
2575                        }
2576
2577                        //-- fetch the next far child from the stack
2578                        if (tQueue.empty())
2579                                break;
2580
2581                        entp = extp;
2582                       
2583                        BspRayTraversalData &s = tQueue.top();
2584
2585                        node = s.mNode;
2586                        extp = s.mExitPoint;
2587
2588                        tQueue.pop();
2589                }
2590        }
2591
2592        return hits;
2593}
2594
2595
2596
2597
2598int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2) const
2599{
2600        std::deque<BspNode *> path1;
2601        BspNode *p1 = n1;
2602
2603        // create path from node 1 to root
2604        while (p1)
2605        {
2606                if (p1 == n2) // second node on path
2607                        return (int)path1.size();
2608
2609                path1.push_front(p1);
2610                p1 = p1->GetParent();
2611        }
2612
2613        int depth = n2->GetDepth();
2614        int d = depth;
2615
2616        BspNode *p2 = n2;
2617
2618        // compare with same depth
2619        while (1)
2620        {
2621                if ((d < (int)path1.size()) && (p2 == path1[d]))
2622                        return (depth - d) + ((int)path1.size() - 1 - d);
2623
2624                -- d;
2625                p2 = p2->GetParent();
2626        }
2627
2628        return 0; // never come here
2629}
2630
2631
2632BspNode *VspBspTree::CollapseTree(BspNode *node, int &collapsed)
2633{
2634// TODO
2635#if VC_HISTORY
2636        if (node->IsLeaf())
2637                return node;
2638
2639        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2640
2641        BspNode *front = CollapseTree(interior->GetFront(), collapsed);
2642        BspNode *back = CollapseTree(interior->GetBack(), collapsed);
2643
2644        if (front->IsLeaf() && back->IsLeaf())
2645        {
2646                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
2647                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
2648
2649                //-- collapse tree
2650                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
2651                {
2652                        BspViewCell *vc = frontLeaf->GetViewCell();
2653
2654                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
2655                        leaf->SetTreeValid(frontLeaf->TreeValid());
2656
2657                        // replace a link from node's parent
2658                        if (leaf->GetParent())
2659                                leaf->GetParent()->ReplaceChildLink(node, leaf);
2660                        else
2661                                mRoot = leaf;
2662
2663                        ++ collapsed;
2664                        delete interior;
2665
2666                        return leaf;
2667                }
2668        }
2669#endif
2670        return node;
2671}
2672
2673
2674int VspBspTree::CollapseTree()
2675{
2676        int collapsed = 0;
2677        //TODO
2678#if VC_HISTORY
2679        (void)CollapseTree(mRoot, collapsed);
2680
2681        // revalidate leaves
2682        RepairViewCellsLeafLists();
2683#endif
2684        return collapsed;
2685}
2686
2687
2688void VspBspTree::RepairViewCellsLeafLists()
2689{
2690// TODO
2691#if VC_HISTORY
2692        // list not valid anymore => clear
2693        stack<BspNode *> nodeStack;
2694        nodeStack.push(mRoot);
2695
2696        ViewCell::NewMail();
2697
2698        while (!nodeStack.empty())
2699        {
2700                BspNode *node = nodeStack.top();
2701                nodeStack.pop();
2702
2703                if (node->IsLeaf())
2704                {
2705                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2706
2707                        BspViewCell *viewCell = leaf->GetViewCell();
2708
2709                        if (!viewCell->Mailed())
2710                        {
2711                                viewCell->mLeaves.clear();
2712                                viewCell->Mail();
2713                        }
2714       
2715                        viewCell->mLeaves.push_back(leaf);
2716
2717                }
2718                else
2719                {
2720                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2721
2722                        nodeStack.push(interior->GetFront());
2723                        nodeStack.push(interior->GetBack());
2724                }
2725        }
2726// TODO
2727#endif
2728}
2729
2730
2731typedef pair<BspNode *, BspNodeGeometry *> bspNodePair;
2732
2733
2734int VspBspTree::CastBeam(Beam &beam)
2735{
2736    stack<bspNodePair> nodeStack;
2737        BspNodeGeometry *rgeom = new BspNodeGeometry();
2738        ConstructGeometry(mRoot, *rgeom);
2739
2740        nodeStack.push(bspNodePair(mRoot, rgeom));
2741 
2742        ViewCell::NewMail();
2743
2744        while (!nodeStack.empty())
2745        {
2746                BspNode *node = nodeStack.top().first;
2747                BspNodeGeometry *geom = nodeStack.top().second;
2748                nodeStack.pop();
2749               
2750                AxisAlignedBox3 box;
2751                box.Initialize();
2752                geom->IncludeInBox(box);
2753
2754                const int side = beam.ComputeIntersection(box);
2755               
2756                switch (side)
2757                {
2758                case -1:
2759                        CollectViewCells(node, true, beam.mViewCells, true);
2760                        break;
2761                case 0:
2762                       
2763                        if (node->IsLeaf())
2764                        {
2765                                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2766                       
2767                                if (!leaf->GetViewCell()->Mailed() && leaf->TreeValid())
2768                                {
2769                                        leaf->GetViewCell()->Mail();
2770                                        beam.mViewCells.push_back(leaf->GetViewCell());
2771                                }
2772                        }
2773                        else
2774                        {
2775                                BspInterior *interior = dynamic_cast<BspInterior *>(node);
2776                       
2777                                BspNode *first = interior->GetFront();
2778                                BspNode *second = interior->GetBack();
2779           
2780                                BspNodeGeometry *firstGeom = new BspNodeGeometry();
2781                                BspNodeGeometry *secondGeom = new BspNodeGeometry();
2782
2783                                geom->SplitGeometry(*firstGeom,
2784                                                                        *secondGeom,
2785                                                                        interior->GetPlane(),
2786                                                                        mBox,
2787                                                                        mEpsilon);
2788
2789                                // decide on the order of the nodes
2790                                if (DotProd(beam.mPlanes[0].mNormal,
2791                                        interior->GetPlane().mNormal) > 0)
2792                                {
2793                                        swap(first, second);
2794                                        swap(firstGeom, secondGeom);
2795                                }
2796
2797                                nodeStack.push(bspNodePair(first, firstGeom));
2798                                nodeStack.push(bspNodePair(second, secondGeom));
2799                        }
2800                       
2801                        break;
2802                default:
2803                        // default: cull
2804                        break;
2805                }
2806               
2807                DEL_PTR(geom);
2808               
2809        }
2810
2811        return (int)beam.mViewCells.size();
2812}
2813
2814
2815void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
2816{
2817        mViewCellsManager = vcm;
2818}
2819
2820
2821int VspBspTree::CollectMergeCandidates(const vector<BspLeaf *> leaves,
2822                                                                           vector<MergeCandidate> &candidates)
2823{
2824        BspLeaf::NewMail();
2825       
2826        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2827
2828        int numCandidates = 0;
2829
2830        // find merge candidates and push them into queue
2831        for (it = leaves.begin(); it != it_end; ++ it)
2832        {
2833                BspLeaf *leaf = *it;
2834               
2835                // the same leaves must not be part of two merge candidates
2836                leaf->Mail();
2837                vector<BspLeaf *> neighbors;
2838                FindNeighbors(leaf, neighbors, true);
2839                //FindApproximateNeighbors(leaf, neighbors, true);
2840                vector<BspLeaf *>::const_iterator nit, nit_end = neighbors.end();
2841
2842                // TODO: test if at least one ray goes from one leaf to the other
2843                for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2844                {
2845                        if ((*nit)->GetViewCell() != leaf->GetViewCell())
2846                        {
2847                                MergeCandidate mc(leaf->GetViewCell(), (*nit)->GetViewCell());
2848                                candidates.push_back(mc);
2849
2850                                ++ numCandidates;
2851                                if ((numCandidates % 1000) == 0)
2852                                {
2853                                        cout << "collected " << numCandidates << " merge candidates" << endl;
2854                                }
2855                        }
2856                }
2857        }
2858
2859        Debug << "merge queue: " << (int)candidates.size() << endl;
2860        Debug << "leaves in queue: " << numCandidates << endl;
2861       
2862
2863        return (int)leaves.size();
2864}
2865
2866
2867int VspBspTree::CollectMergeCandidates(const VssRayContainer &rays,
2868                                                                           vector<MergeCandidate> &candidates)
2869{
2870        ViewCell::NewMail();
2871        long startTime = GetTime();
2872       
2873        map<BspLeaf *, vector<BspLeaf*> > neighborMap;
2874        ViewCellContainer::const_iterator iit;
2875
2876        int numLeaves = 0;
2877       
2878        BspLeaf::NewMail();
2879
2880        for (int i = 0; i < (int)rays.size(); ++ i)
2881        { 
2882                VssRay *ray = rays[i];
2883       
2884                // traverse leaves stored in the rays and compare and
2885                // merge consecutive leaves (i.e., the neighbors in the tree)
2886                if (ray->mViewCells.size() < 2)
2887                        continue;
2888//TODO viewcellhierarchy
2889                iit = ray->mViewCells.begin();
2890                BspViewCell *bspVc = dynamic_cast<BspViewCell *>(*(iit ++));
2891                BspLeaf *leaf = bspVc->mLeaf;
2892               
2893                // traverse intersections
2894                // consecutive leaves are neighbors => add them to queue
2895                for (; iit != ray->mViewCells.end(); ++ iit)
2896                {
2897                        // next pair
2898                        BspLeaf *prevLeaf = leaf;
2899                        bspVc = dynamic_cast<BspViewCell *>(*iit);
2900            leaf = bspVc->mLeaf;
2901
2902                        // view space not valid or same view cell
2903                        if (!leaf->TreeValid() || !prevLeaf->TreeValid() ||
2904                                (leaf->GetViewCell() == prevLeaf->GetViewCell()))
2905                                continue;
2906
2907                vector<BspLeaf *> &neighbors = neighborMap[leaf];
2908                       
2909                        bool found = false;
2910
2911                        // both leaves inserted in queue already =>
2912                        // look if double pair already exists
2913                        if (leaf->Mailed() && prevLeaf->Mailed())
2914                        {
2915                                vector<BspLeaf *>::const_iterator it, it_end = neighbors.end();
2916                               
2917                for (it = neighbors.begin(); !found && (it != it_end); ++ it)
2918                                        if (*it == prevLeaf)
2919                                                found = true; // already in queue
2920                        }
2921               
2922                        if (!found)
2923                        {
2924                                // this pair is not in map yet
2925                                // => insert into the neighbor map and the queue
2926                                neighbors.push_back(prevLeaf);
2927                                neighborMap[prevLeaf].push_back(leaf);
2928
2929                                leaf->Mail();
2930                                prevLeaf->Mail();
2931               
2932                                MergeCandidate mc(leaf->GetViewCell(), prevLeaf->GetViewCell());
2933                               
2934                                candidates.push_back(mc);
2935
2936                                if (((int)candidates.size() % 1000) == 0)
2937                                {
2938                                        cout << "collected " << (int)candidates.size() << " merge candidates" << endl;
2939                                }
2940                        }
2941        }
2942        }
2943
2944        Debug << "neighbormap size: " << (int)neighborMap.size() << endl;
2945        Debug << "merge queue: " << (int)candidates.size() << endl;
2946        Debug << "leaves in queue: " << numLeaves << endl;
2947
2948
2949        //-- collect the leaves which haven't been found by ray casting
2950        if (0)
2951        {
2952                cout << "finding additional merge candidates using geometry" << endl;
2953                vector<BspLeaf *> leaves;
2954                CollectLeaves(leaves, true);
2955                Debug << "found " << (int)leaves.size() << " new leaves" << endl << endl;
2956                CollectMergeCandidates(leaves, candidates);
2957        }
2958
2959        return numLeaves;
2960}
2961
2962
2963
2964
2965ViewCell *VspBspTree::GetViewCell(const Vector3 &point)
2966{
2967  if (mRoot == NULL)
2968        return NULL;
2969 
2970  stack<BspNode *> nodeStack;
2971  nodeStack.push(mRoot);
2972 
2973  ViewCell *viewcell = NULL;
2974 
2975  while (!nodeStack.empty())  {
2976        BspNode *node = nodeStack.top();
2977        nodeStack.pop();
2978       
2979        if (node->IsLeaf()) {
2980          viewcell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
2981          break;
2982        } else {
2983         
2984          BspInterior *interior = dynamic_cast<BspInterior *>(node);
2985               
2986          // random decision
2987          if (interior->GetPlane().Side(point) < 0)
2988                nodeStack.push(interior->GetBack());
2989          else
2990                nodeStack.push(interior->GetFront());
2991        }
2992  }
2993 
2994  return viewcell;
2995}
2996
2997
2998bool VspBspTree::ViewPointValid(const Vector3 &viewPoint) const
2999{
3000        BspNode *node = mRoot;
3001
3002        while (1)
3003        {
3004                // early exit
3005                if (node->TreeValid())
3006                        return true;
3007
3008                if (node->IsLeaf())
3009                        return false;
3010                       
3011                BspInterior *in = dynamic_cast<BspInterior *>(node);
3012                                       
3013                if (in->GetPlane().Side(viewPoint) <= 0)
3014                {
3015                        node = in->GetBack();
3016                }
3017                else
3018                {
3019                        node = in->GetFront();
3020                }
3021        }
3022
3023        // should never come here
3024        return false;
3025}
3026
3027
3028void VspBspTree::PropagateUpValidity(BspNode *node)
3029{
3030        const bool isValid = node->TreeValid();
3031
3032        // propagative up invalid flag until only invalid nodes exist over this node
3033        if (!isValid)
3034        {
3035                while (!node->IsRoot() && node->GetParent()->TreeValid())
3036                {
3037                        node = node->GetParent();
3038                        node->SetTreeValid(false);
3039                }
3040        }
3041        else
3042        {
3043                // propagative up valid flag until one of the subtrees is invalid
3044                while (!node->IsRoot() && !node->TreeValid())
3045                {
3046            node = node->GetParent();
3047                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
3048                       
3049                        // the parent is valid iff both leaves are valid
3050                        node->SetTreeValid(interior->GetBack()->TreeValid() &&
3051                                                           interior->GetFront()->TreeValid());
3052                }
3053        }
3054}
3055
3056
3057bool VspBspTree::Export(ofstream &stream)
3058{
3059        ExportNode(mRoot, stream);
3060
3061        return true;
3062}
3063
3064
3065void VspBspTree::ExportNode(BspNode *node, ofstream &stream)
3066{
3067        if (node->IsLeaf())
3068        {
3069                BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
3070                ViewCell *viewCell = mViewCellsTree->GetActiveViewCell(leaf->GetViewCell());
3071
3072                int id = -1;
3073                if (viewCell != mOutOfBoundsCell)
3074                        id = viewCell->GetId();
3075
3076                stream << "<Leaf viewCellId=\"" << id << "\" />" << endl;
3077        }
3078        else
3079        {
3080                BspInterior *interior = dynamic_cast<BspInterior *>(node);
3081       
3082                Plane3 plane = interior->GetPlane();
3083                stream << "<Interior plane=\"" << plane.mNormal.x << " "
3084                           << plane.mNormal.y << " " << plane.mNormal.z << " "
3085                           << plane.mD << "\">" << endl;
3086
3087                ExportNode(interior->GetBack(), stream);
3088                ExportNode(interior->GetFront(), stream);
3089
3090                stream << "</Interior>" << endl;
3091        }
3092}
Note: See TracBrowser for help on using the repository browser.