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

Revision 1582, 24.1 KB checked in by bittner, 18 years ago (diff)

ViewcellsManager? issue solved

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