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

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

added new view cell
deleted other view cell generation stuff (please use generate_viewcells.sh script)
added visualizaton method for gvs

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