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

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