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

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