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

Revision 1595, 14.2 KB checked in by mattausch, 18 years ago (diff)
  • Property svn:executable set to *
Line 
1#include "Environment.h"
2#include "GvsPreprocessor.h"
3#include "GlRenderer.h"
4#include "VssRay.h"
5#include "ViewCellsManager.h"
6#include "Triangle3.h"
7#include "IntersectableWrapper.h"
8#include "Plane3.h"
9#include "RayCaster.h"
10#include "Exporter.h"
11#include "SamplingStrategy.h"
12
13
14namespace GtpVisibilityPreprocessor
15{
16 
17struct VizStruct
18{
19        Polygon3 *enlargedTriangle;
20        Triangle3 originalTriangle;
21        VssRay *ray;
22};
23
24static vector<VizStruct> vizContainer;
25
26GvsPreprocessor::GvsPreprocessor():
27Preprocessor(),
28//mSamplingType(SamplingStrategy::DIRECTION_BASED_DISTRIBUTION),
29mSamplingType(SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION),
30mSampleContriPerPass(0),
31mTotalSampleContri(0),
32mReverseSamples(0),
33mBorderSamples(0)
34{
35        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.totalSamples", mTotalSamples);
36        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.initialSamples", mInitialSamples);
37        Environment::GetSingleton()->GetIntValue("GvsPreprocessor.samplesPerPass", mSamplesPerPass);
38        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.epsilon", mEps);
39        Environment::GetSingleton()->GetFloatValue("GvsPreprocessor.threshold", mThreshold);   
40
41        Debug << "Gvs preprocessor options" << endl;
42        Debug << "number of total samples: " << mTotalSamples << endl;
43        Debug << "number of initial samples: " << mInitialSamples << endl;
44        Debug << "number of samples per pass: " << mSamplesPerPass << endl;
45        Debug << "threshold: " << mThreshold << endl;
46        Debug << "eps: " << mEps << endl;
47
48        mStats.open("gvspreprocessor.log");
49}
50
51
52bool GvsPreprocessor::CheckDiscontinuity(const VssRay &currentRay,
53                                                                                 const Triangle3 &hitTriangle,
54                                                                                 const VssRay &oldRay)
55{
56        const float dist = Magnitude(oldRay.GetDir());
57        const float newDist = Magnitude(currentRay.GetDir());
58 
59#if 0
60        if ((dist - newDist) > mThresHold)
61#else
62        // rather take relative distance
63        if ((dist / newDist) > mThreshold)
64#endif
65        {
66                VssRay *newRay = ReverseSampling(currentRay, hitTriangle, oldRay);
67                // set flag for visualization
68                newRay->mFlags |= VssRay::ReverseSample;
69               
70                // ray is not pushed into the queue => can delete ray
71                if (!HandleRay(newRay))
72                        delete newRay;
73               
74                return true;
75        }
76
77        return false;
78}
79
80
81bool GvsPreprocessor::HandleRay(VssRay *vssRay)
82{
83        const bool storeRaysForViz = true;
84        mViewCellsManager->ComputeSampleContribution(*vssRay, true, storeRaysForViz);
85               
86        // some pvs contribution for this ray?
87        if (vssRay->mPvsContribution > 0)
88        {
89                // add new ray to ray queue
90                mRayQueue.push(vssRay);
91
92                if (storeRaysForViz)
93                {
94                        ViewCellContainer::const_iterator vit, vit_end = vssRay->mViewCells.end();
95                        for (vit = vssRay->mViewCells.begin(); vit != vit_end; ++ vit)
96                        {
97                                VssRay *nray = new VssRay(*vssRay);
98                                (*vit)->mVssRays.push_back(nray);                               
99                        }
100                }
101                //mVssRays.push_back(new VssRay(*vssRay));
102        ++ mSampleContriPerPass;
103
104                return true;
105        }
106
107        return false;
108}
109
110
111/** Creates 3 new vertices for triangle vertex with specified index.
112*/
113static void CreateNewVertices(VertexContainer &vertices,
114                                                          const Triangle3 &hitTriangle,
115                                                          const VssRay &ray,
116                                                          const int index,
117                                                          const float eps)
118{
119        const int indexU = (index + 1) % 3;
120        const int indexL = (index == 0) ? 2 : index - 1;
121
122        const Vector3 a = hitTriangle.mVertices[index] - ray.GetOrigin();
123        const Vector3 b = hitTriangle.mVertices[indexU] - hitTriangle.mVertices[index];
124        const Vector3 c = hitTriangle.mVertices[index] - hitTriangle.mVertices[indexL];
125       
126        const float len = Magnitude(a);
127
128        const Vector3 dir1 = Normalize(CrossProd(a, b)); //N((pi-xp)×(pi+1- pi));
129        const Vector3 dir2 = Normalize(CrossProd(a, c)); // N((pi-xp)×(pi- pi-1))
130        const Vector3 dir3 = DotProd(dir2, dir1) > 0 ? // N((pi-xp)×di,i-1+di,i+1×(pi-xp))
131                Normalize(dir2 + dir1) : Normalize(CrossProd(a, dir1) + CrossProd(dir2, a));
132
133        // compute the new three hit points
134        // pi, i + 1:  pi+ e·|pi-xp|·di, j
135        const Vector3 pt1 = hitTriangle.mVertices[index] + eps * len * dir1;
136        // pi, i - 1:  pi+ e·|pi-xp|·di, j
137    const Vector3 pt2 = hitTriangle.mVertices[index] + eps * len * dir2;
138        // pi, i:  pi+ e·|pi-xp|·di, j
139        const Vector3 pt3 = hitTriangle.mVertices[index] + eps * len * dir3;
140       
141        vertices.push_back(pt2);
142        vertices.push_back(pt3);
143        vertices.push_back(pt1);
144}
145
146
147void GvsPreprocessor::EnlargeTriangle(VertexContainer &vertices,
148                                                                          const Triangle3 &hitTriangle,
149                                                                          const VssRay &ray)
150{
151        CreateNewVertices(vertices, hitTriangle, ray, 0, mEps);
152        CreateNewVertices(vertices, hitTriangle, ray, 1, mEps);
153        CreateNewVertices(vertices, hitTriangle, ray, 2, mEps);
154}
155
156
157static Vector3 CalcPredictedHitPoint(const VssRay &newRay,
158                                                                         const Triangle3 &hitTriangle,
159                                                                         const VssRay &oldRay)
160{
161        Plane3 plane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
162
163        const Vector3 hitPt =
164                plane.FindIntersection(newRay.mTermination, newRay.mOrigin);
165       
166        return hitPt;
167}
168
169
170static bool EqualVisibility(const VssRay &a, const VssRay &b)
171{
172        return a.mTerminationObject == b.mTerminationObject;
173}
174
175
176int GvsPreprocessor::SubdivideEdge(const Triangle3 &hitTriangle,
177                                                                   const Vector3 &p1,
178                                                                   const Vector3 &p2,
179                                                                   const VssRay &x,
180                                                                   const VssRay &y,
181                                                                   const VssRay &oldRay)
182{
183        // the predicted hitpoint expects to hit the same mesh again
184        const Vector3 predictedHitX = CalcPredictedHitPoint(x, hitTriangle, oldRay);
185        const Vector3 predictedHitY = CalcPredictedHitPoint(y, hitTriangle, oldRay);
186
187        CheckDiscontinuity(x, hitTriangle, oldRay);
188        CheckDiscontinuity(y, hitTriangle, oldRay);
189
190        if (EqualVisibility(x, y))
191        {
192                return 0;
193        }
194        else
195        {
196                cout << "s";
197                const Vector3 p = (p1 + p2) * 0.5f;
198                SimpleRay sray(oldRay.mOrigin, p - oldRay.mOrigin);
199       
200                // cast ray into the new subdivision point
201                VssRay *newRay = mRayCaster->CastRay(sray, mViewCellsManager->GetViewSpaceBox(), false);
202               
203                if (!newRay) return 0;
204
205                newRay->mFlags |= VssRay::BorderSample;
206
207                // add new ray to queue
208                const bool enqueued = HandleRay(newRay);
209               
210                // subdivide further
211                const int s1 = SubdivideEdge(hitTriangle, p1, p, x, *newRay, oldRay);
212                const int s2 = SubdivideEdge(hitTriangle, p, p2, *newRay, y, oldRay);
213                               
214                if (!enqueued)
215                        delete newRay;
216               
217                return s1 + s2 + 1;
218        }
219}
220
221
222int GvsPreprocessor::AdaptiveBorderSampling(const VssRay &currentRay)
223{
224        cout << "a";
225        Intersectable *tObj = currentRay.mTerminationObject;
226        Triangle3 hitTriangle;
227
228        // other types not implemented yet
229        if (tObj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
230        {
231                hitTriangle = dynamic_cast<TriangleIntersectable *>(tObj)->GetItem();
232        }
233        else
234        {
235                cout << "not yet implemented" << endl;
236        }
237
238        VertexContainer enlargedTriangle;
239       
240        /// create 3 new hit points for each vertex
241        EnlargeTriangle(enlargedTriangle, hitTriangle, currentRay);
242       
243        /// create rays from sample points and handle them
244        SimpleRayContainer simpleRays;
245        simpleRays.reserve(9);
246
247        VertexContainer::const_iterator vit, vit_end = enlargedTriangle.end();
248
249        for (vit = enlargedTriangle.begin(); vit != vit_end; ++ vit)
250        {
251                const Vector3 rayDir = (*vit) - currentRay.GetOrigin();
252                SimpleRay sr(currentRay.GetOrigin(), rayDir);
253                simpleRays.AddRay(sr);
254        }
255
256        if (0)
257        {
258                VizStruct dummy;
259                dummy.enlargedTriangle = new Polygon3(enlargedTriangle);
260                dummy.originalTriangle = hitTriangle;
261                //dummy.ray = new VssRay(currentRay);
262                vizContainer.push_back(dummy);
263        }
264
265        // cast rays to triangle vertices and determine visibility
266        VssRayContainer vssRays;
267        CastRays(simpleRays, vssRays, false, false);
268
269        // set flags
270        VssRayContainer::const_iterator rit, rit_end = vssRays.end();
271        for (rit = vssRays.begin(); rit != rit_end; ++ rit)
272        {
273                (*rit)->mFlags |= VssRay::BorderSample;
274        }
275
276        // add to ray queue
277        EnqueueRays(vssRays);
278       
279        const int n = (int)enlargedTriangle.size();
280        int castRays = (int)vssRays.size();
281
282    // recursivly subdivide each edge
283        for (int i = 0; 1 && (i < n); ++ i)
284        {
285                castRays += SubdivideEdge(
286                        hitTriangle,
287                        enlargedTriangle[i],
288                        enlargedTriangle[(i + 1) % n],
289                        *vssRays[i],
290                        *vssRays[(i + 1) % n],
291                        currentRay);
292        }
293
294        mBorderSamples += castRays;
295        return castRays;
296}
297
298
299static Vector3 GetPassingPoint(const VssRay &currentRay,
300                                                           const Triangle3 &hitTriangle,
301                                                           const VssRay &oldRay)
302{
303        // intersect triangle plane with plane spanned by current samples
304        Plane3 plane(currentRay.GetOrigin(), currentRay.GetTermination(), oldRay.GetTermination());
305        Plane3 triPlane(hitTriangle.GetNormal(), hitTriangle.mVertices[0]);
306
307        SimpleRay intersectLine = GetPlaneIntersection(plane, triPlane);
308
309        // Evaluate new hitpoint just outside the triangle
310        const float factor = 0.95f;
311        float t = triPlane.FindT(intersectLine);
312        const Vector3 newPoint = intersectLine.mOrigin + t * factor * intersectLine.mDirection;
313
314        return newPoint;
315}
316
317
318VssRay *GvsPreprocessor::ReverseSampling(const VssRay &currentRay,
319                                                                                 const Triangle3 &hitTriangle,
320                                                                                 const VssRay &oldRay)
321{
322        //-- The plane p = (xp, hit(x), hit(xold)) is intersected
323        //-- with the newly found triangle (xold is the previous ray from
324        //-- which x was generated). On the intersecting line, we select a point
325        //-- pnew which lies just outside of the new triangle so the ray
326        //-- just passes by inside the gap
327    const Vector3 newPoint = GetPassingPoint(currentRay, hitTriangle, oldRay);
328        const Vector3 predicted = CalcPredictedHitPoint(currentRay, hitTriangle, oldRay);
329
330        //-- Construct the mutated ray with xnew,dir = predicted(x)- pnew
331        //-- as direction vector
332        const Vector3 newDir = predicted - newPoint ;
333        // take xnew,p = intersect(viewcell, line(pnew, predicted(x)) as origin ?
334        // difficult to say!!
335        const Vector3 newOrigin = newDir * -5000.0f;
336
337        ++ mReverseSamples;
338
339        return new VssRay(currentRay);
340}
341
342
343int GvsPreprocessor::CastInitialSamples(const int numSamples,
344                                                                                const int sampleType)
345{       
346        const long startTime = GetTime();
347
348        // generate simple rays
349        SimpleRayContainer simpleRays;
350        GenerateRays(numSamples, sampleType, simpleRays);
351
352        // generate vss rays
353        VssRayContainer samples;
354        CastRays(simpleRays, samples, true);
355        // add to ray queue
356        EnqueueRays(samples);
357
358        //Debug << "generated " <<  numSamples << " samples in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
359        return (int)samples.size();
360}
361
362
363void GvsPreprocessor::EnqueueRays(VssRayContainer &samples)
364{
365        // add samples to ray queue
366        VssRayContainer::const_iterator vit, vit_end = samples.end();
367        for (vit = samples.begin(); vit != vit_end; ++ vit)
368        {
369                HandleRay(*vit);
370        }
371}
372
373
374int GvsPreprocessor::Pass()
375{
376        // reset samples
377        int castSamples = 0;
378        mSampleContriPerPass = 0;
379
380        while (castSamples < mSamplesPerPass)
381        {       
382                // Ray queue empty =>
383                // cast a number of uniform samples to fill ray queue
384                castSamples += CastInitialSamples(mInitialSamples, mSamplingType);
385                castSamples += ProcessQueue();
386                //cout << "\ncast " << castSamples << " samples in a processing pass" << endl;
387        }
388
389        mTotalSampleContri += mSampleContriPerPass;
390        return castSamples;
391}
392
393
394int GvsPreprocessor::ProcessQueue()
395{
396        int castSamples = 0;
397        ++ mGvsPass;
398
399        while (!mRayQueue.empty())
400        {
401                // handle next ray
402                VssRay *ray = mRayQueue.top();
403                mRayQueue.pop();
404
405                castSamples += AdaptiveBorderSampling(*ray);
406                delete ray;
407        }
408       
409        return castSamples;
410}
411
412
413bool GvsPreprocessor::ComputeVisibility()
414{
415        cout << "Gvs Preprocessor started\n" << flush;
416        const long startTime = GetTime();
417
418        Randomize(0);
419       
420        mPass = 0;
421        mGvsPass = 0;
422        mSampleContriPerPass = 0;
423        mTotalSampleContri = 0;
424        mReverseSamples = 0;
425        mBorderSamples = 0;
426
427        int castSamples = 0;
428
429        if (!mLoadViewCells)
430        {       
431                /// construct the view cells from the scratch
432                ConstructViewCells();
433                // reset pvs already gathered during view cells construction
434                mViewCellsManager->ResetPvs();
435                cout << "finished view cell construction" << endl;
436        }
437        else if (0)
438        {       
439                //-- load view cells from file
440                //-- test successful view cells loading by exporting them again
441                VssRayContainer dummies;
442                mViewCellsManager->Visualize(mObjects, dummies);
443                mViewCellsManager->ExportViewCells("test.xml.gz", mViewCellsManager->GetExportPvs(), mObjects);
444        }
445
446        while (castSamples < mTotalSamples)
447        {
448                castSamples += Pass();
449                               
450                ////////
451                //-- stats
452                cout << "\nPass " << mPass << " #samples: " << castSamples << " of " << mTotalSamples << endl;
453
454                //mVssRays.PrintStatistics(mStats);
455                mStats
456                        << "#Pass\n" << mPass << endl
457                        << "#Time\n" << TimeDiff(startTime, GetTime())*1e-3 << endl
458                        << "#TotalSamples\n" << castSamples << endl
459                        << "#ScDiff\n" << mSampleContriPerPass << endl
460                        << "#SamplesContri\n" << mTotalSampleContri << endl
461                        << "#ReverseSamples\n" << mReverseSamples << endl
462                        << "#BorderSamples\n" << mBorderSamples << endl                 
463                        << "#GvsRuns\n" << mGvsPass << endl;
464
465                mViewCellsManager->PrintPvsStatistics(mStats);
466
467                char str[64]; sprintf(str, "tmp/pass%04d-", mPass);
468               
469        // visualization
470                if (mSampleContriPerPass > 0)
471                {
472                        const bool exportRays = true;
473                        const bool exportPvs = true;
474
475                        mViewCellsManager->ExportSingleViewCells(mObjects, 10, false, exportPvs, exportRays, 1000, str);
476                }
477
478                // remove pass samples
479                ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
480                for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit)
481                {
482                        CLEAR_CONTAINER((*vit)->mVssRays);
483                }
484
485                CLEAR_CONTAINER(mVssRays);
486                // ComputeRenderError();
487                ++ mPass;
488        }
489
490        cout << 2 * castSamples / (1e3f * TimeDiff(startTime, GetTime())) << "M rays/s" << endl;
491        Visualize();
492
493        return true;
494}
495
496
497void GvsPreprocessor::Visualize()
498{
499        Exporter *exporter = Exporter::GetExporter("gvs.wrl");
500
501        if (!exporter)
502                return;
503       
504        vector<VizStruct>::const_iterator vit, vit_end = vizContainer.end();
505        for (vit = vizContainer.begin(); vit != vit_end; ++ vit)
506        {
507                exporter->SetWireframe();
508                exporter->ExportPolygon((*vit).enlargedTriangle);
509                //Material m;
510                exporter->SetFilled();
511                Polygon3 poly = Polygon3((*vit).originalTriangle);
512                exporter->ExportPolygon(&poly);
513        }
514
515        exporter->ExportRays(mVssRays);
516        delete exporter;
517}
518
519}
Note: See TracBrowser for help on using the repository browser.