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

Revision 1563, 24.0 KB checked in by mattausch, 18 years ago (diff)

fixed bug with view space box

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