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

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