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

Revision 2543, 40.5 KB checked in by mattausch, 17 years ago (diff)
RevLine 
[372]1#include "SceneGraph.h"
2#include "Exporter.h"
3#include "UnigraphicsParser.h"
4#include "X3dParser.h"
5#include "Preprocessor.h"
6#include "ViewCell.h"
7#include "Environment.h"
[439]8#include "ViewCellsManager.h"
[445]9#include "ViewCellBsp.h"
10#include "VspBspTree.h"
[469]11#include "RenderSimulator.h"
[496]12#include "GlRenderer.h"
[749]13#include "PlyParser.h"
[1020]14#include "SamplingStrategy.h"
[1233]15#include "VspTree.h"
16#include "OspTree.h"
[1221]17#include "ObjParser.h"
[1264]18#include "BvHierarchy.h"
[1279]19#include "HierarchyManager.h"
[1287]20#include "VssRay.h"
[1520]21#include "IntelRayCaster.h"
22#include "InternalRayCaster.h"
[1968]23#include "GlobalLinesRenderer.h"
[2183]24#include "ObjectsParser.h"
[1264]25
[1287]26
[1292]27#define DEBUG_RAYCAST 0
[1584]28#define SHOW_RAYCAST_TIMING 1
[1292]29
[2183]30using namespace std;
[1292]31
[863]32namespace GtpVisibilityPreprocessor {
[860]33
34
[2187]35Preprocessor *preprocessor = NULL;
[1867]36 
[752]37
[372]38Preprocessor::Preprocessor():
39mKdTree(NULL),
[409]40mBspTree(NULL),
[445]41mVspBspTree(NULL),
[1002]42mViewCellsManager(NULL),
[1251]43mRenderSimulator(NULL),
[1279]44mPass(0),
[1520]45mSceneGraph(NULL),
[1613]46mRayCaster(NULL),
[1926]47mStopComputation(false),
[1968]48mThread(NULL),
[2076]49mGlobalLinesRenderer(NULL),
50mUseHwGlobalLines(false)
[308]51{
[1004]52        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlRenderer", mUseGlRenderer);
[538]53 
[840]54        // renderer will be constructed when the scene graph and viewcell manager will be known
55        renderer = NULL;
[1785]56       
[1004]57        Environment::GetSingleton()->GetBoolValue("Preprocessor.useGlDebugger", mUseGlDebugger);
[1379]58        Environment::GetSingleton()->GetBoolValue("Preprocessor.loadMeshes", mLoadMeshes);
[1004]59        Environment::GetSingleton()->GetBoolValue("Preprocessor.quitOnFinish", mQuitOnFinish);
60        Environment::GetSingleton()->GetBoolValue("Preprocessor.computeVisibility", mComputeVisibility);
61        Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
62        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportVisibility", mExportVisibility );
[1520]63       
[871]64        char buffer[256];
[1004]65        Environment::GetSingleton()->GetStringValue("Preprocessor.visibilityFile",  buffer);
[871]66        mVisibilityFileName = buffer;
[1771]67       
68        Environment::GetSingleton()->GetStringValue("Preprocessor.stats",  buffer);
69        mStats.open(buffer);
[2048]70               
[1749]71        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilityFilter", mApplyVisibilityFilter);
[1004]72        Environment::GetSingleton()->GetBoolValue("Preprocessor.applyVisibilitySpatialFilter",
[1695]73                                                                                          mApplyVisibilitySpatialFilter );
[1004]74        Environment::GetSingleton()->GetFloatValue("Preprocessor.visibilityFilterWidth", mVisibilityFilterWidth);
[878]75
[1695]76        Environment::GetSingleton()->GetBoolValue("Preprocessor.exportObj", mExportObj);
77       
[1723]78        Environment::GetSingleton()->GetBoolValue("Preprocessor.useViewSpaceBox", mUseViewSpaceBox);
79
[1900]80        Environment::GetSingleton()->GetBoolValue("Preprocessor.Export.rays", mExportRays);
[2008]81        Environment::GetSingleton()->GetBoolValue("Preprocessor.Export.animation", mExportAnimation);
[1900]82        Environment::GetSingleton()->GetIntValue("Preprocessor.Export.numRays", mExportNumRays);
83
[1966]84        Environment::GetSingleton()->GetIntValue("Preprocessor.samplesPerPass", mSamplesPerPass);
85        Environment::GetSingleton()->GetIntValue("Preprocessor.totalSamples", mTotalSamples);
[2046]86        Environment::GetSingleton()->GetIntValue("Preprocessor.totalTime", mTotalTime);
[1966]87        Environment::GetSingleton()->GetIntValue("Preprocessor.samplesPerEvaluation",
88                                                                                         mSamplesPerEvaluation);
89
[1695]90        Debug << "******* Preprocessor Options **********" << endl;
[840]91        Debug << "detect empty view space=" << mDetectEmptyViewSpace << endl;
[1379]92        Debug << "load meshes: " << mLoadMeshes << endl;
[1695]93        Debug << "load meshes: " << mLoadMeshes << endl;
94        Debug << "export obj: " << mExportObj << endl;
[1723]95        Debug << "use view space box: " << mUseViewSpaceBox << endl;
[2048]96
97        cout << "samples per pass " << mSamplesPerPass << endl;
[372]98}
99
100
101Preprocessor::~Preprocessor()
102{
[1291]103        cout << "cleaning up" << endl;
[752]104
[1291]105        cout << "Deleting view cells manager ... \n";
106        DEL_PTR(mViewCellsManager);
107        cout << "done.\n";
[752]108
[2047]109       
[1291]110        cout << "Deleting bsp tree ... \n";
111        DEL_PTR(mBspTree);
[1924]112        cout << "done.\n";
[752]113
[1924]114        cout << "Deleting kd tree ...\n";
[1291]115        DEL_PTR(mKdTree);
116        cout << "done.\n";
[752]117
[1923]118        cout << "Deleting vspbsp tree ... \n";
[1291]119        DEL_PTR(mVspBspTree);
120        cout << "done.\n";
[1002]121
[1923]122        cout << "Deleting scene graph ... \n";
[1291]123        DEL_PTR(mSceneGraph);
124        cout << "done.\n";
125
[2017]126        cout << "deleting render simulator ... \n";
[1291]127        DEL_PTR(mRenderSimulator);
[2017]128        mRenderSimulator = NULL;
129        cout << "deleting renderer ... \n";
[1291]130        DEL_PTR(renderer);
[2017]131        renderer = NULL;
132        cout << "deleting ray caster ... \n";
[1523]133        DEL_PTR(mRayCaster);
[1999]134
[1990]135#ifdef USE_CG
[2017]136        cout << "deleting global lines renderer ... \n";
[1968]137        DEL_PTR(mGlobalLinesRenderer);
[1990]138#endif
[2017]139        cout << "finished" << endl;
[372]140}
141
[1521]142
143GlRendererBuffer *Preprocessor::GetRenderer()
144{
145        return renderer;
146}
147
148
149static int SplitFilenames(const string str, vector<string> &filenames)
[387]150{
151        int pos = 0;
152
153        while(1) {
[469]154                int npos = (int)str.find(';', pos);
[387]155               
156                if (npos < 0 || npos - pos < 1)
157                        break;
158                filenames.push_back(string(str, pos, npos - pos));
159                pos = npos + 1;
160        }
161       
162        filenames.push_back(string(str, pos, str.size() - pos));
[440]163        return (int)filenames.size();
[387]164}
165
[750]166
[1926]167void Preprocessor::SetThread(PreprocessorThread *t)
168{
169        mThread = t;
170}
171
172
173PreprocessorThread *Preprocessor::GetThread() const
174{
175        return mThread;
176}
177
178
[2183]179bool Preprocessor::LoadBinaryObj(const string &filename,
[1655]180                                                                 SceneGraphNode *root,
181                                                                 vector<FaceParentInfo> *parents)
182{
[2452]183        //ifstream inStream(filename, ios::binary);
184        igzstream inStream(filename.c_str());
[1658]185       
[2452]186        if (!inStream.is_open())
[1655]187                return false;
188
[1658]189        cout << "binary obj dump available, loading " << filename.c_str() << endl;
[2003]190       
[2004]191        // read in triangle size
192        int numTriangles;
193
[2452]194        inStream.read(reinterpret_cast<char *>(&numTriangles), sizeof(int));
[2004]195        root->mGeometry.reserve(numTriangles);
[2005]196        cout << "loading " << numTriangles << " triangles ("
197                 << numTriangles * (sizeof(TriangleIntersectable) + sizeof(TriangleIntersectable *)) / (1024 * 1024) << " MB)" << endl;
[2003]198
[2004]199        int i = 0;
[1655]200        while (1)
201        {
202                Triangle3 tri;
203               
[2452]204                inStream.read(reinterpret_cast<char *>(tri.mVertices + 0), sizeof(Vector3));
205                inStream.read(reinterpret_cast<char *>(tri.mVertices + 1), sizeof(Vector3));
206                inStream.read(reinterpret_cast<char *>(tri.mVertices + 2), sizeof(Vector3));
[2005]207
[1655]208                // end of file reached
[2452]209                if (inStream.eof())
[1655]210                        break;
211
212                TriangleIntersectable *obj = new TriangleIntersectable(tri);
213                root->mGeometry.push_back(obj);
[2005]214               
[2183]215                if ((i ++) % 500000 == 499999)
[2005]216                         cout<<"\r"<<i<<"/"<<numTriangles<<"\r";
[1655]217        }
218       
[2004]219        if (i != numTriangles)
220        {
221                cout << "warning: triangle size does not match with loaded triangle size" << endl;
222                return false;
223        }
224
225        cout << "loaded " << numTriangles << " triangles" << endl;
226
[1655]227        return true;
228}
229
230
[2342]231bool Preprocessor::ExportBinaryObj(const string &filename, SceneGraphNode *root)
[1658]232{
233        ogzstream samplesOut(filename.c_str());
[2004]234
[1658]235        if (!samplesOut.is_open())
236                return false;
237
[2004]238        int numTriangles = (int)root->mGeometry.size();
239
240        samplesOut.write(reinterpret_cast<char *>(&numTriangles), sizeof(int));
241
[1658]242        ObjectContainer::const_iterator oit, oit_end = root->mGeometry.end();
243
244        for (oit = root->mGeometry.begin(); oit != oit_end; ++ oit)
245        {
246                Intersectable *obj = *oit;
247
248                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
249                {
[2017]250                        Triangle3 tri = static_cast<TriangleIntersectable *>(obj)->GetItem();
[1658]251
252                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 0), sizeof(Vector3));
253                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 1), sizeof(Vector3));
254                        samplesOut.write(reinterpret_cast<char *>(tri.mVertices + 2), sizeof(Vector3));
255                }
256                else
257                {
258                        cout << "not implemented intersectable type " << obj->Type() << endl;
259                }
260        }
261
[2004]262        cout << "exported " << numTriangles << " triangles" << endl;
263
[1658]264        return true;
265}
266
[1695]267
[2342]268bool Preprocessor::ExportObj(const string &filename, const ObjectContainer &objects)
[1695]269{
270        ofstream samplesOut(filename.c_str());
271
272        if (!samplesOut.is_open())
273                return false;
274
275        ObjectContainer::const_iterator oit, oit_end = objects.end();
276
[2004]277        //AxisAlignedBox3 bbox = mSceneGraph->GetBox(); bbox.Enlarge(30.0);
[1695]278        for (oit = objects.begin(); oit != oit_end; ++ oit)
279        {
280                Intersectable *obj = *oit;
281
282                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
283                {
[2017]284                        Triangle3 tri = static_cast<TriangleIntersectable *>(obj)->GetItem();
[2004]285                        //if (!(bbox.IsInside(tri.mVertices[0]) && bbox.IsInside(tri.mVertices[1]) && bbox.IsInside(tri.mVertices[2])))continue;
286                       
287                        samplesOut << "v " << tri.mVertices[0].x << " " << tri.mVertices[0].y << " " << tri.mVertices[0].z << endl;
288                        samplesOut << "v " << tri.mVertices[1].x << " " << tri.mVertices[1].y << " " << tri.mVertices[1].z << endl;
289                        samplesOut << "v " << tri.mVertices[2].x << " " << tri.mVertices[2].y << " " << tri.mVertices[2].z << endl;
[1701]290                        //}
[1695]291                }
292                else
293                {
294                        cout << "not implemented intersectable type " << obj->Type() << endl;
295                }
296        }
297
298        // write faces
299        int i = 1;
[1713]300        for (oit = objects.begin(); oit != oit_end; ++ oit)
[1695]301        {
302                Intersectable *obj = *oit;
303                if (obj->Type() == Intersectable::TRIANGLE_INTERSECTABLE)
304                {
[2017]305                        //Triangle3 tri = static_cast<TriangleIntersectable *>(obj)->GetItem();
[2004]306                        //if (!(bbox.IsInside(tri.mVertices[0]) && bbox.IsInside(tri.mVertices[1]) && bbox.IsInside(tri.mVertices[2]))) continue;
307                       
[2017]308                        Triangle3 tri = static_cast<TriangleIntersectable *>(obj)->GetItem();
[2004]309                        samplesOut << "f " << i << " " << i + 1 << " " << i + 2 << endl;
310                        i += 3;
[1695]311                }
312                else
313                {
314                        cout << "not implemented intersectable type " << obj->Type() << endl;
315                }
316        }
317
318        return true;
319
320}
321
[2342]322static string ReplaceSuffix(const string &filename, string a, string b)
[1658]323{
324        string result = filename;
325
326        int pos = (int)filename.rfind(a, (int)filename.size() - 1);
327        if (pos == filename.size() - a.size()) {
328                result.replace(pos, a.size(), b);
329        }
330        return result;
331}
332
333
[1786]334Intersectable *Preprocessor::GetParentObject(const int index) const
335{
[2003]336        if (index < 0)
337        {
[2004]338                //cerr << "Warning: triangle index smaller zero! " << index << endl;
[2003]339                return NULL;
340        }
[1786]341       
342        if (!mFaceParents.empty())
343        {
344                if (index >= (int)mFaceParents.size())
345                {
[1978]346                        cerr << "Warning: triangle index out of range! " << index << endl;
[1786]347                        return NULL;
348                }
349                else
350                {
351                        return mFaceParents[index].mObject;
352                }
353        }
354        else
[2003]355        {
356                  if (index >= (int)mObjects.size())
357                  {
[2307]358                          cerr<<"Warning: triangle index out of range! " << index << " of " << (int)mObjects.size() << endl;
[2003]359                          return NULL;
360                  }
361                  else
362                  {
363                          return mObjects[index];
364                  }
365        }
[1786]366}
367
368
369Vector3 Preprocessor::GetParentNormal(const int index) const
370{
371        if (!mFaceParents.empty())
372        {
373                return mFaceParents[index].mObject->GetNormal(mFaceParents[index].mFaceIndex);
374        }       
375        else
376        {
377                return mObjects[index]->GetNormal(0);
378        }
379}
380
381
[372]382bool
[2342]383Preprocessor::LoadScene(const string &filename)
[372]384{
[1655]385    // use leaf nodes of the original spatial hierarchy as occludees
[508]386        mSceneGraph = new SceneGraph;
[372]387 
[508]388        Parser *parser;
[387]389        vector<string> filenames;
[1404]390        const int files = SplitFilenames(filename, filenames);
[712]391        cout << "number of input files: " << files << endl;
[2183]392
[387]393        bool result = false;
[1695]394        bool isObj = false;
[1344]395
396        // root for different files
397        mSceneGraph->SetRoot(new SceneGraphNode());
398
[1404]399        // intel ray caster can only trace triangles
[1520]400        int rayCastMethod;
401        Environment::GetSingleton()->GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
[1827]402        vector<FaceParentInfo> *fi =
[1867]403          ((rayCastMethod == RayCaster::INTEL_RAYCASTER) && mLoadMeshes) ?
404          &mFaceParents : NULL;
405       
[1658]406        if (files == 1)
[1867]407          {
[387]408                if (strstr(filename.c_str(), ".x3d"))
[1867]409                  {
[1655]410                        parser = new X3dParser;
[1658]411                       
412                        result = parser->ParseFile(filename,
413                                                                           mSceneGraph->GetRoot(),
414                                                                           mLoadMeshes,
415                                                                           fi);
416                        delete parser;
[1655]417                }
[1658]418                else if (strstr(filename.c_str(), ".ply") || strstr(filename.c_str(), ".plb"))
[1655]419                {
[1658]420                        parser = new PlyParser;
[1655]421
[1658]422                        result = parser->ParseFile(filename,
423                                                                           mSceneGraph->GetRoot(),
424                                                                           mLoadMeshes,
425                                                                           fi);
426                        delete parser;
[1655]427                }
[1658]428                else if (strstr(filename.c_str(), ".obj"))
429                {
[1695]430                        isObj = true;
431
[1658]432                        // hack: load binary dump
[2004]433                        const string bnFile = ReplaceSuffix(filename, ".obj", ".bn");
434                       
[1658]435                        if (!mLoadMeshes)
436                        {
[2004]437                                result = LoadBinaryObj(bnFile, mSceneGraph->GetRoot(), fi);
[1658]438                        }
439
[2004]440                        // parse obj
441            if (!result)
[1658]442                        {
443                                cout << "no binary dump available or loading full meshes, parsing file" << endl;
444                                parser = new ObjParser;
[1404]445               
[1658]446                                result = parser->ParseFile(filename,
[2172]447                                                                   mSceneGraph->GetRoot(),
448                                                                   mLoadMeshes,
449                                                                   fi);
450                                               
[2004]451                                cout << "loaded " << (int)mSceneGraph->GetRoot()->mGeometry.size() << " entities" << endl;
[2183]452
[1658]453                                // only works for triangles
[2004]454                                if (result && !mLoadMeshes)
[1658]455                                {
[2004]456                                        cout << "exporting binary obj to " << bnFile << "... " << endl;
[2183]457
[2004]458                                        ExportBinaryObj(bnFile, mSceneGraph->GetRoot());
[2183]459                               
[1658]460                                        cout << "finished" << endl;
461                                }
[1655]462
[1658]463                                delete parser;
464                        }
465                }
466                else
467                {
468                        parser = new UnigraphicsParser;
469                        result = parser->ParseFile(filename,
470                                                                           mSceneGraph->GetRoot(),
471                                                                           mLoadMeshes,                                                           
472                                                                           fi);
473                        delete parser;
474                }
475               
476                cout << filename << endl;
[1404]477        }
[1658]478        else
479        {
[1404]480                vector<string>::const_iterator fit, fit_end = filenames.end();
[1344]481               
[1404]482                for (fit = filenames.begin(); fit != fit_end; ++ fit)
483                {
484                        const string filename = *fit;
[1328]485
[1404]486                        cout << "parsing file " << filename.c_str() << endl;
487                        if (strstr(filename.c_str(), ".x3d"))
488                                parser = new X3dParser;
489                        else
490                                parser = new UnigraphicsParser;
491
492                        SceneGraphNode *node = new SceneGraphNode();
[1695]493                        const bool success =
494                                parser->ParseFile(filename, node, mLoadMeshes, fi);
[1404]495
496                        if (success)
497                        {
498                                mSceneGraph->GetRoot()->mChildren.push_back(node);
499                                result = true; // at least one file parsed
500                        }
501
[1713]502                        // temporare hack
[1701]503                        //if (!strstr(filename.c_str(), "plane")) mSceneGraph->GetRoot()->UpdateBox();
504
[1404]505                        delete parser;
[387]506                }
507        }
[1344]508       
[752]509        if (result)
[1344]510        {
[1020]511                mSceneGraph->AssignObjectIds();
[1344]512 
[1020]513                int intersectables, faces;
514                mSceneGraph->GetStatistics(intersectables, faces);
[1344]515 
[1020]516                cout<<filename<<" parsed successfully."<<endl;
517                cout<<"#NUM_OBJECTS (Total numner of objects)\n"<<intersectables<<endl;
518                cout<<"#NUM_FACES (Total numner of faces)\n"<<faces<<endl;
[1701]519               
[1697]520                mObjects.reserve(intersectables);
[1020]521                mSceneGraph->CollectObjects(&mObjects);
[1713]522               
523                // temp hack
524                //ExportObj("cropped_vienna.obj", mObjects);
[1328]525                mSceneGraph->GetRoot()->UpdateBox();
[1713]526                               
527                cout << "finished loading" << endl;
[387]528        }
[1328]529
[492]530        return result;
[372]531}
532
533bool
[2342]534Preprocessor::ExportPreprocessedData(const string &filename)
[372]535{
[1486]536        mViewCellsManager->ExportViewCells(filename, true, mObjects);
537        return true;
[372]538}
539
[1486]540
[372]541bool
[871]542Preprocessor::PostProcessVisibility()
543{
544 
[904]545  if (mApplyVisibilityFilter || mApplyVisibilitySpatialFilter) {
[997]546        cout<<"Applying visibility filter ...";
[1002]547        cout<<"filter width = " << mVisibilityFilterWidth << endl;
[904]548       
[1002]549        if (!mViewCellsManager)
[1199]550          return false;
551       
[2076]552       
[871]553        mViewCellsManager->ApplyFilter(mKdTree,
[2076]554                                                                   mApplyVisibilityFilter ?
555                                                                   mVisibilityFilterWidth : -1.0f,
556                                                                   mApplyVisibilitySpatialFilter ?
557                                                                   mVisibilityFilterWidth : -1.0f);
[997]558        cout << "done." << endl;
[871]559  }
560 
561  // export the preprocessed information to a file
[2053]562  if (1 && mExportVisibility)
[1486]563  {
564          ExportPreprocessedData(mVisibilityFileName);
565  }
566
[871]567  return true;
568}
569
570
571bool
[372]572Preprocessor::BuildKdTree()
573{
574  mKdTree = new KdTree;
[1344]575
[372]576  // add mesh instances of the scene graph to the root of the tree
577  KdLeaf *root = (KdLeaf *)mKdTree->GetRoot();
[1344]578       
[372]579  mSceneGraph->CollectObjects(&root->mObjects);
[1344]580 
[1415]581  const long startTime = GetTime();
[1201]582  cout << "building kd tree ... " << endl;
[1344]583
[372]584  mKdTree->Construct();
[1344]585
[1415]586  cout << "finished kd tree construction in " << TimeDiff(startTime, GetTime()) * 1e-3
587           << " secs " << endl;
[1344]588
[372]589  return true;
590}
591
[1415]592
[372]593void
594Preprocessor::KdTreeStatistics(ostream &s)
595{
596  s<<mKdTree->GetStatistics();
597}
598
599void
600Preprocessor::BspTreeStatistics(ostream &s)
601{
602        s << mBspTree->GetStatistics();
603}
604
605bool
[2342]606Preprocessor::Export( const string &filename,
[492]607                                          const bool scene,
[1545]608                                          const bool kdtree
[492]609                                          )
[372]610{
611  Exporter *exporter = Exporter::GetExporter(filename);
612       
613  if (exporter) {
[1545]614    if (2 && scene)
[1328]615      exporter->ExportScene(mSceneGraph->GetRoot());
[372]616
[1545]617    if (1 && kdtree) {
[372]618      exporter->SetWireframe();
619      exporter->ExportKdTree(*mKdTree);
620    }
621
622    delete exporter;
623    return true;
624  }
625
626  return false;
627}
[429]628
[508]629
[463]630bool Preprocessor::PrepareViewCells()
631{
[2543]632        // load the view cells assigning the found objects to the pvss
633#if 1
634        cerr << "loading binary view cells" << endl;
635        ViewCellsManager *dummyViewCellsManager =
636                LoadViewCellsBinary("test.vc", mObjects, false, NULL);
637
638    //cerr << "reexporting the binary view cells" << endl;
639        //dummyViewCellsManager->ExportViewCellsBinary("outvc.xml.gz", true, mObjects);
640       
641        return false;
642#endif
643
[1523]644        ///////
[577]645        //-- parse view cells construction method
[1563]646
[1004]647        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
[577]648        char buf[100];
[1585]649
[2172]650        if (mLoadViewCells)
[997]651        {       
[2183]652               
653#ifdef USE_BIT_PVS
654                // HACK: for kd pvs, set pvs size to maximal number of kd nodes
655                vector<KdLeaf *> leaves;
656                preprocessor->mKdTree->CollectLeaves(leaves);
657
658                ObjectPvs::SetPvsSize((int)leaves.size());
659#endif
660
[2172]661                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
[2183]662                cout << "loading objects from " << buf << endl;
[2117]663
[2183]664                // load objects which will be used as pvs entries
665                ObjectContainer pvsObjects;
666                if (0) LoadObjects(buf, pvsObjects, mObjects);
[2117]667
[2183]668                const bool finalizeViewCells = true;
669                cout << "loading view cells from " << buf << endl;
670
671                mViewCellsManager = ViewCellsManager::LoadViewCells(buf,
672                                                                                                                        pvsObjects,
673                                                                                                                        mObjects,
674                                                                                                                        finalizeViewCells,
675                                                                                                                        NULL);
676
[1740]677                cout << "view cells loaded." << endl<<flush;
678
679                if (!mViewCellsManager)
680                {
[2072]681                        cerr << "no view cells manager could be loaded" << endl;
[1740]682                        return false;
683                }
[577]684        }
685        else
686        {
[2543]687                // parse type of view cells manager
[1004]688                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
[1740]689                mViewCellsManager = CreateViewCellsManager(buf);
[1112]690
691                // default view space is the extent of the scene
[1723]692                AxisAlignedBox3 viewSpaceBox;
[1740]693
[1723]694                if (mUseViewSpaceBox)
[1563]695                {
[1723]696                        viewSpaceBox = mSceneGraph->GetBox();
697
[1563]698                        // use a small box outside of the scene
[1723]699                        viewSpaceBox.Scale(Vector3(0.15f, 0.3f, 0.5f));
700                        //viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.5f, 0, 0));
701                        viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.3f, 0, 0));
702                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
[1563]703                }
[1723]704                else
705                {
706                        viewSpaceBox = mSceneGraph->GetBox();
707                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
708                }
[1545]709
710                bool loadVcGeometry;
711                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
712
713                bool extrudeBaseTriangles;
714                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
715
716                char vcGeomFilename[100];
717                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
[1740]718
[1940]719                // create view cells from specified geometry
[1627]720                if (loadVcGeometry)
[1545]721                {
[1627]722                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
[1545]723                        {
[1627]724                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
725                                {
726                                        cerr << "loading view cells geometry failed" << endl;
727                                }
[1545]728                        }
[1627]729                        else
730                        {
731                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
732                        }
[1545]733                }
[577]734        }
[1740]735
[1486]736        ////////
[1523]737        //-- evaluation of render cost heuristics
[1768]738
[473]739        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
740
[1004]741        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
742        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
743        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
[1740]744
[473]745        mRenderSimulator =
746                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]747
[480]748        mViewCellsManager->SetRenderer(mRenderSimulator);
[1785]749       
[1581]750        mViewCellsManager->SetPreprocessor(this);
[1940]751
[463]752        return true;
[490]753}
754
[1292]755 
[1563]756bool Preprocessor::ConstructViewCells()
[1292]757{
[1627]758        // construct view cells using it's own set of samples
759        mViewCellsManager->Construct(this);
760
761        // visualizations and statistics
762        Debug << "finished view cells:" << endl;
763        mViewCellsManager->PrintStatistics(Debug);
764
765        return true;
[1292]766}
[490]767
[1294]768
[575]769ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
770{
[1264]771        ViewCellsTree *vcTree = new ViewCellsTree;
772
[575]773        if (strcmp(name, "kdTree") == 0)
774        {
[1264]775                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
[575]776        }
777        else if (strcmp(name, "bspTree") == 0)
778        {
779                Debug << "view cell type: Bsp" << endl;
780
[577]781                mBspTree = new BspTree();
[1264]782                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]783        }
784        else if (strcmp(name, "vspBspTree") == 0)
785        {
786                Debug << "view cell type: VspBsp" << endl;
787
[1004]788                mVspBspTree = new VspBspTree();
[1264]789                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
[575]790        }
[1006]791        else if (strcmp(name, "vspOspTree") == 0)
[575]792        {
[1421]793                Debug << "view cell type: VspOsp" << endl;
[1288]794                char buf[100];         
795                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
[1022]796
[1740]797                mViewCellsManager = new VspOspViewCellsManager(vcTree, buf);
[575]798        }
[1421]799        else if (strcmp(name, "sceneDependent") == 0) //TODO
[575]800        {
[1143]801                Debug << "view cell type: Bsp" << endl;
[1421]802               
[575]803                mBspTree = new BspTree();
[1264]804                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]805        }
806        else
807        {
[664]808                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]809                exit(1);
810        }
811
812        return mViewCellsManager;
813}
814
815
[491]816// use ascii format to store rays
817#define USE_ASCII 0
818
819
[1145]820static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
[490]821{
822        return obj1->mId < obj2->mId;
823}
824
825
[2342]826bool Preprocessor::LoadKdTree(const string &filename)
[1197]827{
[1414]828        mKdTree = new KdTree();
[2539]829        return mKdTree->ImportBinTree(filename.c_str(), mObjects);
[1197]830}
831
[1414]832
[2342]833bool Preprocessor::ExportKdTree(const string &filename)
[1197]834{
[1414]835        return mKdTree->ExportBinTree(filename.c_str());
[1197]836}
837
838
[490]839bool Preprocessor::LoadSamples(VssRayContainer &samples,
840                                                           ObjectContainer &objects) const
841{
842        std::stable_sort(objects.begin(), objects.end(), ilt);
843        char fileName[100];
[1004]844        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[490]845       
[491]846    Vector3 origin, termination;
847        // HACK: needed only for lower_bound algorithm to find the
848        // intersected objects
849        MeshInstance sObj(NULL);
850        MeshInstance tObj(NULL);
[490]851
[491]852#if USE_ASCII
[2452]853        ifstream inStream(fileName);
854        if (!inStream.is_open())
[490]855                return false;
856
857        string buf;
[2452]858        while (!(getline(inStream, buf)).eof())
[490]859        {
[491]860                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]861                           &origin.x, &origin.y, &origin.z,
[491]862                           &termination.x, &termination.y, &termination.z,
863                           &(sObj.mId), &(tObj.mId));
[490]864               
[491]865                Intersectable *sourceObj = NULL;
866                Intersectable *termObj = NULL;
867               
868                if (sObj.mId >= 0)
[490]869                {
870                        ObjectContainer::iterator oit =
[491]871                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
872                        sourceObj = *oit;
873                }
874               
875                if (tObj.mId >= 0)
876                {
877                        ObjectContainer::iterator oit =
878                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
879                        termObj = *oit;
880                }
[490]881
[491]882                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
883        }
884#else
[2452]885        ifstream inStream(fileName, ios::binary);
886        if (!inStream.is_open())
[491]887                return false;
888
889        while (1)
890        {
[2452]891                 inStream.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
892                 inStream.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
893                 inStream.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
894                 inStream.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
[491]895               
[2452]896                 if (inStream.eof())
[491]897                        break;
898
899                Intersectable *sourceObj = NULL;
900                Intersectable *termObj = NULL;
901               
902                if (sObj.mId >= 0)
903                {
904                        ObjectContainer::iterator oit =
905                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
906                        sourceObj = *oit;
[490]907                }
[491]908               
909                if (tObj.mId >= 0)
[490]910                {
[491]911                        ObjectContainer::iterator oit =
912                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
913                        termObj = *oit;
[490]914                }
[491]915
916                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]917        }
[1779]918#endif
[491]919
[2452]920        inStream.close();
[490]921
922        return true;
923}
924
[508]925
926bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]927{
[491]928        char fileName[100];
[1004]929        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[491]930       
[490]931
932        VssRayContainer::const_iterator it, it_end = samples.end();
933       
[491]934#if USE_ASCII
935        ofstream samplesOut(fileName);
[490]936        if (!samplesOut.is_open())
937                return false;
938
939        for (it = samples.begin(); it != it_end; ++ it)
940        {
941                VssRay *ray = *it;
[491]942                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
943                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
944
[490]945                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
946                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]947                                   << sourceid << " " << termid << "\n";
[490]948        }
[491]949#else
950        ofstream samplesOut(fileName, ios::binary);
951        if (!samplesOut.is_open())
952                return false;
953
954        for (it = samples.begin(); it != it_end; ++ it)
955        {       
956                VssRay *ray = *it;
957                Vector3 origin(ray->GetOrigin());
958                Vector3 termination(ray->GetTermination());
959               
960                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
961                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
962
963                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
964                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
965                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
966                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
967    }
968#endif
[490]969        samplesOut.close();
[1194]970
[490]971        return true;
972}
[563]973
[1771]974
975int
976Preprocessor::GenerateRays(const int number,
[1867]977                                                   SamplingStrategy &strategy,
978                                                   SimpleRayContainer &rays)
[1020]979{
[1867]980  return strategy.GenerateSamples(number, rays);
[1771]981}
[860]982
[1990]983
[1771]984int
985Preprocessor::GenerateRays(const int number,
[1898]986                                                   const int sampleType,
987                                                   SimpleRayContainer &rays)
[1771]988{
[1772]989        const int startSize = (int)rays.size();
990        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
991        int castRays = 0;
992
993        if (!strategy)
[1381]994        {
[1772]995                return 0;
[1381]996        }
[1772]997
[1381]998#if 1
[1772]999        castRays = strategy->GenerateSamples(number, rays);
[1381]1000#else
[1772]1001        GenerateRayBundle(rays, newRay, 16, 0);
1002        castRays += 16;
[1381]1003#endif
[1772]1004
1005        delete strategy;
1006        return castRays;
[878]1007}
[1020]1008
1009
[1884]1010SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
[1020]1011{
1012        switch (strategyId)
1013        {
[1520]1014        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
[1020]1015                return new ObjectBasedDistribution(*this);
[1520]1016        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
[1020]1017                return new ObjectDirectionBasedDistribution(*this);
[1520]1018        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
[1020]1019                return new DirectionBasedDistribution(*this);
[1520]1020        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
[1020]1021                return new DirectionBoxBasedDistribution(*this);
[1520]1022        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
[1020]1023                return new SpatialBoxBasedDistribution(*this);
[1695]1024        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1025                return new ReverseObjectBasedDistribution(*this);
[1769]1026        case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1027                return new ViewCellBorderBasedDistribution(*this);
[1772]1028        case SamplingStrategy::VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1029                return new ViewSpaceBorderBasedDistribution(*this);
1030        case SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1031                return new ReverseViewSpaceBorderBasedDistribution(*this);
[1824]1032        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1033                return new GlobalLinesDistribution(*this);
1034               
1035                //case OBJECTS_INTERIOR_DISTRIBUTION:
1036                //      return new ObjectsInteriorDistribution(*this);
[1020]1037        default: // no valid strategy
[1279]1038                Debug << "warning: no valid sampling strategy" << endl;
[1020]1039                return NULL;
1040        }
[1221]1041
[1570]1042        return NULL; // should never come here
[1020]1043}
1044
1045
[2342]1046bool Preprocessor::LoadInternKdTree(const string &internKdTree)
[2003]1047{
[2342]1048        bool mUseKdTree = true;
1049
1050        if (!mUseKdTree) {
1051                // create just a dummy KdTree
1052                mKdTree = new KdTree;
1053                return true;
1054        }
1055
1056        // always try to load the kd tree
1057        cout << "loading kd tree file " << internKdTree << " ... " << endl;
1058
1059        if (!LoadKdTree(internKdTree)) {
1060                cout << "error loading kd tree with filename "
1061                        << internKdTree << ", rebuilding it instead ... " << endl;
1062                // build new kd tree from scene geometry
1063                BuildKdTree();
1064
1065                // export kd tree?
1066                const long startTime = GetTime();
1067                cout << "exporting kd tree ... ";
1068
1069                if (!ExportKdTree(internKdTree))
1070                {
1071                        cout << " error exporting kd tree with filename "
1072                                << internKdTree << endl;
1073                }
1074                else
1075                {
1076                        cout << "finished in "
1077                                << TimeDiff(startTime, GetTime()) * 1e-3
1078                                << " secs" << endl;
1079                }
1080        }
1081
1082        KdTreeStatistics(cout);
1083        cout << mKdTree->GetBox() << endl;
1084
[2035]1085        return true;
[2003]1086}
1087
1088
[2342]1089bool Preprocessor::InitRayCast(const string &externKdTree,
1090                                                           const string &internKdTree)
[1221]1091{
[1633]1092        // always try to load the kd tree
[2003]1093/*      cout << "loading kd tree file " << internKdTree << " ... " << endl;
[1634]1094
1095        if (!LoadKdTree(internKdTree))
1096        {
[1968]1097                cout << "error loading kd tree with filename "
1098                         << internKdTree << ", rebuilding it instead ... " << endl;
[1633]1099                // build new kd tree from scene geometry
[1415]1100                BuildKdTree();
1101
[1627]1102                // export kd tree?
[1633]1103                const long startTime = GetTime();
[1627]1104                cout << "exporting kd tree ... ";
1105
1106                if (!ExportKdTree(internKdTree))
1107                {
[1968]1108                        cout << " error exporting kd tree with filename "
1109                                 << internKdTree << endl;
[1627]1110                }
1111                else
1112                {
[1968]1113                        cout << "finished in "
1114                                 << TimeDiff(startTime, GetTime()) * 1e-3
1115                                 << " secs" << endl;
[1627]1116                }
[1415]1117        }
[1633]1118       
1119        KdTreeStatistics(cout);
1120        cout << mKdTree->GetBox() << endl;
[2003]1121*/
[1520]1122        int rayCastMethod;
[1968]1123        Environment::GetSingleton()->
1124                GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
[1520]1125
1126        if (rayCastMethod == 0)
[1221]1127        {
[1867]1128                cout << "ray cast method: internal" << endl;
[2003]1129                mRayCaster = new InternalRayCaster(*this);
[1221]1130        }
[1251]1131        else
[1520]1132        {
[1524]1133#ifdef GTP_INTERNAL
[1867]1134          cout << "ray cast method: intel" << endl;
1135          mRayCaster = new IntelRayCaster(*this, externKdTree);
[1524]1136#endif
[1251]1137        }
[1867]1138       
[2072]1139        /////
1140        //-- reserve constant block of rays
1141       
1142        // hack: If we dont't use view cells loading, there must be at least as much rays
1143        // as are needed for the view cells construction
1144        bool loadViewCells;
1145        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", loadViewCells);
1146
[2187]1147        int reserveRays;       
1148        int constructionSamples;
[2072]1149
1150        if (!loadViewCells)
1151        {
[2187]1152                cout << "hack: setting ray pool size to view cell construction or evaluation size" << endl;
[2072]1153
[2187]1154                constructionSamples = 1000000;
1155
[2072]1156                char buf[100];
1157                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);     
[2187]1158
[2072]1159                if (strcmp(buf, "vspBspTree") == 0)
1160                {
[2187]1161                        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", constructionSamples);
1162                       
[2072]1163                }
1164                else if (strcmp(buf, "vspOspTree") == 0)
1165                {
[2187]1166                        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", constructionSamples);               
[2072]1167                }
[2187]1168
1169                int evalSamplesPerPass;
1170
1171                Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", evalSamplesPerPass);
1172
1173                reserveRays = max(constructionSamples, evalSamplesPerPass);
1174                reserveRays *= 2;
[2072]1175        }
1176        else
1177        {
[2187]1178                cout << "setting ray pool size to samples per pass" << endl;       
[2072]1179                reserveRays = mSamplesPerPass * 2;
1180        }
1181
[2048]1182        cout << "======================" << endl;
[2072]1183        cout << "reserving " << reserveRays << " rays " << endl;
1184        mRayCaster->ReserveVssRayPool(reserveRays);
[2012]1185       
[1520]1186        return true;
[1281]1187}
1188
[1292]1189
[1281]1190void
1191Preprocessor::CastRays(
1192                                           SimpleRayContainer &rays,
[1520]1193                                           VssRayContainer &vssRays,
[1528]1194                                           const bool castDoubleRays,
[1996]1195                                           const bool pruneInvalidRays
[1281]1196                                           )
1197{
[2035]1198
[2069]1199        const long t1 = GetTime();
[2035]1200       
[2198]1201        if (rays.size() > 10000)
[2187]1202        {
[2539]1203
[2072]1204                mRayCaster->SortRays(rays);
[2069]1205                cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" ms."<<endl;
[1984]1206        }
[1972]1207
[2072]1208
[2076]1209        if (mUseHwGlobalLines)
[2187]1210        {
[2539]1211                CastRaysWithHwGlobalLines(
1212                        rays,
1213                        vssRays,
1214                        castDoubleRays,
1215                        pruneInvalidRays
1216                        );
[2187]1217        }
[2076]1218        else
[2187]1219        {
[2539]1220                mRayCaster->CastRays(
1221                        rays,                           
1222                        vssRays,
1223                        mViewCellsManager->GetViewSpaceBox(),
1224                        castDoubleRays,
1225                        pruneInvalidRays);
[2187]1226        }
1227
1228        if (rays.size() > 10000)
[2076]1229        {
1230                cout << endl;
[2539]1231                long t2 = GetTime();
[2072]1232
[2076]1233#if SHOW_RAYCAST_TIMING
1234                if (castDoubleRays)
1235                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1236                else
1237                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1238#endif
1239        }
1240
1241        DeterminePvsObjects(vssRays);
1242}
1243
1244 
1245void
1246Preprocessor::CastRaysWithHwGlobalLines(
1247                                                                                SimpleRayContainer &rays,
[2187]1248                                                                                VssRayContainer &vssRays,
1249                                                                                const bool castDoubleRays,
1250                                                                                const bool pruneInvalidRays)
[2076]1251{
1252  SimpleRayContainer::const_iterator rit, rit_end = rays.end();
1253  SimpleRayContainer rayBucket;
1254  int i = 0;
1255  for (rit = rays.begin(); rit != rit_end; ++ rit, ++ i)
[1292]1256        {
[2076]1257          SimpleRay ray = *rit;
[1990]1258#ifdef USE_CG
[1972]1259                // HACK: global lines must be treated special
[2076]1260          if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
[1968]1261                {
[2076]1262                  mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1263                  continue;
[1968]1264                }
[1990]1265#endif
[2187]1266                rayBucket.push_back(ray);
1267
1268                // 16 rays gathered => do ray casting
1269                if (rayBucket.size() >= 16)
[1520]1270                {
[2187]1271                        mRayCaster->CastRays16(
1272                                rayBucket,                             
1273                                vssRays,
1274                                mViewCellsManager->GetViewSpaceBox(),
1275                                castDoubleRays,
1276                                pruneInvalidRays);
1277
1278                        rayBucket.clear();
[1292]1279                }
[2187]1280
1281                if (rays.size() > 100000 && i % 100000 == 0)
[2072]1282                        cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
[1972]1283        }
[2072]1284   
[1972]1285        // cast rest of rays
1286        SimpleRayContainer::const_iterator sit, sit_end = rayBucket.end();
1287
1288        for (sit = rayBucket.begin(); sit != sit_end; ++ sit)
1289        {
1290                SimpleRay ray = *sit;
[1990]1291
1292#ifdef USE_CG
[1972]1293                // HACK: global lines must be treated special
1294                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
[1932]1295                {
[1972]1296                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
[1990]1297                        continue;
[1972]1298                }
[1990]1299#endif
1300                mRayCaster->CastRay(
1301                                                        ray,
1302                                                        vssRays,
1303                                                        mViewCellsManager->GetViewSpaceBox(),
1304                                                        castDoubleRays,
[1996]1305                                                        pruneInvalidRays);
[1990]1306               
[1524]1307        }
[1743]1308
[1251]1309}
1310
1311
[1381]1312bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1313                                                                         const SimpleRay &mainRay,
1314                                                                         const int number,
1315                                                                         const int pertubType) const
1316{
1317        rayBundle.push_back(mainRay);
1318
[1564]1319        const float pertubOrigin = 0.0f;
1320        const float pertubDir = 0.2f;
[1381]1321
1322        for (int i = 0; i < number - 1; ++ i)
1323        {
1324                Vector3 pertub;
1325
1326                pertub.x = RandomValue(0.0f, pertubDir);
1327                pertub.y = RandomValue(0.0f, pertubDir);
1328                pertub.z = RandomValue(0.0f, pertubDir);
[1713]1329
[1381]1330                const Vector3 newDir = mainRay.mDirection + pertub;
1331                //const Vector3 newDir = mainRay.mDirection;
1332
1333                pertub.x = RandomValue(0.0f, pertubOrigin);
1334                pertub.y = RandomValue(0.0f, pertubOrigin);
1335                pertub.z = RandomValue(0.0f, pertubOrigin);
[1713]1336
[1381]1337                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1338                //const Vector3 newOrigin = mainRay.mOrigin;
1339
[1883]1340                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
[1381]1341        }
1342
1343        return true;
1344}
1345
1346
[1251]1347void Preprocessor::SetupRay(Ray &ray,
1348                                                        const Vector3 &point,
[1713]1349                                                        const Vector3 &direction) const
[1251]1350{
1351        ray.Clear();
1352        // do not store anything else then intersections at the ray
[1713]1353        ray.Init(point, direction, Ray::LOCAL_RAY);     
[1251]1354}
1355
[1968]1356
[1917]1357void Preprocessor::EvalViewCellHistogram()
[1771]1358{
[1917]1359        char filename[256];
1360        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
[1771]1361 
[1917]1362        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1363        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
[1771]1364}
[1520]1365
[1900]1366
1367bool
1368Preprocessor::ExportRays(const char *filename,
1369                                                 const VssRayContainer &vssRays,
[2001]1370                                                 const int number,
1371                                                 const bool exportScene
[1900]1372                                                 )
1373{
1374  cout<<"Exporting vss rays..."<<endl<<flush;
1375 
1376  Exporter *exporter = NULL;
1377  exporter = Exporter::GetExporter(filename);
1378
1379  if (0) {
1380        exporter->SetWireframe();
1381        exporter->ExportKdTree(*mKdTree);
1382  }
1383 
1384  exporter->SetFilled();
1385  // $$JB temporarily do not export the scene
[2001]1386  if (exportScene)
[1900]1387        exporter->ExportScene(mSceneGraph->GetRoot());
1388
1389  exporter->SetWireframe();
1390
1391  if (1) {
1392        exporter->SetForcedMaterial(RgbColor(1,0,1));
1393        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1394        exporter->ResetForcedMaterial();
1395  }
1396 
1397  VssRayContainer rays;
1398  vssRays.SelectRays(number, rays);
1399  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1400  delete exporter;
1401  cout<<"done."<<endl<<flush;
1402
1403  return true;
[1251]1404}
[1900]1405
[2002]1406bool
1407Preprocessor::ExportRayAnimation(const char *filename,
1408                                                                 const vector<VssRayContainer> &vssRays
1409                                                                 )
1410{
1411  cout<<"Exporting vss rays..."<<endl<<flush;
1412       
1413  Exporter *exporter = NULL;
1414  exporter = Exporter::GetExporter(filename);
1415  if (0) {
1416        exporter->SetWireframe();
1417        exporter->ExportKdTree(*mKdTree);
1418  }
1419  exporter->SetFilled();
1420  // $$JB temporarily do not export the scene
[2008]1421  if (0)
[2002]1422        exporter->ExportScene(mSceneGraph->GetRoot());
1423  exporter->SetWireframe();
1424
1425  if (1) {
1426        exporter->SetForcedMaterial(RgbColor(1,0,1));
1427        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1428        exporter->ResetForcedMaterial();
1429  }
1430 
1431  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
1432       
1433  delete exporter;
1434
1435  cout<<"done."<<endl<<flush;
1436
1437  return true;
1438}
1439
[1931]1440void
1441Preprocessor::ComputeRenderError()
1442{
1443  // compute rendering error
1444       
1445  if (renderer && renderer->mPvsStatFrames) {
1446        //      emit EvalPvsStat();
1447        //      QMutex mutex;
1448        //      mutex.lock();
1449        //      renderer->mRenderingFinished.wait(&mutex);
1450        //      mutex.unlock();
[2049]1451
1452        if (mViewCellsManager->GetViewCellPoints()->size()) {
1453         
1454          vector<ViewCellPoints *> *vcPoints = mViewCellsManager->GetViewCellPoints();
1455         
[2050]1456          vector<ViewCellPoints *>::const_iterator
1457                vit = vcPoints->begin(),
1458                vit_end = vcPoints->end();
1459
[2049]1460          SimpleRayContainer viewPoints;
1461         
[2050]1462          for (; vit != vit_end; ++ vit) {
[2049]1463                ViewCellPoints *vp = *vit;
1464
1465                SimpleRayContainer::const_iterator rit = vp->second.begin(), rit_end = vp->second.end();
1466                for (; rit!=rit_end; ++rit)
1467                  viewPoints.push_back(*rit);
1468          }
[2050]1469
1470          if (viewPoints.size() != renderer->mPvsErrorBuffer.size()) {
1471                renderer->mPvsErrorBuffer.resize(viewPoints.size());
1472                renderer->ClearErrorBuffer();
1473          }
1474
[2049]1475          renderer->EvalPvsStat(viewPoints);
1476        } else
1477          renderer->EvalPvsStat();
[2050]1478
[1931]1479        mStats <<
1480          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
[2002]1481          "#AvgPixelError\n" <<renderer->GetAvgPixelError()<<endl<<
[2008]1482          "#MaxPixelError\n" <<renderer->GetMaxPixelError()<<endl<<
[1931]1483          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1484          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1485          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1486  }
[1900]1487}
[1931]1488
[1958]1489
1490Intersectable *Preprocessor::GetObjectById(const int id)
1491{
[1960]1492#if 1
[1958]1493        // create a dummy mesh instance to be able to use stl
1494        MeshInstance object(NULL);
1495        object.SetId(id);
1496
1497        ObjectContainer::const_iterator oit =
1498                lower_bound(mObjects.begin(), mObjects.end(), &object, ilt);
1499                               
1500        // objects sorted by id
1501        if ((oit != mObjects.end()) && ((*oit)->GetId() == object.GetId()))
1502        {
1503                return (*oit);
1504        }
1505        else
1506        {
1507                return NULL;
1508        }
1509#else
[1960]1510        return mObjects[id - 1];
[1958]1511#endif
[1931]1512}
[1958]1513
[1968]1514
1515void Preprocessor::PrepareHwGlobalLines()
1516{
1517        int texHeight, texWidth;
1518        float eps;
1519        int maxDepth;
1520        bool sampleReverse;
1521
1522        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texHeight", texHeight);
[1969]1523        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texWidth", texWidth);
[1968]1524        Environment::GetSingleton()->GetFloatValue("Preprocessor.HwGlobalLines.stepSize", eps);
1525        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.maxDepth", maxDepth);
1526        Environment::GetSingleton()->GetBoolValue("Preprocessor.HwGlobalLines.sampleReverse", sampleReverse);
1527
[1969]1528        Debug << "****** hw global line options *******" << endl;
1529        Debug << "texWidth: " << texWidth << endl;
1530        Debug << "texHeight: " << texHeight << endl;
1531        Debug << "sampleReverse: " << sampleReverse << endl;
1532        Debug << "max depth: " << maxDepth << endl;
1533        Debug << "step size: " << eps << endl;
1534        Debug << endl;
1535
[1990]1536#ifdef USE_CG
[1969]1537        globalLinesRenderer = mGlobalLinesRenderer =
[1968]1538                new GlobalLinesRenderer(this,
1539                                                                texHeight,
1540                                                                texWidth,
1541                                                                eps,
1542                                                                maxDepth,
1543                                                                sampleReverse);
[1990]1544
[1968]1545        mGlobalLinesRenderer->InitGl();
[1990]1546
1547#endif
[1958]1548}
[1968]1549
[2048]1550
1551void Preprocessor::DeterminePvsObjects(VssRayContainer &rays)
1552{
1553        mViewCellsManager->DeterminePvsObjects(rays, false);
[1968]1554}
[2048]1555
1556
[2183]1557bool Preprocessor::LoadObjects(const string &filename,
1558                                                           ObjectContainer &pvsObjects,
1559                                                           const ObjectContainer &preprocessorObjects)
1560{
1561        ObjectsParser parser;
1562
1563        const bool success = parser.ParseObjects(filename,
1564                                                                                         pvsObjects,
1565                                                                                         preprocessorObjects);
1566
1567        if (!success)
1568        {
1569                Debug << "Error: loading objects failed!" << endl;
1570        }
1571
1572        // hack: no bvh object could be found => take preprocessor objects
1573        if (pvsObjects.empty())
1574        {
1575                Debug << "no objects" << endl;
1576                pvsObjects = preprocessorObjects;
1577        }
1578
1579        return success;
[2048]1580}
[2183]1581
1582
1583}
Note: See TracBrowser for help on using the repository browser.