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

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