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

Revision 2542, 40.1 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{
[1523]632        ///////
[577]633        //-- parse view cells construction method
[1563]634
[1004]635        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", mLoadViewCells);
[577]636        char buf[100];
[1585]637
[2172]638        if (mLoadViewCells)
[997]639        {       
[2183]640               
641#ifdef USE_BIT_PVS
642                // HACK: for kd pvs, set pvs size to maximal number of kd nodes
643                vector<KdLeaf *> leaves;
644                preprocessor->mKdTree->CollectLeaves(leaves);
645
646                ObjectPvs::SetPvsSize((int)leaves.size());
647#endif
648
[2172]649                Environment::GetSingleton()->GetStringValue("ViewCells.filename", buf);
[2183]650                cout << "loading objects from " << buf << endl;
[2117]651
[2183]652                // load objects which will be used as pvs entries
653                ObjectContainer pvsObjects;
654                if (0) LoadObjects(buf, pvsObjects, mObjects);
[2117]655
[2183]656                const bool finalizeViewCells = true;
657                cout << "loading view cells from " << buf << endl;
658
659                mViewCellsManager = ViewCellsManager::LoadViewCells(buf,
660                                                                                                                        pvsObjects,
661                                                                                                                        mObjects,
662                                                                                                                        finalizeViewCells,
663                                                                                                                        NULL);
664
[1740]665                cout << "view cells loaded." << endl<<flush;
666
667                if (!mViewCellsManager)
668                {
[2072]669                        cerr << "no view cells manager could be loaded" << endl;
[1740]670                        return false;
671                }
[577]672        }
673        else
674        {
[1288]675                // parse type of view cell container
[1004]676                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);             
[1740]677                mViewCellsManager = CreateViewCellsManager(buf);
[1112]678
679                // default view space is the extent of the scene
[1723]680                AxisAlignedBox3 viewSpaceBox;
[1740]681
[1723]682                if (mUseViewSpaceBox)
[1563]683                {
[1723]684                        viewSpaceBox = mSceneGraph->GetBox();
685
[1563]686                        // use a small box outside of the scene
[1723]687                        viewSpaceBox.Scale(Vector3(0.15f, 0.3f, 0.5f));
688                        //viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.5f, 0, 0));
689                        viewSpaceBox.Translate(Vector3(Magnitude(mSceneGraph->GetBox().Size()) * 0.3f, 0, 0));
690                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
[1563]691                }
[1723]692                else
693                {
694                        viewSpaceBox = mSceneGraph->GetBox();
695                        mViewCellsManager->SetViewSpaceBox(viewSpaceBox);
696                }
[1545]697
698                bool loadVcGeometry;
699                Environment::GetSingleton()->GetBoolValue("ViewCells.loadGeometry", loadVcGeometry);
700
701                bool extrudeBaseTriangles;
702                Environment::GetSingleton()->GetBoolValue("ViewCells.useBaseTrianglesAsGeometry", extrudeBaseTriangles);
703
704                char vcGeomFilename[100];
705                Environment::GetSingleton()->GetStringValue("ViewCells.geometryFilename", vcGeomFilename);
[1740]706
[1940]707                // create view cells from specified geometry
[1627]708                if (loadVcGeometry)
[1545]709                {
[1627]710                        if (mViewCellsManager->GetType() == ViewCellsManager::BSP)
[1545]711                        {
[1627]712                                if (!mViewCellsManager->LoadViewCellsGeometry(vcGeomFilename, extrudeBaseTriangles))
713                                {
714                                        cerr << "loading view cells geometry failed" << endl;
715                                }
[1545]716                        }
[1627]717                        else
718                        {
719                                cerr << "loading view cells geometry is not implemented for this manager" << endl;
720                        }
[1545]721                }
[577]722        }
[1740]723
[1486]724        ////////
[1523]725        //-- evaluation of render cost heuristics
[1768]726
[473]727        float objRenderCost = 0, vcOverhead = 0, moveSpeed = 0;
728
[1004]729        Environment::GetSingleton()->GetFloatValue("Simulation.objRenderCost",objRenderCost);
730        Environment::GetSingleton()->GetFloatValue("Simulation.vcOverhead", vcOverhead);
731        Environment::GetSingleton()->GetFloatValue("Simulation.moveSpeed", moveSpeed);
[1740]732
[473]733        mRenderSimulator =
734                new RenderSimulator(mViewCellsManager, objRenderCost, vcOverhead, moveSpeed);
[440]735
[480]736        mViewCellsManager->SetRenderer(mRenderSimulator);
[1785]737       
[1581]738        mViewCellsManager->SetPreprocessor(this);
[1940]739
[463]740        return true;
[490]741}
742
[1292]743 
[1563]744bool Preprocessor::ConstructViewCells()
[1292]745{
[1627]746        // construct view cells using it's own set of samples
747        mViewCellsManager->Construct(this);
748
749        // visualizations and statistics
750        Debug << "finished view cells:" << endl;
751        mViewCellsManager->PrintStatistics(Debug);
752
753        return true;
[1292]754}
[490]755
[1294]756
[575]757ViewCellsManager *Preprocessor::CreateViewCellsManager(const char *name)
758{
[1264]759        ViewCellsTree *vcTree = new ViewCellsTree;
760
[575]761        if (strcmp(name, "kdTree") == 0)
762        {
[1264]763                mViewCellsManager = new KdViewCellsManager(vcTree, mKdTree);
[575]764        }
765        else if (strcmp(name, "bspTree") == 0)
766        {
767                Debug << "view cell type: Bsp" << endl;
768
[577]769                mBspTree = new BspTree();
[1264]770                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]771        }
772        else if (strcmp(name, "vspBspTree") == 0)
773        {
774                Debug << "view cell type: VspBsp" << endl;
775
[1004]776                mVspBspTree = new VspBspTree();
[1264]777                mViewCellsManager = new VspBspViewCellsManager(vcTree, mVspBspTree);
[575]778        }
[1006]779        else if (strcmp(name, "vspOspTree") == 0)
[575]780        {
[1421]781                Debug << "view cell type: VspOsp" << endl;
[1288]782                char buf[100];         
783                Environment::GetSingleton()->GetStringValue("Hierarchy.type", buf);     
[1022]784
[1740]785                mViewCellsManager = new VspOspViewCellsManager(vcTree, buf);
[575]786        }
[1421]787        else if (strcmp(name, "sceneDependent") == 0) //TODO
[575]788        {
[1143]789                Debug << "view cell type: Bsp" << endl;
[1421]790               
[575]791                mBspTree = new BspTree();
[1264]792                mViewCellsManager = new BspViewCellsManager(vcTree, mBspTree);
[575]793        }
794        else
795        {
[664]796                cerr << "Wrong view cells type " << name << "!!!" << endl;
[575]797                exit(1);
798        }
799
800        return mViewCellsManager;
801}
802
803
[491]804// use ascii format to store rays
805#define USE_ASCII 0
806
807
[1145]808static inline bool ilt(Intersectable *obj1, Intersectable *obj2)
[490]809{
810        return obj1->mId < obj2->mId;
811}
812
813
[2342]814bool Preprocessor::LoadKdTree(const string &filename)
[1197]815{
[1414]816        mKdTree = new KdTree();
[2539]817        return mKdTree->ImportBinTree(filename.c_str(), mObjects);
[1197]818}
819
[1414]820
[2342]821bool Preprocessor::ExportKdTree(const string &filename)
[1197]822{
[1414]823        return mKdTree->ExportBinTree(filename.c_str());
[1197]824}
825
826
[490]827bool Preprocessor::LoadSamples(VssRayContainer &samples,
828                                                           ObjectContainer &objects) const
829{
830        std::stable_sort(objects.begin(), objects.end(), ilt);
831        char fileName[100];
[1004]832        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[490]833       
[491]834    Vector3 origin, termination;
835        // HACK: needed only for lower_bound algorithm to find the
836        // intersected objects
837        MeshInstance sObj(NULL);
838        MeshInstance tObj(NULL);
[490]839
[491]840#if USE_ASCII
[2452]841        ifstream inStream(fileName);
842        if (!inStream.is_open())
[490]843                return false;
844
845        string buf;
[2452]846        while (!(getline(inStream, buf)).eof())
[490]847        {
[491]848                sscanf(buf.c_str(), "%f %f %f %f %f %f %d %d",
[490]849                           &origin.x, &origin.y, &origin.z,
[491]850                           &termination.x, &termination.y, &termination.z,
851                           &(sObj.mId), &(tObj.mId));
[490]852               
[491]853                Intersectable *sourceObj = NULL;
854                Intersectable *termObj = NULL;
855               
856                if (sObj.mId >= 0)
[490]857                {
858                        ObjectContainer::iterator oit =
[491]859                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
860                        sourceObj = *oit;
861                }
862               
863                if (tObj.mId >= 0)
864                {
865                        ObjectContainer::iterator oit =
866                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
867                        termObj = *oit;
868                }
[490]869
[491]870                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
871        }
872#else
[2452]873        ifstream inStream(fileName, ios::binary);
874        if (!inStream.is_open())
[491]875                return false;
876
877        while (1)
878        {
[2452]879                 inStream.read(reinterpret_cast<char *>(&origin), sizeof(Vector3));
880                 inStream.read(reinterpret_cast<char *>(&termination), sizeof(Vector3));
881                 inStream.read(reinterpret_cast<char *>(&(sObj.mId)), sizeof(int));
882                 inStream.read(reinterpret_cast<char *>(&(tObj.mId)), sizeof(int));
[491]883               
[2452]884                 if (inStream.eof())
[491]885                        break;
886
887                Intersectable *sourceObj = NULL;
888                Intersectable *termObj = NULL;
889               
890                if (sObj.mId >= 0)
891                {
892                        ObjectContainer::iterator oit =
893                                lower_bound(objects.begin(), objects.end(), &sObj, ilt);
894                        sourceObj = *oit;
[490]895                }
[491]896               
897                if (tObj.mId >= 0)
[490]898                {
[491]899                        ObjectContainer::iterator oit =
900                                lower_bound(objects.begin(), objects.end(), &tObj, ilt);
901                        termObj = *oit;
[490]902                }
[491]903
904                samples.push_back(new VssRay(origin, termination, sourceObj, termObj));
[490]905        }
[1779]906#endif
[491]907
[2452]908        inStream.close();
[490]909
910        return true;
911}
912
[508]913
914bool Preprocessor::ExportSamples(const VssRayContainer &samples) const
[490]915{
[491]916        char fileName[100];
[1004]917        Environment::GetSingleton()->GetStringValue("Preprocessor.samplesFilename", fileName);
[491]918       
[490]919
920        VssRayContainer::const_iterator it, it_end = samples.end();
921       
[491]922#if USE_ASCII
923        ofstream samplesOut(fileName);
[490]924        if (!samplesOut.is_open())
925                return false;
926
927        for (it = samples.begin(); it != it_end; ++ it)
928        {
929                VssRay *ray = *it;
[491]930                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
931                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;       
932
[490]933                samplesOut << ray->GetOrigin().x << " " << ray->GetOrigin().y << " " << ray->GetOrigin().z << " "
934                                   << ray->GetTermination().x << " " << ray->GetTermination().y << " " << ray->GetTermination().z << " "
[491]935                                   << sourceid << " " << termid << "\n";
[490]936        }
[491]937#else
938        ofstream samplesOut(fileName, ios::binary);
939        if (!samplesOut.is_open())
940                return false;
941
942        for (it = samples.begin(); it != it_end; ++ it)
943        {       
944                VssRay *ray = *it;
945                Vector3 origin(ray->GetOrigin());
946                Vector3 termination(ray->GetTermination());
947               
948                int sourceid = ray->mOriginObject ? ray->mOriginObject->mId : -1;               
949                int termid = ray->mTerminationObject ? ray->mTerminationObject->mId : -1;               
950
951                samplesOut.write(reinterpret_cast<char *>(&origin), sizeof(Vector3));
952                samplesOut.write(reinterpret_cast<char *>(&termination), sizeof(Vector3));
953                samplesOut.write(reinterpret_cast<char *>(&sourceid), sizeof(int));
954                samplesOut.write(reinterpret_cast<char *>(&termid), sizeof(int));
955    }
956#endif
[490]957        samplesOut.close();
[1194]958
[490]959        return true;
960}
[563]961
[1771]962
963int
964Preprocessor::GenerateRays(const int number,
[1867]965                                                   SamplingStrategy &strategy,
966                                                   SimpleRayContainer &rays)
[1020]967{
[1867]968  return strategy.GenerateSamples(number, rays);
[1771]969}
[860]970
[1990]971
[1771]972int
973Preprocessor::GenerateRays(const int number,
[1898]974                                                   const int sampleType,
975                                                   SimpleRayContainer &rays)
[1771]976{
[1772]977        const int startSize = (int)rays.size();
978        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
979        int castRays = 0;
980
981        if (!strategy)
[1381]982        {
[1772]983                return 0;
[1381]984        }
[1772]985
[1381]986#if 1
[1772]987        castRays = strategy->GenerateSamples(number, rays);
[1381]988#else
[1772]989        GenerateRayBundle(rays, newRay, 16, 0);
990        castRays += 16;
[1381]991#endif
[1772]992
993        delete strategy;
994        return castRays;
[878]995}
[1020]996
997
[1884]998SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
[1020]999{
1000        switch (strategyId)
1001        {
[1520]1002        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
[1020]1003                return new ObjectBasedDistribution(*this);
[1520]1004        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
[1020]1005                return new ObjectDirectionBasedDistribution(*this);
[1520]1006        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
[1020]1007                return new DirectionBasedDistribution(*this);
[1520]1008        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
[1020]1009                return new DirectionBoxBasedDistribution(*this);
[1520]1010        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
[1020]1011                return new SpatialBoxBasedDistribution(*this);
[1695]1012        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1013                return new ReverseObjectBasedDistribution(*this);
[1769]1014        case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1015                return new ViewCellBorderBasedDistribution(*this);
[1772]1016        case SamplingStrategy::VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1017                return new ViewSpaceBorderBasedDistribution(*this);
1018        case SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1019                return new ReverseViewSpaceBorderBasedDistribution(*this);
[1824]1020        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1021                return new GlobalLinesDistribution(*this);
1022               
1023                //case OBJECTS_INTERIOR_DISTRIBUTION:
1024                //      return new ObjectsInteriorDistribution(*this);
[1020]1025        default: // no valid strategy
[1279]1026                Debug << "warning: no valid sampling strategy" << endl;
[1020]1027                return NULL;
1028        }
[1221]1029
[1570]1030        return NULL; // should never come here
[1020]1031}
1032
1033
[2342]1034bool Preprocessor::LoadInternKdTree(const string &internKdTree)
[2003]1035{
[2342]1036        bool mUseKdTree = true;
1037
1038        if (!mUseKdTree) {
1039                // create just a dummy KdTree
1040                mKdTree = new KdTree;
1041                return true;
1042        }
1043
1044        // always try to load the kd tree
1045        cout << "loading kd tree file " << internKdTree << " ... " << endl;
1046
1047        if (!LoadKdTree(internKdTree)) {
1048                cout << "error loading kd tree with filename "
1049                        << internKdTree << ", rebuilding it instead ... " << endl;
1050                // build new kd tree from scene geometry
1051                BuildKdTree();
1052
1053                // export kd tree?
1054                const long startTime = GetTime();
1055                cout << "exporting kd tree ... ";
1056
1057                if (!ExportKdTree(internKdTree))
1058                {
1059                        cout << " error exporting kd tree with filename "
1060                                << internKdTree << endl;
1061                }
1062                else
1063                {
1064                        cout << "finished in "
1065                                << TimeDiff(startTime, GetTime()) * 1e-3
1066                                << " secs" << endl;
1067                }
1068        }
1069
1070        KdTreeStatistics(cout);
1071        cout << mKdTree->GetBox() << endl;
1072
[2035]1073        return true;
[2003]1074}
1075
1076
[2342]1077bool Preprocessor::InitRayCast(const string &externKdTree,
1078                                                           const string &internKdTree)
[1221]1079{
[1633]1080        // always try to load the kd tree
[2003]1081/*      cout << "loading kd tree file " << internKdTree << " ... " << endl;
[1634]1082
1083        if (!LoadKdTree(internKdTree))
1084        {
[1968]1085                cout << "error loading kd tree with filename "
1086                         << internKdTree << ", rebuilding it instead ... " << endl;
[1633]1087                // build new kd tree from scene geometry
[1415]1088                BuildKdTree();
1089
[1627]1090                // export kd tree?
[1633]1091                const long startTime = GetTime();
[1627]1092                cout << "exporting kd tree ... ";
1093
1094                if (!ExportKdTree(internKdTree))
1095                {
[1968]1096                        cout << " error exporting kd tree with filename "
1097                                 << internKdTree << endl;
[1627]1098                }
1099                else
1100                {
[1968]1101                        cout << "finished in "
1102                                 << TimeDiff(startTime, GetTime()) * 1e-3
1103                                 << " secs" << endl;
[1627]1104                }
[1415]1105        }
[1633]1106       
1107        KdTreeStatistics(cout);
1108        cout << mKdTree->GetBox() << endl;
[2003]1109*/
[1520]1110        int rayCastMethod;
[1968]1111        Environment::GetSingleton()->
1112                GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
[1520]1113
1114        if (rayCastMethod == 0)
[1221]1115        {
[1867]1116                cout << "ray cast method: internal" << endl;
[2003]1117                mRayCaster = new InternalRayCaster(*this);
[1221]1118        }
[1251]1119        else
[1520]1120        {
[1524]1121#ifdef GTP_INTERNAL
[1867]1122          cout << "ray cast method: intel" << endl;
1123          mRayCaster = new IntelRayCaster(*this, externKdTree);
[1524]1124#endif
[1251]1125        }
[1867]1126       
[2072]1127        /////
1128        //-- reserve constant block of rays
1129       
1130        // hack: If we dont't use view cells loading, there must be at least as much rays
1131        // as are needed for the view cells construction
1132        bool loadViewCells;
1133        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", loadViewCells);
1134
[2187]1135        int reserveRays;       
1136        int constructionSamples;
[2072]1137
1138        if (!loadViewCells)
1139        {
[2187]1140                cout << "hack: setting ray pool size to view cell construction or evaluation size" << endl;
[2072]1141
[2187]1142                constructionSamples = 1000000;
1143
[2072]1144                char buf[100];
1145                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);     
[2187]1146
[2072]1147                if (strcmp(buf, "vspBspTree") == 0)
1148                {
[2187]1149                        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", constructionSamples);
1150                       
[2072]1151                }
1152                else if (strcmp(buf, "vspOspTree") == 0)
1153                {
[2187]1154                        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", constructionSamples);               
[2072]1155                }
[2187]1156
1157                int evalSamplesPerPass;
1158
1159                Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", evalSamplesPerPass);
1160
1161                reserveRays = max(constructionSamples, evalSamplesPerPass);
1162                reserveRays *= 2;
[2072]1163        }
1164        else
1165        {
[2187]1166                cout << "setting ray pool size to samples per pass" << endl;       
[2072]1167                reserveRays = mSamplesPerPass * 2;
1168        }
1169
[2048]1170        cout << "======================" << endl;
[2072]1171        cout << "reserving " << reserveRays << " rays " << endl;
1172        mRayCaster->ReserveVssRayPool(reserveRays);
[2012]1173       
[1520]1174        return true;
[1281]1175}
1176
[1292]1177
[1281]1178void
1179Preprocessor::CastRays(
1180                                           SimpleRayContainer &rays,
[1520]1181                                           VssRayContainer &vssRays,
[1528]1182                                           const bool castDoubleRays,
[1996]1183                                           const bool pruneInvalidRays
[1281]1184                                           )
1185{
[2035]1186
[2069]1187        const long t1 = GetTime();
[2035]1188       
[2198]1189        if (rays.size() > 10000)
[2187]1190        {
[2539]1191
[2072]1192                mRayCaster->SortRays(rays);
[2069]1193                cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" ms."<<endl;
[1984]1194        }
[1972]1195
[2072]1196
[2076]1197        if (mUseHwGlobalLines)
[2187]1198        {
[2539]1199                CastRaysWithHwGlobalLines(
1200                        rays,
1201                        vssRays,
1202                        castDoubleRays,
1203                        pruneInvalidRays
1204                        );
[2187]1205        }
[2076]1206        else
[2187]1207        {
[2539]1208                mRayCaster->CastRays(
1209                        rays,                           
1210                        vssRays,
1211                        mViewCellsManager->GetViewSpaceBox(),
1212                        castDoubleRays,
1213                        pruneInvalidRays);
[2187]1214        }
1215
1216        if (rays.size() > 10000)
[2076]1217        {
1218                cout << endl;
[2539]1219                long t2 = GetTime();
[2072]1220
[2076]1221#if SHOW_RAYCAST_TIMING
1222                if (castDoubleRays)
1223                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1224                else
1225                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M rays/s" << endl;
1226#endif
1227        }
1228
1229        DeterminePvsObjects(vssRays);
1230}
1231
1232 
1233void
1234Preprocessor::CastRaysWithHwGlobalLines(
1235                                                                                SimpleRayContainer &rays,
[2187]1236                                                                                VssRayContainer &vssRays,
1237                                                                                const bool castDoubleRays,
1238                                                                                const bool pruneInvalidRays)
[2076]1239{
1240  SimpleRayContainer::const_iterator rit, rit_end = rays.end();
1241  SimpleRayContainer rayBucket;
1242  int i = 0;
1243  for (rit = rays.begin(); rit != rit_end; ++ rit, ++ i)
[1292]1244        {
[2076]1245          SimpleRay ray = *rit;
[1990]1246#ifdef USE_CG
[1972]1247                // HACK: global lines must be treated special
[2076]1248          if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
[1968]1249                {
[2076]1250                  mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1251                  continue;
[1968]1252                }
[1990]1253#endif
[2187]1254                rayBucket.push_back(ray);
1255
1256                // 16 rays gathered => do ray casting
1257                if (rayBucket.size() >= 16)
[1520]1258                {
[2187]1259                        mRayCaster->CastRays16(
1260                                rayBucket,                             
1261                                vssRays,
1262                                mViewCellsManager->GetViewSpaceBox(),
1263                                castDoubleRays,
1264                                pruneInvalidRays);
1265
1266                        rayBucket.clear();
[1292]1267                }
[2187]1268
1269                if (rays.size() > 100000 && i % 100000 == 0)
[2072]1270                        cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
[1972]1271        }
[2072]1272   
[1972]1273        // cast rest of rays
1274        SimpleRayContainer::const_iterator sit, sit_end = rayBucket.end();
1275
1276        for (sit = rayBucket.begin(); sit != sit_end; ++ sit)
1277        {
1278                SimpleRay ray = *sit;
[1990]1279
1280#ifdef USE_CG
[1972]1281                // HACK: global lines must be treated special
1282                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
[1932]1283                {
[1972]1284                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
[1990]1285                        continue;
[1972]1286                }
[1990]1287#endif
1288                mRayCaster->CastRay(
1289                                                        ray,
1290                                                        vssRays,
1291                                                        mViewCellsManager->GetViewSpaceBox(),
1292                                                        castDoubleRays,
[1996]1293                                                        pruneInvalidRays);
[1990]1294               
[1524]1295        }
[1743]1296
[1251]1297}
1298
1299
[1381]1300bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1301                                                                         const SimpleRay &mainRay,
1302                                                                         const int number,
1303                                                                         const int pertubType) const
1304{
1305        rayBundle.push_back(mainRay);
1306
[1564]1307        const float pertubOrigin = 0.0f;
1308        const float pertubDir = 0.2f;
[1381]1309
1310        for (int i = 0; i < number - 1; ++ i)
1311        {
1312                Vector3 pertub;
1313
1314                pertub.x = RandomValue(0.0f, pertubDir);
1315                pertub.y = RandomValue(0.0f, pertubDir);
1316                pertub.z = RandomValue(0.0f, pertubDir);
[1713]1317
[1381]1318                const Vector3 newDir = mainRay.mDirection + pertub;
1319                //const Vector3 newDir = mainRay.mDirection;
1320
1321                pertub.x = RandomValue(0.0f, pertubOrigin);
1322                pertub.y = RandomValue(0.0f, pertubOrigin);
1323                pertub.z = RandomValue(0.0f, pertubOrigin);
[1713]1324
[1381]1325                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1326                //const Vector3 newOrigin = mainRay.mOrigin;
1327
[1883]1328                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
[1381]1329        }
1330
1331        return true;
1332}
1333
1334
[1251]1335void Preprocessor::SetupRay(Ray &ray,
1336                                                        const Vector3 &point,
[1713]1337                                                        const Vector3 &direction) const
[1251]1338{
1339        ray.Clear();
1340        // do not store anything else then intersections at the ray
[1713]1341        ray.Init(point, direction, Ray::LOCAL_RAY);     
[1251]1342}
1343
[1968]1344
[1917]1345void Preprocessor::EvalViewCellHistogram()
[1771]1346{
[1917]1347        char filename[256];
1348        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
[1771]1349 
[1917]1350        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1351        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
[1771]1352}
[1520]1353
[1900]1354
1355bool
1356Preprocessor::ExportRays(const char *filename,
1357                                                 const VssRayContainer &vssRays,
[2001]1358                                                 const int number,
1359                                                 const bool exportScene
[1900]1360                                                 )
1361{
1362  cout<<"Exporting vss rays..."<<endl<<flush;
1363 
1364  Exporter *exporter = NULL;
1365  exporter = Exporter::GetExporter(filename);
1366
1367  if (0) {
1368        exporter->SetWireframe();
1369        exporter->ExportKdTree(*mKdTree);
1370  }
1371 
1372  exporter->SetFilled();
1373  // $$JB temporarily do not export the scene
[2001]1374  if (exportScene)
[1900]1375        exporter->ExportScene(mSceneGraph->GetRoot());
1376
1377  exporter->SetWireframe();
1378
1379  if (1) {
1380        exporter->SetForcedMaterial(RgbColor(1,0,1));
1381        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1382        exporter->ResetForcedMaterial();
1383  }
1384 
1385  VssRayContainer rays;
1386  vssRays.SelectRays(number, rays);
1387  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1388  delete exporter;
1389  cout<<"done."<<endl<<flush;
1390
1391  return true;
[1251]1392}
[1900]1393
[2002]1394bool
1395Preprocessor::ExportRayAnimation(const char *filename,
1396                                                                 const vector<VssRayContainer> &vssRays
1397                                                                 )
1398{
1399  cout<<"Exporting vss rays..."<<endl<<flush;
1400       
1401  Exporter *exporter = NULL;
1402  exporter = Exporter::GetExporter(filename);
1403  if (0) {
1404        exporter->SetWireframe();
1405        exporter->ExportKdTree(*mKdTree);
1406  }
1407  exporter->SetFilled();
1408  // $$JB temporarily do not export the scene
[2008]1409  if (0)
[2002]1410        exporter->ExportScene(mSceneGraph->GetRoot());
1411  exporter->SetWireframe();
1412
1413  if (1) {
1414        exporter->SetForcedMaterial(RgbColor(1,0,1));
1415        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1416        exporter->ResetForcedMaterial();
1417  }
1418 
1419  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
1420       
1421  delete exporter;
1422
1423  cout<<"done."<<endl<<flush;
1424
1425  return true;
1426}
1427
[1931]1428void
1429Preprocessor::ComputeRenderError()
1430{
1431  // compute rendering error
1432       
1433  if (renderer && renderer->mPvsStatFrames) {
1434        //      emit EvalPvsStat();
1435        //      QMutex mutex;
1436        //      mutex.lock();
1437        //      renderer->mRenderingFinished.wait(&mutex);
1438        //      mutex.unlock();
[2049]1439
1440        if (mViewCellsManager->GetViewCellPoints()->size()) {
1441         
1442          vector<ViewCellPoints *> *vcPoints = mViewCellsManager->GetViewCellPoints();
1443         
[2050]1444          vector<ViewCellPoints *>::const_iterator
1445                vit = vcPoints->begin(),
1446                vit_end = vcPoints->end();
1447
[2049]1448          SimpleRayContainer viewPoints;
1449         
[2050]1450          for (; vit != vit_end; ++ vit) {
[2049]1451                ViewCellPoints *vp = *vit;
1452
1453                SimpleRayContainer::const_iterator rit = vp->second.begin(), rit_end = vp->second.end();
1454                for (; rit!=rit_end; ++rit)
1455                  viewPoints.push_back(*rit);
1456          }
[2050]1457
1458          if (viewPoints.size() != renderer->mPvsErrorBuffer.size()) {
1459                renderer->mPvsErrorBuffer.resize(viewPoints.size());
1460                renderer->ClearErrorBuffer();
1461          }
1462
[2049]1463          renderer->EvalPvsStat(viewPoints);
1464        } else
1465          renderer->EvalPvsStat();
[2050]1466
[1931]1467        mStats <<
1468          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
[2002]1469          "#AvgPixelError\n" <<renderer->GetAvgPixelError()<<endl<<
[2008]1470          "#MaxPixelError\n" <<renderer->GetMaxPixelError()<<endl<<
[1931]1471          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1472          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1473          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1474  }
[1900]1475}
[1931]1476
[1958]1477
1478Intersectable *Preprocessor::GetObjectById(const int id)
1479{
[1960]1480#if 1
[1958]1481        // create a dummy mesh instance to be able to use stl
1482        MeshInstance object(NULL);
1483        object.SetId(id);
1484
1485        ObjectContainer::const_iterator oit =
1486                lower_bound(mObjects.begin(), mObjects.end(), &object, ilt);
1487                               
1488        // objects sorted by id
1489        if ((oit != mObjects.end()) && ((*oit)->GetId() == object.GetId()))
1490        {
1491                return (*oit);
1492        }
1493        else
1494        {
1495                return NULL;
1496        }
1497#else
[1960]1498        return mObjects[id - 1];
[1958]1499#endif
[1931]1500}
[1958]1501
[1968]1502
1503void Preprocessor::PrepareHwGlobalLines()
1504{
1505        int texHeight, texWidth;
1506        float eps;
1507        int maxDepth;
1508        bool sampleReverse;
1509
1510        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texHeight", texHeight);
[1969]1511        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texWidth", texWidth);
[1968]1512        Environment::GetSingleton()->GetFloatValue("Preprocessor.HwGlobalLines.stepSize", eps);
1513        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.maxDepth", maxDepth);
1514        Environment::GetSingleton()->GetBoolValue("Preprocessor.HwGlobalLines.sampleReverse", sampleReverse);
1515
[1969]1516        Debug << "****** hw global line options *******" << endl;
1517        Debug << "texWidth: " << texWidth << endl;
1518        Debug << "texHeight: " << texHeight << endl;
1519        Debug << "sampleReverse: " << sampleReverse << endl;
1520        Debug << "max depth: " << maxDepth << endl;
1521        Debug << "step size: " << eps << endl;
1522        Debug << endl;
1523
[1990]1524#ifdef USE_CG
[1969]1525        globalLinesRenderer = mGlobalLinesRenderer =
[1968]1526                new GlobalLinesRenderer(this,
1527                                                                texHeight,
1528                                                                texWidth,
1529                                                                eps,
1530                                                                maxDepth,
1531                                                                sampleReverse);
[1990]1532
[1968]1533        mGlobalLinesRenderer->InitGl();
[1990]1534
1535#endif
[1958]1536}
[1968]1537
[2048]1538
1539void Preprocessor::DeterminePvsObjects(VssRayContainer &rays)
1540{
1541        mViewCellsManager->DeterminePvsObjects(rays, false);
[1968]1542}
[2048]1543
1544
[2183]1545bool Preprocessor::LoadObjects(const string &filename,
1546                                                           ObjectContainer &pvsObjects,
1547                                                           const ObjectContainer &preprocessorObjects)
1548{
1549        ObjectsParser parser;
1550
1551        const bool success = parser.ParseObjects(filename,
1552                                                                                         pvsObjects,
1553                                                                                         preprocessorObjects);
1554
1555        if (!success)
1556        {
1557                Debug << "Error: loading objects failed!" << endl;
1558        }
1559
1560        // hack: no bvh object could be found => take preprocessor objects
1561        if (pvsObjects.empty())
1562        {
1563                Debug << "no objects" << endl;
1564                pvsObjects = preprocessorObjects;
1565        }
1566
1567        return success;
[2048]1568}
[2183]1569
1570
1571}
Note: See TracBrowser for help on using the repository browser.