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

Revision 2643, 33.3 KB checked in by mattausch, 16 years ago (diff)

compiling under release internal

  • 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
16
17
18namespace GtpVisibilityPreprocessor
19{
20 
21#define GVS_DEBUG 0
22static ObjectContainer myobjects;
23
24struct VizStruct
25{
26        Polygon3 *enlargedTriangle;
27        Triangle3 originalTriangle;
28        VssRay *ray;
29};
30
31
32static const float MIN_DIST = 0.001f;
33
34static vector<VizStruct> vizContainer;
35
36GvsPreprocessor::GvsPreprocessor():
37Preprocessor(),
38mSamplingType(SamplingStrategy::VIEWCELL_BASED_DISTRIBUTION),
39mProcessedViewCells(0),
40mCurrentViewCell(NULL),
41mCurrentViewPoint(Vector3(0.0f, 0.0f, 0.0f))
42{
43        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
44        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
45        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.gvsSamplesPerPass", mGvsSamplesPerPass);
46        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.minContribution", mMinContribution);
47        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
48        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
49        Environment::GetSingleton()->GetBoolValue("GvsPreprocessor.perViewCell", mPerViewCell);
50        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.maxViewCells", mMaxViewCells);
51
52        Environment::GetSingleton()->GetBoolValue("Preprocessor.evaluatePixelError", mEvaluatePixelError);
53
54        Environment::GetSingleton()->GetBoolValue("ViewCells.useKdPvs", mUseKdPvs);
55
56
57        char gvsStatsLog[100];
58        Environment::GetSingleton()->GetStringValue("GvsPreprocessor.stats", gvsStatsLog);
59        mGvsStatsStream.open(gvsStatsLog);
60
61        Debug << "Gvs preprocessor options" << endl;
62        Debug << "number of total samples: " << mTotalSamples << endl;
63        Debug << "number of initial samples: " << mInitialSamples << endl;
64        cout << "number of gvs samples per pass: " << mGvsSamplesPerPass << endl;
65        cout << "number of samples per pass: " << mSamplesPerPass << endl;
66        Debug << "threshold: " << mThreshold << endl;
67        Debug << "epsilon: " << mEps << endl;
68        Debug << "stats: " << gvsStatsLog << endl;
69        Debug << "per view cell: " << mPerViewCell << endl;
70        Debug << "max view cells: " << mMaxViewCells << endl;
71        Debug << "min contribution: " << mMinContribution << endl;
72
73        if (1)
74                mOnlyRandomSampling = false;           
75        else
76                mOnlyRandomSampling = true;
77
78        mGvsStats.Reset();
79
80        mGenericStats = 0;
81        mGenericStats2 = 0;
82}
83
84
85GvsPreprocessor::~GvsPreprocessor()
86{
87        ClearRayQueue();
88}
89
90
91void GvsPreprocessor::ClearRayQueue()
92{
93        // clean ray queue
94        while (!mRayQueue.empty())
95        {
96                // handle next ray
97                VssRay *ray = mRayQueue.top();
98                mRayQueue.pop();
99
100                //delete ray;
101        }
102}
103
104
105ViewCell *GvsPreprocessor::NextViewCell()
106{
107        //if (mViewCellsManager->GetNumViewCells() == mProcessedViewCells)
108        //      return false; // no more view cells
109
110        if (mProcessedViewCells == (int)mViewCells.size())
111                return NULL; // no more view cells
112
113        ViewCell *vc = mViewCells[mProcessedViewCells];
114
115   if (!vc->GetMesh())
116                mViewCellsManager->CreateMesh(vc);
117
118        mGvsStats.mViewCellId = vc->GetId();
119
120        Debug << "vc: " << vc->GetId() << endl;
121
122        ++ mProcessedViewCells;
123   
124        return vc;
125}
126
127
128int GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
129                                                                                const Triangle3 &hitTriangle,
130                                                                                const VssRay &oldRay)
131{
132        // the predicted hitpoint: we expect to hit the same mesh again
133        const Vector3 predictedHit = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
134
135        const float predictedLen = Magnitude(predictedHit - currentRay.mOrigin);
136        const float len = Magnitude(currentRay.mTermination - currentRay.mOrigin);
137       
138        // distance large => this is likely to be a discontinuity
139#if 1
140        if ((predictedLen - len) > mThreshold)
141#else // rather use relative distance
142        if ((predictedLen / len) > mThreshold)
143#endif
144        {
145                //cout << "r";
146                // apply reverse sampling to find the gap
147                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
148
149                if (!newRay)
150                        return 1;
151
152                // set flag for visualization
153                //newRay->mFlags |= VssRay::ReverseSample;
154               
155                // if ray is not further processed => delete ray
156                if (!HandleRay(newRay))
157                {
158                        //delete newRay;
159                }
160               
161                return 1;
162        }
163
164        return 0;
165}
166
167
168bool GvsPreprocessor::HasContribution(VssRay &ray)
169{
170        if (!ray.mTerminationObject)
171                return false;
172
173        bool result;
174
175        if (!mPerViewCell)
176        {
177                // store the rays + the intersected view cells
178                const bool storeViewCells = false; //GVS_DEBUG;
179
180                mViewCellsManager->ComputeSampleContribution(ray,
181                                                                                                         true,
182                                                                                                         storeViewCells,
183                                                                                                         true);
184
185                result = ray.mPvsContribution > 0;
186        }
187        else // original per view cell gvs
188        {
189                Intersectable *obj = ray.mTerminationObject;
190
191                if (obj->mCounter < 2)
192                {
193                        obj->mCounter += 2;
194                        mTrianglePvs.push_back(obj);
195               
196                        mGenericStats = mTrianglePvs.size();
197
198                        // if using kd pvs, exchange the triangle with the node in the pvs
199                        if (mUseKdPvs)
200                        {
201                                KdNode *node = mKdTree->GetPvsNode(ray.mTermination);
202
203                                if (!node->Mailed())
204                                {
205                                        node->Mail();
206                                        KdIntersectable *kdInt = mKdTree->GetOrCreateKdIntersectable(node);
207                                        mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
208                                        //mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
209                                       
210                                        mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt);
211                                        myobjects.clear();
212                                        mKdTree->CollectObjects(node, myobjects);
213
214                                        // account for kd object pvs
215                                        ObjectContainer::const_iterator oit, oit_end = myobjects.end();
216
217                                        for (oit = myobjects.begin(); oit != oit_end; ++ oit)
218                                        {
219                                                TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
220
221                                                if ((triObj->mCounter != 1) && (triObj->mCounter != 3))
222                                                {
223                                                        ++ triObj->mCounter;
224                                                        ++ mGenericStats2;
225                                                }
226                                        }
227                                }                       
228                        }
229
230                        result = true;
231                }
232                else
233                {
234                        result = false;
235                }
236        }
237
238        return result;
239}
240
241
242bool GvsPreprocessor::HandleRay(VssRay *vssRay)
243{
244        if (!HasContribution(*vssRay))
245                return false;
246
247//      cout << "t";
248        if (0 && GVS_DEBUG)
249                mVssRays.push_back(new VssRay(*vssRay));
250
251        // add new ray to ray queue
252        mRayQueue.push(vssRay);
253
254        ++ mGvsStats.mTotalContribution;
255
256        return true;
257}
258
259
260/** Creates 3 new vertices for triangle vertex with specified index.
261*/
262void GvsPreprocessor::CreateDisplacedVertices(VertexContainer &vertices,
263                                                                                          const Triangle3 &hitTriangle,
264                                                                                          const VssRay &ray,
265                                                                                          const int index) const
266{
267        const int indexU = (index + 1) % 3;
268        const int indexL = (index == 0) ? 2 : index - 1;
269
270        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
271        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
272        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
273       
274        const float len = Magnitude(a);
275       
276        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
277        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
278        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
279                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
280
281        // compute the new three hit points
282        // pi, i + 1:  pi+ e·|pi-xp|·di, j
283        const Vector3 pt1 = hitTriangle.mVertices[index] + mEps * len * dir1;
284        // pi, i - 1:  pi+ e·|pi-xp|·di, j
285    const Vector3 pt2 = hitTriangle.mVertices[index] + mEps * len * dir2;
286        // pi, i:  pi+ e·|pi-xp|·di, j
287        const Vector3 pt3 = hitTriangle.mVertices[index] + mEps * len * dir3;
288       
289        vertices.push_back(pt2);
290        vertices.push_back(pt3);
291        vertices.push_back(pt1);
292}
293
294
295void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
296                                                                          const Triangle3 &hitTriangle,
297                                                                          const VssRay &ray) const
298{
299        CreateDisplacedVertices(vertices, hitTriangle, ray, 0);
300        CreateDisplacedVertices(vertices, hitTriangle, ray, 1);
301        CreateDisplacedVertices(vertices, hitTriangle, ray, 2);
302}
303
304
305Vector3 GvsPreprocessor::CalcPredictedHitPoint(const VssRay &newRay,
306                                                                                           const Triangle3 &hitTriangle,
307                                                                                           const VssRay &oldRay) const
308{
309        // find the intersection of the plane induced by the
310        // hit triangle with the new ray
311        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
312
313        const Vector3 hitPt =
314                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
315       
316        return hitPt;
317}
318
319
320static bool EqualVisibility(const VssRay &a, const VssRay &b)
321{
322        return a.mTerminationObject == b.mTerminationObject;
323}
324
325
326int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
327                                                                   const Vector3 &p1,
328                                                                   const Vector3 &p2,
329                                                                   const VssRay &ray1,
330                                                                   const VssRay &ray2,
331                                                                   const VssRay &oldRay)
332{
333        //cout <<"y"<<Magnitude(p1 - p2) << " ";
334        int castRays = 0;
335
336        // cast reverse rays if necessary
337        castRays += CheckDiscontinuity(ray1, hitTriangle, oldRay);
338        castRays += CheckDiscontinuity(ray2, hitTriangle, oldRay);
339
340        if (EqualVisibility(ray1, ray2) || (SqrMagnitude(p1 - p2) <= MIN_DIST))
341        {
342                return castRays;
343        }
344       
345        // the new subdivision point
346        const Vector3 p = (p1 + p2) * 0.5f;
347        //cout << "p: " << p << " " << p1 << " " << p2 << endl;
348        // cast ray into the new point
349        SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin, SamplingStrategy::GVS, 1.0f);
350
351        VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
352       
353        ++ castRays;
354
355        if (!newRay) return castRays;
356
357        //newRay->mFlags |= VssRay::BorderSample;
358
359        // add new ray to queue
360        const bool enqueued = HandleRay(newRay);
361
362        // subdivide further
363        castRays += SubdivideEdge(hitTriangle, p1, p, ray1, *newRay, oldRay);
364        castRays += SubdivideEdge(hitTriangle, p, p2, *newRay, ray2, oldRay);
365
366        // this ray will not be further processed
367        //if (!enqueued) delete newRay;
368
369        return castRays;
370}
371
372
373int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
374{
375        Intersectable *tObj = currentRay.mTerminationObject;
376        // q matt: can this be possible
377        if (!tObj) return 0;
378
379        Triangle3 hitTriangle;
380
381        // other types not implemented yet
382        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
383                hitTriangle = static_cast<TriangleIntersectable *>(tObj)->GetItem();
384        else
385                cout << "border sampling: " << Intersectable::GetTypeName(tObj) << " not yet implemented" << endl;
386
387        //cout << "type: " << Intersectable::GetTypeName(tObj) << endl;
388
389        VertexContainer enlargedTriangle;
390       
391        /// create 3 new hit points for each vertex
392        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
393       
394        /// create rays from sample points and handle them
395        SimpleRayContainer simpleRays;
396        simpleRays.reserve(9);
397
398        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
399
400        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
401        {
402                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
403
404                SimpleRay sr(currentRay.GetOrigin(), rayDir, SamplingStrategy::GVS, 1.0f);
405                simpleRays.AddRay(sr); 
406        }
407
408        if (0)
409        {
410                // visualize enlarged triangles
411                VizStruct dummy;
412                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
413                dummy.originalTriangle = hitTriangle;
414                vizContainer.push_back(dummy);
415        }
416
417        // cast rays to triangle vertices and determine visibility
418        VssRayContainer vssRays;
419
420        // don't cast double rays as we need only the forward rays
421        const bool castDoubleRays = !mPerViewCell;
422        // cannot prune invalid rays because we have to compare adjacent  rays.
423        const bool pruneInvalidRays = false;
424
425
426        //////////
427        //-- fill up simple rays with random rays so we can cast 16
428
429        //const int numRandomRays = 0;
430        const int numRandomRays = 16 - (int)simpleRays.size();
431        ViewCellBasedDistribution vcStrat(*this, mCurrentViewCell);
432
433        GenerateRays(numRandomRays, vcStrat, simpleRays);
434
435
436        /////////////////////
437
438        // keep origin for per view cell sampling
439        CastRays(simpleRays, vssRays, castDoubleRays, pruneInvalidRays);
440
441        const int numBorderSamples = (int)vssRays.size() - numRandomRays;
442        // set flags
443        /*VssRayContainer::const_iterator rit, rit_end = vssRays.end();
444        for (rit = vssRays.begin(); rit != rit_end; ++ rit, ++ i)
445                (*rit)->mFlags |= VssRay::BorderSample;
446                */
447        int castRays = (int)simpleRays.size();
448
449        VssRayContainer invalidSamples;
450
451
452        // handle rays
453        EnqueueRays(vssRays, invalidSamples);
454
455    // recursivly subdivide each edge
456        for (int i = 0; i < numBorderSamples; ++ i)
457        {
458                castRays += SubdivideEdge(hitTriangle,
459                                                                  enlargedTriangle[i],
460                                                                  enlargedTriangle[(i + 1) % numBorderSamples],
461                                                                  *vssRays[i],
462                                                                  *vssRays[(i + 1) % numBorderSamples],
463                                                                  currentRay);
464        }
465       
466        mGvsStats.mBorderSamples += castRays;
467
468        //CLEAR_CONTAINER(invalidSamples);
469       
470        //cout << "cast rays: " << castRays << endl;
471        return castRays;
472}
473
474
475bool GvsPreprocessor::GetPassingPoint(const VssRay &currentRay,
476                                                                          const Triangle3 &occluder,
477                                                                          const VssRay &oldRay,
478                                                                          Vector3 &newPoint) const
479{
480        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
481        //-- with the newly found occluder (xold is the previous ray from
482        //-- which x was generated). On the intersecting line, we select a point
483        //-- pnew which lies just outside of the new triangle so the ray
484        //-- just passes through the gap
485
486        const Plane3 plane(currentRay.GetOrigin(),
487                                           currentRay.GetTermination(),
488                                           oldRay.GetTermination());
489       
490        Vector3 pt1, pt2;
491
492        const bool intersects = occluder.GetPlaneIntersection(plane, pt1, pt2);
493
494        if (!intersects)
495        {
496                //cerr << "big error!! no intersection " << pt1 << " " << pt2 << endl;
497                return false;
498        }
499
500        // get the intersection point on the old ray
501        const Plane3 triPlane(occluder.GetNormal(), occluder.mVertices[0]);
502
503        const float t = triPlane.FindT(oldRay.mOrigin, oldRay.mTermination);
504        const Vector3 pt3 = oldRay.mOrigin + t * (oldRay.mTermination - oldRay.mOrigin);
505
506        // Evaluate new hitpoint just outside the triangle
507        const float eps = mEps;
508
509        // the point is chosen to be on the side closer to the original ray
510        if (Distance(pt1, pt3) < Distance(pt2, pt3))
511                newPoint = pt1 + eps * (pt1 - pt2);
512        else
513                newPoint = pt2 + eps * (pt2 - pt1);
514
515        //cout << "passing point: " << newPoint << endl << endl;
516        return true;
517}
518
519
520VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
521                                                                                 const Triangle3 &hitTriangle,
522                                                                                 const VssRay &oldRay)
523{
524        // get triangle occluding the path to the hit mesh
525        Triangle3 occluder;
526        Intersectable *tObj = currentRay.mTerminationObject;
527
528        // q: why can this happen?
529        if (!tObj)
530                return NULL;
531
532        // other types not implemented yet
533        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
534        {
535                occluder = static_cast<TriangleIntersectable *>(tObj)->GetItem();
536        }
537        else
538        {
539                cout << "reverse sampling: " << tObj->Type() << " not yet implemented" << endl;
540        }
541        // get a point which is passing just outside of the occluder
542    Vector3 newPoint;
543
544        // why is there sometimes no intersecton found?
545        if (!GetPassingPoint(currentRay, occluder, oldRay, newPoint))
546                return NULL;
547
548        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
549
550        Vector3 newDir, newOrigin;
551
552        //-- Construct the mutated ray with xnew,
553        //-- dir = predicted(x)- pnew as direction vector
554        newDir = predicted - newPoint;
555
556        // take xnew, p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
557        // difficult to say!!
558        const float offset = 0.5f;
559        newOrigin = newPoint - newDir * offset;
560       
561        //////////////
562        //-- for per view cell sampling, we must check for intersection
563        //-- with the current view cell
564
565    if (mPerViewCell)
566        {
567                // send ray to view cell
568                static Ray ray;
569                ray.Clear();
570                ray.Init(newOrigin, -newDir, Ray::LOCAL_RAY);
571               
572                //cout << "z";
573                // check if ray intersects view cell
574                if (!mCurrentViewCell->CastRay(ray))
575                        return NULL;
576
577                Ray::Intersection &hit = ray.intersections[0];
578       
579                //cout << "q";
580                // the ray starts from the view cell
581                newOrigin = ray.Extrap(hit.mT);
582        }
583
584        const SimpleRay simpleRay(newOrigin, newDir, SamplingStrategy::GVS, 1.0f);
585
586        VssRay *reverseRay =
587                mRayCaster->CastRay(simpleRay, mViewCellsManager->GetViewSpaceBox(), !mPerViewCell);
588
589    ++ mGvsStats.mReverseSamples;
590
591        return reverseRay;
592}
593
594
595int GvsPreprocessor::CastInitialSamples(const int numSamples,
596                                                                                const int sampleType)
597{       
598        const long startTime = GetTime();
599
600        // generate simple rays
601        SimpleRayContainer simpleRays;
602       
603        ViewCellBasedDistribution vcStrat(*this, mCurrentViewCell);
604    GenerateRays(numSamples, vcStrat, simpleRays);
605
606        //cout << "sr: " << simpleRays.size() << endl;
607        // generate vss rays
608        VssRayContainer samples;
609       
610        const bool castDoubleRays = !mPerViewCell;
611        const bool pruneInvalidRays = true;
612       
613        CastRays(simpleRays, samples, castDoubleRays, pruneInvalidRays);
614       
615        VssRayContainer invalidSamples;
616
617        // add to ray queue
618        EnqueueRays(samples, invalidSamples);
619
620        //CLEAR_CONTAINER(invalidSamples);
621        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
622        return (int)simpleRays.size();
623}
624
625
626void GvsPreprocessor::EnqueueRays(VssRayContainer &samples, VssRayContainer &invalidSamples)
627{
628        // add samples to ray queue
629        VssRayContainer::const_iterator vit, vit_end = samples.end();
630        for (vit = samples.begin(); vit != vit_end; ++ vit)
631        {
632                VssRay *ray = *vit;
633
634                HandleRay(ray);
635                //if (!HandleRay(ray)) invalidSamples.push_back(ray);
636        }
637}
638
639
640int GvsPreprocessor::ProcessQueue()
641{
642        int castSamples = 0;
643        ++ mGvsStats.mGvsPass;
644
645        while (!mRayQueue.empty())//&& (mGvsStats.mTotalSamples + castSamples < mTotalSamples) )
646        {
647                //cout << "queue size: " << mRayQueue.size() << endl;
648                // handle next ray
649                VssRay *ray = mRayQueue.top();
650                mRayQueue.pop();
651               
652                const int newSamples = AdaptiveBorderSampling(*ray);
653
654                castSamples += newSamples;
655                //delete ray;
656        }
657
658        /*if (mRayCaster->mVssRayPool.mIndex > mSamplesPerPass)
659        {
660                cout << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
661                Debug << "warning: new samples: " << castSamples << " " << "queue: "  << (int)mRayQueue.size() << endl;
662        }*/
663
664        return castSamples;
665}
666
667
668void ExportVssRays(Exporter *exporter, const VssRayContainer &vssRays)
669{
670        VssRayContainer vcRays, vcRays2, vcRays3;
671
672        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
673
674        // prepare some rays for output
675        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
676        {
677                //const float p = RandomValue(0.0f, (float)vssRays.size());
678
679                if (1)//(p < raysOut)
680                {
681                        if ((*rit)->mFlags & VssRay::BorderSample)
682                        {
683                                vcRays.push_back(*rit);
684                        }
685                        else if ((*rit)->mFlags & VssRay::ReverseSample)
686                        {
687                                vcRays2.push_back(*rit);
688                        }
689                        else
690                        {
691                                vcRays3.push_back(*rit);
692                        }       
693                }
694        }
695
696        exporter->ExportRays(vcRays, RgbColor(1, 0, 0));
697        exporter->ExportRays(vcRays2, RgbColor(0, 1, 0));
698        exporter->ExportRays(vcRays3, RgbColor(1, 1, 1));
699}
700
701
702void GvsPreprocessor::VisualizeViewCell(const ObjectContainer &objects)
703{
704    Intersectable::NewMail();
705        Material m;
706       
707        char str[64]; sprintf(str, "pass%06d.wrl", mProcessedViewCells);
708
709        Exporter *exporter = Exporter::GetExporter(str);
710        if (!exporter)
711                return;
712
713        ObjectContainer::const_iterator oit, oit_end = objects.end();
714
715        for (oit = objects.begin(); oit != oit_end; ++ oit)
716        {
717                Intersectable *intersect = *oit;
718               
719                m = RandomMaterial();
720                exporter->SetForcedMaterial(m);
721                exporter->ExportIntersectable(intersect);
722        }
723
724        cout << "vssrays: " << (int)mVssRays.size() << endl;
725        ExportVssRays(exporter, mVssRays);
726
727
728        /////////////////
729        //-- export view cell geometry
730
731        //exporter->SetWireframe();
732
733        m.mDiffuseColor = RgbColor(0, 1, 0);
734        exporter->SetForcedMaterial(m);
735
736        //mViewCellsManager->ExportViewCellGeometry(exporter, vc, NULL, NULL);
737        //mViewCellsManager->ExportViewCellGeometry(exporter, mCurrentViewCell, NULL, NULL);
738
739        AxisAlignedBox3 bbox = mCurrentViewCell->GetMesh()->mBox;
740        exporter->ExportBox(bbox);
741        //exporter->SetFilled();
742
743        delete exporter;
744}
745
746
747void GvsPreprocessor::VisualizeViewCells()
748{
749        char str[64]; sprintf(str, "tmp/pass%06d_%04d-", mProcessedViewCells, mPass);
750                       
751        // visualization
752        if (mGvsStats.mPassContribution > 0)
753        {
754                const bool exportRays = true;
755                const bool exportPvs = true;
756
757                mViewCellsManager->ExportSingleViewCells(mObjects,
758                                                                                                 10,
759                                                                                                 false,
760                                                                                                 exportPvs,
761                                                                                                 exportRays,
762                                                                                                 1000,
763                                                                                                 str);
764        }
765
766        // remove pass samples
767        ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
768
769        for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
770        {
771                (*vit)->DelRayRefs();
772        }
773}
774
775
776void GvsPreprocessor::ProcessViewCell()
777{
778        // compute object that directly intersect view cell
779        IntersectWithViewCell();
780
781        mGvsStats.mPerViewCellSamples = 0;
782
783        int oldContribution = mGvsStats.mTotalContribution;
784        int passSamples = 0;
785        mGenericStats = 0;
786        mGenericStats2 = 0;
787
788        //while (mGvsStats.mPerViewCellSamples < mTotalSamples)
789        while (1)
790        {
791                mRayCaster->InitPass();
792
793                // Ray queue empty =>
794                // cast a number of uniform samples to fill ray queue
795                int newSamples = CastInitialSamples(mInitialSamples, mSamplingType);
796
797                if (!mOnlyRandomSampling)
798                        newSamples += ProcessQueue();
799               
800                passSamples += newSamples;
801        mGvsStats.mPerViewCellSamples += newSamples;
802
803                if (passSamples >= mGvsSamplesPerPass)
804                {
805                        ++ mPass;
806                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
807
808                        ////////
809                        //-- stats
810
811                        mGvsStats.mPass = mPass;
812
813                        cout << "\nPass " << mPass << " #samples: " << mGvsStats.mPerViewCellSamples << endl;
814                        cout << "contribution=" << mGvsStats.mPassContribution << " (of " << mMinContribution << ")" << endl;
815
816                        //mGenericStats = mGvsStats.mPassContribution;
817
818                        // termination criterium
819                        if (mGvsStats.mPassContribution < mMinContribution)
820                                break;
821
822                        // reset
823                        oldContribution = mGvsStats.mTotalContribution;
824                        mGvsStats.mPassContribution = 0;
825                        passSamples = 0;
826                }
827        }
828}
829
830
831void GvsPreprocessor::CompileViewCellsList()
832{
833        ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
834
835       
836        int i = 0;
837
838        if (!vcPoints->empty())
839        {
840                cout << "processing view cell list" << endl;
841               
842                vector<ViewCellPoints *>::const_iterator vit, vit_end = vcPoints->end();
843
844                for (vit = vcPoints->begin(); vit != vit_end; ++ vit)
845                {//cout << i ++ << " " << (*vit)->first->GetId() << endl;
846                        mViewCells.push_back((*vit)->first);
847                }
848
849                return;
850        }
851
852        while ((int)mViewCells.size() < mMaxViewCells)
853    {
854                if (0)
855                {
856                        mViewCells.push_back(mViewCellsManager->GetViewCell((int)mViewCells.size()));
857                        continue;
858                }
859               
860                // HACK
861                const int tries = 10000;
862                int i = 0;
863
864                for (i = 0; i < tries; ++ i)
865                {
866                        const int idx = (int)RandomValue(0.0f, (float)mViewCellsManager->GetNumViewCells() - 0.5f);
867       
868                        ViewCell *viewCell = mViewCellsManager->GetViewCell(idx);
869
870                        if (!viewCell->Mailed())
871                        {
872                                viewCell->Mail();
873                                break;
874                        }
875
876                        mViewCells.push_back(viewCell);
877                }
878
879                if (i == tries)
880                {
881                        cerr << "big error! no view cell found" << endl;
882                        return;
883                }
884        }
885}
886
887
888void GvsPreprocessor::IntersectWithViewCell()
889{
890        mCurrentViewCell->GetMesh()->ComputeBoundingBox();
891        AxisAlignedBox3 box = mCurrentViewCell->GetMesh()->mBox;
892       
893        //vector<KdLeaf *> leaves;
894        //mKdTree->GetBoxIntersections(box, leaves);
895
896        ObjectContainer kdobjects;
897        mKdTree->CollectKdObjects(box, kdobjects);
898        //vector<KdLeaf *>::const_iterator lit, lit_end = leaves.end();
899        //for (lit = leaves.begin(); lit != lit_end; ++ lit)
900        ObjectContainer::const_iterator oit, oit_end = kdobjects.end();
901        for (oit = kdobjects.begin(); oit != oit_end; ++ oit)
902        {
903        // add to kdnode pvs
904                KdIntersectable *kdInt = static_cast<KdIntersectable *>(*oit);
905               
906                //mCurrentViewCell->GetPvs().AddSampleDirty(kdInt, 1.0f);
907                mCurrentViewCell->GetPvs().AddSampleDirtyCheck(kdInt, 1.0f);
908                mViewCellsManager->UpdateStatsForViewCell(mCurrentViewCell, kdInt);
909
910                myobjects.clear();
911                mKdTree->CollectObjects(kdInt->GetItem(), myobjects);
912
913                // account for kd object pvs
914                ObjectContainer::const_iterator oit, oit_end = myobjects.end();
915
916                for (oit = myobjects.begin(); oit != oit_end; ++ oit)
917                {
918                        TriangleIntersectable *triObj = static_cast<TriangleIntersectable *>(*oit);
919           
920                        // account for the overall pvs
921                        if ((triObj->mCounter != 1) && (triObj->mCounter != 3))
922                        {
923                                ++ triObj->mCounter;
924                                ++ mGenericStats2;
925                        }
926           
927                        // the triangle itself intersects
928                        if (box.Intersects(triObj->GetItem()))
929                        {
930                                if ((triObj->mCounter < 2))
931                                {
932                                        triObj->mCounter += 2;
933
934                                        mTrianglePvs.push_back(triObj);
935                                        mGenericStats = mTrianglePvs.size();
936                                }
937                        }                       
938                }
939        }
940}
941
942
943
944void GvsPreprocessor::PerViewCellComputation()
945{
946        ViewCell *vc;
947
948        while (vc = NextViewCell())
949        {
950                // hack: reset counters
951                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
952
953                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
954                        (*oit)->mCounter = 0;
955
956                ComputeViewCell(vc);
957        }
958}
959
960
961void GvsPreprocessor::PerViewCellComputation2()
962{
963        ViewCell *vc;
964
965        while (1)
966        {
967                if (!mRendererWidget)
968                        continue;
969
970        ViewCell *vc = mViewCellsManager->GetViewCell(mRendererWidget->GetViewPoint());
971
972                // no valid view cell or view cell already computed
973                if (!vc || !vc->GetPvs().Empty() || !mRendererWidget->mComputeGVS)
974                        continue;
975
976                mRendererWidget->mComputeGVS = false;
977                // hack: reset counters
978                ObjectContainer::const_iterator oit, oit_end = mObjects.end();
979
980                for (oit = mObjects.begin(); oit != oit_end; ++ oit)
981                        (*oit)->mCounter = 0;
982
983                ComputeViewCell(vc);
984                ++ mProcessedViewCells;
985        }
986}
987
988
989void GvsPreprocessor::StorePvs(const ObjectContainer &objectPvs)
990{
991        ObjectContainer::const_iterator oit, oit_end = objectPvs.end();
992
993        for (oit = objectPvs.begin(); oit != oit_end; ++ oit)
994        {
995                mCurrentViewCell->GetPvs().AddSample(*oit, 1);
996        }
997}
998
999
1000void GvsPreprocessor::UpdatePvs(ViewCell *currentViewCell)
1001{
1002        ObjectPvs newPvs;
1003        BvhLeaf::NewMail();
1004
1005        ObjectPvsIterator pit = currentViewCell->GetPvs().GetIterator();
1006
1007        // output PVS of view cell
1008        while (pit.HasMoreEntries())
1009        {               
1010                Intersectable *intersect = pit.Next();
1011
1012                BvhLeaf *bv = intersect->mBvhLeaf;
1013
1014                if (!bv || bv->Mailed())
1015                        continue;
1016               
1017                bv->Mail();
1018
1019                //m.mDiffuseColor = RgbColor(1, 0, 0);
1020                newPvs.AddSampleDirty(bv, 1.0f);
1021        }
1022
1023        newPvs.SimpleSort();
1024
1025        currentViewCell->SetPvs(newPvs);
1026}
1027
1028 
1029void GvsPreprocessor::GetObjectPvs(ObjectContainer &objectPvs) const
1030{
1031        objectPvs.reserve((int)mTrianglePvs.size());
1032
1033        BvhLeaf::NewMail();
1034
1035        ObjectContainer::const_iterator oit, oit_end = mTrianglePvs.end();
1036
1037        for (oit = mTrianglePvs.begin(); oit != oit_end; ++ oit)
1038        {
1039                Intersectable *intersect = *oit;
1040       
1041                BvhLeaf *bv = intersect->mBvhLeaf;
1042
1043                // hack: reset counter
1044                (*oit)->mCounter = 0;
1045
1046                if (!bv || bv->Mailed())
1047                        continue;
1048
1049                bv->Mail();
1050                objectPvs.push_back(bv);
1051        }
1052}
1053
1054
1055void GvsPreprocessor::GlobalComputation()
1056{
1057        int passSamples = 0;
1058        int oldContribution = 0;
1059
1060        while (mGvsStats.mTotalSamples < mTotalSamples)
1061        {
1062                mRayCaster->InitPass();
1063                // Ray queue empty =>
1064                // cast a number of uniform samples to fill ray queue
1065                int newSamples = CastInitialSamples(mInitialSamples, mSamplingType);
1066
1067                if (!mOnlyRandomSampling)
1068                        newSamples += ProcessQueue();
1069
1070                passSamples += newSamples;
1071                mGvsStats.mTotalSamples += newSamples;
1072
1073                if (passSamples % (mGvsSamplesPerPass + 1) == mGvsSamplesPerPass)
1074                {
1075                        ++ mPass;
1076
1077                        mGvsStats.mPassContribution = mGvsStats.mTotalContribution - oldContribution;
1078
1079                        ////////
1080                        //-- stats
1081
1082                        //cout << "\nPass " << mPass << " #samples: " << mGvsStats.mTotalSamples << " of " << mTotalSamples << endl;
1083                        mGvsStats.mPass = mPass;
1084                        mGvsStats.Stop();
1085                        mGvsStats.Print(mGvsStatsStream);
1086
1087                        // reset
1088                        oldContribution = mGvsStats.mTotalContribution;
1089                        mGvsStats.mPassContribution = 0;
1090                        passSamples = 0;
1091
1092                        if (GVS_DEBUG)
1093                                VisualizeViewCells();
1094                }
1095        }
1096}
1097
1098
1099bool GvsPreprocessor::ComputeVisibility()
1100{
1101        cout << "Gvs Preprocessor started\n" << flush;
1102        const long startTime = GetTime();
1103
1104        //Randomize(0);
1105        mGvsStats.Reset();
1106        mGvsStats.Start();
1107
1108        if (!mLoadViewCells)
1109        {       
1110                /// construct the view cells from the scratch
1111                ConstructViewCells();
1112                // reset pvs already gathered during view cells construction
1113                mViewCellsManager->ResetPvs();
1114                cout << "finished view cell construction" << endl;
1115        }
1116#if 0
1117        else
1118        {       
1119                //-- test successful view cells loading by exporting them again
1120                VssRayContainer dummies;
1121                mViewCellsManager->Visualize(mObjects, dummies);
1122                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
1123        }
1124#endif
1125
1126        mGvsStats.Stop();
1127        mGvsStats.Print(mGvsStatsStream);
1128
1129        if (mPerViewCell)
1130        {
1131#if 0
1132                // provide list of view cells to compute
1133                CompileViewCellsList();
1134
1135                // start per view cell gvs
1136                PerViewCellComputation();
1137
1138                if (mEvaluatePixelError)
1139                {
1140                        ComputeRenderError();
1141                }
1142#else
1143                PerViewCellComputation2();
1144
1145#endif
1146        }
1147        else
1148        {
1149                GlobalComputation();
1150        }
1151
1152        cout << "cast " << 2 * mGvsStats.mTotalSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
1153
1154        if (GVS_DEBUG)
1155        {
1156                Visualize();
1157                CLEAR_CONTAINER(mVssRays);
1158        }
1159       
1160        // export the preprocessed information to a file
1161        if (0 && mExportVisibility)
1162        {
1163                ExportPreprocessedData(mVisibilityFileName);
1164        }
1165
1166        return true;
1167}
1168
1169
1170void GvsPreprocessor::DeterminePvsObjects(VssRayContainer &rays)
1171{
1172        // store triangle directly
1173        mViewCellsManager->DeterminePvsObjects(rays, true);
1174}
1175
1176
1177void GvsPreprocessor::Visualize()
1178{
1179        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
1180
1181        if (!exporter)
1182                return;
1183       
1184        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
1185       
1186        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
1187        {
1188                exporter->SetWireframe();
1189                exporter->ExportPolygon((*vit).enlargedTriangle);
1190                //Material m;
1191                exporter->SetFilled();
1192                Polygon3 poly = Polygon3((*vit).originalTriangle);
1193                exporter->ExportPolygon(&poly);
1194        }
1195
1196        VssRayContainer::const_iterator rit, rit_end = mVssRays.end();
1197
1198        for (rit = mVssRays.begin(); rit != rit_end; ++ rit)
1199        {
1200                Intersectable *obj = (*rit)->mTerminationObject;
1201                exporter->ExportIntersectable(obj);
1202        }
1203
1204        ExportVssRays(exporter, mVssRays);
1205       
1206        delete exporter;
1207}
1208
1209
1210void GvsStatistics::Print(ostream &app) const
1211{
1212        app << "#ViewCells\n" << mViewCells << endl;
1213        app << "#ViewCellId\n" << mViewCellId << endl;
1214        app << "#TotalTime\n" << mTotalTime << endl;
1215        app << "#TimePerViewCell\n" << mTimePerViewCell << endl;;
1216
1217        app << "#RaysPerSec\n" << RaysPerSec() << endl;
1218
1219        app << "#TrianglePvs\n" << mTrianglePvs << endl;
1220        app << "#TotalTrianglePvs\n" << mTotalTrianglePvs << endl;
1221
1222        app << "#PerViewCellPvs\n" << mPerViewCellPvs << endl;
1223        app << "#TotalPvs\n" << mTotalPvs << endl;
1224       
1225        app << "#PerViewCellSamples\n" << mPerViewCellSamples << endl;
1226        app << "#TotalSamples\n" << mTotalSamples << endl;
1227        app     << "#SamplesContri\n" << mTotalContribution << endl;
1228               
1229        //app << "#ReverseSamples\n" << mReverseSamples << endl;
1230        //app << "#BorderSamples\n" << mBorderSamples << endl;
1231
1232        //app << "#Pass\n" << mPass << endl;
1233        //app << "#ScDiff\n" << mPassContribution << endl;
1234        //app << "#GvsRuns\n" << mGvsPass << endl;     
1235
1236        app << endl;
1237}
1238
1239
1240void GvsPreprocessor::ComputeViewCell(ViewCell *vc)
1241{
1242        mCurrentViewCell = vc;
1243        KdNode::NewMail();
1244
1245        long startTime = GetTime();
1246        cout << "\n***********************\n"
1247                << "computing view cell " << mProcessedViewCells
1248                << " (id: " << mCurrentViewCell->GetId() << ")" << endl;
1249
1250        // compute the pvs of the current view cell
1251        ProcessViewCell();
1252
1253        //mGvsStats.mTrianglePvs = mCurrentViewCell->GetPvs().GetSize();
1254        mGvsStats.mTrianglePvs = (int)mTrianglePvs.size();
1255        mGvsStats.mTotalTrianglePvs += mGvsStats.mTrianglePvs;
1256
1257        if (!mUseKdPvs)
1258        {
1259                ObjectContainer objectPvs;
1260
1261                // optain object pvs
1262                GetObjectPvs(objectPvs);
1263
1264                // add pvs
1265                ObjectContainer::const_iterator it, it_end = objectPvs.end();
1266
1267                for (it = objectPvs.begin(); it != it_end; ++ it)
1268                {
1269                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1270                }
1271
1272                cout << "triangle pvs of " << (int)mTrianglePvs.size()
1273                        << " was converted to object pvs of " << (int)objectPvs.size() << endl;
1274
1275                mGvsStats.mPerViewCellPvs = (int)objectPvs.size();
1276        }
1277        else
1278        {
1279                /*// add pvs
1280                ObjectContainer::const_iterator it, it_end = mKdPvs.end();
1281
1282                for (it = mKdPvs.begin(); it != it_end; ++ it)
1283                        mCurrentViewCell->GetPvs().AddSampleDirty(*it, 1.0f);
1284                */
1285                mGvsStats.mPerViewCellPvs = mCurrentViewCell->GetPvs().GetSize();
1286
1287                cout << "pvs cost: " << mCurrentViewCell->GetPvs().EvalPvsCost() << " pvs tri: " << mGenericStats2 << endl;
1288        }
1289
1290
1291        ////////
1292        //-- stats
1293
1294        mGvsStats.mViewCells = mProcessedViewCells;//mPass;
1295
1296
1297        mGvsStats.mTotalPvs += mGvsStats.mPerViewCellPvs;
1298        mGvsStats.mTotalSamples += mGvsStats.mPerViewCellSamples;
1299
1300        // timing
1301        const long currentTime = GetTime();
1302
1303        mGvsStats.mTimePerViewCell = TimeDiff(startTime, currentTime) * 1e-3f;
1304        mGvsStats.mTotalTime += mGvsStats.mTimePerViewCell;
1305
1306        mGvsStats.Stop();
1307        mGvsStats.Print(mGvsStatsStream);
1308
1309        mTrianglePvs.clear();
1310}
1311
1312}
Note: See TracBrowser for help on using the repository browser.