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

Revision 2615, 43.2 KB checked in by mattausch, 16 years ago (diff)

did some stuff for the visualization

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