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

Revision 1917, 32.2 KB checked in by mattausch, 18 years ago (diff)
RevLine 
[372]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"
[439]8#include "ViewCellsManager.h"
[445]9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
[469]11#include "RenderSimulator.h"
[496]12#include "GlRenderer.h"
[749]13#include "PlyParser.h"
[1020]14#include "SamplingStrategy.h"
[1233]15#include "VspTree.h"
16#include "OspTree.h"
[1221]17#include "ObjParser.h"
[1264]18#include "BvHierarchy.h"
[1279]19#include "HierarchyManager.h"
[1287]20#include "VssRay.h"
[1520]21#include "IntelRayCaster.h"
22#include "InternalRayCaster.h"
[1264]23
[1287]24
[372]25
[1292]26#define DEBUG_RAYCAST 0
[1584]27#define SHOW_RAYCAST_TIMING 1
[1292]28
29
[863]30namespace GtpVisibilityPreprocessor {
[860]31
[1867]32  const static bool ADDITIONAL_GEOMETRY_HACK = false;
[860]33
[1867]34  Preprocessor *preprocessor = NULL;
35 
[1001]36// HACK: Artificially modify scene to watch rendercost changes
[750]37static void AddGeometry(SceneGraph *scene)
38{
[1328]39        scene->GetRoot()->UpdateBox();
[752]40
[750]41        AxisAlignedBox3 sceneBox = scene->GetBox();
42
43        int n = 200;
44
[1291]45        if (0)
[750]46        {
[1291]47                // form grid of boxes
48                for (int i = 0; i < n; ++ i)
[750]49                {
[1291]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);
[750]53
[1291]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);
[1328]63                                scene->GetRoot()->mGeometry.push_back(mi);
[1291]64                        }
[750]65                }
66
[1291]67                for (int i = 0; i < n; ++ i)
[750]68                {
[1291]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);
[1328]82                                scene->GetRoot()->mGeometry.push_back(mi);
[1291]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
[750]90                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
[1291]91                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
92
93                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
[991]94                        Mesh *mesh = CreateMeshFromBox(box);
[750]95
96                        mesh->Preprocess();
[1291]97
[750]98                        MeshInstance *mi = new MeshInstance(mesh);
[1328]99                        scene->GetRoot()->mGeometry.push_back(mi);
[750]100                }
[1291]101
[1328]102                scene->GetRoot()->UpdateBox();
[750]103        }
104
[840]105        if (1)
106        {
[1221]107                // plane separating view space regions
[1135]108                const Vector3 scale(1.0f, 0.0, 0);
[750]109
[840]110                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
[750]111
[840]112                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
113                Mesh *planeMesh = new Mesh();
[1291]114
[840]115                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
116                IncludePolyInMesh(*poly, *planeMesh);
[1291]117
[840]118                planeMesh->Preprocess();
[1291]119
[840]120                MeshInstance *planeMi = new MeshInstance(planeMesh);
[1328]121                scene->GetRoot()->mGeometry.push_back(planeMi);
[840]122        }       
[750]123}
124
125
[372]126Preprocessor::Preprocessor():
127mKdTree(NULL),
[409]128mBspTree(NULL),
[445]129mVspBspTree(NULL),
[1002]130mViewCellsManager(NULL),
[1251]131mRenderSimulator(NULL),
[1279]132mPass(0),
[1520]133mSceneGraph(NULL),
[1613]134mRayCaster(NULL),
135mStopComputation(false)
[308]136{
[1004]137        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
[538]138 
[840]139        // renderer will be constructed when the scene graph and viewcell manager will be known
140        renderer = NULL;
[1785]141       
[1613]142        Environment::GetSingleton()->GetBoolValue("Preprocessor.delayVisibilityComputation",
143                                                                                          mDelayVisibilityComputation);
144       
[1004]145        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
[1379]146        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
[1004]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 );
[1520]151       
[871]152        char buffer[256];
[1004]153        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
[871]154        mVisibilityFileName = buffer;
[1771]155       
156        Environment::GetSingleton()->GetStringValue("Preprocessor.stats",  buffer);
157        mStats.open(buffer);
158       
159       
[1749]160        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter);
[1004]161        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
[1695]162                                                                                          mApplyVisibilitySpatialFilter );
[1004]163        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
[878]164
[1695]165        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportObj", mExportObj);
166       
[1723]167        Environment::GetSingleton()->GetBoolValue("Preprocessor.useViewSpaceBox", mUseViewSpaceBox);
168
[1900]169        Environment::GetSingleton()->GetBoolValue("Preprocessor.Export.rays", mExportRays);
170        Environment::GetSingleton()->GetIntValue("Preprocessor.Export.numRays", mExportNumRays);
171
[1695]172        Debug << "******* Preprocessor Options **********" << endl;
[840]173        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
[1379]174        Debug << "load meshes: " << mLoadMeshes << endl;
[1695]175        Debug << "load meshes: " << mLoadMeshes << endl;
176        Debug << "export obj: " << mExportObj << endl;
[1723]177        Debug << "use view space box: " << mUseViewSpaceBox << endl;
[372]178}
179
180
181Preprocessor::~Preprocessor()
182{
[1291]183        cout << "cleaning up" << endl;
[752]184
[1291]185        cout << "Deleting view cells manager ... \n";
186        DEL_PTR(mViewCellsManager);
187        cout << "done.\n";
[752]188
[1291]189        cout << "Deleting bsp tree ... \n";
190        DEL_PTR(mBspTree);
191        cout << "done.\n";
[752]192
[1291]193        cout << "Deleting kd tree...\n";
194        DEL_PTR(mKdTree);
195        cout << "done.\n";
[752]196
[1291]197        cout << "Deleting vspbsp tree...\n";
198        DEL_PTR(mVspBspTree);
199        cout << "done.\n";
[1002]200
[1291]201        cout << "Deleting scene graph...\n";
202        DEL_PTR(mSceneGraph);
203        cout << "done.\n";
204
205        DEL_PTR(mRenderSimulator);
206        DEL_PTR(renderer);
[1523]207        DEL_PTR(mRayCaster);
[372]208}
209
[1521]210
211GlRendererBuffer *Preprocessor::GetRenderer()
212{
213        return renderer;
214}
215
216
217static int SplitFilenames(const string str, vector<string> &filenames)
[387]218{
219        int pos = 0;
220
221        while(1) {
[469]222                int npos = (int)str.find(';', pos);
[387]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));
[440]231        return (int)filenames.size();
[387]232}
233
[750]234
[1655]235bool Preprocessor::LoadBinaryObj(const string filename,
236                                                                 SceneGraphNode *root,
237                                                                 vector<FaceParentInfo> *parents)
238{
[1658]239        //ifstream samplesIn(filename, ios::binary);
240        igzstream samplesIn(filename.c_str());
241       
[1655]242        if (!samplesIn.is_open())
243                return false;
244
[1658]245        cout << "binary obj dump available, loading " << filename.c_str() << endl;
[1655]246        // table associating indices with vectors
247        map<int, Vector3> hashTable;
[1658]248
[1655]249        // table for vertices
250        VertexContainer vertices;
251        FaceContainer faces;
252
[1786]253        if (parents)
254                cout << "using face parents" << endl;
255        else
256                cout << "not using face parents" << endl;
257
[1655]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
[1658]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
[1695]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
[1713]326        AxisAlignedBox3 bbox = mSceneGraph->GetBox(); bbox.Enlarge(30.0);
[1695]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();
[1701]334                        //if (bbox.IsInside(tri.mVertices[0]) && bbox.IsInside(tri.mVertices[1]) && bbox.IsInside(tri.mVertices[2]))
335                        //{
[1713]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;
[1701]339                        //}
[1695]340                }
341                else
342                {
343                        cout << "not implemented intersectable type " << obj->Type() << endl;
344                }
345        }
346
347        // write faces
348        int i = 1;
[1713]349        for (oit = objects.begin(); oit != oit_end; ++ oit)
[1695]350        {
351                Intersectable *obj = *oit;
352                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
353                {
[1713]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                        //}
[1695]361                }
362                else
363                {
364                        cout << "not implemented intersectable type " << obj->Type() << endl;
365                }
366        }
367
368        return true;
369
370}
371
[1658]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
[1786]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
[372]429bool
430Preprocessor::LoadScene(const string filename)
431{
[1655]432    // use leaf nodes of the original spatial hierarchy as occludees
[508]433        mSceneGraph = new SceneGraph;
[372]434 
[508]435        Parser *parser;
[387]436        vector<string> filenames;
[1404]437        const int files = SplitFilenames(filename, filenames);
[712]438        cout << "number of input files: " << files << endl;
[387]439        bool result = false;
[1695]440        bool isObj = false;
[1344]441
442        // root for different files
443        mSceneGraph->SetRoot(new SceneGraphNode());
444
[1404]445        // intel ray caster can only trace triangles
[1520]446        int rayCastMethod;
447        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
[1827]448        vector<FaceParentInfo> *fi =
[1867]449          ((rayCastMethod == RayCaster::INTEL_RAYCASTER) && mLoadMeshes) ?
450          &mFaceParents : NULL;
451       
[1658]452        if (files == 1)
[1867]453          {
[387]454                if (strstr(filename.c_str(), ".x3d"))
[1867]455                  {
[1655]456                        parser = new X3dParser;
[1658]457                       
458                        result = parser->ParseFile(filename,
459                                                                           mSceneGraph->GetRoot(),
460                                                                           mLoadMeshes,
461                                                                           fi);
462                        delete parser;
[1655]463                }
[1658]464                else if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
[1655]465                {
[1658]466                        parser = new PlyParser;
[1655]467
[1658]468                        result = parser->ParseFile(filename,
469                                                                           mSceneGraph->GetRoot(),
470                                                                           mLoadMeshes,
471                                                                           fi);
472                        delete parser;
[1655]473                }
[1658]474                else if (strstr(filename.c_str(), ".obj"))
475                {
[1695]476                        isObj = true;
477
[1658]478                        // hack: load binary dump
479                        string binFile = ReplaceSuffix(filename, ".obj", ".bin");
[372]480
[1658]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;
[1404]490               
[1658]491                                result = parser->ParseFile(filename,
[1655]492                                                                   mSceneGraph->GetRoot(),
493                                                                   mLoadMeshes,
494                                                                   fi);
[1658]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                                }
[1655]503
[1658]504                                delete parser;
505                        }
[1660]506                        else if (0)
[1658]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;
[1404]522        }
[1658]523        else
524        {
[1404]525                vector<string>::const_iterator fit, fit_end = filenames.end();
[1344]526               
[1404]527                for (fit = filenames.begin(); fit != fit_end; ++ fit)
528                {
529                        const string filename = *fit;
[1328]530
[1404]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();
[1695]538                        const bool success =
539                                parser->ParseFile(filename, node, mLoadMeshes, fi);
[1404]540
541                        if (success)
542                        {
543                                mSceneGraph->GetRoot()->mChildren.push_back(node);
544                                result = true; // at least one file parsed
545                        }
546
[1713]547                        // temporare hack
[1701]548                        //if (!strstr(filename.c_str(), "plane")) mSceneGraph->GetRoot()->UpdateBox();
549
[1404]550                        delete parser;
[387]551                }
552        }
[1344]553       
[752]554        if (result)
[1344]555        {
[752]556                // HACK
[1020]557                if (ADDITIONAL_GEOMETRY_HACK)
558                        AddGeometry(mSceneGraph);
[1328]559
[1020]560                mSceneGraph->AssignObjectIds();
[1344]561 
[1020]562                int intersectables, faces;
563                mSceneGraph->GetStatistics(intersectables, faces);
[1344]564 
[1020]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;
[1701]568               
[1697]569                mObjects.reserve(intersectables);
[1020]570                mSceneGraph->CollectObjects(&mObjects);
[1713]571               
572                // temp hack
573                //ExportObj("cropped_vienna.obj", mObjects);
[1328]574                mSceneGraph->GetRoot()->UpdateBox();
[1713]575                               
576                cout << "finished loading" << endl;
[387]577        }
[1328]578
[492]579        return result;
[372]580}
581
582bool
583Preprocessor::ExportPreprocessedData(const string filename)
584{
[1486]585        mViewCellsManager->ExportViewCells(filename, true, mObjects);
586        return true;
[372]587}
588
[1486]589
[372]590bool
[871]591Preprocessor::PostProcessVisibility()
592{
593 
[904]594  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
[997]595        cout<<"Applying visibility filter ...";
[1002]596        cout<<"filter width = " << mVisibilityFilterWidth << endl;
[904]597       
[1002]598        if (!mViewCellsManager)
[1199]599          return false;
600       
[871]601        mViewCellsManager->ApplyFilter(mKdTree,
[904]602                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
603                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
[997]604        cout << "done." << endl;
[871]605  }
606 
607  // export the preprocessed information to a file
608  if (mExportVisibility)
[1486]609  {
610          ExportPreprocessedData(mVisibilityFileName);
611  }
612
[871]613  return true;
614}
615
616
617bool
[372]618Preprocessor::BuildKdTree()
619{
620  mKdTree = new KdTree;
[1344]621
[372]622  // add mesh instances of the scene graph to the root of the tree
623  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
[1344]624       
[372]625  mSceneGraph->CollectObjects(&root->mObjects);
[1344]626 
[1415]627  const long startTime = GetTime();
[1201]628  cout << "building kd tree ... " << endl;
[1344]629
[372]630  mKdTree->Construct();
[1344]631
[1415]632  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
633           << " secs " << endl;
[1344]634
[372]635  return true;
636}
637
[1415]638
[372]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,
[492]653                                          const bool scene,
[1545]654                                          const bool kdtree
[492]655                                          )
[372]656{
657  Exporter *exporter = Exporter::GetExporter(filename);
658       
659  if (exporter) {
[1545]660    if (2 && scene)
[1328]661      exporter->ExportScene(mSceneGraph->GetRoot());
[372]662
[1545]663    if (1 && kdtree) {
[372]664      exporter->SetWireframe();
665      exporter->ExportKdTree(*mKdTree);
666    }
667
668    delete exporter;
669    return true;
670  }
671
672  return false;
673}
[429]674
[508]675
[463]676bool Preprocessor::PrepareViewCells()
677{
[1523]678        ///////
[577]679        //-- parse view cells construction method
[1563]680
[1004]681        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
[577]682        char buf[100];
[1585]683
[577]684        if (mLoadViewCells)
[997]685        {       
[1740]686                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
687                cout << "loading view cells from " << buf << endl<<flush;
[1715]688
[1740]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                }
[577]697        }
698        else
699        {
[1288]700                // parse type of view cell container
[1004]701                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
[1740]702                mViewCellsManager = CreateViewCellsManager(buf);
[1112]703
704                // default view space is the extent of the scene
[1723]705                AxisAlignedBox3 viewSpaceBox;
[1740]706
[1723]707                if (mUseViewSpaceBox)
[1563]708                {
[1723]709                        viewSpaceBox = mSceneGraph->GetBox();
710
[1563]711                        // use a small box outside of the scene
[1723]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);
[1563]716                }
[1723]717                else
718                {
719                        viewSpaceBox = mSceneGraph->GetBox();
720                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
721                }
[1545]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);
[1740]731
[1627]732                if (loadVcGeometry)
[1545]733                {
[1627]734                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
[1545]735                        {
[1627]736                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
737                                {
738                                        cerr << "loading view cells geometry failed" << endl;
739                                }
[1545]740                        }
[1627]741                        else
742                        {
743                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
744                        }
[1545]745                }
[577]746        }
[1740]747
[1486]748        ////////
[1523]749        //-- evaluation of render cost heuristics
[1768]750
[473]751        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
752
[1004]753        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
754        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
755        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
[1740]756
[473]757        mRenderSimulator =
758                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]759
[480]760        mViewCellsManager->SetRenderer(mRenderSimulator);
[1740]761
[1785]762       
[1581]763        mViewCellsManager->SetPreprocessor(this);
[463]764        return true;
[490]765}
766
[1292]767 
[1563]768bool Preprocessor::ConstructViewCells()
[1292]769{
[1627]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;
[1292]778}
[490]779
[1294]780
[575]781ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
782{
[1264]783        ViewCellsTree *vcTree = new ViewCellsTree;
784
[575]785        if (strcmp(name, "kdTree") == 0)
786        {
[1264]787                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
[575]788        }
789        else if (strcmp(name, "bspTree") == 0)
790        {
791                Debug << "view cell type: Bsp" << endl;
792
[577]793                mBspTree = new BspTree();
[1264]794                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]795        }
796        else if (strcmp(name, "vspBspTree") == 0)
797        {
798                Debug << "view cell type: VspBsp" << endl;
799
[1004]800                mVspBspTree = new VspBspTree();
[1264]801                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
[575]802        }
[1006]803        else if (strcmp(name, "vspOspTree") == 0)
[575]804        {
[1421]805                Debug << "view cell type: VspOsp" << endl;
[1288]806                char buf[100];         
807                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
[1022]808
[1740]809                mViewCellsManager = new VspOspViewCellsManager(vcTree, buf);
[575]810        }
[1421]811        else if (strcmp(name, "sceneDependent") == 0) //TODO
[575]812        {
[1143]813                Debug << "view cell type: Bsp" << endl;
[1421]814               
[575]815                mBspTree = new BspTree();
[1264]816                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]817        }
818        else
819        {
[664]820                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]821                exit(1);
822        }
823
824        return mViewCellsManager;
825}
826
827
[491]828// use ascii format to store rays
829#define USE_ASCII 0
830
831
[1145]832static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
[490]833{
834        return obj1->mId < obj2->mId;
835}
836
837
[1414]838bool Preprocessor::LoadKdTree(const string filename)
[1197]839{
[1414]840        mKdTree = new KdTree();
[1633]841
[1414]842        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
[1197]843}
844
[1414]845
846bool Preprocessor::ExportKdTree(const string filename)
[1197]847{
[1414]848        return mKdTree->ExportBinTree(filename.c_str());
[1197]849}
850
851
[490]852bool Preprocessor::LoadSamples(VssRayContainer &samples,
853                                                           ObjectContainer &objects) const
854{
855        std::stable_sort(objects.begin(), objects.end(), ilt);
856        char fileName[100];
[1004]857        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[490]858       
[491]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);
[490]864
[491]865#if USE_ASCII
[656]866        ifstream samplesIn(fileName);
[490]867        if (!samplesIn.is_open())
868                return false;
869
870        string buf;
871        while (!(getline(samplesIn, buf)).eof())
872        {
[491]873                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]874                           &origin.x, &origin.y, &origin.z,
[491]875                           &termination.x, &termination.y, &termination.z,
876                           &(sObj.mId), &(tObj.mId));
[490]877               
[491]878                Intersectable *sourceObj = NULL;
879                Intersectable *termObj = NULL;
880               
881                if (sObj.mId >= 0)
[490]882                {
883                        ObjectContainer::iterator oit =
[491]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                }
[490]894
[491]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;
[490]920                }
[491]921               
922                if (tObj.mId >= 0)
[490]923                {
[491]924                        ObjectContainer::iterator oit =
925                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
926                        termObj = *oit;
[490]927                }
[491]928
929                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]930        }
[1779]931#endif
[491]932
[490]933        samplesIn.close();
934
935        return true;
936}
937
[508]938
939bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]940{
[491]941        char fileName[100];
[1004]942        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[491]943       
[490]944
945        VssRayContainer::const_iterator it, it_end = samples.end();
946       
[491]947#if USE_ASCII
948        ofstream samplesOut(fileName);
[490]949        if (!samplesOut.is_open())
950                return false;
951
952        for (it = samples.begin(); it != it_end; ++ it)
953        {
954                VssRay *ray = *it;
[491]955                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
956                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
957
[490]958                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
959                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]960                                   << sourceid << " " << termid << "\n";
[490]961        }
[491]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
[490]982        samplesOut.close();
[1194]983
[490]984        return true;
985}
[563]986
[1771]987
988int
989Preprocessor::GenerateRays(const int number,
[1867]990                                                   SamplingStrategy &strategy,
991                                                   SimpleRayContainer &rays)
[1020]992{
[1867]993  return strategy.GenerateSamples(number, rays);
[1771]994}
[860]995
[1771]996int
997Preprocessor::GenerateRays(const int number,
[1898]998                                                   const int sampleType,
999                                                   SimpleRayContainer &rays)
[1771]1000{
[1772]1001        const int startSize = (int)rays.size();
1002        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
1003        int castRays = 0;
1004
1005        if (!strategy)
[1381]1006        {
[1772]1007                return 0;
[1381]1008        }
[1772]1009
[1381]1010#if 1
[1772]1011        castRays = strategy->GenerateSamples(number, rays);
[1381]1012#else
[1772]1013        GenerateRayBundle(rays, newRay, 16, 0);
1014        castRays += 16;
[1381]1015#endif
[1772]1016
1017        delete strategy;
1018        return castRays;
[878]1019}
[1020]1020
1021
[1884]1022SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
[1020]1023{
1024        switch (strategyId)
1025        {
[1520]1026        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
[1020]1027                return new ObjectBasedDistribution(*this);
[1520]1028        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
[1020]1029                return new ObjectDirectionBasedDistribution(*this);
[1520]1030        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
[1020]1031                return new DirectionBasedDistribution(*this);
[1520]1032        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
[1020]1033                return new DirectionBoxBasedDistribution(*this);
[1520]1034        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
[1020]1035                return new SpatialBoxBasedDistribution(*this);
[1695]1036        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1037                return new ReverseObjectBasedDistribution(*this);
[1769]1038        case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1039                return new ViewCellBorderBasedDistribution(*this);
[1772]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);
[1824]1044        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1045                return new GlobalLinesDistribution(*this);
1046               
1047                //case OBJECTS_INTERIOR_DISTRIBUTION:
1048                //      return new ObjectsInteriorDistribution(*this);
[1020]1049        default: // no valid strategy
[1279]1050                Debug << "warning: no valid sampling strategy" << endl;
[1020]1051                return NULL;
1052        }
[1221]1053
[1570]1054        return NULL; // should never come here
[1020]1055}
1056
1057
[1627]1058bool Preprocessor::InitRayCast(const string externKdTree, const string internKdTree)
[1221]1059{
[1633]1060        // always try to load the kd tree
[1664]1061        cout << "loading kd tree file " << internKdTree << " ... " << endl;
[1634]1062
1063        if (!LoadKdTree(internKdTree))
1064        {
1065                cout << "error loading kd tree with filename " << internKdTree << ", rebuilding it instead ... " << endl;
[1633]1066                // build new kd tree from scene geometry
[1415]1067                BuildKdTree();
1068
[1627]1069                // export kd tree?
[1633]1070                const long startTime = GetTime();
[1627]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                }
[1415]1081        }
[1633]1082       
1083        KdTreeStatistics(cout);
1084        cout << mKdTree->GetBox() << endl;
[1415]1085
[1633]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
[1520]1097        int rayCastMethod;
1098        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
1099
1100        if (rayCastMethod == 0)
[1221]1101        {
[1867]1102                cout << "ray cast method: internal" << endl;
[1520]1103                mRayCaster = new InternalRayCaster(*this, mKdTree);
[1221]1104        }
[1251]1105        else
[1520]1106        {
[1524]1107#ifdef GTP_INTERNAL
[1867]1108          cout << "ray cast method: intel" << endl;
1109          mRayCaster = new IntelRayCaster(*this, externKdTree);
[1524]1110#endif
[1251]1111        }
[1867]1112       
[1520]1113        return true;
[1281]1114}
1115
[1292]1116
[1281]1117void
1118Preprocessor::CastRays(
1119                                           SimpleRayContainer &rays,
[1520]1120                                           VssRayContainer &vssRays,
[1528]1121                                           const bool castDoubleRays,
1122                                           const bool pruneInvalidRays
[1281]1123                                           )
1124{
[1757]1125  const long t1 = GetTime();
[1344]1126
[1524]1127        for (int i = 0; i < (int)rays.size();)
[1292]1128        {
[1524]1129                if (i + 16 < (int)rays.size())
[1520]1130                {
[1524]1131                        mRayCaster->CastRays16(
[1584]1132                                                                   i,
1133                                                                   rays,                               
1134                                                                   vssRays,
1135                                                                   mViewCellsManager->GetViewSpaceBox(),
1136                                                                   castDoubleRays,
1137                                                                   pruneInvalidRays);
[1524]1138                        i += 16;
[1292]1139                }
[1524]1140                else
[1584]1141                  {
[1524]1142                        mRayCaster->CastRay(
[1584]1143                                                                rays[i],
1144                                                                vssRays,
1145                                                                mViewCellsManager->GetViewSpaceBox(),
1146                                                                castDoubleRays,
1147                                                                pruneInvalidRays);
[1524]1148                        i ++;
[1584]1149                  }
[1743]1150
1151                if (rays.size() > 10000 && i % 10000 == 0)
[1627]1152                  cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
[1524]1153        }
[1743]1154
1155        if (rays.size() > 10000) {
1156          cout<<endl;
[1584]1157       
1158        long t2 = GetTime();
[1286]1159
[1584]1160#if SHOW_RAYCAST_TIMING
[1524]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;
[1743]1165#endif
1166        }
[1251]1167}
1168
1169
[1381]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
[1564]1177        const float pertubOrigin = 0.0f;
1178        const float pertubDir = 0.2f;
[1381]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);
[1713]1187
[1381]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);
[1713]1194
[1381]1195                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1196                //const Vector3 newOrigin = mainRay.mOrigin;
1197
[1883]1198                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
[1381]1199        }
1200
1201        return true;
1202}
1203
1204
[1251]1205void Preprocessor::SetupRay(Ray &ray,
1206                                                        const Vector3 &point,
[1713]1207                                                        const Vector3 &direction) const
[1251]1208{
1209        ray.Clear();
1210        // do not store anything else then intersections at the ray
[1713]1211        ray.Init(point, direction, Ray::LOCAL_RAY);     
[1251]1212}
1213
[1917]1214void Preprocessor::EvalViewCellHistogram()
[1771]1215{
[1917]1216        char filename[256];
1217        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
[1771]1218 
[1917]1219        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1220        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
[1771]1221}
[1520]1222
[1900]1223
1224bool
1225Preprocessor::ExportRays(const char *filename,
1226                                                 const VssRayContainer &vssRays,
1227                                                 const int number
1228                                                 )
1229{
1230  cout<<"Exporting vss rays..."<<endl<<flush;
1231 
1232  Exporter *exporter = NULL;
1233  exporter = Exporter::GetExporter(filename);
1234
1235  if (0) {
1236        exporter->SetWireframe();
1237        exporter->ExportKdTree(*mKdTree);
1238  }
1239 
1240  exporter->SetFilled();
1241  // $$JB temporarily do not export the scene
1242  if (0)
1243        exporter->ExportScene(mSceneGraph->GetRoot());
1244
1245  exporter->SetWireframe();
1246
1247  if (1) {
1248        exporter->SetForcedMaterial(RgbColor(1,0,1));
1249        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1250        exporter->ResetForcedMaterial();
1251  }
1252 
1253  VssRayContainer rays;
1254  vssRays.SelectRays(number, rays);
1255  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1256  delete exporter;
1257  cout<<"done."<<endl<<flush;
1258
1259  return true;
[1251]1260}
[1900]1261
1262}
Note: See TracBrowser for help on using the repository browser.