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

Revision 2050, 40.2 KB checked in by bittner, 17 years ago (diff)

render error

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