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

Revision 2575, 40.8 KB checked in by bittner, 17 years ago (diff)

big merge: preparation for havran ray caster, check if everything works

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