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

Revision 1627, 24.8 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
[1020]32const static bool ADDITIONAL_GEOMETRY_HACK = false;
[860]33
[492]34
[1001]35// HACK: Artificially modify scene to watch rendercost changes
[750]36static void AddGeometry(SceneGraph *scene)
37{
[1328]38        scene->GetRoot()->UpdateBox();
[752]39
[750]40        AxisAlignedBox3 sceneBox = scene->GetBox();
41
42        int n = 200;
43
[1291]44        if (0)
[750]45        {
[1291]46                // form grid of boxes
47                for (int i = 0; i < n; ++ i)
[750]48                {
[1291]49                        for (int j = 0; j < n; ++ j)
50                        {
51                                const Vector3 scale2((float)j * 0.8f / n + 0.1f,  0.05f, (float)i * 0.8f  / (float)n + 0.1f);
[750]52
[1291]53                                const Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
54
55                                const Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
56                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
57                                Mesh *mesh = CreateMeshFromBox(box);
58
59                                mesh->Preprocess();
60
61                                MeshInstance *mi = new MeshInstance(mesh);
[1328]62                                scene->GetRoot()->mGeometry.push_back(mi);
[1291]63                        }
[750]64                }
65
[1291]66                for (int i = 0; i < n; ++ i)
[750]67                {
[1291]68                        for (int j = 0; j < n; ++ j)
69                        {
70                                const Vector3 scale2(0.15f, (float)j * 0.8f / n + 0.1f, (float)i * 0.8f  / (float)n + 0.1f);
71
72                                Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
73
74                                Vector3 boxSize = sceneBox.Size() * Vector3(0.0025f, 0.01f, 0.0025f);
75                                AxisAlignedBox3 box(pt2, pt2 + boxSize);
76                                Mesh *mesh = CreateMeshFromBox(box);
77
78                                mesh->Preprocess();
79
80                                MeshInstance *mi = new MeshInstance(mesh);
[1328]81                                scene->GetRoot()->mGeometry.push_back(mi);
[1291]82                        }
83                }
84
85                for (int i = 0; i < n; ++ i)
86                {
87                        const Vector3 scale2(2, 0.2f, (float)i * 0.8f  / (float)n + 0.1f);
88
[750]89                        Vector3 pt2 = sceneBox.Min() + scale2 * (sceneBox.Max() - sceneBox.Min());
[1291]90
91                        //Vector3 boxSize = sceneBox.Size() * Vector3(0.0025, 0.01, 0.0025);
92                        Vector3 boxSize = sceneBox.Size() * Vector3(0.005f, 0.02f, 0.005f);
93
94                        AxisAlignedBox3 box(pt2 + 0.1f, pt2 + boxSize);
[991]95                        Mesh *mesh = CreateMeshFromBox(box);
[750]96
97                        mesh->Preprocess();
[1291]98
[750]99                        MeshInstance *mi = new MeshInstance(mesh);
[1328]100                        scene->GetRoot()->mGeometry.push_back(mi);
[750]101                }
[1291]102
[1328]103                scene->GetRoot()->UpdateBox();
[750]104        }
105
[840]106        if (1)
107        {
[1221]108                // plane separating view space regions
[1135]109                const Vector3 scale(1.0f, 0.0, 0);
[750]110
[840]111                Vector3 pt = sceneBox.Min() + scale * (sceneBox.Max() - sceneBox.Min());
[750]112
[840]113                Plane3 cuttingPlane(Vector3(1, 0, 0), pt);
114                Mesh *planeMesh = new Mesh();
[1291]115
[840]116                Polygon3 *poly = sceneBox.CrossSection(cuttingPlane);
117                IncludePolyInMesh(*poly, *planeMesh);
[1291]118
[840]119                planeMesh->Preprocess();
[1291]120
[840]121                MeshInstance *planeMi = new MeshInstance(planeMesh);
[1328]122                scene->GetRoot()->mGeometry.push_back(planeMi);
[840]123        }       
[750]124}
125
126
[372]127Preprocessor::Preprocessor():
128mKdTree(NULL),
[409]129mBspTree(NULL),
[445]130mVspBspTree(NULL),
[1279]131mHierarchyManager(NULL),
[1002]132mViewCellsManager(NULL),
[1251]133mRenderSimulator(NULL),
[1279]134mPass(0),
[1520]135mSceneGraph(NULL),
[1613]136mRayCaster(NULL),
137mStopComputation(false)
[308]138{
[1004]139        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
[538]140 
[840]141        // renderer will be constructed when the scene graph and viewcell manager will be known
142        renderer = NULL;
[496]143 
[1613]144        Environment::GetSingleton()->GetBoolValue("Preprocessor.delayVisibilityComputation",
145                                                                                          mDelayVisibilityComputation);
146       
[1004]147        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
[1379]148        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
[1004]149        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
150        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
151        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
152        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
[1520]153       
[871]154        char buffer[256];
[1004]155        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
[1415]156   
[871]157        mVisibilityFileName = buffer;
[1004]158        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter );
159        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
[904]160                                                          mApplyVisibilitySpatialFilter );
[1004]161        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
[878]162
[840]163        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
[1379]164        Debug << "load meshes: " << mLoadMeshes << endl;
[372]165}
166
167
168Preprocessor::~Preprocessor()
169{
[1291]170        cout << "cleaning up" << endl;
[752]171
[1291]172        cout << "Deleting view cells manager ... \n";
173        DEL_PTR(mViewCellsManager);
174        cout << "done.\n";
[752]175
[1291]176        cout << "Deleting bsp tree ... \n";
177        DEL_PTR(mBspTree);
178        cout << "done.\n";
[752]179
[1291]180        cout << "Deleting kd tree...\n";
181        DEL_PTR(mKdTree);
182        cout << "done.\n";
[752]183
[1291]184        cout << "Deleting hierarchy manager...\n";
185        DEL_PTR(mHierarchyManager);
186        cout << "done.\n";
[1002]187
[1291]188        cout << "Deleting vspbsp tree...\n";
189        DEL_PTR(mVspBspTree);
190        cout << "done.\n";
[1002]191
[1291]192        cout << "Deleting scene graph...\n";
193        DEL_PTR(mSceneGraph);
194        cout << "done.\n";
195
196        DEL_PTR(mRenderSimulator);
197        DEL_PTR(renderer);
[1523]198        DEL_PTR(mRayCaster);
[372]199}
200
[1521]201
202GlRendererBuffer *Preprocessor::GetRenderer()
203{
204        return renderer;
205}
206
207
208static int SplitFilenames(const string str, vector<string> &filenames)
[387]209{
210        int pos = 0;
211
212        while(1) {
[469]213                int npos = (int)str.find(';', pos);
[387]214               
215                if (npos < 0 || npos - pos < 1)
216                        break;
217                filenames.push_back(string(str, pos, npos - pos));
218                pos = npos + 1;
219        }
220       
221        filenames.push_back(string(str, pos, str.size() - pos));
[440]222        return (int)filenames.size();
[387]223}
224
[750]225
[372]226bool
227Preprocessor::LoadScene(const string filename)
228{
[925]229        // use leaf nodes of the original spatial hierarchy as occludees
[508]230        mSceneGraph = new SceneGraph;
[372]231 
[508]232        Parser *parser;
[387]233        vector<string> filenames;
[1404]234        const int files = SplitFilenames(filename, filenames);
[712]235        cout << "number of input files: " << files << endl;
[387]236        bool result = false;
[1344]237
238        // root for different files
239        mSceneGraph->SetRoot(new SceneGraphNode());
240
[1404]241        // intel ray caster can only trace triangles
[1520]242        int rayCastMethod;
243        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
244        vector<FaceParentInfo> *fi = (rayCastMethod == RayCaster::INTEL_RAYCASTER) ?
[1404]245                &mFaceParents : NULL;
246
[387]247        if (files == 1) {
248               
249                if (strstr(filename.c_str(), ".x3d"))
[749]250                  parser = new X3dParser;
[387]251                else
[811]252                  if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
[749]253                        parser = new PlyParser;
[1221]254                  else if (strstr(filename.c_str(), ".obj"))
255                          parser = new ObjParser;
256                  else
257                          parser = new UnigraphicsParser;
[372]258
[1328]259                cout << filename << endl;
[1404]260               
261                result = parser->ParseFile(
[1328]262                                filename,
[1344]263                                mSceneGraph->GetRoot(),
[1379]264                                mLoadMeshes,
[1404]265                                fi);
266                       
[387]267                delete parser;
[372]268
[1404]269        }
270        else {
271                vector<string>::const_iterator fit, fit_end = filenames.end();
[1344]272               
[1404]273                for (fit = filenames.begin(); fit != fit_end; ++ fit)
274                {
275                        const string filename = *fit;
[1328]276
[1404]277                        cout << "parsing file " << filename.c_str() << endl;
278                        if (strstr(filename.c_str(), ".x3d"))
279                                parser = new X3dParser;
280                        else
281                                parser = new UnigraphicsParser;
282
283                        SceneGraphNode *node = new SceneGraphNode();
284                        const bool success = parser->ParseFile(
285                                filename,
286                                node,
287                                mLoadMeshes,
288                                fi);
289
290                        if (success)
291                        {
292                                mSceneGraph->GetRoot()->mChildren.push_back(node);
293                                result = true; // at least one file parsed
294                        }
295
296                        delete parser;
[387]297                }
298        }
[1344]299       
[752]300        if (result)
[1344]301        {
[752]302                // HACK
[1020]303                if (ADDITIONAL_GEOMETRY_HACK)
304                        AddGeometry(mSceneGraph);
[1328]305
[1020]306                mSceneGraph->AssignObjectIds();
[1344]307 
[1020]308                int intersectables, faces;
309                mSceneGraph->GetStatistics(intersectables, faces);
[1344]310 
[1020]311                cout<<filename<<" parsed successfully."<<endl;
312                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
313                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
314                mSceneGraph->CollectObjects(&mObjects);
[1328]315                mSceneGraph->GetRoot()->UpdateBox();
[1344]316 
[1020]317                if (0)
318                {
319                        Exporter *exporter = Exporter::GetExporter("testload.x3d");
320                        if (exporter)
321                        {
322                                exporter->ExportGeometry(mObjects);
323                                delete exporter;
324                        }
325                }
[387]326        }
[1328]327
[492]328        return result;
[372]329}
330
331bool
332Preprocessor::ExportPreprocessedData(const string filename)
333{
[1486]334        mViewCellsManager->ExportViewCells(filename, true, mObjects);
335        return true;
[372]336}
337
[1486]338
[372]339bool
[871]340Preprocessor::PostProcessVisibility()
341{
342 
[904]343  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
[997]344        cout<<"Applying visibility filter ...";
[1002]345        cout<<"filter width = " << mVisibilityFilterWidth << endl;
[904]346       
[1002]347        if (!mViewCellsManager)
[1199]348          return false;
349       
[871]350        mViewCellsManager->ApplyFilter(mKdTree,
[904]351                                                                   mApplyVisibilityFilter ? mVisibilityFilterWidth : -1.0f,
352                                                                   mApplyVisibilitySpatialFilter ? mVisibilityFilterWidth : -1.0f);
[997]353        cout << "done." << endl;
[871]354  }
355 
356  // export the preprocessed information to a file
357  if (mExportVisibility)
[1486]358  {
359          ExportPreprocessedData(mVisibilityFileName);
360  }
361
[871]362  return true;
363}
364
365
366bool
[372]367Preprocessor::BuildKdTree()
368{
369  mKdTree = new KdTree;
[1344]370
[372]371  // add mesh instances of the scene graph to the root of the tree
372  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
[1344]373       
[372]374  mSceneGraph->CollectObjects(&root->mObjects);
[1344]375 
[1415]376  const long startTime = GetTime();
[1201]377  cout << "building kd tree ... " << endl;
[1344]378
[372]379  mKdTree->Construct();
[1344]380
[1415]381  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
382           << " secs " << endl;
[1344]383
[372]384  return true;
385}
386
[1415]387
[372]388void
389Preprocessor::KdTreeStatistics(ostream &s)
390{
391  s<<mKdTree->GetStatistics();
392}
393
394void
395Preprocessor::BspTreeStatistics(ostream &s)
396{
397        s << mBspTree->GetStatistics();
398}
399
400bool
401Preprocessor::Export( const string filename,
[492]402                                          const bool scene,
[1545]403                                          const bool kdtree
[492]404                                          )
[372]405{
406  Exporter *exporter = Exporter::GetExporter(filename);
407       
408  if (exporter) {
[1545]409    if (2 && scene)
[1328]410      exporter->ExportScene(mSceneGraph->GetRoot());
[372]411
[1545]412    if (1 && kdtree) {
[372]413      exporter->SetWireframe();
414      exporter->ExportKdTree(*mKdTree);
415    }
416
417    delete exporter;
418    return true;
419  }
420
421  return false;
422}
[429]423
[508]424
[463]425bool Preprocessor::PrepareViewCells()
426{
[1523]427        ///////
[577]428        //-- parse view cells construction method
[1563]429
[1004]430        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
[577]431        char buf[100];
[1585]432
[577]433        if (mLoadViewCells)
[997]434        {       
[1581]435          Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
436          cout << "loading view cells from " << buf << endl;
437         
[1593]438         mViewCellsManager = ViewCellsManager::LoadViewCells(buf, &mObjects, true, NULL);
[1581]439         
440          if (!mViewCellsManager)
[1593]441          {
442                  return false;
443          }
[577]444        }
445        else
446        {
[1288]447                // parse type of view cell container
[1004]448                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
[1002]449            mViewCellsManager = CreateViewCellsManager(buf);
[1112]450
451                // default view space is the extent of the scene
[1563]452                AxisAlignedBox3 box = mSceneGraph->GetBox();
453                                       
454                if (0)
455                {
456                        // use a small box outside of the scene
457                        box.Scale(Vector3(0.1f,0.5f,0.5f));
458                        box.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size())*0.5f, 0, 0));
459                }
[1545]460
[1563]461                mViewCellsManager->SetViewSpaceBox(box);
462         
[1545]463                bool loadVcGeometry;
464                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
465
466                bool extrudeBaseTriangles;
467                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
468
469                char vcGeomFilename[100];
470                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
471               
[1627]472                if (loadVcGeometry)
[1545]473                {
[1627]474                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
[1545]475                        {
[1627]476                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
477                                {
478                                        cerr << "loading view cells geometry failed" << endl;
479                                }
[1545]480                        }
[1627]481                        else
482                        {
483                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
484                        }
[1545]485                }
[577]486        }
[1112]487       
[1486]488        ////////
[1523]489        //-- evaluation of render cost heuristics
[473]490        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
491
[1004]492        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
493        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
494        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
[694]495       
[473]496        mRenderSimulator =
497                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]498
[480]499        mViewCellsManager->SetRenderer(mRenderSimulator);
[1581]500       
[538]501        if (mUseGlRenderer || mUseGlDebugger)
[1581]502          {
[540]503                // NOTE: render texture should be power of 2 and square
504                // renderer must be initialised
[1145]505                // $$matt
[1581]506                //              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
[556]507                //              renderer->makeCurrent();
[746]508               
[1581]509          }
510
511        mViewCellsManager->SetPreprocessor(this);
[463]512        return true;
[490]513}
514
[1292]515 
[1563]516bool Preprocessor::ConstructViewCells()
[1292]517{
[1627]518        // construct view cells using it's own set of samples
519        mViewCellsManager->Construct(this);
520
521        // visualizations and statistics
522        Debug << "finished view cells:" << endl;
523        mViewCellsManager->PrintStatistics(Debug);
524
525        return true;
[1292]526}
[490]527
[1294]528
[1288]529HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
530{
531        HierarchyManager *hierarchyManager;
532
533        if (strcmp(name, "osp") == 0)
534        {
[1291]535                Debug << "hierarchy manager: osp" << endl;
[1288]536                // HACK for testing if per kd evaluation works!!
[1293]537                const bool ishack = false;
[1288]538                if (ishack)
[1421]539                        hierarchyManager = new HierarchyManager(mKdTree);
[1288]540                else
[1421]541                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
[1288]542        }
543        else if (strcmp(name, "bvh") == 0)
544        {
[1291]545                Debug << "hierarchy manager: bvh" << endl;
[1421]546                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
[1288]547        }
[1291]548        else // only view space partition
549        {
550                Debug << "hierarchy manager: obj" << endl;
[1421]551                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
[1291]552        }
[1288]553
554        return hierarchyManager;
555}
556
557
[575]558ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
559{
[1264]560        ViewCellsTree *vcTree = new ViewCellsTree;
561
[575]562        if (strcmp(name, "kdTree") == 0)
563        {
[1264]564                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
[575]565        }
566        else if (strcmp(name, "bspTree") == 0)
567        {
568                Debug << "view cell type: Bsp" << endl;
569
[577]570                mBspTree = new BspTree();
[1264]571                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]572        }
573        else if (strcmp(name, "vspBspTree") == 0)
574        {
575                Debug << "view cell type: VspBsp" << endl;
576
[1004]577                mVspBspTree = new VspBspTree();
[1264]578                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
[575]579        }
[1006]580        else if (strcmp(name, "vspOspTree") == 0)
[575]581        {
[1421]582                Debug << "view cell type: VspOsp" << endl;
[1288]583                char buf[100];         
584                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
[1022]585
[1288]586                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
[1279]587                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
[575]588        }
[1421]589        else if (strcmp(name, "sceneDependent") == 0) //TODO
[575]590        {
[1143]591                Debug << "view cell type: Bsp" << endl;
[1421]592               
[575]593                mBspTree = new BspTree();
[1264]594                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]595        }
596        else
597        {
[664]598                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]599                exit(1);
600        }
601
602        return mViewCellsManager;
603}
604
605
[491]606// use ascii format to store rays
607#define USE_ASCII 0
608
609
[1145]610static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
[490]611{
612        return obj1->mId < obj2->mId;
613}
614
615
[1414]616bool Preprocessor::LoadKdTree(const string filename)
[1197]617{
[1414]618        mKdTree = new KdTree();
619        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
[1197]620}
621
[1414]622
623bool Preprocessor::ExportKdTree(const string filename)
[1197]624{
[1414]625        return mKdTree->ExportBinTree(filename.c_str());
[1197]626}
627
628
[490]629bool Preprocessor::LoadSamples(VssRayContainer &samples,
630                                                           ObjectContainer &objects) const
631{
632        std::stable_sort(objects.begin(), objects.end(), ilt);
633        char fileName[100];
[1004]634        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[490]635       
[491]636    Vector3 origin, termination;
637        // HACK: needed only for lower_bound algorithm to find the
638        // intersected objects
639        MeshInstance sObj(NULL);
640        MeshInstance tObj(NULL);
[490]641
[491]642#if USE_ASCII
[656]643        ifstream samplesIn(fileName);
[490]644        if (!samplesIn.is_open())
645                return false;
646
647        string buf;
648        while (!(getline(samplesIn, buf)).eof())
649        {
[491]650                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]651                           &origin.x, &origin.y, &origin.z,
[491]652                           &termination.x, &termination.y, &termination.z,
653                           &(sObj.mId), &(tObj.mId));
[490]654               
[491]655                Intersectable *sourceObj = NULL;
656                Intersectable *termObj = NULL;
657               
658                if (sObj.mId >= 0)
[490]659                {
660                        ObjectContainer::iterator oit =
[491]661                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
662                        sourceObj = *oit;
663                }
664               
665                if (tObj.mId >= 0)
666                {
667                        ObjectContainer::iterator oit =
668                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
669                        termObj = *oit;
670                }
[490]671
[491]672                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
673        }
674#else
675        ifstream samplesIn(fileName, ios::binary);
676        if (!samplesIn.is_open())
677                return false;
678
679        while (1)
680        {
681                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
682                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
683                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
684                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
685               
686                 if (samplesIn.eof())
687                        break;
688
689                Intersectable *sourceObj = NULL;
690                Intersectable *termObj = NULL;
691               
692                if (sObj.mId >= 0)
693                {
694                        ObjectContainer::iterator oit =
695                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
696                        sourceObj = *oit;
[490]697                }
[491]698               
699                if (tObj.mId >= 0)
[490]700                {
[491]701                        ObjectContainer::iterator oit =
702                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
703                        termObj = *oit;
[490]704                }
[491]705
706                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]707        }
[491]708
709#endif
[490]710        samplesIn.close();
711
712        return true;
713}
714
[508]715
716bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]717{
[491]718        char fileName[100];
[1004]719        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[491]720       
[490]721
722        VssRayContainer::const_iterator it, it_end = samples.end();
723       
[491]724#if USE_ASCII
725        ofstream samplesOut(fileName);
[490]726        if (!samplesOut.is_open())
727                return false;
728
729        for (it = samples.begin(); it != it_end; ++ it)
730        {
731                VssRay *ray = *it;
[491]732                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
733                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
734
[490]735                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
736                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]737                                   << sourceid << " " << termid << "\n";
[490]738        }
[491]739#else
740        ofstream samplesOut(fileName, ios::binary);
741        if (!samplesOut.is_open())
742                return false;
743
744        for (it = samples.begin(); it != it_end; ++ it)
745        {       
746                VssRay *ray = *it;
747                Vector3 origin(ray->GetOrigin());
748                Vector3 termination(ray->GetTermination());
749               
750                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
751                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
752
753                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
754                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
755                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
756                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
757    }
758#endif
[490]759        samplesOut.close();
[1194]760
[490]761        return true;
762}
[563]763
[1020]764bool Preprocessor::GenerateRays(const int number,
765                                                                const int sampleType,
766                                                                SimpleRayContainer &rays)
767{
768        const int startSize = (int)rays.size();
769        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
[860]770
[1020]771        if (!strategy)
[1381]772        {
[1020]773                return false;
[1381]774        }
[1020]775
776        for (int i=0; (int)rays.size() - startSize < number; ++ i)
777        {
778                SimpleRay newRay;
779
[1381]780                if (strategy->GenerateSample(newRay))
781                {
782#if 1
[1020]783                        rays.AddRay(newRay);
[1381]784#else
785                        GenerateRayBundle(rays, newRay, 16, 0);
786#endif
787                }       
[1020]788        }
789
790        delete strategy;
791    return true;
[878]792}
[1020]793
794
795SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
796{
797        switch (strategyId)
798        {
[1520]799        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
[1020]800                return new ObjectBasedDistribution(*this);
[1520]801        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
[1020]802                return new ObjectDirectionBasedDistribution(*this);
[1520]803        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
[1020]804                return new DirectionBasedDistribution(*this);
[1520]805        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
[1020]806                return new DirectionBoxBasedDistribution(*this);
[1520]807        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
[1020]808                return new SpatialBoxBasedDistribution(*this);
[1021]809        //case OBJECTS_INTERIOR_DISTRIBUTION:
810        //      return new ObjectsInteriorDistribution(*this);
[1020]811        default: // no valid strategy
[1279]812                Debug << "warning: no valid sampling strategy" << endl;
[1020]813                return NULL;
814        }
[1221]815
[1570]816        return NULL; // should never come here
[1020]817}
818
819
[1627]820bool Preprocessor::InitRayCast(const string externKdTree, const string internKdTree)
[1221]821{
[1626]822        bool loadKdTree = true;
823        //Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
[1415]824       
[1626]825       
[1415]826        if (!loadKdTree)
[1626]827        {       /////////
[1415]828                //-- build new kd tree from scene geometry
[1626]829
[1415]830                BuildKdTree();
831                KdTreeStatistics(cout);
832        }
833        else
834        {
[1627]835                long startTime = GetTime();
836                cout << "loading kd tree file " << internKdTree << " ... ";
[1415]837
[1627]838                if (!LoadKdTree(internKdTree))
[1415]839                {
[1627]840                        cout << "error loading kd tree with filename " << internKdTree << ", rebuilding it instead ..." << endl;
[1418]841
842                        BuildKdTree();
843                        KdTreeStatistics(cout);
[1415]844                }
[1416]845
[1415]846                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
847
848                if (0)
849                {
850                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
851                       
852                        if (exporter)
853                        {
854                                exporter->ExportKdTree(*mKdTree, true);
855                                delete exporter;
856                        }
857                }
[1627]858
859                // export kd tree?
860                startTime = GetTime();
861                cout << "exporting kd tree ... ";
862
863                if (!ExportKdTree(internKdTree))
864                {
865                        cout << " error exporting kd tree with filename " << internKdTree << endl;
866                }
867                else
868                {
869                        cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
870                }
[1415]871        }
872
[1520]873        int rayCastMethod;
874        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
875
876        if (rayCastMethod == 0)
[1221]877        {
[1520]878                mRayCaster = new InternalRayCaster(*this, mKdTree);
879                cout << "ray cast method: internal" << endl;
[1221]880        }
[1251]881        else
[1520]882        {
[1524]883#ifdef GTP_INTERNAL
[1520]884                mRayCaster = new IntelRayCaster(*this, externKdTree);
885                cout << "ray cast method: intel" << endl;
[1524]886#endif
[1251]887        }
888
[1520]889        return true;
[1281]890}
891
[1292]892
[1281]893void
894Preprocessor::CastRays(
895                                           SimpleRayContainer &rays,
[1520]896                                           VssRayContainer &vssRays,
[1528]897                                           const bool castDoubleRays,
898                                           const bool pruneInvalidRays
[1281]899                                           )
900{
[1524]901        const long t1 = GetTime();
[1344]902
[1524]903        for (int i = 0; i < (int)rays.size();)
[1292]904        {
[1524]905                if (i + 16 < (int)rays.size())
[1520]906                {
[1524]907                        mRayCaster->CastRays16(
[1584]908                                                                   i,
909                                                                   rays,                               
910                                                                   vssRays,
911                                                                   mViewCellsManager->GetViewSpaceBox(),
912                                                                   castDoubleRays,
913                                                                   pruneInvalidRays);
[1524]914                        i += 16;
[1292]915                }
[1524]916                else
[1584]917                  {
[1524]918                        mRayCaster->CastRay(
[1584]919                                                                rays[i],
920                                                                vssRays,
921                                                                mViewCellsManager->GetViewSpaceBox(),
922                                                                castDoubleRays,
923                                                                pruneInvalidRays);
[1524]924                        i ++;
[1584]925                  }
926                if (i % 10000 == 0)
[1627]927                  cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
[1524]928        }
[1608]929        cout<<endl;
[1584]930       
931        long t2 = GetTime();
[1286]932
[1584]933#if SHOW_RAYCAST_TIMING
[1524]934        if (castDoubleRays)
935                cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
936        else
937                cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
938#endif 
[1251]939}
940
941
[1381]942bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
943                                                                         const SimpleRay &mainRay,
944                                                                         const int number,
945                                                                         const int pertubType) const
946{
947        rayBundle.push_back(mainRay);
948
[1564]949        const float pertubOrigin = 0.0f;
950        const float pertubDir = 0.2f;
[1381]951
952        for (int i = 0; i < number - 1; ++ i)
953        {
954                Vector3 pertub;
955
956                pertub.x = RandomValue(0.0f, pertubDir);
957                pertub.y = RandomValue(0.0f, pertubDir);
958                pertub.z = RandomValue(0.0f, pertubDir);
959                const Vector3 newDir = mainRay.mDirection + pertub;
960                //const Vector3 newDir = mainRay.mDirection;
961
962                pertub.x = RandomValue(0.0f, pertubOrigin);
963                pertub.y = RandomValue(0.0f, pertubOrigin);
964                pertub.z = RandomValue(0.0f, pertubOrigin);
965                const Vector3 newOrigin = mainRay.mOrigin + pertub;
966                //const Vector3 newOrigin = mainRay.mOrigin;
967
968                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
969        }
970
971        return true;
972}
973
974
[1251]975void Preprocessor::SetupRay(Ray &ray,
976                                                        const Vector3 &point,
977                                                        const Vector3 &direction
[1520]978                                                        ) const
[1251]979{
980        ray.Clear();
981        // do not store anything else then intersections at the ray
982        ray.Init(point, direction, Ray::LOCAL_RAY);
[1584]983       
[1251]984}
985
[1520]986
[1251]987}
Note: See TracBrowser for help on using the repository browser.