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

Revision 1664, 27.9 KB checked in by mattausch, 18 years ago (diff)

changed priority computation:
taking ratio render cost decrease / pvs size increase rather
then render cost decrease alone
this should rather emphasise object space splits, as they
seem to cost less memory.

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