source: GTP/trunk/Lib/Vis/Preprocessing/src/VspBspTree.cpp @ 1160

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