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

Revision 2695, 44.5 KB checked in by mattausch, 16 years ago (diff)

debug version: problematic view points for vienna detected

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