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

Revision 2603, 41.0 KB checked in by bittner, 16 years ago (diff)

sse disabled for hr

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