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

Revision 1608, 24.2 KB checked in by bittner, 18 years ago (diff)

vsp osp tests

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         mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true, NULL);
435         
436          if (!mViewCellsManager)
437          {
438                  return false;
439          }
440        }
441        else
442        {
443                // parse type of view cell container
444                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
445            mViewCellsManager = CreateViewCellsManager(buf);
446
447                // default view space is the extent of the scene
448                AxisAlignedBox3 box = mSceneGraph->GetBox();
449                                       
450                if (0)
451                {
452                        // use a small box outside of the scene
453                        box.Scale(Vector3(0.1f,0.5f,0.5f));
454                        box.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size())*0.5f, 0, 0));
455                }
456
457                mViewCellsManager->SetViewSpaceBox(box);
458         
459                bool loadVcGeometry;
460                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
461
462                bool extrudeBaseTriangles;
463                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
464
465                char vcGeomFilename[100];
466                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
467               
468                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
469                {
470                        if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
471                        {
472                                cerr << "loading view cells geometry failed" << endl;
473                        }
474                }
475                else
476                {
477                        cerr << "loading view cells geometry is not implemented for this manager" << endl;
478                }
479        }
480       
481        ////////
482        //-- evaluation of render cost heuristics
483        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
484
485        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
486        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
487        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
488       
489        mRenderSimulator =
490                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
491
492        mViewCellsManager->SetRenderer(mRenderSimulator);
493       
494        if (mUseGlRenderer || mUseGlDebugger)
495          {
496                // NOTE: render texture should be power of 2 and square
497                // renderer must be initialised
498                // $$matt
499                //              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
500                //              renderer->makeCurrent();
501               
502          }
503
504        mViewCellsManager->SetPreprocessor(this);
505        return true;
506}
507
508 
509bool Preprocessor::ConstructViewCells()
510{
511  // construct view cells using it's own set of samples
512  mViewCellsManager->Construct(this);
513 
514  // visualizations and statistics
515  Debug << "finished view cells:" << endl;
516  mViewCellsManager->PrintStatistics(Debug);
517 
518  return true;
519}
520
521
522HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
523{
524        HierarchyManager *hierarchyManager;
525
526        if (strcmp(name, "osp") == 0)
527        {
528                Debug << "hierarchy manager: osp" << endl;
529                // HACK for testing if per kd evaluation works!!
530                const bool ishack = false;
531                if (ishack)
532                        hierarchyManager = new HierarchyManager(mKdTree);
533                else
534                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
535        }
536        else if (strcmp(name, "bvh") == 0)
537        {
538                Debug << "hierarchy manager: bvh" << endl;
539                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
540        }
541        else // only view space partition
542        {
543                Debug << "hierarchy manager: obj" << endl;
544                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
545        }
546
547        return hierarchyManager;
548}
549
550
551ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
552{
553        ViewCellsTree *vcTree = new ViewCellsTree;
554
555        if (strcmp(name, "kdTree") == 0)
556        {
557                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
558        }
559        else if (strcmp(name, "bspTree") == 0)
560        {
561                Debug << "view cell type: Bsp" << endl;
562
563                mBspTree = new BspTree();
564                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
565        }
566        else if (strcmp(name, "vspBspTree") == 0)
567        {
568                Debug << "view cell type: VspBsp" << endl;
569
570                mVspBspTree = new VspBspTree();
571                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
572        }
573        else if (strcmp(name, "vspOspTree") == 0)
574        {
575                Debug << "view cell type: VspOsp" << endl;
576                char buf[100];         
577                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
578
579                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
580                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
581        }
582        else if (strcmp(name, "sceneDependent") == 0) //TODO
583        {
584                Debug << "view cell type: Bsp" << endl;
585               
586                mBspTree = new BspTree();
587                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
588        }
589        else
590        {
591                cerr << "Wrong view cells type " << name << "!!!" << endl;
592                exit(1);
593        }
594
595        return mViewCellsManager;
596}
597
598
599// use ascii format to store rays
600#define USE_ASCII 0
601
602
603static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
604{
605        return obj1->mId < obj2->mId;
606}
607
608
609bool Preprocessor::LoadKdTree(const string filename)
610{
611        mKdTree = new KdTree();
612        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
613}
614
615
616bool Preprocessor::ExportKdTree(const string filename)
617{
618        return mKdTree->ExportBinTree(filename.c_str());
619}
620
621
622bool Preprocessor::LoadSamples(VssRayContainer &samples,
623                                                           ObjectContainer &objects) const
624{
625        std::stable_sort(objects.begin(), objects.end(), ilt);
626        char fileName[100];
627        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
628       
629    Vector3 origin, termination;
630        // HACK: needed only for lower_bound algorithm to find the
631        // intersected objects
632        MeshInstance sObj(NULL);
633        MeshInstance tObj(NULL);
634
635#if USE_ASCII
636        ifstream samplesIn(fileName);
637        if (!samplesIn.is_open())
638                return false;
639
640        string buf;
641        while (!(getline(samplesIn, buf)).eof())
642        {
643                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
644                           &origin.x, &origin.y, &origin.z,
645                           &termination.x, &termination.y, &termination.z,
646                           &(sObj.mId), &(tObj.mId));
647               
648                Intersectable *sourceObj = NULL;
649                Intersectable *termObj = NULL;
650               
651                if (sObj.mId >= 0)
652                {
653                        ObjectContainer::iterator oit =
654                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
655                        sourceObj = *oit;
656                }
657               
658                if (tObj.mId >= 0)
659                {
660                        ObjectContainer::iterator oit =
661                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
662                        termObj = *oit;
663                }
664
665                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
666        }
667#else
668        ifstream samplesIn(fileName, ios::binary);
669        if (!samplesIn.is_open())
670                return false;
671
672        while (1)
673        {
674                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
675                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
676                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
677                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
678               
679                 if (samplesIn.eof())
680                        break;
681
682                Intersectable *sourceObj = NULL;
683                Intersectable *termObj = NULL;
684               
685                if (sObj.mId >= 0)
686                {
687                        ObjectContainer::iterator oit =
688                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
689                        sourceObj = *oit;
690                }
691               
692                if (tObj.mId >= 0)
693                {
694                        ObjectContainer::iterator oit =
695                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
696                        termObj = *oit;
697                }
698
699                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
700        }
701
702#endif
703        samplesIn.close();
704
705        return true;
706}
707
708
709bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
710{
711        char fileName[100];
712        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
713       
714
715        VssRayContainer::const_iterator it, it_end = samples.end();
716       
717#if USE_ASCII
718        ofstream samplesOut(fileName);
719        if (!samplesOut.is_open())
720                return false;
721
722        for (it = samples.begin(); it != it_end; ++ it)
723        {
724                VssRay *ray = *it;
725                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
726                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
727
728                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
729                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
730                                   << sourceid << " " << termid << "\n";
731        }
732#else
733        ofstream samplesOut(fileName, ios::binary);
734        if (!samplesOut.is_open())
735                return false;
736
737        for (it = samples.begin(); it != it_end; ++ it)
738        {       
739                VssRay *ray = *it;
740                Vector3 origin(ray->GetOrigin());
741                Vector3 termination(ray->GetTermination());
742               
743                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
744                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
745
746                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
747                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
748                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
749                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
750    }
751#endif
752        samplesOut.close();
753
754        return true;
755}
756
757bool Preprocessor::GenerateRays(const int number,
758                                                                const int sampleType,
759                                                                SimpleRayContainer &rays)
760{
761        const int startSize = (int)rays.size();
762        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
763
764        if (!strategy)
765        {
766                return false;
767        }
768
769        for (int i=0; (int)rays.size() - startSize < number; ++ i)
770        {
771                SimpleRay newRay;
772
773                if (strategy->GenerateSample(newRay))
774                {
775#if 1
776                        rays.AddRay(newRay);
777#else
778                        GenerateRayBundle(rays, newRay, 16, 0);
779#endif
780                }       
781        }
782
783        delete strategy;
784    return true;
785}
786
787
788SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
789{
790        switch (strategyId)
791        {
792        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
793                return new ObjectBasedDistribution(*this);
794        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
795                return new ObjectDirectionBasedDistribution(*this);
796        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
797                return new DirectionBasedDistribution(*this);
798        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
799                return new DirectionBoxBasedDistribution(*this);
800        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
801                return new SpatialBoxBasedDistribution(*this);
802        //case OBJECTS_INTERIOR_DISTRIBUTION:
803        //      return new ObjectsInteriorDistribution(*this);
804        default: // no valid strategy
805                Debug << "warning: no valid sampling strategy" << endl;
806                return NULL;
807        }
808
809        return NULL; // should never come here
810}
811
812
813bool Preprocessor::InitRayCast(const string externKdTree, const string internkdtree)
814{
815        bool loadKdTree;
816        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
817       
818        if (!loadKdTree)
819        {       
820                //-- build new kd tree from scene geometry
821                BuildKdTree();
822                KdTreeStatistics(cout);
823        }
824        else
825        {
826                const long startTime = GetTime();
827                cout << "loading kd tree file " << internkdtree << " ... ";
828
829                if (!LoadKdTree(internkdtree))
830                {
831                        cout << "error loading kd tree with filename " << internkdtree << ", rebuilding it instead ..." << endl;
832
833                        BuildKdTree();
834                        KdTreeStatistics(cout);
835                }
836
837                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
838
839                if (0)
840                {
841                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
842                       
843                        if (exporter)
844                        {
845                                exporter->ExportKdTree(*mKdTree, true);
846                                delete exporter;
847                        }
848                }
849        }
850
851        int rayCastMethod;
852        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
853
854        if (rayCastMethod == 0)
855        {
856                mRayCaster = new InternalRayCaster(*this, mKdTree);
857                cout << "ray cast method: internal" << endl;
858        }
859        else
860        {
861#ifdef GTP_INTERNAL
862                mRayCaster = new IntelRayCaster(*this, externKdTree);
863                cout << "ray cast method: intel" << endl;
864#endif
865        }
866
867        return true;
868}
869
870
871void
872Preprocessor::CastRays(
873                                           SimpleRayContainer &rays,
874                                           VssRayContainer &vssRays,
875                                           const bool castDoubleRays,
876                                           const bool pruneInvalidRays
877                                           )
878{
879        const long t1 = GetTime();
880
881        for (int i = 0; i < (int)rays.size();)
882        {
883                if (i + 16 < (int)rays.size())
884                {
885                        mRayCaster->CastRays16(
886                                                                   i,
887                                                                   rays,                               
888                                                                   vssRays,
889                                                                   mViewCellsManager->GetViewSpaceBox(),
890                                                                   castDoubleRays,
891                                                                   pruneInvalidRays);
892                        i += 16;
893                }
894                else
895                  {
896                        mRayCaster->CastRay(
897                                                                rays[i],
898                                                                vssRays,
899                                                                mViewCellsManager->GetViewSpaceBox(),
900                                                                castDoubleRays,
901                                                                pruneInvalidRays);
902                        i ++;
903                  }
904                if (i % 10000 == 0)
905                  cout<<"\r"<<i<<"/"<<rays.size()<<"\r";
906        }
907        cout<<endl;
908       
909        long t2 = GetTime();
910
911#if SHOW_RAYCAST_TIMING
912        if (castDoubleRays)
913                cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
914        else
915                cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
916#endif 
917}
918
919
920bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
921                                                                         const SimpleRay &mainRay,
922                                                                         const int number,
923                                                                         const int pertubType) const
924{
925        rayBundle.push_back(mainRay);
926
927        const float pertubOrigin = 0.0f;
928        const float pertubDir = 0.2f;
929
930        for (int i = 0; i < number - 1; ++ i)
931        {
932                Vector3 pertub;
933
934                pertub.x = RandomValue(0.0f, pertubDir);
935                pertub.y = RandomValue(0.0f, pertubDir);
936                pertub.z = RandomValue(0.0f, pertubDir);
937                const Vector3 newDir = mainRay.mDirection + pertub;
938                //const Vector3 newDir = mainRay.mDirection;
939
940                pertub.x = RandomValue(0.0f, pertubOrigin);
941                pertub.y = RandomValue(0.0f, pertubOrigin);
942                pertub.z = RandomValue(0.0f, pertubOrigin);
943                const Vector3 newOrigin = mainRay.mOrigin + pertub;
944                //const Vector3 newOrigin = mainRay.mOrigin;
945
946                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
947        }
948
949        return true;
950}
951
952
953void Preprocessor::SetupRay(Ray &ray,
954                                                        const Vector3 &point,
955                                                        const Vector3 &direction
956                                                        ) const
957{
958        ray.Clear();
959        // do not store anything else then intersections at the ray
960        ray.Init(point, direction, Ray::LOCAL_RAY);
961       
962}
963
964
965}
Note: See TracBrowser for help on using the repository browser.