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

Revision 2113, 41.7 KB checked in by mattausch, 17 years ago (diff)

warning: debug version

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