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

Revision 1972, 35.7 KB checked in by mattausch, 17 years ago (diff)

implemented improved ray casting

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