source: GTP/trunk/Lib/Vis/Preprocessing/src/Preprocessor.cpp @ 1521

Revision 1521, 23.2 KB checked in by mattausch, 18 years ago (diff)
Line 
1#include "SceneGraph.h"
2#include "Exporter.h"
3#include "UnigraphicsParser.h"
4#include "X3dParser.h"
5#include "Preprocessor.h"
6#include "ViewCell.h"
7#include "Environment.h"
8#include "ViewCellsManager.h"
9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
11#include "RenderSimulator.h"
12#include "GlRenderer.h"
13#include "PlyParser.h"
14#include "SamplingStrategy.h"
15#include "VspTree.h"
16#include "OspTree.h"
17#include "ObjParser.h"
18#include "BvHierarchy.h"
19#include "HierarchyManager.h"
20#include "VssRay.h"
21#include "IntelRayCaster.h"
22#include "InternalRayCaster.h"
23
24
25
26#define DEBUG_RAYCAST 0
27
28
29namespace GtpVisibilityPreprocessor {
30
31const static bool ADDITIONAL_GEOMETRY_HACK = false;
32
33
34// HACK: Artificially modify scene to watch rendercost changes
35static void AddGeometry(SceneGraph *scene)
36{
37        scene->GetRoot()->UpdateBox();
38
39        AxisAlignedBox3 sceneBox = scene->GetBox();
40
41        int n = 200;
42
43        if (0)
44        {
45                // form grid of boxes
46                for (int i = 0; i < n; ++ i)
47                {
48                        for (int j = 0; j < n; ++ j)
49                        {
50                                const Vector3 scale2((float)j * 0.8f / n + 0.1f,  0.05f, (float)i * 0.8f  / (float)n + 0.1f);
51
52                                const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
53
54                                const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
55                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
56                                Mesh *mesh = CreateMeshFromBox(box);
57
58                                mesh->Preprocess();
59
60                                MeshInstance *mi = new MeshInstance(mesh);
61                                scene->GetRoot()->mGeometry.push_back(mi);
62                        }
63                }
64
65                for (int i = 0; i < n; ++ i)
66                {
67                        for (int j = 0; j < n; ++ j)
68                        {
69                                const Vector3 scale2(0.15f, (float)j * 0.8f / n + 0.1f, (float)i * 0.8f  / (float)n + 0.1f);
70
71                                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
72
73                                Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
74                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
75                                Mesh *mesh = CreateMeshFromBox(box);
76
77                                mesh->Preprocess();
78
79                                MeshInstance *mi = new MeshInstance(mesh);
80                                scene->GetRoot()->mGeometry.push_back(mi);
81                        }
82                }
83
84                for (int i = 0; i < n; ++ i)
85                {
86                        const Vector3 scale2(2, 0.2f, (float)i * 0.8f  / (float)n + 0.1f);
87
88                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
89
90                        //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
91                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
92
93                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
94                        Mesh *mesh = CreateMeshFromBox(box);
95
96                        mesh->Preprocess();
97
98                        MeshInstance *mi = new MeshInstance(mesh);
99                        scene->GetRoot()->mGeometry.push_back(mi);
100                }
101
102                scene->GetRoot()->UpdateBox();
103        }
104
105        if (1)
106        {
107                // plane separating view space regions
108                const Vector3 scale(1.0f, 0.0, 0);
109
110                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
111
112                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
113                Mesh *planeMesh = new Mesh();
114
115                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
116                IncludePolyInMesh(*poly, *planeMesh);
117
118                planeMesh->Preprocess();
119
120                MeshInstance *planeMi = new MeshInstance(planeMesh);
121                scene->GetRoot()->mGeometry.push_back(planeMi);
122        }       
123}
124
125
126Preprocessor::Preprocessor():
127mKdTree(NULL),
128mBspTree(NULL),
129mVspBspTree(NULL),
130mHierarchyManager(NULL),
131mViewCellsManager(NULL),
132mRenderSimulator(NULL),
133mPass(0),
134mSceneGraph(NULL),
135mRayCaster(NULL)
136{
137        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
138 
139        // renderer will be constructed when the scene graph and viewcell manager will be known
140        renderer = NULL;
141 
142        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
143        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
144        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
145        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
146        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
147        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
148       
149        char buffer[256];
150        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
151   
152        mVisibilityFileName = buffer;
153        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
154        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
155                                                          mApplyVisibilitySpatialFilter );
156        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
157
158        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
159        Debug << "load meshes: " << mLoadMeshes << endl;
160}
161
162
163Preprocessor::~Preprocessor()
164{
165        cout << "cleaning up" << endl;
166
167        cout << "Deleting view cells manager ... \n";
168        DEL_PTR(mViewCellsManager);
169        cout << "done.\n";
170
171        cout << "Deleting bsp tree ... \n";
172        DEL_PTR(mBspTree);
173        cout << "done.\n";
174
175        cout << "Deleting kd tree...\n";
176        DEL_PTR(mKdTree);
177        cout << "done.\n";
178
179        cout << "Deleting hierarchy manager...\n";
180        DEL_PTR(mHierarchyManager);
181        cout << "done.\n";
182
183        cout << "Deleting vspbsp tree...\n";
184        DEL_PTR(mVspBspTree);
185        cout << "done.\n";
186
187        cout << "Deleting scene graph...\n";
188        DEL_PTR(mSceneGraph);
189        cout << "done.\n";
190
191        DEL_PTR(mRenderSimulator);
192        DEL_PTR(renderer);
193}
194
195
196GlRendererBuffer *Preprocessor::GetRenderer()
197{
198        return renderer;
199}
200
201
202static int SplitFilenames(const string str, vector<string> &filenames)
203{
204        int pos = 0;
205
206        while(1) {
207                int npos = (int)str.find(';', pos);
208               
209                if (npos < 0 || npos - pos < 1)
210                        break;
211                filenames.push_back(string(str, pos, npos - pos));
212                pos = npos + 1;
213        }
214       
215        filenames.push_back(string(str, pos, str.size() - pos));
216        return (int)filenames.size();
217}
218
219
220bool
221Preprocessor::LoadScene(const string filename)
222{
223        // use leaf nodes of the original spatial hierarchy as occludees
224        mSceneGraph = new SceneGraph;
225 
226        Parser *parser;
227        vector<string> filenames;
228        const int files = SplitFilenames(filename, filenames);
229        cout << "number of input files: " << files << endl;
230        bool result = false;
231
232        // root for different files
233        mSceneGraph->SetRoot(new SceneGraphNode());
234
235        // intel ray caster can only trace triangles
236        int rayCastMethod;
237        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
238        vector<FaceParentInfo> *fi = (rayCastMethod == RayCaster::INTEL_RAYCASTER) ?
239                &mFaceParents : NULL;
240
241        if (files == 1) {
242               
243                if (strstr(filename.c_str(), ".x3d"))
244                  parser = new X3dParser;
245                else
246                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
247                        parser = new PlyParser;
248                  else if (strstr(filename.c_str(), ".obj"))
249                          parser = new ObjParser;
250                  else
251                          parser = new UnigraphicsParser;
252
253                cout << filename << endl;
254               
255                result = parser->ParseFile(
256                                filename,
257                                mSceneGraph->GetRoot(),
258                                mLoadMeshes,
259                                fi);
260                       
261                delete parser;
262
263        }
264        else {
265                vector<string>::const_iterator fit, fit_end = filenames.end();
266               
267                for (fit = filenames.begin(); fit != fit_end; ++ fit)
268                {
269                        const string filename = *fit;
270
271                        cout << "parsing file " << filename.c_str() << endl;
272                        if (strstr(filename.c_str(), ".x3d"))
273                                parser = new X3dParser;
274                        else
275                                parser = new UnigraphicsParser;
276
277                        SceneGraphNode *node = new SceneGraphNode();
278                        const bool success = parser->ParseFile(
279                                filename,
280                                node,
281                                mLoadMeshes,
282                                fi);
283
284                        if (success)
285                        {
286                                mSceneGraph->GetRoot()->mChildren.push_back(node);
287                                result = true; // at least one file parsed
288                        }
289
290                        delete parser;
291                }
292        }
293       
294        if (result)
295        {
296                // HACK
297                if (ADDITIONAL_GEOMETRY_HACK)
298                        AddGeometry(mSceneGraph);
299
300                mSceneGraph->AssignObjectIds();
301 
302                int intersectables, faces;
303                mSceneGraph->GetStatistics(intersectables, faces);
304 
305                cout<<filename<<" parsed successfully."<<endl;
306                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
307                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
308                mSceneGraph->CollectObjects(&mObjects);
309                mSceneGraph->GetRoot()->UpdateBox();
310 
311                if (0)
312                {
313                        Exporter *exporter = Exporter::GetExporter("testload.x3d");
314                        if (exporter)
315                        {
316                                exporter->ExportGeometry(mObjects);
317                                delete exporter;
318                        }
319                }
320        }
321
322        return result;
323}
324
325bool
326Preprocessor::ExportPreprocessedData(const string filename)
327{
328        mViewCellsManager->ExportViewCells(filename, true, mObjects);
329        return true;
330}
331
332
333bool
334Preprocessor::PostProcessVisibility()
335{
336 
337  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
338        cout<<"Applying visibility filter ...";
339        cout<<"filter width = " << mVisibilityFilterWidth << endl;
340       
341        if (!mViewCellsManager)
342          return false;
343       
344        mViewCellsManager->ApplyFilter(mKdTree,
345                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
346                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
347        cout << "done." << endl;
348  }
349 
350  // export the preprocessed information to a file
351  if (mExportVisibility)
352  {
353          ExportPreprocessedData(mVisibilityFileName);
354  }
355
356  return true;
357}
358
359
360bool
361Preprocessor::BuildKdTree()
362{
363  mKdTree = new KdTree;
364
365  // add mesh instances of the scene graph to the root of the tree
366  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
367       
368  mSceneGraph->CollectObjects(&root->mObjects);
369 
370  const long startTime = GetTime();
371  cout << "building kd tree ... " << endl;
372
373  mKdTree->Construct();
374
375  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
376           << " secs " << endl;
377
378  return true;
379}
380
381
382void
383Preprocessor::KdTreeStatistics(ostream &s)
384{
385  s<<mKdTree->GetStatistics();
386}
387
388void
389Preprocessor::BspTreeStatistics(ostream &s)
390{
391        s << mBspTree->GetStatistics();
392}
393
394bool
395Preprocessor::Export( const string filename,
396                                          const bool scene,
397                                          const bool kdtree,
398                                          const bool bsptree
399                                          )
400{
401  Exporter *exporter = Exporter::GetExporter(filename);
402       
403  if (exporter) {
404    if (0 && scene)
405      exporter->ExportScene(mSceneGraph->GetRoot());
406
407    if (0 && kdtree) {
408      exporter->SetWireframe();
409      exporter->ExportKdTree(*mKdTree);
410    }
411
412        if (0 && bsptree) {
413                //exporter->SetWireframe();
414                exporter->ExportBspTree(*mBspTree);
415        }
416
417    delete exporter;
418    return true;
419  }
420
421  return false;
422}
423
424
425bool Preprocessor::PrepareViewCells()
426{
427        //-- parse view cells construction method
428        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
429        char buf[100];
430       
431        if (mLoadViewCells)
432        {       
433                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
434                cout << "loading view cells from " << buf << endl;
435                mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true);
436        }
437        else
438        {
439                // parse type of view cell container
440                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
441            mViewCellsManager = CreateViewCellsManager(buf);
442
443                // default view space is the extent of the scene
444                mViewCellsManager->SetViewSpaceBox(mSceneGraph->GetBox());
445        }
446       
447        ////////
448        //-- render heuristics evaluation
449        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
450
451        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
452        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
453        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
454       
455        mRenderSimulator =
456                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
457
458        mViewCellsManager->SetRenderer(mRenderSimulator);
459
460
461        if (mUseGlRenderer || mUseGlDebugger)
462        {
463                // NOTE: render texture should be power of 2 and square
464                // renderer must be initialised
465                // $$matt
466//              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
467                //              renderer->makeCurrent();
468               
469        }
470       
471        return true;
472}
473
474 
475bool Preprocessor::ConstructViewCells(const AxisAlignedBox3 &viewSpaceBox)
476{
477        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
478       
479        // construct view cells using it's own set of samples
480        mViewCellsManager->Construct(this);
481
482        // visualizations and statistics
483        Debug << "finished view cells:" << endl;
484        mViewCellsManager->PrintStatistics(Debug);
485           
486        return true;
487}
488
489
490HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
491{
492        HierarchyManager *hierarchyManager;
493
494        if (strcmp(name, "osp") == 0)
495        {
496                Debug << "hierarchy manager: osp" << endl;
497                // HACK for testing if per kd evaluation works!!
498                const bool ishack = false;
499                if (ishack)
500                        hierarchyManager = new HierarchyManager(mKdTree);
501                else
502                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
503        }
504        else if (strcmp(name, "bvh") == 0)
505        {
506                Debug << "hierarchy manager: bvh" << endl;
507                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
508        }
509        else // only view space partition
510        {
511                Debug << "hierarchy manager: obj" << endl;
512                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
513        }
514
515        return hierarchyManager;
516}
517
518
519ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
520{
521        ViewCellsTree *vcTree = new ViewCellsTree;
522
523        if (strcmp(name, "kdTree") == 0)
524        {
525                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
526        }
527        else if (strcmp(name, "bspTree") == 0)
528        {
529                Debug << "view cell type: Bsp" << endl;
530
531                mBspTree = new BspTree();
532                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
533        }
534        else if (strcmp(name, "vspBspTree") == 0)
535        {
536                Debug << "view cell type: VspBsp" << endl;
537
538                mVspBspTree = new VspBspTree();
539                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
540        }
541        else if (strcmp(name, "vspOspTree") == 0)
542        {
543                Debug << "view cell type: VspOsp" << endl;
544                char buf[100];         
545                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
546
547                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
548                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
549        }
550        else if (strcmp(name, "sceneDependent") == 0) //TODO
551        {
552                Debug << "view cell type: Bsp" << endl;
553               
554                mBspTree = new BspTree();
555                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
556        }
557        else
558        {
559                cerr << "Wrong view cells type " << name << "!!!" << endl;
560                exit(1);
561        }
562
563        return mViewCellsManager;
564}
565
566
567// use ascii format to store rays
568#define USE_ASCII 0
569
570
571static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
572{
573        return obj1->mId < obj2->mId;
574}
575
576
577bool Preprocessor::LoadKdTree(const string filename)
578{
579        mKdTree = new KdTree();
580        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
581}
582
583
584bool Preprocessor::ExportKdTree(const string filename)
585{
586        return mKdTree->ExportBinTree(filename.c_str());
587}
588
589
590bool Preprocessor::LoadSamples(VssRayContainer &samples,
591                                                           ObjectContainer &objects) const
592{
593        std::stable_sort(objects.begin(), objects.end(), ilt);
594        char fileName[100];
595        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
596       
597    Vector3 origin, termination;
598        // HACK: needed only for lower_bound algorithm to find the
599        // intersected objects
600        MeshInstance sObj(NULL);
601        MeshInstance tObj(NULL);
602
603#if USE_ASCII
604        ifstream samplesIn(fileName);
605        if (!samplesIn.is_open())
606                return false;
607
608        string buf;
609        while (!(getline(samplesIn, buf)).eof())
610        {
611                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
612                           &origin.x, &origin.y, &origin.z,
613                           &termination.x, &termination.y, &termination.z,
614                           &(sObj.mId), &(tObj.mId));
615               
616                Intersectable *sourceObj = NULL;
617                Intersectable *termObj = NULL;
618               
619                if (sObj.mId >= 0)
620                {
621                        ObjectContainer::iterator oit =
622                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
623                        sourceObj = *oit;
624                }
625               
626                if (tObj.mId >= 0)
627                {
628                        ObjectContainer::iterator oit =
629                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
630                        termObj = *oit;
631                }
632
633                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
634        }
635#else
636        ifstream samplesIn(fileName, ios::binary);
637        if (!samplesIn.is_open())
638                return false;
639
640        while (1)
641        {
642                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
643                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
644                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
645                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
646               
647                 if (samplesIn.eof())
648                        break;
649
650                Intersectable *sourceObj = NULL;
651                Intersectable *termObj = NULL;
652               
653                if (sObj.mId >= 0)
654                {
655                        ObjectContainer::iterator oit =
656                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
657                        sourceObj = *oit;
658                }
659               
660                if (tObj.mId >= 0)
661                {
662                        ObjectContainer::iterator oit =
663                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
664                        termObj = *oit;
665                }
666
667                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
668        }
669
670#endif
671        samplesIn.close();
672
673        return true;
674}
675
676
677bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
678{
679        char fileName[100];
680        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
681       
682
683        VssRayContainer::const_iterator it, it_end = samples.end();
684       
685#if USE_ASCII
686        ofstream samplesOut(fileName);
687        if (!samplesOut.is_open())
688                return false;
689
690        for (it = samples.begin(); it != it_end; ++ it)
691        {
692                VssRay *ray = *it;
693                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
694                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
695
696                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
697                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
698                                   << sourceid << " " << termid << "\n";
699        }
700#else
701        ofstream samplesOut(fileName, ios::binary);
702        if (!samplesOut.is_open())
703                return false;
704
705        for (it = samples.begin(); it != it_end; ++ it)
706        {       
707                VssRay *ray = *it;
708                Vector3 origin(ray->GetOrigin());
709                Vector3 termination(ray->GetTermination());
710               
711                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
712                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
713
714                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
715                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
716                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
717                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
718    }
719#endif
720        samplesOut.close();
721
722        return true;
723}
724
725bool Preprocessor::GenerateRays(const int number,
726                                                                const int sampleType,
727                                                                SimpleRayContainer &rays)
728{
729        const int startSize = (int)rays.size();
730        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
731
732        if (!strategy)
733        {
734                return false;
735        }
736
737        for (int i=0; (int)rays.size() - startSize < number; ++ i)
738        {
739                SimpleRay newRay;
740
741                if (strategy->GenerateSample(newRay))
742                {
743#if 1
744                        rays.AddRay(newRay);
745#else
746                        GenerateRayBundle(rays, newRay, 16, 0);
747#endif
748                }       
749        }
750
751        delete strategy;
752    return true;
753}
754
755
756SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
757{
758        switch (strategyId)
759        {
760        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
761                return new ObjectBasedDistribution(*this);
762        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
763                return new ObjectDirectionBasedDistribution(*this);
764        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
765                return new DirectionBasedDistribution(*this);
766        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
767                return new DirectionBoxBasedDistribution(*this);
768        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
769                return new SpatialBoxBasedDistribution(*this);
770        //case OBJECTS_INTERIOR_DISTRIBUTION:
771        //      return new ObjectsInteriorDistribution(*this);
772        default: // no valid strategy
773                Debug << "warning: no valid sampling strategy" << endl;
774                return NULL;
775        }
776
777        // should never come here
778        return NULL;
779}
780
781
782bool Preprocessor::InitRayCast(const string externKdTree, const string internkdtree)
783{
784        bool loadKdTree;
785        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
786       
787        if (!loadKdTree)
788        {       
789                //-- build new kd tree from scene geometry
790                BuildKdTree();
791                KdTreeStatistics(cout);
792        }
793        else
794        {
795                const long startTime = GetTime();
796                cout << "loading kd tree file " << internkdtree << " ... ";
797
798                if (!LoadKdTree(internkdtree))
799                {
800                        cout << "error loading kd tree with filename " << internkdtree << ", rebuilding it instead ..." << endl;
801
802                        BuildKdTree();
803                        KdTreeStatistics(cout);
804                }
805
806                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
807
808                if (0)
809                {
810                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
811                       
812                        if (exporter)
813                        {
814                                exporter->ExportKdTree(*mKdTree, true);
815                                delete exporter;
816                        }
817                }
818        }
819
820        int rayCastMethod;
821        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
822
823        if (rayCastMethod == 0)
824        {
825                mRayCaster = new InternalRayCaster(*this, mKdTree);
826                cout << "ray cast method: internal" << endl;
827        }
828        else
829        {
830                mRayCaster = new IntelRayCaster(*this, externKdTree);
831                cout << "ray cast method: intel" << endl;
832        }
833
834        return true;
835}
836
837
838void
839Preprocessor::CastRays(
840                                           SimpleRayContainer &rays,
841                                           VssRayContainer &vssRays,
842                                           const bool castDoubleRays
843                                           )
844{
845        long t1 = GetTime();
846
847        if (castDoubleRays)
848        {
849                for (int i = 0; i < (int)rays.size(); )
850                {
851                        if (i + 16 < (int)rays.size())
852                        {
853                                mRayCaster->CastRays16(
854                                        i,
855                                        rays,                           
856                                        vssRays,
857                                        mViewCellsManager->GetViewSpaceBox(),
858                                        castDoubleRays);
859                                i += 16;
860                        }
861                        else
862                        {
863                                mRayCaster->CastRay(
864                                        rays[i].mOrigin,
865                                        rays[i].mDirection,
866                                        rays[i].mPdf,
867                                        vssRays,
868                                        mViewCellsManager->GetViewSpaceBox(),
869                                        castDoubleRays);
870                                i++;
871                        }
872                       
873                        if (i % 10000 == 0)
874                                cout<<".";
875                }
876
877                long t2 = GetTime();
878
879                if (castDoubleRays)
880                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
881                else
882                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
883        }
884       
885}
886
887
888bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
889                                                                         const SimpleRay &mainRay,
890                                                                         const int number,
891                                                                         const int pertubType) const
892{
893        rayBundle.push_back(mainRay);
894
895        const float pertubOrigin = 10.0f;
896        const float pertubDir = 0.0f;
897
898        for (int i = 0; i < number - 1; ++ i)
899        {
900                Vector3 pertub;
901
902                pertub.x = RandomValue(0.0f, pertubDir);
903                pertub.y = RandomValue(0.0f, pertubDir);
904                pertub.z = RandomValue(0.0f, pertubDir);
905                const Vector3 newDir = mainRay.mDirection + pertub;
906                //const Vector3 newDir = mainRay.mDirection;
907
908                pertub.x = RandomValue(0.0f, pertubOrigin);
909                pertub.y = RandomValue(0.0f, pertubOrigin);
910                pertub.z = RandomValue(0.0f, pertubOrigin);
911                const Vector3 newOrigin = mainRay.mOrigin + pertub;
912                //const Vector3 newOrigin = mainRay.mOrigin;
913
914                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
915        }
916
917        return true;
918}
919
920
921void Preprocessor::SetupRay(Ray &ray,
922                                                        const Vector3 &point,
923                                                        const Vector3 &direction
924                                                        ) const
925{
926        ray.Clear();
927        // do not store anything else then intersections at the ray
928        ray.Init(point, direction, Ray::LOCAL_RAY);
929}
930
931
932}
Note: See TracBrowser for help on using the repository browser.