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

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