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

Revision 1551, 12.9 KB checked in by mattausch, 18 years ago (diff)

updated view cells loading. probably no optimal for performance

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