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

Revision 1900, 32.2 KB checked in by bittner, 18 years ago (diff)

experiments with different contribution computations

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