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

Revision 2172, 41.8 KB checked in by bittner, 17 years ago (diff)

merge

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