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

Revision 1585, 24.3 KB checked in by bittner, 18 years ago (diff)

renderer changes

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