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

Revision 2005, 38.5 KB checked in by mattausch, 17 years ago (diff)

using large address space

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