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

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