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

Revision 2017, 38.9 KB checked in by mattausch, 17 years ago (diff)

changed to static cast

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