source: GTP/trunk/Lib/Vis/Preprocessing/src/GvsPreprocessor.cpp @ 2727

Revision 2727, 43.5 KB checked in by mattausch, 16 years ago (diff)
  • Property svn:executable set to *
RevLine 
[1460]1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
[1473]4#include "VssRay.h"
5#include "ViewCellsManager.h"
[1486]6#include "Triangle3.h"
[1489]7#include "IntersectableWrapper.h"
[1500]8#include "Plane3.h"
[1521]9#include "RayCaster.h"
[1522]10#include "Exporter.h"
[1545]11#include "SamplingStrategy.h"
[1990]12#include "BvHierarchy.h"
[2116]13#include "Polygon3.h"
[2643]14#include "IntersectableWrapper.h"
[2726]15#include "Timer/PerfTimer.h"
[1460]16
[1473]17
[1460]18namespace GtpVisibilityPreprocessor
19{
20 
[2633]21#define GVS_DEBUG 0
[2669]22#define NOT_ACCOUNTED_OBJECT 0
23#define ACCOUNTED_OBJECT 2
[1934]24
[2705]25
[2669]26static const float MIN_DIST = 0.001f;
27
28static ObjectContainer myobjects;
[2726]29static int sInvalidSamples = 0;
[2669]30
[2726]31///////////
32//-- timers
[2669]33
[2726]34
35static PerfTimer rayTimer;
36static PerfTimer kdPvsTimer;
37static PerfTimer gvsTimer;
38static PerfTimer initialTimer;
39static PerfTimer intersectionTimer;
40static PerfTimer preparationTimer;
41static PerfTimer mainLoopTimer;
42static PerfTimer contributionTimer;
43static PerfTimer castTimer;
44static PerfTimer generationTimer;
45
46
47/////////////////////
48
49
[2669]50/** Visualization structure for the GVS algorithm.
51*/
[1522]52struct VizStruct
53{
54        Polygon3 *enlargedTriangle;
55        Triangle3 originalTriangle;
56        VssRay *ray;
57};
[1460]58
[2669]59static vector<VizStruct> vizContainer;
[2048]60
[1990]61
[1522]62
[2648]63
[1533]64GvsPreprocessor::GvsPreprocessor():
[1545]65Preprocessor(),
[1996]66mProcessedViewCells(0),
[2625]67mCurrentViewCell(NULL),
[2691]68mCurrentViewPoint(Vector3(0.0f, 0.0f, 0.0f)),
69mOnlyRandomSampling(false)
70//mOnlyRandomSampling(true)
[1460]71{
[1486]72        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
73        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
[2048]74        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
[1996]75        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
[1486]76        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
[1500]77        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
[1990]78        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
[1996]79        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
[1473]80
[2048]81        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
82
[2615]83        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
84
85
[1934]86        char gvsStatsLog[100];
87        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
88        mGvsStatsStream.open(gvsStatsLog);
89
[2677]90        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
91        cout << "number of samples per pass: " << mSamplesPerPass << endl;
[2691]92        cout << "only random sampling: " << mOnlyRandomSampling << endl;
[2677]93
[1486]94        Debug << "Gvs preprocessor options" << endl;
95        Debug << "number of total samples: " << mTotalSamples << endl;
96        Debug << "number of initial samples: " << mInitialSamples << endl;
[1501]97        Debug << "threshold: " << mThreshold << endl;
[1934]98        Debug << "epsilon: " << mEps << endl;
99        Debug << "stats: " << gvsStatsLog << endl;
[1996]100        Debug << "per view cell: " << mPerViewCell << endl;
101        Debug << "max view cells: " << mMaxViewCells << endl;
102        Debug << "min contribution: " << mMinContribution << endl;
[1486]103
[2691]104        mDistribution = new ViewCellBasedDistribution(*this, NULL);
[1934]105
106        mGvsStats.Reset();
[2643]107
[2695]108        // hack: some generic statistical values that can be used
[2648]109        // by an application using the preprocessor
[2691]110        for (int i = 0; i < 2; ++ i)
111                mGenericStats[i] = 0;
[1460]112}
113
[1473]114
[1990]115GvsPreprocessor::~GvsPreprocessor()
116{
[2691]117        delete mDistribution;
[1996]118        ClearRayQueue();
119}
120
121
122void GvsPreprocessor::ClearRayQueue()
123{
[1990]124        // clean ray queue
125        while (!mRayQueue.empty())
126        {
127                // handle next ray
128                VssRay *ray = mRayQueue.top();
129                mRayQueue.pop();
130
[2695]131                // note: deletion of the ray is handled by ray pool
[1990]132        }
133}
134
135
[2625]136ViewCell *GvsPreprocessor::NextViewCell()
[1982]137{
[1996]138        if (mProcessedViewCells == (int)mViewCells.size())
[2625]139                return NULL; // no more view cells
[1982]140
[2625]141        ViewCell *vc = mViewCells[mProcessedViewCells];
[1982]142
[2625]143   if (!vc->GetMesh())
144                mViewCellsManager->CreateMesh(vc);
[1990]145
[2625]146        mGvsStats.mViewCellId = vc->GetId();
[1996]147
[2625]148        Debug << "vc: " << vc->GetId() << endl;
[1996]149
150        ++ mProcessedViewCells;
[1982]151   
[2625]152        return vc;
[1982]153}
154
155
[1996]156int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
157                                                                                const Triangle3 &hitTriangle,
158                                                                                const VssRay &oldRay)
[1460]159{
[1932]160        // the predicted hitpoint: we expect to hit the same mesh again
161        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
162
163        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
164        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
165       
166        // distance large => this is likely to be a discontinuity
[2726]167        if ((predictedLen - len) > mThreshold)
[2695]168        // q: rather use relative distance?
[2726]169        //if ((predictedLen / len) > mThreshold)
[1500]170        {
[2726]171#if 0
[1933]172                // apply reverse sampling to find the gap
[1500]173                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
[1933]174
[2695]175                // check if reverse sampling was successful
176                if (newRay)
177                {
178                        // set flag for visualization
179                        if (0) newRay->mFlags |= VssRay::ReverseSample;
180               
[2726]181                        rayTimer.Entry();
[2695]182                        // check if ray can be processed further
183                        // note: ray deletion handled by ray pool)
184                        HandleRay(newRay);
[2726]185                        rayTimer.Exit();
[2695]186
[1996]187                        return 1;
[2695]188                }
[2726]189#else
190                static VssRayContainer reverseRays;
191                reverseRays.clear();
192
193                // apply reverse sampling to find the gap
194                ReverseSampling2(currentRay, hitTriangle, oldRay, reverseRays);
195
196                rayTimer.Entry();
197
198                int castRays = 0;
199                // check if reverse sampling was successful
200                for (size_t i = 0; i < reverseRays.size(); ++ i)
201                {
202                        // check if ray can be processed further
203                        // note: ray deletion handled by ray pool)
204                        if (reverseRays[i])
205                        {
206                                ++ castRays;
207                                HandleRay(reverseRays[i]);
208                        }
209                }
210               
211                rayTimer.Exit();
212
213                return castRays;
214
215#endif
[1500]216        }
217
[1996]218        return 0;
[1486]219}
[1473]220
[2053]221
[2705]222int GvsPreprocessor::CountObject(Intersectable *triObj)
[2669]223{
[2705]224        int numObjects = 0;
225
[2687]226        if ((triObj->mCounter != (NOT_ACCOUNTED_OBJECT + 1)) &&
227                (triObj->mCounter != (ACCOUNTED_OBJECT + 1)))
[2669]228        {
229                ++ triObj->mCounter;
[2705]230                ++ numObjects;
[2669]231        }
[2705]232
233        mGenericStats[1] += numObjects;
234
235        return numObjects;
[2669]236}
237
238
239void GvsPreprocessor::UpdateStatsForVisualization(KdIntersectable *kdInt)
240{
[2726]241        int numObj = 0;
242
[2669]243        // count new objects in pvs due to kd node conversion   
244        myobjects.clear();
[2705]245        // also gather duplicates to avoid mailing
246        mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2669]247
248        ObjectContainer::const_iterator oit, oit_end = myobjects.end();
249
250        for (oit = myobjects.begin(); oit != oit_end; ++ oit)
[2726]251                numObj += CountObject(*oit);
[2705]252
253        mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt, numObj);
[2669]254}       
255
256
[2726]257void GvsPreprocessor::AddKdNodeToPvs(const Vector3 &termination)
258{
259        kdPvsTimer.Entry();
260
261        // exchange the triangle with the node in the pvs for kd pvs
262        KdNode *node = mKdTree->GetPvsNode(termination);
263
264        //KdNode *node = mKdTree->GetPvsNodeCheck(ray.mTermination, obj);
265        //if (!node) cerr << "e " << obj->GetBox() << " " << ray.mTermination << endl; else
266        if (!node->Mailed())
267        {
268                // add to pvs
269                node->Mail();
270                KdIntersectable *kdInt = mKdTree->GetOrCreateKdIntersectable(node);
271                mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
272
273                if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
274        }
275
276        kdPvsTimer.Exit();
277}
278
279
[1999]280bool GvsPreprocessor::HasContribution(VssRay &ray)
[1486]281{
[1999]282        if (!ray.mTerminationObject)
283                return false;
[1933]284
[2726]285        contributionTimer.Entry();
286
[1999]287        bool result;
288
[1977]289        if (!mPerViewCell)
290        {
[1999]291                // store the rays + the intersected view cells
[2726]292                const bool storeViewCells = false;
[1999]293
294                mViewCellsManager->ComputeSampleContribution(ray,
[1977]295                                                                                                         true,
[1999]296                                                                                                         storeViewCells,
[1990]297                                                                                                         true);
[1999]298
299                result = ray.mPvsContribution > 0;
[1977]300        }
[2625]301        else // original per view cell gvs
[1977]302        {
[2692]303                // test if triangle was accounted for yet
[2726]304                result = AddTriangleObject(ray.mTerminationObject);
[2691]305               
[2726]306                if (mUseKdPvs)
307                        AddKdNodeToPvs(ray.mTermination);
308        }
[2691]309
[2726]310        contributionTimer.Exit();
[1999]311
312        return result;
313}
314
315
316bool GvsPreprocessor::HandleRay(VssRay *vssRay)
317{
318        if (!HasContribution(*vssRay))
[1977]319                return false;
320
[2005]321        if (0 && GVS_DEBUG)
[1990]322                mVssRays.push_back(new VssRay(*vssRay));
323
[1977]324        // add new ray to ray queue
325        mRayQueue.push(vssRay);
326
[1990]327        ++ mGvsStats.mTotalContribution;
[1533]328
[1977]329        return true;
[1460]330}
331
[1500]332
333/** Creates 3 new vertices for triangle vertex with specified index.
[1489]334*/
[1932]335void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
336                                                                                          const Triangle3 &hitTriangle,
337                                                                                          const VssRay &ray,
338                                                                                          const int index) const
[1460]339{
[1486]340        const int indexU = (index + 1) % 3;
341        const int indexL = (index == 0) ? 2 : index - 1;
342
[1524]343        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
[1486]344        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
345        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
[1492]346       
[1533]347        const float len = Magnitude(a);
[1932]348       
[1523]349        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
350        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
[1524]351        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
352                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
[1492]353
[1486]354        // compute the new three hit points
[1500]355        // pi, i + 1:  pi+ e·|pi-xp|·di, j
[1932]356        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
[1500]357        // pi, i - 1:  pi+ e·|pi-xp|·di, j
[1932]358    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
[1500]359        // pi, i:  pi+ e·|pi-xp|·di, j
[1932]360        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
[1489]361       
[1524]362        vertices.push_back(pt2);
363        vertices.push_back(pt3);
[1500]364        vertices.push_back(pt1);
[1489]365}
366
367
[1500]368void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
369                                                                          const Triangle3 &hitTriangle,
[1932]370                                                                          const VssRay &ray) const
[1500]371{
[1932]372        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
373        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
374        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
[1500]375}
[1492]376
[1500]377
[1932]378Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
379                                                                                           const Triangle3 &hitTriangle,
380                                                                                           const VssRay &oldRay) const
[1489]381{
[1932]382        // find the intersection of the plane induced by the
383        // hit triangle with the new ray
[1500]384        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
385
386        const Vector3 hitPt =
387                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
388       
389        return hitPt;
390}
391
392
393static bool EqualVisibility(const VssRay &a, const VssRay &b)
394{
395        return a.mTerminationObject == b.mTerminationObject;
396}
397
398
399int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
400                                                                   const Vector3 &p1,
401                                                                   const Vector3 &p2,
[1932]402                                                                   const VssRay &ray1,
403                                                                   const VssRay &ray2,
[1500]404                                                                   const VssRay &oldRay)
[2048]405{
406        //cout <<"y"<<Magnitude(p1 - p2) << " ";
[1996]407        int castRays = 0;
408
[1990]409        // cast reverse rays if necessary
[1996]410        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
411        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
[1500]412
[2017]413        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
[1500]414        {
[1996]415                return castRays;
[1500]416        }
[1932]417       
[1990]418        // the new subdivision point
419        const Vector3 p = (p1 + p2) * 0.5f;
[2017]420        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
[2726]421
[1990]422        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
[1932]423
[2726]424#if 1
425        castTimer.Entry();
426        // cast single ray to check if a triangle was missed
[2727]427        // note: not efficient!!
[1996]428        VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
[2726]429        castTimer.Exit();
[1996]430        ++ castRays;
[1580]431
[2726]432        // this ray will not be further processed
433        // note: ray deletion is handled by ray pool
[1996]434        if (!newRay) return castRays;
[1580]435
[2727]436        rayTimer.Entry();
437
[2726]438        // new triangle discovered? => add new ray to queue
439        HandleRay(newRay);
[2727]440
[2726]441        rayTimer.Exit();
[1990]442
[2726]443#else
444
445        // cast ray into the new point
446        static SimpleRayContainer importanceRays;
447        importanceRays.clear();
448
449        generationTimer.Entry();
450
451       
452        importanceRays.push_back(sray);
453
454        const int numRandomRays = 15;
455
456        GenerateJitteredRays(importanceRays, sray, numRandomRays, 0);
457        GenerateRays(numRandomRays, *mDistribution, importanceRays, sInvalidSamples);
458
459        generationTimer.Exit();
460       
461        // for the original implementation we don't cast double rays
462        const bool castDoubleRays = !mPerViewCell;
463        // cannot prune invalid rays because we have to compare adjacent rays
464        const bool pruneInvalidRays = false;
465
466        static VssRayContainer vssRays;
467        vssRays.clear();
468
469        castTimer.Entry();
470        CastRays(importanceRays, vssRays, castDoubleRays, pruneInvalidRays);
471        castTimer.Exit();
472
473        castRays += (int)vssRays.size();
474
475        VssRay *newRay = vssRays.empty() ? NULL : vssRays[0];
476
477        // new triangle discovered? => add new ray to queue
478        rayTimer.Entry();
479        for (size_t i = 0; i < vssRays.size(); ++ i)
480        {
481                if (vssRays[i])
482                        HandleRay(vssRays[i]);
483        }
484
485        rayTimer.Exit();
486
[1990]487        // this ray will not be further processed
[2692]488        // note: ray deletion is handled by ray pool
[2726]489        if (!newRay) return castRays;
490#endif
[1990]491
[2726]492        //newRay->mFlags |= VssRay::BorderSample;
493
494        // subdivide further
495        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
496        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
497       
[1996]498        return castRays;
[1500]499}
500
501
502int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
503{
504        Intersectable *tObj = currentRay.mTerminationObject;
[2726]505
506        // question matt: can this be possible?
[2597]507        if (!tObj) return 0;
508
[1486]509        Triangle3 hitTriangle;
[1489]510
511        // other types not implemented yet
512        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2017]513                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[1522]514        else
[2601]515                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
[1489]516
[2601]517        //cout << "type: " << Intersectable::GetTypeName(tObj) << endl;
518
[1500]519        VertexContainer enlargedTriangle;
520       
521        /// create 3 new hit points for each vertex
522        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
523       
524        /// create rays from sample points and handle them
[2726]525        static SimpleRayContainer simpleRays;
526        simpleRays.clear();
527        //simpleRays.reserve(9);
[1486]528
[1500]529        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
[1486]530
[1500]531        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
532        {
533                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
[1990]534
[1883]535                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
[1990]536                simpleRays.AddRay(sr); 
[1500]537        }
[1522]538
[1566]539        if (0)
540        {
[1932]541                // visualize enlarged triangles
[1566]542                VizStruct dummy;
543                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
544                dummy.originalTriangle = hitTriangle;
545                vizContainer.push_back(dummy);
546        }
547
[2726]548       
[1996]549        //////////
[2726]550        //-- fill up simple rays with random rays so we can cast 16 rays at a time
[1996]551
552        const int numRandomRays = 16 - (int)simpleRays.size();
[2726]553        SimpleRay mainRay = SimpleRay(currentRay.GetOrigin(), currentRay.GetNormalizedDir(), SamplingStrategy::GVS, 1.0f);
[1996]554
[2726]555        GenerateJitteredRays(simpleRays, mainRay, numRandomRays, 0);
556        //GenerateRays(numRandomRays, *mDistribution, simpleRays, sInvalidSamples);
[1996]557
[2053]558
[1996]559        /////////////////////
[2726]560        //-- cast rays to vertices and determine visibility
561       
562        VssRayContainer vssRays;
[1996]563
[2726]564        // for the original implementation we don't cast double rays
565        const bool castDoubleRays = !mPerViewCell;
566        // cannot prune invalid rays because we have to compare adjacent rays
567        const bool pruneInvalidRays = false;
568
569        castTimer.Entry();
[1996]570        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
[2726]571        castTimer.Exit();
[1932]572
[1996]573        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
[2726]574        int castRays = (int)simpleRays.size();
[2648]575
[2726]576        // handle cast rays
577        EnqueueRays(vssRays);
578       
[2648]579#if 0
[1580]580        // set flags
[2648]581        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
[1996]582        for (rit = vssRays.begin(); rit != rit_end; ++ rit, ++ i)
[2053]583                (*rit)->mFlags |= VssRay::BorderSample;
[2648]584#endif
585
[1999]586
[1500]587    // recursivly subdivide each edge
[1996]588        for (int i = 0; i < numBorderSamples; ++ i)
[1500]589        {
[1932]590                castRays += SubdivideEdge(hitTriangle,
591                                                                  enlargedTriangle[i],
[1996]592                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
[1932]593                                                                  *vssRays[i],
[1996]594                                                                  *vssRays[(i + 1) % numBorderSamples],
[1932]595                                                                  currentRay);
[1500]596        }
[1999]597       
[1934]598        mGvsStats.mBorderSamples += castRays;
[2048]599       
[1533]600        return castRays;
[1473]601}
602
603
[1996]604bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
605                                                                          const Triangle3 &occluder,
606                                                                          const VssRay &oldRay,
607                                                                          Vector3 &newPoint) const
[1933]608{
609        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
610        //-- with the newly found occluder (xold is the previous ray from
611        //-- which x was generated). On the intersecting line, we select a point
612        //-- pnew which lies just outside of the new triangle so the ray
613        //-- just passes through the gap
614
615        const Plane3 plane(currentRay.GetOrigin(),
616                                           currentRay.GetTermination(),
617                                           oldRay.GetTermination());
618       
619        Vector3 pt1, pt2;
620
621        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
622
623        if (!intersects)
[1996]624        {
[1999]625                //cerr << "big error!! no intersection " << pt1 << " " << pt2 << endl;
[1996]626                return false;
627        }
[1933]628
629        // get the intersection point on the old ray
630        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
631
632        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
633        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
634
[2695]635        // evaluate new hitpoint just outside the triangle
[1933]636        // the point is chosen to be on the side closer to the original ray
637        if (Distance(pt1, pt3) < Distance(pt2, pt3))
[2695]638                newPoint = pt1 + mEps * (pt1 - pt2);
[1933]639        else
[2695]640                newPoint = pt2 + mEps * (pt2 - pt1);
[1933]641
[1934]642        //cout << "passing point: " << newPoint << endl << endl;
[1996]643        return true;
[1500]644}
645
646
647VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
648                                                                                 const Triangle3 &hitTriangle,
649                                                                                 const VssRay &oldRay)
650{
[1933]651        // get triangle occluding the path to the hit mesh
652        Triangle3 occluder;
653        Intersectable *tObj = currentRay.mTerminationObject;
[1934]654
[1933]655        // q: why can this happen?
656        if (!tObj)
657                return NULL;
658
659        // other types not implemented yet
660        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
[2017]661                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
[1933]662        else
[2048]663                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
[2726]664       
[1933]665        // get a point which is passing just outside of the occluder
[1996]666    Vector3 newPoint;
667
[2695]668        // q: why is there sometimes no intersecton found?
[1996]669        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
670                return NULL;
671
[1500]672        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
673
[1990]674        Vector3 newDir, newOrigin;
675
[2726]676        //////////////
[1932]677        //-- Construct the mutated ray with xnew,
678        //-- dir = predicted(x)- pnew as direction vector
[2726]679
[1990]680        newDir = predicted - newPoint;
[1932]681
[1933]682        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
[1500]683        // difficult to say!!
[1935]684        const float offset = 0.5f;
[1990]685        newOrigin = newPoint - newDir * offset;
686       
[2694]687
[1990]688        //////////////
689        //-- for per view cell sampling, we must check for intersection
690        //-- with the current view cell
[1500]691
[1990]692    if (mPerViewCell)
693        {
694                // send ray to view cell
695                static Ray ray;
696                ray.Clear();
697                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
698               
699                //cout << "z";
700                // check if ray intersects view cell
701                if (!mCurrentViewCell->CastRay(ray))
702                        return NULL;
[1981]703
[1990]704                Ray::Intersection &hit = ray.intersections[0];
705       
706                //cout << "q";
707                // the ray starts from the view cell
708                newOrigin = ray.Extrap(hit.mT);
709        }
[1981]710
[2695]711        ++ mGvsStats.mReverseSamples;
712
[1933]713        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
[1571]714
[1933]715        VssRay *reverseRay =
[1996]716                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
[1933]717
718        return reverseRay;
[1473]719}
720
[1489]721
[2726]722bool GvsPreprocessor::ReverseSampling2(const VssRay &currentRay,
723                                                                           const Triangle3 &hitTriangle,
724                                                                           const VssRay &oldRay,
725                                                                           VssRayContainer &reverseRays)
726{
727        // get triangle occluding the path to the hit mesh
728        Triangle3 occluder;
729        Intersectable *tObj = currentRay.mTerminationObject;
730
731        // q: why can this happen?
732        if (!tObj)
733                return NULL;
734
735        // other types not implemented yet
736        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
737                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
738        else
739                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
740       
741        // get a point which is passing just outside of the occluder
742    Vector3 newPoint;
743
744        // q: why is there sometimes no intersecton found?
745        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
746                return NULL;
747
748        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
749
750        Vector3 newDir, newOrigin;
751
752        //////////////
753        //-- Construct the mutated ray with xnew,
754        //-- dir = predicted(x)- pnew as direction vector
755
756        newDir = predicted - newPoint;
757
758        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
759        // difficult to say!!
760        const float offset = 0.5f;
761        newOrigin = newPoint - newDir * offset;
762       
763
764        //////////////
765        //-- for per view cell sampling, we must check for intersection
766        //-- with the current view cell
767
768    if (mPerViewCell)
769        {
770                // send ray to view cell
771                static Ray ray;
772
773                ray.Clear();
774                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
775               
776                // check if ray intersects view cell
777                if (!mCurrentViewCell->CastRay(ray))
778                        return NULL;
779
780                Ray::Intersection &hit = ray.intersections[0];
781       
782                // the ray starts from the view cell
783                newOrigin = ray.Extrap(hit.mT);
784        }
785
786        static SimpleRayContainer reverseSimpleRays;
787        reverseSimpleRays.clear();
788
789        SimpleRay mainRay = SimpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
790
791        reverseSimpleRays.push_back(mainRay);
792        GenerateJitteredRays(reverseSimpleRays, mainRay, 15, 0);
793
794        castTimer.Entry();
795        CastRays(reverseSimpleRays, reverseRays, false, false);
796        castTimer.Exit();
797
[2727]798        mGvsStats.mReverseSamples += (int)reverseRays.size();
[2726]799
800        return true;
801}
802
803
[2691]804int GvsPreprocessor::CastInitialSamples(int numSamples)
[1489]805{       
[2726]806        initialTimer.Entry();
[1595]807
[1489]808        // generate simple rays
[2726]809        static SimpleRayContainer simpleRays;
810        simpleRays.clear();
811
812        generationTimer.Entry();
[2727]813
[2691]814        ViewCellBorderBasedDistribution vcStrat(*this, mCurrentViewCell);
[2727]815        GenerateRays(numSamples, *mDistribution, simpleRays, sInvalidSamples);
816
[2726]817        generationTimer.Exit();
[1990]818
[2727]819        // cast generated samples
[2726]820        static VssRayContainer samples;
821        samples.clear();
822
[1996]823        const bool castDoubleRays = !mPerViewCell;
[1990]824        const bool pruneInvalidRays = true;
825       
[2727]826#if 0
[2726]827        castTimer.Entry();
[2727]828
[1996]829        CastRays(simpleRays, samples, castDoubleRays, pruneInvalidRays);
[2727]830       
[2726]831        castTimer.Exit();
[1999]832
[2727]833#else
834        static SimpleRayContainer jitteredRays;
835
836        for (size_t i = 0; i < simpleRays.size(); ++ i)
837        {
838                SimpleRay mainRay = simpleRays[i];
839               
840                jitteredRays.clear();
841                jitteredRays.push_back(mainRay);
842
843                generationTimer.Entry();
844
845                GenerateJitteredRays(jitteredRays, mainRay, 15, 0);
846
847                generationTimer.Exit();
848                castTimer.Entry();
849
850                CastRays(jitteredRays, samples, castDoubleRays, pruneInvalidRays);
851
852                castTimer.Entry();
853        }
854#endif
855
[1489]856        // add to ray queue
[2726]857        EnqueueRays(samples);
[1533]858
[2726]859        initialTimer.Exit();
860
[2727]861        return (int)samples.size();
[1489]862}
863
864
[2726]865void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
[1489]866{
[2726]867        rayTimer.Entry();
868
[1486]869        // add samples to ray queue
[1473]870        VssRayContainer::const_iterator vit, vit_end = samples.end();
[1576]871        for (vit = samples.begin(); vit != vit_end; ++ vit)
[1473]872        {
[1999]873                VssRay *ray = *vit;
[2053]874                HandleRay(ray);
[2726]875                // note: deletion of invalid samples handked by ray pool
[1460]876        }
[2726]877
878        rayTimer.Exit();
[1460]879}
880
[1473]881
[1990]882int GvsPreprocessor::ProcessQueue()
[1460]883{
[2726]884        gvsTimer.Entry();
885
[2695]886        ++ mGvsStats.mGvsRuns;
[1545]887
[2687]888        int castSamples = 0;
889
[2726]890        while (!mRayQueue.empty())
[2690]891        {
[1990]892                // handle next ray
893                VssRay *ray = mRayQueue.top();
894                mRayQueue.pop();
[1996]895               
[2726]896                castSamples += AdaptiveBorderSampling(*ray);
[2687]897                // note: don't have to delete because handled by ray pool
[1473]898        }
899
[2726]900        gvsTimer.Exit();
[2048]901
[1533]902        return castSamples;
[1460]903}
904
[1473]905
[1990]906void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
[1460]907{
[1990]908        VssRayContainer vcRays, vcRays2, vcRays3;
[1473]909
[1990]910        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
911
912        // prepare some rays for output
913        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
[1473]914        {
[1990]915                //const float p = RandomValue(0.0f, (float)vssRays.size());
[1545]916
[1990]917                if (1)//(p < raysOut)
918                {
919                        if ((*rit)->mFlags & VssRay::BorderSample)
920                                vcRays.push_back(*rit);
921                        else if ((*rit)->mFlags & VssRay::ReverseSample)
922                                vcRays2.push_back(*rit);
923                        else
924                                vcRays3.push_back(*rit);
[2726]925                }
[1460]926        }
[1990]927
[2005]928        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
929        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
[2003]930        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
[1990]931}
932
933
[1999]934void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
[1990]935{
936    Intersectable::NewMail();
937        Material m;
[1528]938       
[2726]939        char str[64]; sprintf_s(str, "pass%06d.wrl", mProcessedViewCells);
[1990]940
941        Exporter *exporter = Exporter::GetExporter(str);
942        if (!exporter)
943                return;
944
[1999]945        ObjectContainer::const_iterator oit, oit_end = objects.end();
946
947        for (oit = objects.begin(); oit != oit_end; ++ oit)
948        {
949                Intersectable *intersect = *oit;
950               
951                m = RandomMaterial();
952                exporter->SetForcedMaterial(m);
953                exporter->ExportIntersectable(intersect);
[1990]954        }
955
956        cout << "vssrays: " << (int)mVssRays.size() << endl;
957        ExportVssRays(exporter, mVssRays);
958
[2597]959
[1990]960        /////////////////
961        //-- export view cell geometry
962
[2597]963        //exporter->SetWireframe();
[1990]964
965        m.mDiffuseColor = RgbColor(0, 1, 0);
966        exporter->SetForcedMaterial(m);
967
[1999]968        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
969        exporter->ExportBox(bbox);
[1990]970        //exporter->SetFilled();
971
[2053]972        delete exporter;
[1460]973}
974
975
[1982]976void GvsPreprocessor::VisualizeViewCells()
977{
[1996]978        char str[64]; sprintf(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
[1982]979                       
980        // visualization
981        if (mGvsStats.mPassContribution > 0)
982        {
983                const bool exportRays = true;
984                const bool exportPvs = true;
985
986                mViewCellsManager->ExportSingleViewCells(mObjects,
987                                                                                                 10,
988                                                                                                 false,
989                                                                                                 exportPvs,
990                                                                                                 exportRays,
991                                                                                                 1000,
992                                                                                                 str);
993        }
994
995        // remove pass samples
996        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
997
998        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
999        {
1000                (*vit)->DelRayRefs();
1001        }
1002}
1003
1004
[2687]1005void GvsPreprocessor::CompileViewCellsFromPointList()
[1996]1006{
[2687]1007        ViewCell::NewMail();
1008
[2648]1009        // Receive list of view cells from view cells manager
[2598]1010        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
[2687]1011
1012        vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
1013
1014        for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
[2048]1015        {
[2687]1016                ViewCellPoints *vp = *vit;
[2048]1017
[2687]1018                if (vp->first) // view cell  specified
[2648]1019                {
[2687]1020                        ViewCell *viewCell = vp->first;
[2048]1021
[2687]1022                        if (!viewCell->Mailed())
1023                        {
1024                                viewCell->Mail();
1025                                mViewCells.push_back(viewCell);
1026
1027                                if (mViewCells.size() >= mMaxViewCells)
1028                                        break;
1029                        }
[2662]1030                }
[2687]1031                else // no view cell specified => compute view cells using view point
1032                {
1033                        SimpleRayContainer::const_iterator rit, rit_end = vp->second.end();
1034
1035                        for (rit = vp->second.begin(); rit != rit_end; ++ rit)
1036                        {
1037                                SimpleRay ray = *rit;
1038
1039                                ViewCell *viewCell = mViewCellsManager->GetViewCell(ray.mOrigin);
1040
1041                                if (viewCell && !viewCell->Mailed())
1042                                {
1043                                        viewCell->Mail();
1044                                        mViewCells.push_back(viewCell);
1045
1046                                        if (mViewCells.size() >= mMaxViewCells)
1047                                                break;
1048                                }
1049                        }
1050                }
[2048]1051        }
[2687]1052}
1053
1054
1055void GvsPreprocessor::CompileViewCellsList()
1056{
1057        if (!mViewCellsManager->GetViewCellPointsList()->empty())
1058        {
1059                cout << "processing view point list" << endl;
1060                CompileViewCellsFromPointList();
1061        }
[2662]1062        else
1063        {
[2687]1064                ViewCell::NewMail();
1065
[2662]1066                while ((int)mViewCells.size() < mMaxViewCells)
[1996]1067                {
[2662]1068                        const int tries = 10000;
1069                        int i = 0;
[1996]1070
[2662]1071                        for (i = 0; i < tries; ++ i)
[1996]1072                        {
[2662]1073                                const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
1074
1075                                ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
1076
1077                                if (!viewCell->Mailed())
1078                                {
1079                                        viewCell->Mail();
1080                                        break;
1081                                }
1082
1083                                mViewCells.push_back(viewCell);
[1999]1084                        }
[2597]1085
[2662]1086                        if (i == tries)
1087                        {
1088                                cerr << "big error! no view cell found" << endl;
1089                                break;
1090                        }
[1999]1091                }
1092        }
[2662]1093
1094        cout << "\ncomputing list of " << mViewCells.size() << " view cells" << endl;
[1999]1095}
[1996]1096
[2669]1097
[2705]1098void GvsPreprocessor::ComputeViewCellGeometryIntersection()
[2687]1099{
[2726]1100        intersectionTimer.Entry();
1101
[2691]1102        AxisAlignedBox3 box = mCurrentViewCell->GetBox();
[2687]1103
[2691]1104        int oldTrianglePvs = (int)mTrianglePvs.size();
1105        int newKdObj = 0;
1106
[2687]1107        // compute pvs kd nodes that intersect view cell
1108        ObjectContainer kdobjects;
[2691]1109
1110        // find intersecting objects not in pvs (i.e., only unmailed)
[2687]1111        mKdTree->CollectKdObjects(box, kdobjects);
1112
1113        ObjectContainer pvsKdObjects;
1114
1115        ObjectContainer::const_iterator oit, oit_end = kdobjects.end();
1116
1117        for (oit = kdobjects.begin(); oit != oit_end; ++ oit)
1118        {
1119        KdIntersectable *kdInt = static_cast<KdIntersectable *>(*oit);
1120       
1121                myobjects.clear();
[2691]1122                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), myobjects);
[2687]1123
1124                // account for kd object pvs
1125                bool addkdobj = false;
1126
1127                ObjectContainer::const_iterator oit, oit_end = myobjects.end();
1128
1129                for (oit = myobjects.begin(); oit != oit_end; ++ oit)
1130                {
1131                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
[2691]1132             
1133                        // test if the triangle itself intersects
[2687]1134                        if (box.Intersects(triObj->GetItem()))
[2691]1135                                addkdobj = AddTriangleObject(triObj);
[2687]1136                }
1137               
[2691]1138                // add node to kd pvs
1139                if (1 && addkdobj)
1140                {
1141                        ++ newKdObj;
1142                        mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
1143                        //mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
[2705]1144                        if (QT_VISUALIZATION_SHOWN) UpdateStatsForVisualization(kdInt);
[2691]1145                }
[2687]1146        }
1147
[2691]1148        cout << "added " << (int)mTrianglePvs.size() - oldTrianglePvs << " triangles (" << newKdObj << " objects) by intersection" << endl;
[2726]1149
1150        intersectionTimer.Exit();
[2687]1151}
1152
[2691]1153
[1990]1154void GvsPreprocessor::PerViewCellComputation()
[1982]1155{
[2690]1156        while (mCurrentViewCell = NextViewCell())
[1999]1157        {
[2726]1158                preparationTimer.Entry();
1159
1160                // hack: reset counters (could be done with a mailing-like approach
[2625]1161                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
1162                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]1163                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[1982]1164
[2726]1165                preparationTimer.Exit();
1166
[2691]1167                mDistribution->SetViewCell(mCurrentViewCell);
[2726]1168
[2690]1169        ComputeViewCell();
[2625]1170        }
1171}
[1990]1172
[1996]1173
[2625]1174void GvsPreprocessor::PerViewCellComputation2()
1175{
1176        while (1)
1177        {
1178                if (!mRendererWidget)
1179                        continue;
[1990]1180
[2690]1181        mCurrentViewCell = mViewCellsManager->GetViewCell(mRendererWidget->GetViewPoint());
[2601]1182
[2625]1183                // no valid view cell or view cell already computed
[2690]1184                if (!mCurrentViewCell || !mCurrentViewCell->GetPvs().Empty() || !mRendererWidget->mComputeGVS)
[2625]1185                        continue;
[2615]1186
[2643]1187                mRendererWidget->mComputeGVS = false;
[2625]1188                // hack: reset counters
1189                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
[2615]1190
[2625]1191                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
[2669]1192                        (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2601]1193
[2690]1194                ComputeViewCell();
[2625]1195                ++ mProcessedViewCells;
1196        }
1197}
[1999]1198
[1982]1199
[2048]1200void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
1201{
1202        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
1203
1204        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
1205        {
1206                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
1207        }
1208}
1209
1210
[1990]1211void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
1212{
1213        ObjectPvs newPvs;
1214        BvhLeaf::NewMail();
1215
1216        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
1217
1218        // output PVS of view cell
1219        while (pit.HasMoreEntries())
1220        {               
[2117]1221                Intersectable *intersect = pit.Next();
[1990]1222
1223                BvhLeaf *bv = intersect->mBvhLeaf;
1224
1225                if (!bv || bv->Mailed())
1226                        continue;
1227               
1228                bv->Mail();
1229
1230                //m.mDiffuseColor = RgbColor(1, 0, 0);
1231                newPvs.AddSampleDirty(bv, 1.0f);
[1982]1232        }
[1990]1233
1234        newPvs.SimpleSort();
1235
1236        currentViewCell->SetPvs(newPvs);
[1982]1237}
1238
[1999]1239 
1240void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1241{
[2695]1242        BvhLeaf::NewMail();
1243
[2053]1244        objectPvs.reserve((int)mTrianglePvs.size());
1245
[1999]1246        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1247
1248        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1249        {
1250                Intersectable *intersect = *oit;
1251       
1252                BvhLeaf *bv = intersect->mBvhLeaf;
1253
[2053]1254                // hack: reset counter
[2669]1255                (*oit)->mCounter = NOT_ACCOUNTED_OBJECT;
[2053]1256
[1999]1257                if (!bv || bv->Mailed())
1258                        continue;
[2615]1259
[1999]1260                bv->Mail();
1261                objectPvs.push_back(bv);
1262        }
1263}
1264
1265
[1990]1266void GvsPreprocessor::GlobalComputation()
1267{
1268        int passSamples = 0;
[2726]1269        int randomSamples = 0;
1270        int gvsSamples = 0;
[1990]1271        int oldContribution = 0;
1272
1273        while (mGvsStats.mTotalSamples < mTotalSamples)
1274        {
[2048]1275                mRayCaster->InitPass();
[2691]1276
[2726]1277                int newRandomSamples, newGvsSamples;
1278
[1990]1279                // Ray queue empty =>
1280                // cast a number of uniform samples to fill ray queue
[2726]1281                newRandomSamples = CastInitialSamples(mInitialSamples);
1282               
[1990]1283                if (!mOnlyRandomSampling)
[2726]1284                        newGvsSamples = ProcessQueue();
[1990]1285
[2726]1286                passSamples += newRandomSamples + newGvsSamples;
1287                mGvsStats.mTotalSamples += newRandomSamples + newGvsSamples;
[1990]1288
[2726]1289                mGvsStats.mRandomSamples += newRandomSamples;
1290                mGvsStats.mGvsSamples += newGvsSamples;
1291
1292
[2048]1293                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
[1990]1294                {
1295                        ++ mPass;
1296
1297                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
[2726]1298                       
[1990]1299                        ////////
1300                        //-- stats
1301
1302                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1303                        mGvsStats.mPass = mPass;
1304                        mGvsStats.Stop();
1305                        mGvsStats.Print(mGvsStatsStream);
1306
1307                        // reset
1308                        oldContribution = mGvsStats.mTotalContribution;
1309                        mGvsStats.mPassContribution = 0;
1310                        passSamples = 0;
1311
1312                        if (GVS_DEBUG)
1313                                VisualizeViewCells();
1314                }
1315        }
1316}
1317
1318
[1489]1319bool GvsPreprocessor::ComputeVisibility()
[1460]1320{
[1533]1321        cout << "Gvs Preprocessor started\n" << flush;
[1545]1322        const long startTime = GetTime();
[1533]1323
[1990]1324        //Randomize(0);
[1934]1325        mGvsStats.Reset();
1326        mGvsStats.Start();
[1545]1327
[1486]1328        if (!mLoadViewCells)
[1563]1329        {       
1330                /// construct the view cells from the scratch
1331                ConstructViewCells();
[1580]1332                // reset pvs already gathered during view cells construction
1333                mViewCellsManager->ResetPvs();
[1563]1334                cout << "finished view cell construction" << endl;
[1486]1335        }
[1460]1336
[1982]1337        if (mPerViewCell)
[1473]1338        {
[2648]1339#if 1
[2597]1340                // provide list of view cells to compute
[1996]1341                CompileViewCellsList();
[2686]1342
[2597]1343                // start per view cell gvs
[2048]1344                PerViewCellComputation();
[2625]1345#else
1346                PerViewCellComputation2();
1347
1348#endif
[1460]1349        }
[1982]1350        else
1351        {
1352                GlobalComputation();
1353        }
[1460]1354
[2687]1355        cout << "cast " << mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M single rays/s" << endl;
[1545]1356
[1934]1357        if (GVS_DEBUG)
1358        {
1359                Visualize();
1360                CLEAR_CONTAINER(mVssRays);
1361        }
[2048]1362       
1363        // export the preprocessed information to a file
1364        if (0 && mExportVisibility)
1365        {
1366                ExportPreprocessedData(mVisibilityFileName);
1367        }
[2648]1368       
1369        // compute the pixel error of this visibility solution
1370        if (mEvaluatePixelError)
1371        {
1372                ComputeRenderError();
1373        }
[1934]1374
[1473]1375        return true;
[1460]1376}
1377
[1522]1378
[2048]1379void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1380{
[2187]1381        // store triangle directly
[2048]1382        mViewCellsManager->DeterminePvsObjects(rays, true);
1383}
1384
1385
[1522]1386void GvsPreprocessor::Visualize()
1387{
1388        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1389
1390        if (!exporter)
1391                return;
1392       
1393        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
[1999]1394       
[1522]1395        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1396        {
[1524]1397                exporter->SetWireframe();
[1522]1398                exporter->ExportPolygon((*vit).enlargedTriangle);
1399                //Material m;
[1524]1400                exporter->SetFilled();
1401                Polygon3 poly = Polygon3((*vit).originalTriangle);
1402                exporter->ExportPolygon(&poly);
[1522]1403        }
1404
[1933]1405        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
[1999]1406
[1933]1407        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1408        {
1409                Intersectable *obj = (*rit)->mTerminationObject;
1410                exporter->ExportIntersectable(obj);
1411        }
1412
[1990]1413        ExportVssRays(exporter, mVssRays);
1414       
[1522]1415        delete exporter;
[1460]1416}
[1522]1417
[1934]1418
1419void GvsStatistics::Print(ostream &app) const
1420{
[2003]1421        app << "#ViewCells\n" << mViewCells << endl;
[2648]1422        app << "#Id\n" << mViewCellId << endl;
1423        app << "#Time\n" << mTimePerViewCell << endl;;
[2690]1424        app << "#TriPvs\n" << mTrianglePvs << endl;
[2648]1425        app << "#ObjectPvs\n" << mPerViewCellPvs << endl;
[2687]1426        app << "#UpdatedPvs\n" << (int)mPvsCost << endl;
[2003]1427
[2677]1428        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1429        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1430       
[2003]1431        app << "#TotalPvs\n" << mTotalPvs << endl;
[2648]1432        app << "#TotalTime\n" << mTotalTime << endl;
[1934]1433        app << "#TotalSamples\n" << mTotalSamples << endl;
[2677]1434
[2717]1435        app << "#AvgPvs: " << mPvsCost / mViewCells << endl;
[2648]1436        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1437       
[2677]1438        if (0)
1439        {
1440                app << "#ReverseSamples\n" << mReverseSamples << endl;
1441                app << "#BorderSamples\n" << mBorderSamples << endl;
[2648]1442
[2677]1443                app << "#Pass\n" << mPass << endl;
1444                app << "#ScDiff\n" << mPassContribution << endl;
[2695]1445                app << "#GvsRuns\n" << mGvsRuns << endl;       
[2003]1446
[2677]1447                app     << "#SamplesContri\n" << mTotalContribution << endl;
1448        }
[2003]1449
1450        app << endl;
[1883]1451}
[1934]1452
1453
[2690]1454void GvsPreprocessor::ComputeViewCell()
[2625]1455{
[2726]1456        const long startTime = GetTime();
[2695]1457
[2726]1458        // initialise
1459        mGvsStats.mPerViewCellSamples = 0;
1460
1461        int oldContribution = 0;
1462        int passSamples = 0;
[2727]1463
1464        for (int i = 0; i < 2; ++ i)
[2726]1465                mGenericStats[i] = 0;
1466
[2695]1467        mTrianglePvs.clear();
1468
[2726]1469
1470        // hack: take bounding box of view cell as view cell bounds
[2691]1471        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
1472
[2726]1473        // use mailing for kd node pvs
[2643]1474        KdNode::NewMail();
[2625]1475
1476        cout << "\n***********************\n"
[2643]1477                << "computing view cell " << mProcessedViewCells
[2625]1478                << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
[2691]1479        cout << "bb: " << mCurrentViewCell->GetBox() << endl;
[2625]1480
[2726]1481        mainLoopTimer.Entry();
[2690]1482
1483        while (1)
1484        {
[2726]1485                sInvalidSamples = 0;
[2691]1486                int oldPvsSize = mCurrentViewCell->GetPvs().GetSize();
[2695]1487               
[2690]1488                mRayCaster->InitPass();
1489
[2726]1490                int newRandomSamples, newGvsSamples, newSamples;
1491
[2690]1492                // Ray queue empty =>
1493                // cast a number of uniform samples to fill ray queue
[2726]1494                newRandomSamples = CastInitialSamples(mInitialSamples);
1495               
[2690]1496                if (!mOnlyRandomSampling)
[2726]1497                        newGvsSamples = ProcessQueue();
[2690]1498
[2726]1499                newSamples = newRandomSamples + newGvsSamples;
1500
[2690]1501                passSamples += newSamples;
[2726]1502                mGvsStats.mPerViewCellSamples += newSamples;
[2690]1503
[2726]1504                mGvsStats.mRandomSamples += newRandomSamples;
1505                mGvsStats.mGvsSamples += newGvsSamples;
1506
1507
[2690]1508                if (passSamples >= mGvsSamplesPerPass)
1509                {
1510                        if (GVS_DEBUG) VisualizeViewCell(mTrianglePvs);
1511
[2691]1512                        //const bool convertPerPass = true;
[2690]1513                        const bool convertPerPass = false;
1514
1515                        if (convertPerPass)
1516                        {       
1517                                int newObjects = ConvertObjectPvs();
1518
1519                                cout << "added " << newObjects << " triangles to triangle pvs" << endl;
1520                                mGvsStats.mTotalContribution += newObjects;
1521                        }
1522
1523                        ++ mPass;
1524                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1525
1526
1527                        ////////
1528                        //-- stats
1529
1530                        mGvsStats.mPass = mPass;
1531
1532                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
1533                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
1534                        cout << "obj contri=" << mCurrentViewCell->GetPvs().GetSize() - oldPvsSize << " (of " << mMinContribution << ")" << endl;
1535
1536                        // termination criterium
1537                        if (mGvsStats.mPassContribution < mMinContribution)
1538                                break;
1539
[2695]1540                        // reset stats
[2690]1541                        oldContribution = mGvsStats.mTotalContribution;
1542                        mGvsStats.mPassContribution = 0;
1543                        passSamples = 0;
1544                }
1545        }
[2677]1546       
[2726]1547        mainLoopTimer.Exit();
1548
[2691]1549        // at last compute objects that directly intersect view cell
[2705]1550        ComputeViewCellGeometryIntersection();
[2726]1551               
[2690]1552
[2677]1553        ////////
1554        //-- stats
[2625]1555
[2690]1556        // timing
1557        mGvsStats.mTimePerViewCell = TimeDiff(startTime, GetTime()) * 1e-3f;
1558
1559        ComputeStats();
1560}
1561
1562
1563void GvsPreprocessor::ComputeStats()
1564{
[2677]1565        // compute pvs size using larger (bvh objects)
1566        // note: for kd pvs we had to do this during gvs computation
[2625]1567        if (!mUseKdPvs)
1568        {
1569                ObjectContainer objectPvs;
1570
1571                // optain object pvs
1572                GetObjectPvs(objectPvs);
1573
1574                // add pvs
1575                ObjectContainer::const_iterator it, it_end = objectPvs.end();
1576
1577                for (it = objectPvs.begin(); it != it_end; ++ it)
1578                {
1579                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1580                }
1581
1582                cout << "triangle pvs of " << (int)mTrianglePvs.size()
1583                        << " was converted to object pvs of " << (int)objectPvs.size() << endl;
1584
1585                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
[2677]1586                mGvsStats.mPvsCost = 0; // todo objectPvs.EvalPvsCost();
[2625]1587        }
[2727]1588        else
[2625]1589        {
[2727]1590                 if (0) // compute pvs kd nodes that intersect view cell
1591                 {
1592                         ObjectContainer mykdobjects;
[2691]1593
[2727]1594                         // extract kd pvs
1595                         ObjectContainer::const_iterator it, it_end = mTrianglePvs.end();
[2691]1596
[2727]1597                         for (it = mTrianglePvs.begin(); it != it_end; ++ it)
1598                         {
1599                                 Intersectable *obj = *it;
1600                                 // find intersecting objects not yet in pvs (i.e., only unmailed)
1601                                 mKdTree->CollectKdObjects(obj->GetBox(), mykdobjects);
1602                         }
[2691]1603
[2727]1604                         // add pvs
1605                         it_end = mykdobjects.end();
[2691]1606
[2727]1607                         for (it = mykdobjects.begin(); it != it_end; ++ it)
1608                         {
1609                                 mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1610                         }
1611                 
1612                         cout << "added " << (int)mykdobjects.size() << " new objects " << endl;
1613                 }
[2691]1614
[2727]1615                 mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
1616                 mGvsStats.mPvsCost = mCurrentViewCell->GetPvs().EvalPvsCost();
[2691]1617
[2625]1618        }
1619
[2677]1620        mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
[2625]1621
1622
[2677]1623        ////////////////
1624        // global values
1625
[2690]1626        mGvsStats.mViewCells = mProcessedViewCells;
[2677]1627        mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
1628        mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
1629    mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
[2625]1630        mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
1631
[2726]1632        cout << "id: " << mCurrentViewCell->GetId() << " pvs cost: "
1633             << mGvsStats.mPvsCost << " pvs tri: " << mTrianglePvs.size() << endl;
1634
[2727]1635        //cout << "invalid samples ratio: " << (float)sInvalidSamples / mGvsStats.mPerViewCellSamples << endl;
[2726]1636
1637        float rayTime = rayTimer.TotalTime();
1638        float kdPvsTime = kdPvsTimer.TotalTime();
1639        float gvsTime = gvsTimer.TotalTime();
1640        float initialTime = initialTimer.TotalTime();
1641        float intersectionTime = intersectionTimer.TotalTime();
1642        float preparationTime = preparationTimer.TotalTime();
1643        float mainLoopTime = mainLoopTimer.TotalTime();
1644        float contributionTime = contributionTimer.TotalTime();
1645        float castTime = castTimer.TotalTime();
1646        float generationTime = generationTimer.TotalTime();
1647
1648        cout << "handleRay              : " << rayTime << endl;
1649        cout << "kd pvs                 : " << kdPvsTime << endl;
1650        cout << "gvs sampling           : " << gvsTime << endl;
1651        cout << "initial sampling       : " << initialTime << endl;
1652        cout << "view cell intersection : " << intersectionTime << endl;
1653        cout << "preparation            : " << preparationTime << endl;
1654        cout << "main loop              : " << mainLoopTime << endl;
1655        cout << "has contribution       : " << contributionTime << endl;
1656        cout << "cast time              : " << castTime << endl;
1657        cout << "generation time       : " << generationTime << endl;
1658
1659        float randomRaysPerSec = mGvsStats.mRandomSamples / (1e6f * initialTime);
1660        float gvsRaysPerSec = mGvsStats.mGvsSamples / (1e6f * gvsTime);
1661
1662        cout << "cast " << randomRaysPerSec << " M random rays/s: " << endl;
1663        cout << "cast " << gvsRaysPerSec << " M gvs rays/s: " << endl;
1664       
[2625]1665        mGvsStats.Stop();
1666        mGvsStats.Print(mGvsStatsStream);
1667
[2690]1668}
[2677]1669
1670
[2690]1671
1672int GvsPreprocessor::ConvertObjectPvs()
1673{
[2726]1674        static ObjectContainer triangles;
1675
[2690]1676        int newObjects = 0;
1677
1678        ObjectPvsIterator pit = mCurrentViewCell->GetPvs().GetIterator();
1679
1680        triangles.clear();
1681
1682        // output PVS of view cell
1683        while (pit.HasMoreEntries())
1684        {               
1685                KdIntersectable *kdInt = static_cast<KdIntersectable *>(pit.Next());
1686
1687                mKdTree->CollectObjectsWithDublicates(kdInt->GetItem(), triangles);
1688
1689                ObjectContainer::const_iterator oit, oit_end = triangles.end();
1690
1691                for (oit = triangles.begin(); oit != oit_end; ++ oit)
1692                {
1693                        if (AddTriangleObject(*oit))
1694                                ++ newObjects;
1695                }
1696        }
1697
1698        return newObjects;
[1934]1699}
[2625]1700
[2690]1701
1702bool GvsPreprocessor::AddTriangleObject(Intersectable *triObj)
1703{
1704        if ((triObj->mCounter < ACCOUNTED_OBJECT))
1705        {
1706                triObj->mCounter += ACCOUNTED_OBJECT;
1707
1708                mTrianglePvs.push_back(triObj);
[2695]1709                //mDummyBuffer.push_back(mGvsStats.mGvsRuns);
[2691]1710                mGenericStats[0] = (int)mTrianglePvs.size();
[2690]1711                return true;
1712        }
1713
1714        return false;
[2625]1715}
[2690]1716
[2691]1717
1718
[2690]1719}
Note: See TracBrowser for help on using the repository browser.