source: GTP/trunk/Lib/Vis/Preprocessing/src/ViewCellBsp.cpp @ 1002

Revision 1002, 81.4 KB checked in by mattausch, 18 years ago (diff)

debug run: fixing memory holes

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