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

Revision 1664, 27.9 KB checked in by mattausch, 18 years ago (diff)

changed priority computation:
taking ratio render cost decrease / pvs size increase rather
then render cost decrease alone
this should rather emphasise object space splits, as they
seem to cost less memory.

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