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

Revision 2739, 54.3 KB checked in by mattausch, 16 years ago (diff)

worked on randomized sampling

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