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

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