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

Revision 2708, 43.8 KB checked in by bittner, 16 years ago (diff)

Updates functional for verbose pvs - sprintf_s changed to sprintf due to compiling problem on vs2003

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