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

Revision 482, 53.5 KB checked in by mattausch, 19 years ago (diff)

added visualizations

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"
[463]18
[478]19
[463]20//-- static members
[482]21/** Evaluates split plane classification with respect to the plane's
[463]22        contribution for a minimum number of ray splits.
23*/
24const float VspBspTree::sLeastRaySplitsTable[] = {0, 0, 1, 1, 0};
[482]25/** Evaluates split plane classification with respect to the plane's
[463]26        contribution for balanced rays.
27*/
28const float VspBspTree::sBalancedRaysTable[] = {1, -1, 0, 0, 0};
29
30
[482]31int VspBspTree::sFrontId = 0;
[463]32int VspBspTree::sBackId = 0;
33int VspBspTree::sFrontAndBackId = 0;
34
[478]35float BspMergeCandidate::sOverallCost = Limits::Small;
[463]36
37/****************************************************************/
38/*                  class VspBspTree implementation             */
39/****************************************************************/
40
[482]41VspBspTree::VspBspTree():
[463]42mRoot(NULL),
[472]43mPvsUseArea(true),
[478]44mCostNormalizer(Limits::Small),
45mViewCellsManager(NULL),
[482]46mStoreRays(true),
47mOnlyDrivingAxis(false)
[463]48{
49        mRootCell = new BspViewCell();
50
51        Randomize(); // initialise random generator for heuristics
52
53        //-- termination criteria for autopartition
54        environment->GetIntValue("VspBspTree.Termination.maxDepth", mTermMaxDepth);
55        environment->GetIntValue("VspBspTree.Termination.minPvs", mTermMinPvs);
56        environment->GetIntValue("VspBspTree.Termination.minRays", mTermMinRays);
[482]57        environment->GetFloatValue("VspBspTree.Termination.minArea", mTermMinArea);
[463]58        environment->GetFloatValue("VspBspTree.Termination.maxRayContribution", mTermMaxRayContribution);
59        environment->GetFloatValue("VspBspTree.Termination.minAccRayLenght", mTermMinAccRayLength);
[472]60        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
61        environment->GetIntValue("VspBspTree.Termination.missTolerance", mTermMissTolerance);
[463]62
63        //-- factors for bsp tree split plane heuristics
64        environment->GetFloatValue("VspBspTree.Factor.balancedRays", mBalancedRaysFactor);
65        environment->GetFloatValue("VspBspTree.Factor.pvs", mPvsFactor);
66        environment->GetFloatValue("VspBspTree.Termination.ct_div_ci", mCtDivCi);
67
[482]68        //-- max cost ratio for early tree termination
[472]69        environment->GetFloatValue("VspBspTree.Termination.maxCostRatio", mTermMaxCostRatio);
[482]70
[463]71        //-- partition criteria
72        environment->GetIntValue("VspBspTree.maxPolyCandidates", mMaxPolyCandidates);
73        environment->GetIntValue("VspBspTree.maxRayCandidates", mMaxRayCandidates);
74        environment->GetIntValue("VspBspTree.splitPlaneStrategy", mSplitPlaneStrategy);
75
76        environment->GetFloatValue("VspBspTree.Construction.epsilon", mEpsilon);
77        environment->GetIntValue("VspBspTree.maxTests", mMaxTests);
78
[478]79        // maximum and minimum number of view cells
80        environment->GetIntValue("VspBspTree.Termination.maxViewCells", mMaxViewCells);
81        environment->GetIntValue("VspBspTree.PostProcess.minViewCells", mMergeMinViewCells);
[480]82        environment->GetFloatValue("VspBspTree.PostProcess.maxCostRatio", mMergeMaxCostRatio);
[463]83
[478]84
85        //-- debug output
[473]86        Debug << "******* VSP BSP options ******** " << endl;
87    Debug << "max depth: " << mTermMaxDepth << endl;
88        Debug << "min PVS: " << mTermMinPvs << endl;
89        Debug << "min area: " << mTermMinArea << endl;
90        Debug << "min rays: " << mTermMinRays << endl;
91        Debug << "max ray contri: " << mTermMaxRayContribution << endl;
92        //Debug << "VSP BSP mininam accumulated ray lenght: ", mTermMinAccRayLength) << endl;
93        Debug << "max cost ratio: " << mTermMaxCostRatio << endl;
94        Debug << "miss tolerance: " << mTermMissTolerance << endl;
95        Debug << "max view cells: " << mMaxViewCells << endl;
96        Debug << "max polygon candidates: " << mMaxPolyCandidates << endl;
97        Debug << "max plane candidates: " << mMaxRayCandidates << endl;
[482]98
[463]99        Debug << "Split plane strategy: ";
100        if (mSplitPlaneStrategy & RANDOM_POLYGON)
[474]101        {
[463]102                Debug << "random polygon ";
[474]103        }
[463]104        if (mSplitPlaneStrategy & AXIS_ALIGNED)
[472]105        {
[463]106                Debug << "axis aligned ";
[472]107        }
[463]108        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
[472]109        {
[474]110                mCostNormalizer += mLeastRaySplitsFactor;
[463]111                Debug << "least ray splits ";
[472]112        }
[463]113        if (mSplitPlaneStrategy & BALANCED_RAYS)
[472]114        {
[474]115                mCostNormalizer += mBalancedRaysFactor;
[463]116                Debug << "balanced rays ";
[472]117        }
[463]118        if (mSplitPlaneStrategy & PVS)
[472]119        {
[474]120                mCostNormalizer += mPvsFactor;
[463]121                Debug << "pvs";
[472]122        }
[482]123
[480]124        mSplitCandidates = new vector<SortableEntry>;
[463]125
126        Debug << endl;
127}
128
129
[482]130const BspTreeStatistics &VspBspTree::GetStatistics() const
[463]131{
132        return mStat;
133}
134
135
136VspBspTree::~VspBspTree()
137{
138        DEL_PTR(mRoot);
139        DEL_PTR(mRootCell);
[480]140        DEL_PTR(mSplitCandidates);
[463]141}
142
[482]143int VspBspTree::AddMeshToPolygons(Mesh *mesh,
144                                                                  PolygonContainer &polys,
[463]145                                                                  MeshInstance *parent)
146{
147        FaceContainer::const_iterator fi;
[482]148
[463]149        // copy the face data to polygons
150        for (fi = mesh->mFaces.begin(); fi != mesh->mFaces.end(); ++ fi)
151        {
152                Polygon3 *poly = new Polygon3((*fi), mesh);
[482]153
[463]154                if (poly->Valid(mEpsilon))
155                {
156                        poly->mParent = parent; // set parent intersectable
157                        polys.push_back(poly);
158                }
159                else
160                        DEL_PTR(poly);
161        }
162        return (int)mesh->mFaces.size();
163}
164
[482]165int VspBspTree::AddToPolygonSoup(const ViewCellContainer &viewCells,
166                                                          PolygonContainer &polys,
[463]167                                                          int maxObjects)
168{
[482]169        int limit = (maxObjects > 0) ?
[463]170                Min((int)viewCells.size(), maxObjects) : (int)viewCells.size();
[482]171
[463]172        int polysSize = 0;
173
174        for (int i = 0; i < limit; ++ i)
175        {
176                if (viewCells[i]->GetMesh()) // copy the mesh data to polygons
177                {
178                        mBox.Include(viewCells[i]->GetBox()); // add to BSP tree aabb
[482]179                        polysSize +=
180                                AddMeshToPolygons(viewCells[i]->GetMesh(),
181                                                                  polys,
[463]182                                                                  viewCells[i]);
183                }
184        }
185
186        return polysSize;
187}
188
[482]189int VspBspTree::AddToPolygonSoup(const ObjectContainer &objects,
190                                                                 PolygonContainer &polys,
[463]191                                                                 int maxObjects)
192{
[482]193        int limit = (maxObjects > 0) ?
[463]194                Min((int)objects.size(), maxObjects) : (int)objects.size();
[482]195
[463]196        for (int i = 0; i < limit; ++i)
197        {
198                Intersectable *object = objects[i];//*it;
199                Mesh *mesh = NULL;
200
201                switch (object->Type()) // extract the meshes
202                {
203                case Intersectable::MESH_INSTANCE:
204                        mesh = dynamic_cast<MeshInstance *>(object)->GetMesh();
205                        break;
206                case Intersectable::VIEW_CELL:
207                        mesh = dynamic_cast<ViewCell *>(object)->GetMesh();
208                        break;
209                        // TODO: handle transformed mesh instances
210                default:
211                        Debug << "intersectable type not supported" << endl;
212                        break;
213                }
[482]214
[463]215        if (mesh) // copy the mesh data to polygons
216                {
217                        mBox.Include(object->GetBox()); // add to BSP tree aabb
218                        AddMeshToPolygons(mesh, polys, mRootCell);
219                }
220        }
221
222        return (int)polys.size();
223}
224
225void VspBspTree::Construct(const VssRayContainer &sampleRays)
226{
227    mStat.nodes = 1;
228        mBox.Initialize();      // initialise BSP tree bounding box
[482]229
[463]230        PolygonContainer polys;
231        RayInfoContainer *rays = new RayInfoContainer();
232
233        VssRayContainer::const_iterator rit, rit_end = sampleRays.end();
234
235        long startTime = GetTime();
236
[480]237        cout << "Extracting polygons from rays ... ";
[463]238
239        Intersectable::NewMail();
240
241        //-- extract polygons intersected by the rays
242        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
243        {
244                VssRay *ray = *rit;
[482]245
[463]246                if (ray->mTerminationObject && !ray->mTerminationObject->Mailed())
247                {
248                        ray->mTerminationObject->Mail();
249                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mTerminationObject);
250                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
251                }
252
253                if (ray->mOriginObject && !ray->mOriginObject->Mailed())
254                {
255                        ray->mOriginObject->Mail();
256                        MeshInstance *obj = dynamic_cast<MeshInstance *>(ray->mOriginObject);
257                        AddMeshToPolygons(obj->GetMesh(), polys, obj);
258                }
259        }
260
261        // compute bounding box
262        Polygon3::IncludeInBox(polys, mBox);
263
264        //-- store rays
265        for (rit = sampleRays.begin(); rit != rit_end; ++ rit)
266        {
267                VssRay *ray = *rit;
[482]268
[463]269                float minT, maxT;
270
271                // TODO: not very efficient to implictly cast between rays types ...
272                if (mBox.GetRaySegment(*ray, minT, maxT))
273                {
274                        float len = ray->Length();
[482]275
276                        if (!len)
[463]277                                len = Limits::Small;
[482]278
[463]279                        rays->push_back(RayInfo(ray, minT / len, maxT / len));
280                }
281        }
282
[474]283        mTermMinArea *= mBox.SurfaceArea(); // normalize
[463]284        mStat.polys = (int)polys.size();
285
[475]286        cout << "finished" << endl;
[463]287
[482]288        Debug << "\nPolygon extraction: " << (int)polys.size() << " polys extracted from "
[475]289                  << (int)sampleRays.size() << " rays in "
290                  << TimeDiff(startTime, GetTime())*1e-3 << " secs" << endl << endl;
291
[463]292        Construct(polys, rays);
293
294        // clean up polygons
295        CLEAR_CONTAINER(polys);
296}
297
298void VspBspTree::Construct(const PolygonContainer &polys, RayInfoContainer *rays)
299{
[472]300        VspBspTraversalStack tStack;
[463]301
302        mRoot = new BspLeaf();
303
304        // constrruct root node geometry
305        BspNodeGeometry *geom = new BspNodeGeometry();
306        ConstructGeometry(mRoot, *geom);
307
[482]308        VspBspTraversalData tData(mRoot,
309                                                          new PolygonContainer(polys),
[463]310                                                          0,
[482]311                                                          rays,
312                              ComputePvsSize(*rays),
313                                                          geom->GetArea(),
[463]314                                                          geom);
315
316        tStack.push(tData);
317
318        mStat.Start();
319        cout << "Contructing vsp bsp tree ... ";
320
321        long startTime = GetTime();
[482]322
[478]323        while (!tStack.empty())
[463]324        {
325                tData = tStack.top();
326
327            tStack.pop();
[478]328
[463]329                // subdivide leaf node
330                BspNode *r = Subdivide(tStack, tData);
331
332                if (r == mRoot)
[482]333                        Debug << "VSP BSP tree construction time spent at root: "
[475]334                                  << TimeDiff(startTime, GetTime())*1e-3 << "s" << endl << endl;
[463]335        }
336
337        cout << "finished\n";
338
339        mStat.Stop();
340}
341
[478]342bool VspBspTree::TerminationCriteriaMet(const VspBspTraversalData &data) const
[463]343{
[482]344        return
[463]345                (((int)data.mRays->size() <= mTermMinRays) ||
[473]346                 (data.mPvs <= mTermMinPvs)   ||
[463]347                 (data.mArea <= mTermMinArea) ||
[478]348                 (mStat.nodes / 2 + 1 >= mMaxViewCells) ||
[463]349                // (data.GetAvgRayContribution() >= mTermMaxRayContribution) ||
350                 (data.mDepth >= mTermMaxDepth));
351}
352
[482]353BspNode *VspBspTree::Subdivide(VspBspTraversalStack &tStack,
[463]354                                                           VspBspTraversalData &tData)
355{
[473]356        BspNode *newNode = tData.mNode;
357
[478]358        if (!TerminationCriteriaMet(tData))
[473]359        {
360                PolygonContainer coincident;
[482]361
[473]362                VspBspTraversalData tFrontData;
363                VspBspTraversalData tBackData;
364
365                // create new interior node and two leaf nodes
366                // or return leaf as it is (if maxCostRatio missed)
367                newNode = SubdivideNode(tData, tFrontData, tBackData, coincident);
368
369                if (!newNode->IsLeaf()) //-- continue subdivision
370                {
371                        // push the children on the stack
372                        tStack.push(tFrontData);
373                        tStack.push(tBackData);
374
375                        // delete old leaf node
[482]376                        DEL_PTR(tData.mNode);
[473]377                }
378        }
[482]379
[478]380        //-- terminate traversal and create new view cell
[473]381        if (newNode->IsLeaf())
[463]382        {
[473]383                BspLeaf *leaf = dynamic_cast<BspLeaf *>(newNode);
[482]384
[473]385                // create new view cell for this leaf
[463]386                BspViewCell *viewCell = new BspViewCell();
387                leaf->SetViewCell(viewCell);
[482]388
[478]389                if (mStoreRays)
390                {
391                        RayInfoContainer::const_iterator it, it_end = tData.mRays->end();
392                        for (it = tData.mRays->begin(); it != it_end; ++ it)
393                                leaf->mVssRays.push_back((*it).mRay);
394                }
395
[469]396                viewCell->mLeaves.push_back(leaf);
[478]397                viewCell->SetArea(tData.mArea);
[463]398
[473]399                //-- update pvs
400                int conSamp = 0, sampCon = 0;
401                AddToPvs(leaf, *tData.mRays, conSamp, sampCon);
[482]402
[473]403                mStat.contributingSamples += conSamp;
404                mStat.sampleContributions += sampCon;
[482]405
[463]406                EvaluateLeafStats(tData);
407        }
[482]408
409
[473]410        //-- cleanup
[478]411        tData.Clear();
[463]412
[472]413        return newNode;
[463]414}
415
[472]416BspNode *VspBspTree::SubdivideNode(VspBspTraversalData &tData,
417                                                                   VspBspTraversalData &frontData,
418                                                                   VspBspTraversalData &backData,
419                                                                   PolygonContainer &coincident)
[463]420{
421        BspLeaf *leaf = dynamic_cast<BspLeaf *>(tData.mNode);
[473]422
[472]423        int maxCostMisses = tData.mMaxCostMisses;
424
[463]425        // select subdivision plane
[472]426        Plane3 splitPlane;
427        if (!SelectPlane(splitPlane, leaf, tData))
428        {
429                ++ maxCostMisses;
[463]430
[480]431                if (maxCostMisses > mTermMissTolerance)
[473]432                {
433                        // terminate branch because of max cost
[482]434                        ++ mStat.maxCostNodes;
[472]435            return leaf;
[474]436                }
[472]437        }
438
[473]439        mStat.nodes += 2;
440
441        //-- subdivide further
[482]442        BspInterior *interior = new BspInterior(splitPlane);
[472]443
[463]444#ifdef _DEBUG
445        Debug << interior << endl;
446#endif
[482]447
[473]448        //-- the front and back traversal data is filled with the new values
449        frontData.mPolygons = new PolygonContainer();
450        frontData.mDepth = tData.mDepth + 1;
451        frontData.mRays = new RayInfoContainer();
452        frontData.mGeometry = new BspNodeGeometry();
453
454        backData.mPolygons = new PolygonContainer();
455        backData.mDepth = tData.mDepth + 1;
456        backData.mRays = new RayInfoContainer();
457        backData.mGeometry = new BspNodeGeometry();
458
459        // subdivide rays
[482]460        SplitRays(interior->GetPlane(),
461                          *tData.mRays,
462                          *frontData.mRays,
[463]463                          *backData.mRays);
[482]464
[473]465        // subdivide polygons
[463]466        mStat.splits += SplitPolygons(interior->GetPlane(),
[482]467                                                                  *tData.mPolygons,
468                                          *frontData.mPolygons,
[463]469                                                                  *backData.mPolygons,
470                                                                  coincident);
471
[482]472
[473]473        // how often was max cost ratio missed in this branch?
[472]474        frontData.mMaxCostMisses = maxCostMisses;
475        backData.mMaxCostMisses = maxCostMisses;
476
477        // compute pvs
[463]478        frontData.mPvs = ComputePvsSize(*frontData.mRays);
479        backData.mPvs = ComputePvsSize(*backData.mRays);
480
481        // split geometry and compute area
482        if (1)
483        {
[482]484                tData.mGeometry->SplitGeometry(*frontData.mGeometry,
485                                                                           *backData.mGeometry,
[463]486                                                                           interior->GetPlane(),
487                                                                           mBox,
488                                                                           mEpsilon);
[482]489
[474]490                frontData.mArea = frontData.mGeometry->GetArea();
491                backData.mArea = backData.mGeometry->GetArea();
[463]492        }
493
494        // compute accumulated ray length
495        //frontData.mAccRayLength = AccumulatedRayLength(*frontData.mRays);
496        //backData.mAccRayLength = AccumulatedRayLength(*backData.mRays);
497
498        //-- create front and back leaf
499
500        BspInterior *parent = leaf->GetParent();
501
502        // replace a link from node's parent
503        if (!leaf->IsRoot())
504        {
505                parent->ReplaceChildLink(leaf, interior);
506                interior->SetParent(parent);
507        }
508        else // new root
509        {
510                mRoot = interior;
511        }
512
513        // and setup child links
514        interior->SetupChildLinks(new BspLeaf(interior), new BspLeaf(interior));
[482]515
[463]516        frontData.mNode = interior->GetFront();
517        backData.mNode = interior->GetBack();
[473]518
[463]519        //DEL_PTR(leaf);
520        return interior;
521}
522
523void VspBspTree::AddToPvs(BspLeaf *leaf,
[482]524                                                  const RayInfoContainer &rays,
[463]525                                                  int &sampleContributions,
526                                                  int &contributingSamples)
527{
528        sampleContributions = 0;
529        contributingSamples = 0;
530
531    RayInfoContainer::const_iterator it, it_end = rays.end();
532
533        ViewCell *vc = leaf->GetViewCell();
534
535        // add contributions from samples to the PVS
536        for (it = rays.begin(); it != it_end; ++ it)
537        {
538                int contribution = 0;
539                VssRay *ray = (*it).mRay;
[482]540
[463]541                if (ray->mTerminationObject)
542                        contribution += vc->GetPvs().AddSample(ray->mTerminationObject);
[482]543
[463]544                if (ray->mOriginObject)
545                        contribution += vc->GetPvs().AddSample(ray->mOriginObject);
546
547                if (contribution)
548                {
549                        sampleContributions += contribution;
550                        ++ contributingSamples;
551                }
552                //leaf->mVssRays.push_back(ray);
553        }
554}
555
[480]556void VspBspTree::SortSplitCandidates(const RayInfoContainer &rays, const int axis)
[463]557{
[480]558        mSplitCandidates->clear();
[463]559
[480]560        int requestedSize = 2 * (int)(rays.size());
561        // creates a sorted split candidates array
562        if (mSplitCandidates->capacity() > 500000 &&
563                requestedSize < (int)(mSplitCandidates->capacity()/10) )
564        {
[482]565        delete mSplitCandidates;
[480]566                mSplitCandidates = new vector<SortableEntry>;
567        }
[463]568
[480]569        mSplitCandidates->reserve(requestedSize);
570
571        // insert all queries
572        for(RayInfoContainer::const_iterator ri = rays.begin(); ri < rays.end(); ++ ri)
[473]573        {
[480]574                bool positive = (*ri).mRay->HasPosDir(axis);
575                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMin : SortableEntry::ERayMax,
[482]576                                                                                                  (*ri).ExtrapOrigin(axis), (*ri).mRay));
[480]577
578                mSplitCandidates->push_back(SortableEntry(positive ? SortableEntry::ERayMax : SortableEntry::ERayMin,
[482]579                                                                                                  (*ri).ExtrapTermination(axis), (*ri).mRay));
[473]580        }
[480]581
582        stable_sort(mSplitCandidates->begin(), mSplitCandidates->end());
[463]583}
584
[480]585float VspBspTree::BestCostRatioHeuristics(const RayInfoContainer &rays,
586                                                                                  const AxisAlignedBox3 &box,
587                                                                                  const int pvsSize,
[481]588                                                                                  const int &axis,
[480]589                                          float &position)
[463]590{
[480]591        int raysBack;
592        int raysFront;
593        int pvsBack;
594        int pvsFront;
[463]595
[480]596        SortSplitCandidates(rays, axis);
597
[463]598        // go through the lists, count the number of objects left and right
599        // and evaluate the following cost funcion:
[480]600        // C = ct_div_ci  + (ql*rl + qr*rr)/queries
601
602        int rl = 0, rr = (int)rays.size();
603        int pl = 0, pr = pvsSize;
604
[463]605        float minBox = box.Min(axis);
606        float maxBox = box.Max(axis);
[480]607        float sizeBox = maxBox - minBox;
608
609        float minBand = minBox + 0.1f*(maxBox - minBox);
610        float maxBand = minBox + 0.9f*(maxBox - minBox);
611
612        float sum = rr*sizeBox;
[463]613        float minSum = 1e20f;
614
[480]615        Intersectable::NewMail();
616
617        // set all object as belonging to the fron pvs
618        for(RayInfoContainer::const_iterator ri = rays.begin(); ri != rays.end(); ++ ri)
[463]619        {
[480]620                if ((*ri).mRay->IsActive())
[463]621                {
[480]622                        Intersectable *object = (*ri).mRay->mTerminationObject;
623
624                        if (object)
[482]625                        {
[480]626                                if (!object->Mailed())
627                                {
628                                        object->Mail();
629                                        object->mCounter = 1;
630                                }
631                                else
632                                        ++ object->mCounter;
[482]633                        }
[463]634                }
[480]635        }
636
637        Intersectable::NewMail();
638
639        for (vector<SortableEntry>::const_iterator ci = mSplitCandidates->begin();
640                ci < mSplitCandidates->end(); ++ ci)
641        {
642                VssRay *ray;
643
644                switch ((*ci).type)
[463]645                {
[480]646                        case SortableEntry::ERayMin:
647                                {
648                                        ++ rl;
[482]649                                        ray = (VssRay *) (*ci).ray;
650
[480]651                                        Intersectable *object = ray->mTerminationObject;
[482]652
[480]653                                        if (object && !object->Mailed())
654                                        {
655                                                object->Mail();
656                                                ++ pl;
657                                        }
658                                        break;
659                                }
660                        case SortableEntry::ERayMax:
661                                {
662                                        -- rr;
[482]663                                        ray = (VssRay *) (*ci).ray;
[463]664
[480]665                                        Intersectable *object = ray->mTerminationObject;
666
667                                        if (object)
668                                        {
669                                                if (-- object->mCounter == 0)
[482]670                                                        -- pr;
[480]671                                        }
672
673                                        break;
674                                }
675                }
676
677                // Note: sufficient to compare size of bounding boxes of front and back side?
678                if ((*ci).value > minBand && (*ci).value < maxBand)
679                {
680                        sum = pl*((*ci).value - minBox) + pr*(maxBox - (*ci).value);
681
682                        //  cout<<"pos="<<(*ci).value<<"\t q=("<<ql<<","<<qr<<")\t r=("<<rl<<","<<rr<<")"<<endl;
683                        // cout<<"cost= "<<sum<<endl;
684
685                        if (sum < minSum)
[463]686                        {
687                                minSum = sum;
688                                position = (*ci).value;
689
[480]690                                raysBack = rl;
691                                raysFront = rr;
692
693                                pvsBack = pl;
694                                pvsFront = pr;
695
[463]696                        }
697                }
698        }
699
[480]700        float oldCost = (float)pvsSize;
701        float newCost = mCtDivCi + minSum / sizeBox;
702        float ratio = newCost / oldCost;
[463]703
[480]704        //Debug << "costRatio=" << ratio << " pos=" << position << " t=" << (position - minBox) / (maxBox - minBox)
705        //     <<"\t q=(" << queriesBack << "," << queriesFront << ")\t r=(" << raysBack << "," << raysFront << ")" << endl;
706
707        return ratio;
[463]708}
709
[480]710
[482]711float VspBspTree::SelectAxisAlignedPlane(Plane3 &plane,
[480]712                                                                                 const VspBspTraversalData &tData)
[463]713{
714        AxisAlignedBox3 box;
715        box.Initialize();
[482]716
[463]717        // create bounding box of region
[480]718        RayInfoContainer::const_iterator ri, ri_end = tData.mRays->end();
719
720        for(ri = tData.mRays->begin(); ri < ri_end; ++ ri)
721                box.Include((*ri).ExtrapTermination());
722
723        const bool useCostHeuristics = false;
[463]724
[480]725        //-- regular split
726        float nPosition[3];
727        float nCostRatio[3];
728        int bestAxis = -1;
729
[482]730        const int sAxis = box.Size().DrivingAxis();
[480]731
[481]732        for (int axis = 0; axis < 3; ++ axis)
[480]733        {
734                if (!mOnlyDrivingAxis || axis == sAxis)
[463]735                {
[480]736                        if (!useCostHeuristics)
737                        {
738                                nPosition[axis] = (box.Min()[axis] + box.Max()[axis]) * 0.5f;
739                                Vector3 normal(0,0,0); normal[axis] = 1;
740
741                                nCostRatio[axis] = SplitPlaneCost(Plane3(normal, nPosition[axis]), tData);
742                        }
[481]743                        else
744                        {
[482]745                                nCostRatio[axis] =
[481]746                                        BestCostRatioHeuristics(*tData.mRays,
747                                                                                    box,
748                                                                                        tData.mPvs,
749                                                                                        axis,
750                                                                                        nPosition[axis]);
751                        }
752
[480]753                        if (bestAxis == -1)
754                        {
755                                bestAxis = axis;
756                        }
757
758                        else if (nCostRatio[axis] < nCostRatio[bestAxis])
759                        {
760                                /*Debug << "pvs front " << nPvsBack[axis]
761                                          << " pvs back " << nPvsFront[axis]
762                                          << " overall pvs " << leaf->GetPvsSize() << endl;*/
763                                bestAxis = axis;
764                        }
765
[463]766                }
767        }
768
[480]769        //-- assign best axis
770        Vector3 normal(0,0,0); normal[bestAxis] = 1;
771        plane = Plane3(normal, nPosition[bestAxis]);
[463]772
[480]773        return nCostRatio[bestAxis];
[463]774}
775
[480]776
[482]777bool VspBspTree::SelectPlane(Plane3 &plane,
778                                                         BspLeaf *leaf,
[472]779                                                         VspBspTraversalData &data)
[463]780{
781        // simplest strategy: just take next polygon
782        if (mSplitPlaneStrategy & RANDOM_POLYGON)
783        {
784        if (!data.mPolygons->empty())
785                {
[473]786                        const int randIdx = (int)RandomValue(0, (Real)((int)data.mPolygons->size() - 1));
[463]787                        Polygon3 *nextPoly = (*data.mPolygons)[randIdx];
[472]788
789                        plane = nextPoly->GetSupportingPlane();
790                        return true;
[463]791                }
792                else
793                {
794                        //-- choose plane on midpoint of a ray
[473]795                        const int candidateIdx = (int)RandomValue(0, (Real)((int)data.mRays->size() - 1));
[482]796
[463]797                        const Vector3 minPt = (*data.mRays)[candidateIdx].ExtrapOrigin();
798                        const Vector3 maxPt = (*data.mRays)[candidateIdx].ExtrapTermination();
799
800                        const Vector3 pt = (maxPt + minPt) * 0.5;
801
802                        const Vector3 normal = (*data.mRays)[candidateIdx].mRay->GetDir();
[482]803
[472]804                        plane = Plane3(normal, pt);
805                        return true;
[463]806                }
807
[472]808                return false;
[463]809        }
810
811        // use heuristics to find appropriate plane
[482]812        return SelectPlaneHeuristics(plane, leaf, data);
[463]813}
814
[480]815
[473]816Plane3 VspBspTree::ChooseCandidatePlane(const RayInfoContainer &rays) const
[482]817{
[473]818        const int candidateIdx = (int)RandomValue(0, (Real)((int)rays.size() - 1));
[482]819
[473]820        const Vector3 minPt = rays[candidateIdx].ExtrapOrigin();
821        const Vector3 maxPt = rays[candidateIdx].ExtrapTermination();
822
823        const Vector3 pt = (maxPt + minPt) * 0.5;
824        const Vector3 normal = Normalize(rays[candidateIdx].mRay->GetDir());
825
826        return Plane3(normal, pt);
827}
828
[480]829
[473]830Plane3 VspBspTree::ChooseCandidatePlane2(const RayInfoContainer &rays) const
[482]831{
[473]832        Vector3 pt[3];
[482]833
[473]834        int idx[3];
835        int cmaxT = 0;
836        int cminT = 0;
837        bool chooseMin = false;
838
839        for (int j = 0; j < 3; ++ j)
840        {
841                idx[j] = (int)RandomValue(0, (Real)((int)rays.size() * 2 - 1));
[482]842
[473]843                if (idx[j] >= (int)rays.size())
844                {
845                        idx[j] -= (int)rays.size();
[482]846
[473]847                        chooseMin = (cminT < 2);
848                }
849                else
850                        chooseMin = (cmaxT < 2);
851
852                RayInfo rayInf = rays[idx[j]];
853                pt[j] = chooseMin ? rayInf.ExtrapOrigin() : rayInf.ExtrapTermination();
[482]854        }
[473]855
856        return Plane3(pt[0], pt[1], pt[2]);
857}
858
859Plane3 VspBspTree::ChooseCandidatePlane3(const RayInfoContainer &rays) const
[482]860{
[473]861        Vector3 pt[3];
[482]862
[473]863        int idx1 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
864        int idx2 = (int)RandomValue(0, (Real)((int)rays.size() - 1));
865
866        // check if rays different
867        if (idx1 == idx2)
868                idx2 = (idx2 + 1) % (int)rays.size();
869
870        const RayInfo ray1 = rays[idx1];
871        const RayInfo ray2 = rays[idx2];
872
873        // normal vector of the plane parallel to both lines
874        const Vector3 norm = Normalize(CrossProd(ray1.mRay->GetDir(), ray2.mRay->GetDir()));
875
876        // vector from line 1 to line 2
[479]877        const Vector3 vd = ray2.ExtrapOrigin() - ray1.ExtrapOrigin();
[482]878
[473]879        // project vector on normal to get distance
880        const float dist = DotProd(vd, norm);
881
882        // point on plane lies halfway between the two planes
883        const Vector3 planePt = ray1.ExtrapOrigin() + norm * dist * 0.5;
884
885        return Plane3(norm, planePt);
886}
887
[482]888bool VspBspTree::SelectPlaneHeuristics(Plane3 &bestPlane,
889                                                                           BspLeaf *leaf,
[472]890                                                                           VspBspTraversalData &data)
[463]891{
892        float lowestCost = MAX_FLOAT;
[472]893        // intermediate plane
[463]894        Plane3 plane;
895
[472]896        const int limit = Min((int)data.mPolygons->size(), mMaxPolyCandidates);
[473]897        int maxIdx = (int)data.mPolygons->size();
[482]898
[480]899        float candidateCost;
900
[463]901        for (int i = 0; i < limit; ++ i)
902        {
[473]903                // assure that no index is taken twice
904                const int candidateIdx = (int)RandomValue(0, (Real)(-- maxIdx));
905                //Debug << "current Idx: " << maxIdx << " cand idx " << candidateIdx << endl;
[482]906
[474]907                Polygon3 *poly = (*data.mPolygons)[candidateIdx];
908
[473]909                // swap candidate to the end to avoid testing same plane
910                std::swap((*data.mPolygons)[maxIdx], (*data.mPolygons)[candidateIdx]);
[482]911
[473]912                //Polygon3 *poly = (*data.mPolygons)[(int)RandomValue(0, (int)polys.size() - 1)];
913
[463]914                // evaluate current candidate
[480]915                candidateCost = SplitPlaneCost(poly->GetSupportingPlane(), data);
[463]916
917                if (candidateCost < lowestCost)
918                {
919                        bestPlane = poly->GetSupportingPlane();
920                        lowestCost = candidateCost;
921                }
922        }
[482]923
[480]924#if 0
[463]925        //-- choose candidate planes extracted from rays
[474]926        //-- different methods are available
[473]927        for (int i = 0; i < mMaxRayCandidates; ++ i)
[463]928        {
[473]929                plane = ChooseCandidatePlane3(*data.mRays);
[480]930                candidateCost = SplitPlaneCost(plane, data);
[463]931
932                if (candidateCost < lowestCost)
933                {
[482]934                        bestPlane = plane;
[463]935                        lowestCost = candidateCost;
936                }
937        }
[480]938#endif
[463]939
[480]940        // axis aligned splits
[482]941        candidateCost = SelectAxisAlignedPlane(plane, data);
[480]942
943        if (candidateCost < lowestCost)
944        {
[482]945                bestPlane = plane;
[480]946                lowestCost = candidateCost;
947        }
948
[463]949#ifdef _DEBUG
950        Debug << "plane lowest cost: " << lowestCost << endl;
951#endif
[472]952
[474]953        // cost ratio miss
954        if (lowestCost > mTermMaxCostRatio)
955                return false;
956
[472]957        return true;
[463]958}
959
960
961inline void VspBspTree::GenerateUniqueIdsForPvs()
962{
963        Intersectable::NewMail(); sBackId = ViewCell::sMailId;
964        Intersectable::NewMail(); sFrontId = ViewCell::sMailId;
965        Intersectable::NewMail(); sFrontAndBackId = ViewCell::sMailId;
966}
967
[482]968float VspBspTree::SplitPlaneCost(const Plane3 &candidatePlane,
[480]969                                                                 const VspBspTraversalData &data) const
[463]970{
[472]971        float cost = 0;
[463]972
973        float sumBalancedRays = 0;
974        float sumRaySplits = 0;
[482]975
[463]976        int frontPvs = 0;
977        int backPvs = 0;
978
979        // probability that view point lies in child
980        float pOverall = 0;
981        float pFront = 0;
982        float pBack = 0;
983
984        const bool pvsUseLen = false;
985
986        if (mSplitPlaneStrategy & PVS)
987        {
988                // create unique ids for pvs heuristics
989                GenerateUniqueIdsForPvs();
[482]990
[463]991                if (mPvsUseArea) // use front and back cell areas to approximate volume
[482]992                {
[463]993                        // construct child geometry with regard to the candidate split plane
994                        BspNodeGeometry frontCell;
995                        BspNodeGeometry backCell;
[482]996
997                        data.mGeometry->SplitGeometry(frontCell,
998                                                                                  backCell,
[463]999                                                                                  candidatePlane,
1000                                                                                  mBox,
1001                                                                                  mEpsilon);
[482]1002
[463]1003                        pFront = frontCell.GetArea();
1004                        pBack = backCell.GetArea();
1005
1006                        pOverall = data.mArea;
1007                }
1008        }
[482]1009
[463]1010        int limit;
1011        bool useRand;
1012
1013        // choose test polyongs randomly if over threshold
1014        if ((int)data.mRays->size() > mMaxTests)
1015        {
1016                useRand = true;
1017                limit = mMaxTests;
1018        }
1019        else
1020        {
1021                useRand = false;
1022                limit = (int)data.mRays->size();
1023        }
1024
1025        for (int i = 0; i < limit; ++ i)
1026        {
[473]1027                const int testIdx = useRand ? (int)RandomValue(0, (Real)(limit - 1)) : i;
[463]1028                RayInfo rayInf = (*data.mRays)[testIdx];
1029
1030                VssRay *ray = rayInf.mRay;
1031                float t;
1032                const int cf = rayInf.ComputeRayIntersection(candidatePlane, t);
1033
1034                if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
1035                {
1036                        sumBalancedRays += cf;
1037                }
[482]1038
[463]1039                if (mSplitPlaneStrategy & BALANCED_RAYS)
1040                {
1041                        if (cf == 0)
1042                                ++ sumRaySplits;
1043                }
1044
1045                if (mSplitPlaneStrategy & PVS)
1046                {
1047                        // in case the ray intersects an object
[482]1048                        // assure that we only count the object
[463]1049                        // once for the front and once for the back side of the plane
[482]1050
[463]1051                        // add the termination object
1052                        AddObjToPvs(ray->mTerminationObject, cf, frontPvs, backPvs);
[482]1053
[463]1054                        // add the source object
1055                        AddObjToPvs(ray->mOriginObject, cf, frontPvs, backPvs);
[482]1056
[463]1057                        // use number or length of rays to approximate volume
1058                        if (!mPvsUseArea)
1059                        {
1060                                float len = 1;
1061
1062                                if (pvsUseLen) // use length of rays
1063                                        len = rayInf.SqrSegmentLength();
[482]1064
[463]1065                                pOverall += len;
1066
1067                                if (cf == 1)
1068                                        pFront += len;
1069                                if (cf == -1)
1070                                        pBack += len;
1071                                if (cf == 0)
1072                                {
1073                                        // use length of rays to approximate volume
[482]1074                                        if (pvsUseLen)
[463]1075                                        {
[482]1076                                                float newLen = len *
1077                                                        (rayInf.GetMaxT() - t) /
[463]1078                                                        (rayInf.GetMaxT() - rayInf.GetMinT());
[482]1079
[463]1080                                                if (candidatePlane.Side(rayInf.ExtrapOrigin()) <= 0)
1081                                                {
1082                                                        pBack += newLen;
1083                                                        pFront += len - newLen;
1084                                                }
1085                                                else
1086                                                {
1087                                                        pFront += newLen;
1088                                                        pBack += len - newLen;
1089                                                }
1090                                        }
1091                                        else
1092                                        {
1093                                                ++ pFront;
1094                                                ++ pBack;
1095                                        }
1096                                }
1097                        }
1098                }
1099        }
1100
1101        const float raysSize = (float)data.mRays->size() + Limits::Small;
[482]1102
[463]1103        if (mSplitPlaneStrategy & LEAST_RAY_SPLITS)
[472]1104                cost += mLeastRaySplitsFactor * sumRaySplits / raysSize;
[463]1105
1106        if (mSplitPlaneStrategy & BALANCED_RAYS)
[472]1107                cost += mBalancedRaysFactor * fabs(sumBalancedRays) /  raysSize;
[482]1108
[472]1109        // pvs criterium
[463]1110        if (mSplitPlaneStrategy & PVS)
1111        {
[472]1112                const float oldCost = pOverall * (float)data.mPvs + Limits::Small;
[474]1113                cost += mPvsFactor * (frontPvs * pFront + backPvs * pBack) / oldCost;
[463]1114
[474]1115                //cost += mPvsFactor * 0.5 * (frontPvs * pFront + backPvs * pBack) / oldCost;
1116                //Debug << "new cost: " << cost << " over" << frontPvs * pFront + backPvs * pBack << " old cost " << oldCost << endl;
[482]1117
[474]1118                if (0) // give penalty to unbalanced split
[482]1119                        if (((pFront * 0.2 + Limits::Small) > pBack) ||
[474]1120                                (pFront < (pBack * 0.2 + Limits::Small)))
1121                                        cost += 0.5;
[463]1122        }
1123
1124#ifdef _DEBUG
[474]1125        Debug << "totalpvs: " << data.mPvs << " ptotal: " << pOverall
[482]1126                  << " frontpvs: " << frontPvs << " pFront: " << pFront
[474]1127                  << " backpvs: " << backPvs << " pBack: " << pBack << endl << endl;
[463]1128#endif
[482]1129
[474]1130        // normalize cost by sum of linear factors
1131        return cost / (float)mCostNormalizer;
[463]1132}
1133
1134void VspBspTree::AddObjToPvs(Intersectable *obj,
1135                                                         const int cf,
1136                                                         int &frontPvs,
1137                                                         int &backPvs) const
1138{
1139        if (!obj)
1140                return;
1141        // TODO: does this really belong to no pvs?
1142        //if (cf == Ray::COINCIDENT) return;
1143
1144        // object belongs to both PVS
1145        if (cf >= 0)
1146        {
[482]1147                if ((obj->mMailbox != sFrontId) &&
[463]1148                        (obj->mMailbox != sFrontAndBackId))
1149                {
1150                        ++ frontPvs;
1151
1152                        if (obj->mMailbox == sBackId)
[482]1153                                obj->mMailbox = sFrontAndBackId;
[463]1154                        else
[482]1155                                obj->mMailbox = sFrontId;
[463]1156                }
1157        }
[482]1158
[463]1159        if (cf <= 0)
1160        {
1161                if ((obj->mMailbox != sBackId) &&
1162                        (obj->mMailbox != sFrontAndBackId))
1163                {
1164                        ++ backPvs;
1165
1166                        if (obj->mMailbox == sFrontId)
[482]1167                                obj->mMailbox = sFrontAndBackId;
[463]1168                        else
[482]1169                                obj->mMailbox = sBackId;
[463]1170                }
1171        }
1172}
1173
1174void VspBspTree::CollectLeaves(vector<BspLeaf *> &leaves) const
1175{
1176        stack<BspNode *> nodeStack;
1177        nodeStack.push(mRoot);
[482]1178
1179        while (!nodeStack.empty())
[463]1180        {
1181                BspNode *node = nodeStack.top();
[482]1182
[463]1183                nodeStack.pop();
[482]1184
1185                if (node->IsLeaf())
[463]1186                {
[482]1187                        BspLeaf *leaf = (BspLeaf *)node;
[463]1188                        leaves.push_back(leaf);
[482]1189                }
1190                else
[463]1191                {
1192                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1193
1194                        nodeStack.push(interior->GetBack());
1195                        nodeStack.push(interior->GetFront());
1196                }
1197        }
1198}
1199
1200AxisAlignedBox3 VspBspTree::GetBoundingBox() const
1201{
1202        return mBox;
1203}
1204
1205BspNode *VspBspTree::GetRoot() const
1206{
1207        return mRoot;
1208}
1209
1210void VspBspTree::EvaluateLeafStats(const VspBspTraversalData &data)
1211{
1212        // the node became a leaf -> evaluate stats for leafs
1213        BspLeaf *leaf = dynamic_cast<BspLeaf *>(data.mNode);
1214
1215        // store maximal and minimal depth
1216        if (data.mDepth > mStat.maxDepth)
1217                mStat.maxDepth = data.mDepth;
1218
1219        if (data.mDepth < mStat.minDepth)
1220                mStat.minDepth = data.mDepth;
[482]1221
[463]1222        if (data.mDepth >= mTermMaxDepth)
1223                ++ mStat.maxDepthNodes;
1224
[437]1225        if (data.mPvs < mTermMinPvs)
1226                ++ mStat.minPvsNodes;
1227
1228        if ((int)data.mRays->size() < mTermMinRays)
1229                ++ mStat.minRaysNodes;
1230
1231        if (data.GetAvgRayContribution() > mTermMaxRayContribution)
1232                ++ mStat.maxRayContribNodes;
[482]1233
1234        if (data.mArea <= mTermMinArea)
[474]1235        {
1236                //Debug << "area: " << data.mArea / mBox.SurfaceArea() << " min area: " << mTermMinArea / mBox.SurfaceArea() << endl;
[463]1237                ++ mStat.minAreaNodes;
[474]1238        }
1239        // accumulate depth to compute average depth
1240        mStat.accumDepth += data.mDepth;
[463]1241
1242#ifdef _DEBUG
1243        Debug << "BSP stats: "
1244                  << "Depth: " << data.mDepth << " (max: " << mTermMaxDepth << "), "
1245                  << "PVS: " << data.mPvs << " (min: " << mTermMinPvs << "), "
1246                  << "Area: " << data.mArea << " (min: " << mTermMinArea << "), "
[482]1247                  << "#rays: " << (int)data.mRays->size() << " (max: " << mTermMinRays << "), "
[463]1248                  << "#pvs: " << leaf->GetViewCell()->GetPvs().GetSize() << "=, "
1249                  << "#avg ray contrib (pvs): " << (float)data.mPvs / (float)data.mRays->size() << endl;
1250#endif
1251}
1252
1253int VspBspTree::CastRay(Ray &ray)
1254{
1255        int hits = 0;
[482]1256
[463]1257        stack<BspRayTraversalData> tStack;
[482]1258
[463]1259        float maxt, mint;
1260
1261        if (!mBox.GetRaySegment(ray, mint, maxt))
1262                return 0;
1263
1264        Intersectable::NewMail();
1265
1266        Vector3 entp = ray.Extrap(mint);
1267        Vector3 extp = ray.Extrap(maxt);
[482]1268
[463]1269        BspNode *node = mRoot;
1270        BspNode *farChild = NULL;
[482]1271
[463]1272        while (1)
1273        {
[482]1274                if (!node->IsLeaf())
[463]1275                {
1276                        BspInterior *in = dynamic_cast<BspInterior *>(node);
1277
1278                        Plane3 splitPlane = in->GetPlane();
1279                        const int entSide = splitPlane.Side(entp);
1280                        const int extSide = splitPlane.Side(extp);
1281
1282                        if (entSide < 0)
1283                        {
1284                                node = in->GetBack();
1285
1286                                if(extSide <= 0) // plane does not split ray => no far child
1287                                        continue;
[482]1288
[463]1289                                farChild = in->GetFront(); // plane splits ray
1290
1291                        } else if (entSide > 0)
1292                        {
1293                                node = in->GetFront();
1294
1295                                if (extSide >= 0) // plane does not split ray => no far child
1296                                        continue;
1297
[482]1298                                farChild = in->GetBack(); // plane splits ray
[463]1299                        }
1300                        else // ray and plane are coincident
1301                        {
1302                                // WHAT TO DO IN THIS CASE ?
1303                                //break;
1304                                node = in->GetFront();
1305                                continue;
1306                        }
1307
1308                        // push data for far child
1309                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
1310
1311                        // find intersection of ray segment with plane
1312                        float t;
1313                        extp = splitPlane.FindIntersection(ray.GetLoc(), extp, &t);
1314                        maxt *= t;
[482]1315
[463]1316                } else // reached leaf => intersection with view cell
1317                {
1318                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
[482]1319
[463]1320                        if (!leaf->GetViewCell()->Mailed())
1321                        {
1322                                //ray.bspIntersections.push_back(Ray::VspBspIntersection(maxt, leaf));
1323                                leaf->GetViewCell()->Mail();
1324                                ++ hits;
1325                        }
[482]1326
[463]1327                        //-- fetch the next far child from the stack
1328                        if (tStack.empty())
1329                                break;
[482]1330
[463]1331                        entp = extp;
1332                        mint = maxt; // NOTE: need this?
1333
1334                        if (ray.GetType() == Ray::LINE_SEGMENT && mint > 1.0f)
1335                                break;
1336
1337                        BspRayTraversalData &s = tStack.top();
1338
1339                        node = s.mNode;
1340                        extp = s.mExitPoint;
1341                        maxt = s.mMaxT;
1342
1343                        tStack.pop();
1344                }
1345        }
1346
1347        return hits;
1348}
1349
1350bool VspBspTree::Export(const string filename)
1351{
1352        Exporter *exporter = Exporter::GetExporter(filename);
1353
[482]1354        if (exporter)
[463]1355        {
1356                //exporter->ExportVspBspTree(*this);
1357                return true;
[482]1358        }
[463]1359
1360        return false;
1361}
1362
1363void VspBspTree::CollectViewCells(ViewCellContainer &viewCells) const
1364{
1365        stack<BspNode *> nodeStack;
1366        nodeStack.push(mRoot);
1367
1368        ViewCell::NewMail();
1369
[482]1370        while (!nodeStack.empty())
[463]1371        {
1372                BspNode *node = nodeStack.top();
1373                nodeStack.pop();
1374
[482]1375                if (node->IsLeaf())
[463]1376                {
1377                        ViewCell *viewCell = dynamic_cast<BspLeaf *>(node)->GetViewCell();
1378
[482]1379                        if (!viewCell->Mailed())
[463]1380                        {
1381                                viewCell->Mail();
1382                                viewCells.push_back(viewCell);
1383                        }
1384                }
[482]1385                else
[463]1386                {
1387                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1388
1389                        nodeStack.push(interior->GetFront());
1390                        nodeStack.push(interior->GetBack());
1391                }
1392        }
1393}
1394
1395
1396float VspBspTree::AccumulatedRayLength(const RayInfoContainer &rays) const
1397{
1398        float len = 0;
1399
1400        RayInfoContainer::const_iterator it, it_end = rays.end();
1401
1402        for (it = rays.begin(); it != it_end; ++ it)
1403                len += (*it).SegmentLength();
1404
1405        return len;
1406}
1407
[479]1408
[463]1409int VspBspTree::SplitRays(const Plane3 &plane,
[482]1410                                                  RayInfoContainer &rays,
1411                                                  RayInfoContainer &frontRays,
[463]1412                                                  RayInfoContainer &backRays)
1413{
1414        int splits = 0;
1415
1416        while (!rays.empty())
1417        {
1418                RayInfo bRay = rays.back();
[473]1419                rays.pop_back();
1420
[463]1421                VssRay *ray = bRay.mRay;
[473]1422                float t;
[463]1423
[473]1424                        // get classification and receive new t
[463]1425                const int cf = bRay.ComputeRayIntersection(plane, t);
[482]1426
[463]1427                switch (cf)
1428                {
1429                case -1:
1430                        backRays.push_back(bRay);
1431                        break;
1432                case 1:
1433                        frontRays.push_back(bRay);
1434                        break;
[482]1435                case 0:
[463]1436                        //-- split ray
[473]1437                        //--  look if start point behind or in front of plane
[463]1438                        if (plane.Side(bRay.ExtrapOrigin()) <= 0)
[482]1439                        {
[463]1440                                backRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1441                                frontRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1442                        }
1443                        else
1444                        {
1445                                frontRays.push_back(RayInfo(ray, bRay.GetMinT(), t));
1446                                backRays.push_back(RayInfo(ray, t, bRay.GetMaxT()));
1447                        }
1448                        break;
1449                default:
1450                        Debug << "Should not come here 4" << endl;
1451                        break;
1452                }
1453        }
1454
1455        return splits;
1456}
1457
[479]1458
[463]1459void VspBspTree::ExtractHalfSpaces(BspNode *n, vector<Plane3> &halfSpaces) const
1460{
1461        BspNode *lastNode;
1462
1463        do
1464        {
1465                lastNode = n;
1466
1467                // want to get planes defining geometry of this node => don't take
1468                // split plane of node itself
1469                n = n->GetParent();
[482]1470
[463]1471                if (n)
1472                {
1473                        BspInterior *interior = dynamic_cast<BspInterior *>(n);
1474                        Plane3 halfSpace = dynamic_cast<BspInterior *>(interior)->GetPlane();
1475
1476            if (interior->GetFront() != lastNode)
1477                                halfSpace.ReverseOrientation();
1478
1479                        halfSpaces.push_back(halfSpace);
1480                }
1481        }
1482        while (n);
1483}
1484
[482]1485void VspBspTree::ConstructGeometry(BspNode *n,
[463]1486                                                                   BspNodeGeometry &cell) const
1487{
1488        PolygonContainer polys;
1489        ConstructGeometry(n, polys);
1490        cell.mPolys = polys;
1491}
1492
[482]1493void VspBspTree::ConstructGeometry(BspNode *n,
[448]1494                                                                   PolygonContainer &cell) const
[437]1495{
1496        vector<Plane3> halfSpaces;
1497        ExtractHalfSpaces(n, halfSpaces);
1498
1499        PolygonContainer candidatePolys;
1500
1501        // bounded planes are added to the polygons (reverse polygons
1502        // as they have to be outfacing
1503        for (int i = 0; i < (int)halfSpaces.size(); ++ i)
1504        {
1505                Polygon3 *p = GetBoundingBox().CrossSection(halfSpaces[i]);
[482]1506
[448]1507                if (p->Valid(mEpsilon))
[437]1508                {
1509                        candidatePolys.push_back(p->CreateReversePolygon());
1510                        DEL_PTR(p);
1511                }
1512        }
1513
1514        // add faces of bounding box (also could be faces of the cell)
1515        for (int i = 0; i < 6; ++ i)
1516        {
1517                VertexContainer vertices;
[482]1518
[437]1519                for (int j = 0; j < 4; ++ j)
1520                        vertices.push_back(mBox.GetFace(i).mVertices[j]);
1521
1522                candidatePolys.push_back(new Polygon3(vertices));
1523        }
1524
1525        for (int i = 0; i < (int)candidatePolys.size(); ++ i)
1526        {
1527                // polygon is split by all other planes
1528                for (int j = 0; (j < (int)halfSpaces.size()) && candidatePolys[i]; ++ j)
1529                {
1530                        if (i == j) // polygon and plane are coincident
1531                                continue;
1532
1533                        VertexContainer splitPts;
1534                        Polygon3 *frontPoly, *backPoly;
1535
[482]1536                        const int cf =
[448]1537                                candidatePolys[i]->ClassifyPlane(halfSpaces[j],
1538                                                                                                 mEpsilon);
[482]1539
[437]1540                        switch (cf)
1541                        {
1542                                case Polygon3::SPLIT:
1543                                        frontPoly = new Polygon3();
1544                                        backPoly = new Polygon3();
1545
[482]1546                                        candidatePolys[i]->Split(halfSpaces[j],
1547                                                                                         *frontPoly,
[448]1548                                                                                         *backPoly,
1549                                                                                         mEpsilon);
[437]1550
1551                                        DEL_PTR(candidatePolys[i]);
1552
[448]1553                                        if (frontPoly->Valid(mEpsilon))
[437]1554                                                candidatePolys[i] = frontPoly;
1555                                        else
1556                                                DEL_PTR(frontPoly);
1557
1558                                        DEL_PTR(backPoly);
1559                                        break;
1560                                case Polygon3::BACK_SIDE:
1561                                        DEL_PTR(candidatePolys[i]);
1562                                        break;
1563                                // just take polygon as it is
1564                                case Polygon3::FRONT_SIDE:
1565                                case Polygon3::COINCIDENT:
1566                                default:
1567                                        break;
1568                        }
1569                }
[482]1570
[437]1571                if (candidatePolys[i])
1572                        cell.push_back(candidatePolys[i]);
1573        }
[463]1574}
1575
1576void VspBspTree::ConstructGeometry(BspViewCell *vc, PolygonContainer &vcGeom) const
1577{
[469]1578        vector<BspLeaf *> leaves = vc->mLeaves;
[463]1579
1580        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
1581
1582        for (it = leaves.begin(); it != it_end; ++ it)
1583                ConstructGeometry(*it, vcGeom);
1584}
1585
[482]1586int VspBspTree::FindNeighbors(BspNode *n, vector<BspLeaf *> &neighbors,
[463]1587                                                   const bool onlyUnmailed) const
1588{
1589        PolygonContainer cell;
1590
1591        ConstructGeometry(n, cell);
1592
1593        stack<BspNode *> nodeStack;
1594        nodeStack.push(mRoot);
[482]1595
[463]1596        // planes needed to verify that we found neighbor leaf.
1597        vector<Plane3> halfSpaces;
1598        ExtractHalfSpaces(n, halfSpaces);
1599
[482]1600        while (!nodeStack.empty())
[463]1601        {
1602                BspNode *node = nodeStack.top();
1603                nodeStack.pop();
1604
1605                if (node->IsLeaf())
1606                {
1607            if (node != n && (!onlyUnmailed || !node->Mailed()))
1608                        {
1609                                // test all planes of current node if candidate really
1610                                // is neighbour
1611                                PolygonContainer neighborCandidate;
1612                                ConstructGeometry(node, neighborCandidate);
[482]1613
[463]1614                                bool isAdjacent = true;
1615                                for (int i = 0; (i < halfSpaces.size()) && isAdjacent; ++ i)
1616                                {
[482]1617                                        const int cf =
1618                                                Polygon3::ClassifyPlane(neighborCandidate,
[463]1619                                                                                                halfSpaces[i],
1620                                                                                                mEpsilon);
1621
1622                                        if (cf == Polygon3::BACK_SIDE)
1623                                                isAdjacent = false;
1624                                }
1625
1626                                if (isAdjacent)
1627                                        neighbors.push_back(dynamic_cast<BspLeaf *>(node));
1628
1629                                CLEAR_CONTAINER(neighborCandidate);
1630                        }
1631                }
[482]1632                else
[463]1633                {
1634                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
[482]1635
1636                        const int cf = Polygon3::ClassifyPlane(cell,
1637                                                                                                   interior->GetPlane(),
[463]1638                                                                                                   mEpsilon);
1639
1640                        if (cf == Polygon3::FRONT_SIDE)
1641                                nodeStack.push(interior->GetFront());
1642                        else
1643                                if (cf == Polygon3::BACK_SIDE)
1644                                        nodeStack.push(interior->GetBack());
[482]1645                                else
[463]1646                                {
1647                                        // random decision
1648                                        nodeStack.push(interior->GetBack());
1649                                        nodeStack.push(interior->GetFront());
1650                                }
1651                }
1652        }
[482]1653
[463]1654        CLEAR_CONTAINER(cell);
1655        return (int)neighbors.size();
1656}
1657
1658BspLeaf *VspBspTree::GetRandomLeaf(const Plane3 &halfspace)
1659{
1660    stack<BspNode *> nodeStack;
1661        nodeStack.push(mRoot);
[482]1662
[463]1663        int mask = rand();
[482]1664
1665        while (!nodeStack.empty())
[463]1666        {
1667                BspNode *node = nodeStack.top();
1668                nodeStack.pop();
[482]1669
1670                if (node->IsLeaf())
[463]1671                {
1672                        return dynamic_cast<BspLeaf *>(node);
[482]1673                }
1674                else
[463]1675                {
1676                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
[482]1677
[463]1678                        BspNode *next;
[482]1679
[463]1680                        PolygonContainer cell;
1681
1682                        // todo: not very efficient: constructs full cell everytime
1683                        ConstructGeometry(interior, cell);
1684
1685                        const int cf = Polygon3::ClassifyPlane(cell, halfspace, mEpsilon);
1686
1687                        if (cf == Polygon3::BACK_SIDE)
1688                                next = interior->GetFront();
1689                        else
1690                                if (cf == Polygon3::FRONT_SIDE)
1691                                        next = interior->GetFront();
[482]1692                        else
[463]1693                        {
1694                                // random decision
1695                                if (mask & 1)
1696                                        next = interior->GetBack();
1697                                else
1698                                        next = interior->GetFront();
1699                                mask = mask >> 1;
1700                        }
1701
1702                        nodeStack.push(next);
1703                }
1704        }
[482]1705
[463]1706        return NULL;
1707}
1708
1709BspLeaf *VspBspTree::GetRandomLeaf(const bool onlyUnmailed)
1710{
1711        stack<BspNode *> nodeStack;
[482]1712
[463]1713        nodeStack.push(mRoot);
1714
1715        int mask = rand();
[482]1716
1717        while (!nodeStack.empty())
[463]1718        {
1719                BspNode *node = nodeStack.top();
1720                nodeStack.pop();
[482]1721
1722                if (node->IsLeaf())
[463]1723                {
1724                        if ( (!onlyUnmailed || !node->Mailed()) )
1725                                return dynamic_cast<BspLeaf *>(node);
1726                }
[482]1727                else
[463]1728                {
1729                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1730
1731                        // random decision
1732                        if (mask & 1)
1733                                nodeStack.push(interior->GetBack());
1734                        else
1735                                nodeStack.push(interior->GetFront());
1736
1737                        mask = mask >> 1;
1738                }
1739        }
[482]1740
[463]1741        return NULL;
1742}
1743
1744int VspBspTree::ComputePvsSize(const RayInfoContainer &rays) const
1745{
1746        int pvsSize = 0;
1747
1748        RayInfoContainer::const_iterator rit, rit_end = rays.end();
1749
1750        Intersectable::NewMail();
1751
1752        for (rit = rays.begin(); rit != rays.end(); ++ rit)
1753        {
1754                VssRay *ray = (*rit).mRay;
[482]1755
[463]1756                if (ray->mOriginObject)
1757                {
1758                        if (!ray->mOriginObject->Mailed())
1759                        {
1760                                ray->mOriginObject->Mail();
1761                                ++ pvsSize;
1762                        }
1763                }
1764                if (ray->mTerminationObject)
1765                {
1766                        if (!ray->mTerminationObject->Mailed())
1767                        {
1768                                ray->mTerminationObject->Mail();
1769                                ++ pvsSize;
1770                        }
1771                }
1772        }
1773
1774        return pvsSize;
1775}
1776
1777float VspBspTree::GetEpsilon() const
1778{
1779        return mEpsilon;
1780}
1781
1782BspViewCell *VspBspTree::GetRootCell() const
1783{
1784        return mRootCell;
1785}
1786
1787int VspBspTree::SplitPolygons(const Plane3 &plane,
[482]1788                                                          PolygonContainer &polys,
1789                                                          PolygonContainer &frontPolys,
1790                                                          PolygonContainer &backPolys,
[463]1791                                                          PolygonContainer &coincident) const
1792{
1793        int splits = 0;
1794
1795        while (!polys.empty())
1796        {
1797                Polygon3 *poly = polys.back();
1798                polys.pop_back();
1799
1800                // classify polygon
1801                const int cf = poly->ClassifyPlane(plane, mEpsilon);
1802
1803                switch (cf)
1804                {
1805                        case Polygon3::COINCIDENT:
1806                                coincident.push_back(poly);
[482]1807                                break;
1808                        case Polygon3::FRONT_SIDE:
[463]1809                                frontPolys.push_back(poly);
1810                                break;
1811                        case Polygon3::BACK_SIDE:
1812                                backPolys.push_back(poly);
1813                                break;
1814                        case Polygon3::SPLIT:
1815                                backPolys.push_back(poly);
1816                                frontPolys.push_back(poly);
1817                                ++ splits;
1818                                break;
1819                        default:
1820                Debug << "SHOULD NEVER COME HERE\n";
1821                                break;
1822                }
1823        }
1824
1825        return splits;
1826}
[466]1827
1828
[469]1829int VspBspTree::CastLineSegment(const Vector3 &origin,
1830                                                                const Vector3 &termination,
1831                                                                vector<ViewCell *> &viewcells)
[466]1832{
[469]1833        int hits = 0;
1834        stack<BspRayTraversalData> tStack;
[482]1835
[469]1836        float mint = 0.0f, maxt = 1.0f;
[482]1837
[469]1838        Intersectable::NewMail();
[482]1839
[469]1840        Vector3 entp = origin;
1841        Vector3 extp = termination;
[482]1842
[469]1843        BspNode *node = mRoot;
1844        BspNode *farChild = NULL;
[482]1845
1846        while (1)
[469]1847        {
[482]1848                if (!node->IsLeaf())
[469]1849                {
1850                        BspInterior *in = dynamic_cast<BspInterior *>(node);
[482]1851
[469]1852                        Plane3 splitPlane = in->GetPlane();
1853                        const int entSide = splitPlane.Side(entp);
1854                        const int extSide = splitPlane.Side(extp);
[482]1855
1856                        if (entSide < 0)
[469]1857                        {
1858                                node = in->GetBack();
[482]1859
[469]1860                                if(extSide <= 0) // plane does not split ray => no far child
1861                                        continue;
[482]1862
[469]1863                                farChild = in->GetFront(); // plane splits ray
[482]1864                        } else if (entSide > 0)
[469]1865                        {
1866                                node = in->GetFront();
[482]1867
[469]1868                                if (extSide >= 0) // plane does not split ray => no far child
1869                                        continue;
[482]1870
1871                                farChild = in->GetBack(); // plane splits ray
[469]1872                        }
1873                        else // ray and plane are coincident
1874                        {
1875                                // WHAT TO DO IN THIS CASE ?
1876                                //break;
1877                                node = in->GetFront();
1878                                continue;
1879                        }
[482]1880
[469]1881                        // push data for far child
1882                        tStack.push(BspRayTraversalData(farChild, extp, maxt));
[482]1883
[469]1884                        // find intersection of ray segment with plane
1885                        float t;
1886                        extp = splitPlane.FindIntersection(origin, extp, &t);
1887                        maxt *= t;
[482]1888
1889                } else
[469]1890                {
1891                        // reached leaf => intersection with view cell
1892                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
[482]1893
1894                        if (!leaf->GetViewCell()->Mailed())
[469]1895                        {
1896                                viewcells.push_back(leaf->GetViewCell());
1897                                leaf->GetViewCell()->Mail();
1898                                ++ hits;
1899                        }
[482]1900
[469]1901                        //-- fetch the next far child from the stack
1902                        if (tStack.empty())
1903                                break;
[482]1904
[469]1905                        entp = extp;
1906                        mint = maxt; // NOTE: need this?
[482]1907
1908
[469]1909                        BspRayTraversalData &s = tStack.top();
[482]1910
[469]1911                        node = s.mNode;
1912                        extp = s.mExitPoint;
1913                        maxt = s.mMaxT;
[482]1914
[469]1915                        tStack.pop();
1916                }
[466]1917        }
[469]1918        return hits;
[466]1919}
[478]1920
[482]1921int VspBspTree::TreeDistance(BspNode *n1, BspNode *n2)
1922{
1923        std::deque<BspNode *> path1;
1924        BspNode *p1 = n1;
[479]1925
[482]1926        // create path from node 1 to root
1927        while (p1)
1928        {
1929                if (p1 == n2) // second node on path
1930                        return (int)path1.size();
1931
1932                path1.push_front(p1);
1933                p1 = p1->GetParent();
1934        }
1935
1936        int depth = n2->GetDepth();
1937        int d = depth;
1938
1939        BspNode *p2 = n2;
1940
1941        // compare with same depth
1942        while (1)
1943        {
1944                if ((d < (int)path1.size()) && (p2 == path1[d]))
1945                        return (depth - d) + ((int)path1.size() - 1 - d);
1946
1947                -- d;
1948                p2 = p2->GetParent();
1949        }
1950
1951        return 0; // never come here
1952}
1953
[479]1954BspNode *VspBspTree::CollapseTree(BspNode *node)
1955{
1956    if (node->IsLeaf())
1957                return node;
1958
1959        BspInterior *interior = dynamic_cast<BspInterior *>(node);
1960
1961        BspNode *front = CollapseTree(interior->GetFront());
1962        BspNode *back = CollapseTree(interior->GetBack());
1963
1964        if (front->IsLeaf() && back->IsLeaf())
1965        {
1966                BspLeaf *frontLeaf = dynamic_cast<BspLeaf *>(front);
1967                BspLeaf *backLeaf = dynamic_cast<BspLeaf *>(back);
1968
1969                //-- collapse tree
1970                if (frontLeaf->GetViewCell() == backLeaf->GetViewCell())
1971                {
1972                        BspViewCell *vc = frontLeaf->GetViewCell();
1973
1974                        BspLeaf *leaf = new BspLeaf(interior->GetParent(), vc);
[482]1975
[479]1976                        // replace a link from node's parent
1977                        if (leaf->GetParent())
1978                                leaf->GetParent()->ReplaceChildLink(node, leaf);
1979
1980                        delete interior;
1981
1982                        return leaf;
1983                }
1984        }
1985
1986        return node;
1987}
1988
1989
1990void VspBspTree::RepairVcLeafLists()
1991{
1992        // list not valid anymore => clear
1993        stack<BspNode *> nodeStack;
1994        nodeStack.push(mRoot);
1995
1996        ViewCell::NewMail();
1997
1998        while (!nodeStack.empty())
1999        {
2000                BspNode *node = nodeStack.top();
2001                nodeStack.pop();
2002
2003                if (node->IsLeaf())
2004                {
2005                        BspLeaf *leaf = dynamic_cast<BspLeaf *>(node);
2006
2007                        BspViewCell *viewCell = leaf->GetViewCell();
2008
2009                        if (!viewCell->Mailed())
2010                        {
2011                                viewCell->mLeaves.clear();
2012                                viewCell->Mail();
2013                        }
2014
2015                        viewCell->mLeaves.push_back(leaf);
2016                }
2017                else
2018                {
2019                        BspInterior *interior = dynamic_cast<BspInterior *>(node);
2020
2021                        nodeStack.push(interior->GetFront());
2022                        nodeStack.push(interior->GetBack());
2023                }
2024        }
2025}
2026
2027
[478]2028int VspBspTree::MergeLeaves()
2029{
2030        vector<BspLeaf *> leaves;
2031        priority_queue<BspMergeCandidate> mergeQueue;
2032
2033        // collect the leaves, e.g., the "voxels" that will build the view cells
2034        CollectLeaves(leaves);
2035
2036        int vcSize = (int)leaves.size();
2037        int savedVcSize = vcSize;
2038
2039        BspLeaf::NewMail();
2040
2041        vector<BspLeaf *>::const_iterator it, it_end = leaves.end();
2042
2043        // find merge candidates and push them into queue
2044        for (it = leaves.begin(); it != it_end; ++ it)
2045        {
2046                BspLeaf *leaf = *it;
2047
2048                // no leaf is part of two merge candidates
2049                if (!leaf->Mailed())
2050                {
2051                        leaf->Mail();
2052
2053                        vector<BspLeaf *> neighbors;
2054                        FindNeighbors(leaf, neighbors, true);
2055
2056                        vector<BspLeaf *>::const_iterator nit,
2057                                nit_end = neighbors.end();
2058
2059                        for (nit = neighbors.begin(); nit != nit_end; ++ nit)
2060                        {
2061                                BspMergeCandidate mc = BspMergeCandidate(leaf, *nit);
2062                                mergeQueue.push(mc);
2063
2064                                BspMergeCandidate::sOverallCost += mc.GetLeaf1Cost();
2065                                BspMergeCandidate::sOverallCost += mc.GetLeaf2Cost();
2066                        }
2067                }
2068        }
2069
2070        int merged = 0;
[482]2071        int mergedSiblings = 0;
2072        int accTreeDist = 0;
2073        int maxTreeDist = 0;
2074        const bool mergeStats = true;
[478]2075
[482]2076
[480]2077        //-- use priority queue to merge leaf pairs
[479]2078        while (!mergeQueue.empty() && (vcSize > mMergeMinViewCells) &&
[482]2079                   (mergeQueue.top().GetMergeCost() <
[479]2080                    mMergeMaxCostRatio * BspMergeCandidate::sOverallCost))
[478]2081        {
[480]2082                //Debug << "mergecost: " << mergeQueue.top().GetMergeCost() / BspMergeCandidate::sOverallCost << " " << mMergeMaxCostRatio << endl;
[478]2083                BspMergeCandidate mc = mergeQueue.top();
2084                mergeQueue.pop();
2085
2086                // both view cells equal!
2087                if (mc.GetLeaf1()->GetViewCell() == mc.GetLeaf2()->GetViewCell())
2088                        continue;
2089
2090                if (mc.Valid())
2091                {
2092                        ViewCell::NewMail();
2093                        MergeViewCells(mc.GetLeaf1(), mc.GetLeaf2());
2094                        -- vcSize;
2095                        // increase absolute merge cost
2096                        BspMergeCandidate::sOverallCost += mc.GetMergeCost();
[482]2097
2098                        //-- stats
2099                        ++ merged;
2100
2101                        if (mc.GetLeaf1()->IsSibling(mc.GetLeaf2()))
2102                                ++ mergedSiblings;
2103
2104                        if (mergeStats)
2105                        {
2106                                const int dist = TreeDistance(mc.GetLeaf1(), mc.GetLeaf2());
2107
2108                                if (dist > maxTreeDist)
2109                                        maxTreeDist = dist;
2110
2111                                accTreeDist += dist;
2112                        }
[478]2113                }
2114                // merge candidate not valid, because one of the leaves was already
2115                // merged with another one
2116                else
2117                {
2118                        // validate and reinsert into queue
2119                        mc.SetValid();
2120                        mergeQueue.push(mc);
2121                        //Debug << "validate " << mc.GetMergeCost() << endl;
2122                }
2123        }
2124
2125        // collapse tree according to view cell partition
[479]2126        CollapseTree(mRoot);
[478]2127        // revalidate leaves
[479]2128        RepairVcLeafLists();
[478]2129
[482]2130        Debug << "Merged " << merged << " nodes of " << savedVcSize
2131                  << " (merged " << mergedSiblings << " siblings)" << endl;
[478]2132
[482]2133        if (mergeStats)
2134        {
2135                Debug << "maximal tree distance: " << maxTreeDist << endl;
2136                Debug << "Avg tree distance: " << (float)accTreeDist / (float)merged << endl;
2137        }
2138
[478]2139        //TODO: should return sample contributions
2140        return merged;
2141}
2142
2143
2144bool VspBspTree::MergeViewCells(BspLeaf *l1, BspLeaf *l2)
2145{
[482]2146        //-- change pointer to view cells of all leaves associated
[478]2147        //-- with the previous view cells
2148        BspViewCell *fVc = l1->GetViewCell();
2149        BspViewCell *bVc = l2->GetViewCell();
2150
2151        BspViewCell *vc = dynamic_cast<BspViewCell *>(
2152                mViewCellsManager->MergeViewCells(*fVc, *bVc));
2153
2154        // if merge was unsuccessful
2155        if (!vc) return false;
2156
2157        // set new size of view cell
[479]2158        vc->SetArea(fVc->GetArea() + bVc->GetArea());
[478]2159
2160        vector<BspLeaf *> fLeaves = fVc->mLeaves;
2161        vector<BspLeaf *> bLeaves = bVc->mLeaves;
2162
2163        vector<BspLeaf *>::const_iterator it;
2164
2165        //-- change view cells of all the other leaves the view cell belongs to
2166        for (it = fLeaves.begin(); it != fLeaves.end(); ++ it)
2167        {
2168                (*it)->SetViewCell(vc);
2169                vc->mLeaves.push_back(*it);
2170        }
2171
2172        for (it = bLeaves.begin(); it != bLeaves.end(); ++ it)
2173        {
2174                (*it)->SetViewCell(vc);
2175                vc->mLeaves.push_back(*it);
2176        }
2177
2178        vc->Mail();
2179
2180        // clean up old view cells
2181        DEL_PTR(fVc);
2182        DEL_PTR(bVc);
2183
2184        return true;
2185}
2186
2187
2188void VspBspTree::SetViewCellsManager(ViewCellsManager *vcm)
2189{
2190        mViewCellsManager = vcm;
2191}
2192
2193/************************************************************************/
2194/*                BspMergeCandidate implementation                      */
2195/************************************************************************/
2196
2197
2198BspMergeCandidate::BspMergeCandidate(BspLeaf *l1, BspLeaf *l2):
2199mMergeCost(0),
2200mLeaf1(l1),
2201mLeaf2(l2),
2202mLeaf1Id(l1->GetViewCell()->mMailbox),
2203mLeaf2Id(l2->GetViewCell()->mMailbox)
2204{
2205        EvalMergeCost();
2206}
2207
2208float BspMergeCandidate::GetLeaf1Cost() const
2209{
2210        BspViewCell *vc = mLeaf1->GetViewCell();
2211        return vc->GetPvs().GetSize() * vc->GetArea();
2212}
2213
2214float BspMergeCandidate::GetLeaf2Cost() const
2215{
2216        BspViewCell *vc = mLeaf2->GetViewCell();
2217        return vc->GetPvs().GetSize() * vc->GetVolume();
2218}
2219
2220void BspMergeCandidate::EvalMergeCost()
2221{
2222        //-- compute pvs difference
2223        BspViewCell *vc1 = mLeaf1->GetViewCell();
2224        BspViewCell *vc2 = mLeaf2->GetViewCell();
2225
2226        const int diff1 = vc1->GetPvs().Diff(vc2->GetPvs());
2227        const int vcPvs = diff1 + vc1->GetPvs().GetSize();
2228
2229        //-- compute ratio of old cost
2230        //-- (added size of left and right view cell times pvs size)
2231        //-- to new rendering cost (size of merged view cell times pvs size)
2232        const float oldCost = GetLeaf1Cost() + GetLeaf2Cost();
[482]2233
[478]2234        const float newCost =
2235                (float)vcPvs * (vc1->GetArea() + vc2->GetArea());
2236
2237        mMergeCost = newCost - oldCost;
2238
2239//      if (vcPvs > sMaxPvsSize) // strong penalty if pvs size too large
2240//              mMergeCost += 1.0;
2241}
2242
2243void BspMergeCandidate::SetLeaf1(BspLeaf *l)
2244{
2245        mLeaf1 = l;
2246}
2247
2248void BspMergeCandidate::SetLeaf2(BspLeaf *l)
2249{
2250        mLeaf2 = l;
2251}
2252
2253BspLeaf *BspMergeCandidate::GetLeaf1()
2254{
2255        return mLeaf1;
2256}
2257
2258BspLeaf *BspMergeCandidate::GetLeaf2()
2259{
2260        return mLeaf2;
2261}
2262
2263bool BspMergeCandidate::Valid() const
2264{
2265        return
2266                (mLeaf1->GetViewCell()->mMailbox == mLeaf1Id) &&
2267                (mLeaf2->GetViewCell()->mMailbox == mLeaf2Id);
2268}
2269
2270float BspMergeCandidate::GetMergeCost() const
2271{
2272        return mMergeCost;
2273}
2274
2275void BspMergeCandidate::SetValid()
2276{
2277        mLeaf1Id = mLeaf1->GetViewCell()->mMailbox;
2278        mLeaf2Id = mLeaf2->GetViewCell()->mMailbox;
2279
2280        EvalMergeCost();
2281}
Note: See TracBrowser for help on using the repository browser.