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

Revision 1613, 24.4 KB checked in by bittner, 18 years ago (diff)

kd-tree hack active

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               
472                if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
473                {
474                        if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
475                        {
476                                cerr << "loading view cells geometry failed" << endl;
477                        }
478                }
479                else
480                {
481                        cerr << "loading view cells geometry is not implemented for this manager" << endl;
482                }
[577]483        }
[1112]484       
[1486]485        ////////
[1523]486        //-- evaluation of render cost heuristics
[473]487        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
488
[1004]489        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
490        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
491        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
[694]492       
[473]493        mRenderSimulator =
494                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]495
[480]496        mViewCellsManager->SetRenderer(mRenderSimulator);
[1581]497       
[538]498        if (mUseGlRenderer || mUseGlDebugger)
[1581]499          {
[540]500                // NOTE: render texture should be power of 2 and square
501                // renderer must be initialised
[1145]502                // $$matt
[1581]503                //              renderer = new GlRendererBuffer(1024, 768, mSceneGraph, mViewCellsManager, mKdTree);
[556]504                //              renderer->makeCurrent();
[746]505               
[1581]506          }
507
508        mViewCellsManager->SetPreprocessor(this);
[463]509        return true;
[490]510}
511
[1292]512 
[1563]513bool Preprocessor::ConstructViewCells()
[1292]514{
[1581]515  // construct view cells using it's own set of samples
516  mViewCellsManager->Construct(this);
517 
518  // visualizations and statistics
519  Debug << "finished view cells:" << endl;
520  mViewCellsManager->PrintStatistics(Debug);
521 
522  return true;
[1292]523}
[490]524
[1294]525
[1288]526HierarchyManager *Preprocessor::CreateHierarchyManager(const char *name)
527{
528        HierarchyManager *hierarchyManager;
529
530        if (strcmp(name, "osp") == 0)
531        {
[1291]532                Debug << "hierarchy manager: osp" << endl;
[1288]533                // HACK for testing if per kd evaluation works!!
[1293]534                const bool ishack = false;
[1288]535                if (ishack)
[1421]536                        hierarchyManager = new HierarchyManager(mKdTree);
[1288]537                else
[1421]538                        hierarchyManager = new HierarchyManager(HierarchyManager::KD_BASED_OBJ_SUBDIV);
[1288]539        }
540        else if (strcmp(name, "bvh") == 0)
541        {
[1291]542                Debug << "hierarchy manager: bvh" << endl;
[1421]543                hierarchyManager = new HierarchyManager(HierarchyManager::BV_BASED_OBJ_SUBDIV);
[1288]544        }
[1291]545        else // only view space partition
546        {
547                Debug << "hierarchy manager: obj" << endl;
[1421]548                hierarchyManager = new HierarchyManager(HierarchyManager::NO_OBJ_SUBDIV);
[1291]549        }
[1288]550
551        return hierarchyManager;
552}
553
554
[575]555ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
556{
[1264]557        ViewCellsTree *vcTree = new ViewCellsTree;
558
[575]559        if (strcmp(name, "kdTree") == 0)
560        {
[1264]561                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
[575]562        }
563        else if (strcmp(name, "bspTree") == 0)
564        {
565                Debug << "view cell type: Bsp" << endl;
566
[577]567                mBspTree = new BspTree();
[1264]568                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]569        }
570        else if (strcmp(name, "vspBspTree") == 0)
571        {
572                Debug << "view cell type: VspBsp" << endl;
573
[1004]574                mVspBspTree = new VspBspTree();
[1264]575                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
[575]576        }
[1006]577        else if (strcmp(name, "vspOspTree") == 0)
[575]578        {
[1421]579                Debug << "view cell type: VspOsp" << endl;
[1288]580                char buf[100];         
581                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
[1022]582
[1288]583                HierarchyManager *mHierarchyManager = CreateHierarchyManager(buf);
[1279]584                mViewCellsManager = new VspOspViewCellsManager(vcTree, mHierarchyManager);
[575]585        }
[1421]586        else if (strcmp(name, "sceneDependent") == 0) //TODO
[575]587        {
[1143]588                Debug << "view cell type: Bsp" << endl;
[1421]589               
[575]590                mBspTree = new BspTree();
[1264]591                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]592        }
593        else
594        {
[664]595                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]596                exit(1);
597        }
598
599        return mViewCellsManager;
600}
601
602
[491]603// use ascii format to store rays
604#define USE_ASCII 0
605
606
[1145]607static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
[490]608{
609        return obj1->mId < obj2->mId;
610}
611
612
[1414]613bool Preprocessor::LoadKdTree(const string filename)
[1197]614{
[1414]615        mKdTree = new KdTree();
616        return mKdTree->LoadBinTree(filename.c_str(), mObjects);
[1197]617}
618
[1414]619
620bool Preprocessor::ExportKdTree(const string filename)
[1197]621{
[1414]622        return mKdTree->ExportBinTree(filename.c_str());
[1197]623}
624
625
[490]626bool Preprocessor::LoadSamples(VssRayContainer &samples,
627                                                           ObjectContainer &objects) const
628{
629        std::stable_sort(objects.begin(), objects.end(), ilt);
630        char fileName[100];
[1004]631        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[490]632       
[491]633    Vector3 origin, termination;
634        // HACK: needed only for lower_bound algorithm to find the
635        // intersected objects
636        MeshInstance sObj(NULL);
637        MeshInstance tObj(NULL);
[490]638
[491]639#if USE_ASCII
[656]640        ifstream samplesIn(fileName);
[490]641        if (!samplesIn.is_open())
642                return false;
643
644        string buf;
645        while (!(getline(samplesIn, buf)).eof())
646        {
[491]647                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]648                           &origin.x, &origin.y, &origin.z,
[491]649                           &termination.x, &termination.y, &termination.z,
650                           &(sObj.mId), &(tObj.mId));
[490]651               
[491]652                Intersectable *sourceObj = NULL;
653                Intersectable *termObj = NULL;
654               
655                if (sObj.mId >= 0)
[490]656                {
657                        ObjectContainer::iterator oit =
[491]658                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
659                        sourceObj = *oit;
660                }
661               
662                if (tObj.mId >= 0)
663                {
664                        ObjectContainer::iterator oit =
665                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
666                        termObj = *oit;
667                }
[490]668
[491]669                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
670        }
671#else
672        ifstream samplesIn(fileName, ios::binary);
673        if (!samplesIn.is_open())
674                return false;
675
676        while (1)
677        {
678                 samplesIn.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
679                 samplesIn.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
680                 samplesIn.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
681                 samplesIn.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
682               
683                 if (samplesIn.eof())
684                        break;
685
686                Intersectable *sourceObj = NULL;
687                Intersectable *termObj = NULL;
688               
689                if (sObj.mId >= 0)
690                {
691                        ObjectContainer::iterator oit =
692                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
693                        sourceObj = *oit;
[490]694                }
[491]695               
696                if (tObj.mId >= 0)
[490]697                {
[491]698                        ObjectContainer::iterator oit =
699                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
700                        termObj = *oit;
[490]701                }
[491]702
703                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]704        }
[491]705
706#endif
[490]707        samplesIn.close();
708
709        return true;
710}
711
[508]712
713bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]714{
[491]715        char fileName[100];
[1004]716        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[491]717       
[490]718
719        VssRayContainer::const_iterator it, it_end = samples.end();
720       
[491]721#if USE_ASCII
722        ofstream samplesOut(fileName);
[490]723        if (!samplesOut.is_open())
724                return false;
725
726        for (it = samples.begin(); it != it_end; ++ it)
727        {
728                VssRay *ray = *it;
[491]729                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
730                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
731
[490]732                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
733                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]734                                   << sourceid << " " << termid << "\n";
[490]735        }
[491]736#else
737        ofstream samplesOut(fileName, ios::binary);
738        if (!samplesOut.is_open())
739                return false;
740
741        for (it = samples.begin(); it != it_end; ++ it)
742        {       
743                VssRay *ray = *it;
744                Vector3 origin(ray->GetOrigin());
745                Vector3 termination(ray->GetTermination());
746               
747                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
748                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
749
750                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
751                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
752                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
753                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
754    }
755#endif
[490]756        samplesOut.close();
[1194]757
[490]758        return true;
759}
[563]760
[1020]761bool Preprocessor::GenerateRays(const int number,
762                                                                const int sampleType,
763                                                                SimpleRayContainer &rays)
764{
765        const int startSize = (int)rays.size();
766        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
[860]767
[1020]768        if (!strategy)
[1381]769        {
[1020]770                return false;
[1381]771        }
[1020]772
773        for (int i=0; (int)rays.size() - startSize < number; ++ i)
774        {
775                SimpleRay newRay;
776
[1381]777                if (strategy->GenerateSample(newRay))
778                {
779#if 1
[1020]780                        rays.AddRay(newRay);
[1381]781#else
782                        GenerateRayBundle(rays, newRay, 16, 0);
783#endif
784                }       
[1020]785        }
786
787        delete strategy;
788    return true;
[878]789}
[1020]790
791
792SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId) const
793{
794        switch (strategyId)
795        {
[1520]796        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
[1020]797                return new ObjectBasedDistribution(*this);
[1520]798        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
[1020]799                return new ObjectDirectionBasedDistribution(*this);
[1520]800        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
[1020]801                return new DirectionBasedDistribution(*this);
[1520]802        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
[1020]803                return new DirectionBoxBasedDistribution(*this);
[1520]804        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
[1020]805                return new SpatialBoxBasedDistribution(*this);
[1021]806        //case OBJECTS_INTERIOR_DISTRIBUTION:
807        //      return new ObjectsInteriorDistribution(*this);
[1020]808        default: // no valid strategy
[1279]809                Debug << "warning: no valid sampling strategy" << endl;
[1020]810                return NULL;
811        }
[1221]812
[1570]813        return NULL; // should never come here
[1020]814}
815
816
[1418]817bool Preprocessor::InitRayCast(const string externKdTree, const string internkdtree)
[1221]818{
[1418]819        bool loadKdTree;
[1415]820        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadKdTree", loadKdTree);
821       
822        if (!loadKdTree)
[1418]823        {       
[1415]824                //-- build new kd tree from scene geometry
825                BuildKdTree();
826                KdTreeStatistics(cout);
827        }
828        else
829        {
830                const long startTime = GetTime();
[1418]831                cout << "loading kd tree file " << internkdtree << " ... ";
[1415]832
[1418]833                if (!LoadKdTree(internkdtree))
[1415]834                {
[1418]835                        cout << "error loading kd tree with filename " << internkdtree << ", rebuilding it instead ..." << endl;
836
837                        BuildKdTree();
838                        KdTreeStatistics(cout);
[1415]839                }
[1416]840
[1415]841                cout << "finished in " << TimeDiff(startTime, GetTime()) * 1e-3 << " secs" << endl;
842
843                if (0)
844                {
845                        Exporter *exporter = Exporter::GetExporter("dummykd.x3d");
846                       
847                        if (exporter)
848                        {
849                                exporter->ExportKdTree(*mKdTree, true);
850                                delete exporter;
851                        }
852                }
853        }
854
[1520]855        int rayCastMethod;
856        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
857
858        if (rayCastMethod == 0)
[1221]859        {
[1520]860                mRayCaster = new InternalRayCaster(*this, mKdTree);
861                cout << "ray cast method: internal" << endl;
[1221]862        }
[1251]863        else
[1520]864        {
[1524]865#ifdef GTP_INTERNAL
[1520]866                mRayCaster = new IntelRayCaster(*this, externKdTree);
867                cout << "ray cast method: intel" << endl;
[1524]868#endif
[1251]869        }
870
[1520]871        return true;
[1281]872}
873
[1292]874
[1281]875void
876Preprocessor::CastRays(
877                                           SimpleRayContainer &rays,
[1520]878                                           VssRayContainer &vssRays,
[1528]879                                           const bool castDoubleRays,
880                                           const bool pruneInvalidRays
[1281]881                                           )
882{
[1524]883        const long t1 = GetTime();
[1344]884
[1524]885        for (int i = 0; i < (int)rays.size();)
[1292]886        {
[1524]887                if (i + 16 < (int)rays.size())
[1520]888                {
[1524]889                        mRayCaster->CastRays16(
[1584]890                                                                   i,
891                                                                   rays,                               
892                                                                   vssRays,
893                                                                   mViewCellsManager->GetViewSpaceBox(),
894                                                                   castDoubleRays,
895                                                                   pruneInvalidRays);
[1524]896                        i += 16;
[1292]897                }
[1524]898                else
[1584]899                  {
[1524]900                        mRayCaster->CastRay(
[1584]901                                                                rays[i],
902                                                                vssRays,
903                                                                mViewCellsManager->GetViewSpaceBox(),
904                                                                castDoubleRays,
905                                                                pruneInvalidRays);
[1524]906                        i ++;
[1584]907                  }
908                if (i % 10000 == 0)
[1608]909                  cout<<"\r"<<i<<"/"<<rays.size()<<"\r";
[1524]910        }
[1608]911        cout<<endl;
[1584]912       
913        long t2 = GetTime();
[1286]914
[1584]915#if SHOW_RAYCAST_TIMING
[1524]916        if (castDoubleRays)
917                cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
918        else
919                cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
920#endif 
[1251]921}
922
923
[1381]924bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
925                                                                         const SimpleRay &mainRay,
926                                                                         const int number,
927                                                                         const int pertubType) const
928{
929        rayBundle.push_back(mainRay);
930
[1564]931        const float pertubOrigin = 0.0f;
932        const float pertubDir = 0.2f;
[1381]933
934        for (int i = 0; i < number - 1; ++ i)
935        {
936                Vector3 pertub;
937
938                pertub.x = RandomValue(0.0f, pertubDir);
939                pertub.y = RandomValue(0.0f, pertubDir);
940                pertub.z = RandomValue(0.0f, pertubDir);
941                const Vector3 newDir = mainRay.mDirection + pertub;
942                //const Vector3 newDir = mainRay.mDirection;
943
944                pertub.x = RandomValue(0.0f, pertubOrigin);
945                pertub.y = RandomValue(0.0f, pertubOrigin);
946                pertub.z = RandomValue(0.0f, pertubOrigin);
947                const Vector3 newOrigin = mainRay.mOrigin + pertub;
948                //const Vector3 newOrigin = mainRay.mOrigin;
949
950                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0));
951        }
952
953        return true;
954}
955
956
[1251]957void Preprocessor::SetupRay(Ray &ray,
958                                                        const Vector3 &point,
959                                                        const Vector3 &direction
[1520]960                                                        ) const
[1251]961{
962        ray.Clear();
963        // do not store anything else then intersections at the ray
964        ray.Init(point, direction, Ray::LOCAL_RAY);
[1584]965       
[1251]966}
967
[1520]968
[1251]969}
Note: See TracBrowser for help on using the repository browser.