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

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