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

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