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

Revision 2714, 46.2 KB checked in by bittner, 16 years ago (diff)

dynamic object changes in preprocessor.cpp

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  return strategy.GenerateSamples(number, rays);
969}
970
971
972int
973Preprocessor::GenerateRays(const int number,
974                                                   const int sampleType,
975                                                   SimpleRayContainer &rays)
976{
977        const int startSize = (int)rays.size();
978        SamplingStrategy *strategy = GenerateSamplingStrategy(sampleType);
979        int castRays = 0;
980
981        if (!strategy)
982        {
983                return 0;
984        }
985
986#if 1
987        castRays = strategy->GenerateSamples(number, rays);
988#else
989        GenerateRayBundle(rays, newRay, 16, 0);
990        castRays += 16;
991#endif
992
993        delete strategy;
994        return castRays;
995}
996
997
998SamplingStrategy *Preprocessor::GenerateSamplingStrategy(const int strategyId)
999{
1000        switch (strategyId)
1001        {
1002        case SamplingStrategy::OBJECT_BASED_DISTRIBUTION:
1003                return new ObjectBasedDistribution(*this);
1004        case SamplingStrategy::OBJECT_DIRECTION_BASED_DISTRIBUTION:
1005                return new ObjectDirectionBasedDistribution(*this);
1006        case SamplingStrategy::DIRECTION_BASED_DISTRIBUTION:
1007                return new DirectionBasedDistribution(*this);
1008        case SamplingStrategy::DIRECTION_BOX_BASED_DISTRIBUTION:
1009                return new DirectionBoxBasedDistribution(*this);
1010        case SamplingStrategy::SPATIAL_BOX_BASED_DISTRIBUTION:
1011                return new SpatialBoxBasedDistribution(*this);
1012        case SamplingStrategy::REVERSE_OBJECT_BASED_DISTRIBUTION:
1013                return new ReverseObjectBasedDistribution(*this);
1014        //case SamplingStrategy::VIEWCELL_BORDER_BASED_DISTRIBUTION:
1015        //      return new ViewCellBorderBasedDistribution(*this);
1016        case SamplingStrategy::REVERSE_VIEWSPACE_BORDER_BASED_DISTRIBUTION:
1017                return new ReverseViewSpaceBorderBasedDistribution(*this);
1018        case SamplingStrategy::GLOBAL_LINES_DISTRIBUTION:
1019                return new GlobalLinesDistribution(*this);
1020               
1021                //case OBJECTS_INTERIOR_DISTRIBUTION:
1022                //      return new ObjectsInteriorDistribution(*this);
1023        default: // no valid strategy
1024                Debug << "warning: no valid sampling strategy" << endl;
1025                return NULL;
1026        }
1027
1028        return NULL; // should never come here
1029}
1030
1031
1032bool Preprocessor::LoadInternKdTree(const string &internKdTree)
1033{
1034  bool mUseKdTree = true;
1035
1036
1037  int rayCastMethod;
1038  Environment::GetSingleton()->
1039        GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
1040
1041#ifdef USE_HAVRAN_RAYCASTER
1042
1043  if ((rayCastMethod == 2) || (rayCastMethod == 3))
1044  {
1045          HavranRayCaster *hr = 0;
1046
1047          if (rayCastMethod == 3)
1048                  hr = reinterpret_cast<HavranDynRayCaster*>(mRayCaster);
1049          else
1050                  hr = reinterpret_cast<HavranRayCaster*>(mRayCaster);
1051         
1052          hr->Build(this->mObjects);
1053  }
1054
1055#endif
1056
1057
1058  if (!mUseKdTree) {
1059        // create just a dummy KdTree
1060        mKdTree = new KdTree;
1061        return true;
1062  }
1063 
1064 
1065 
1066  // always try to load the kd tree
1067  cout << "loading kd tree file " << internKdTree << " ... " << endl;
1068 
1069  if (!LoadKdTree(internKdTree)) {
1070        cout << "error loading kd tree with filename "
1071                 << internKdTree << ", rebuilding it instead ... " << endl;
1072        // build new kd tree from scene geometry
1073        BuildKdTree();
1074       
1075        // export kd tree?
1076        const long startTime = GetTime();
1077        cout << "exporting kd tree ... ";
1078       
1079        if (!ExportKdTree(internKdTree))
1080          {
1081                cout << " error exporting kd tree with filename "
1082                         << internKdTree << endl;
1083          }
1084        else
1085          {
1086                cout << "finished in "
1087                         << TimeDiff(startTime, GetTime()) * 1e-3
1088                         << " secs" << endl;
1089          }
1090  }
1091 
1092  KdTreeStatistics(cout);
1093  sceneBox = mKdTree->GetBox();
1094
1095  cout << mKdTree->GetBox() << endl;
1096 
1097  return true;
1098}
1099
1100
1101bool Preprocessor::InitRayCast(const string &externKdTree,
1102                                                           const string &internKdTree)
1103{
1104        int rayCastMethod;
1105        Environment::GetSingleton()->
1106                GetIntValue("Preprocessor.rayCastMethod", rayCastMethod);
1107
1108        if (rayCastMethod == 0)
1109        {
1110                cout << "ray cast method: internal" << endl;
1111                mRayCaster = new InternalRayCaster(*this);
1112        }
1113        if (rayCastMethod == 1)
1114        {
1115#ifdef GTP_INTERNAL
1116                cout << "ray cast method: intel" << endl;
1117                mRayCaster = new IntelRayCaster(*this, externKdTree);
1118#endif
1119        }
1120        if (rayCastMethod == 2)
1121        {
1122#ifdef USE_HAVRAN_RAYCASTER
1123          cout << "ray cast method: havran" << endl <<flush;
1124          mRayCaster = new GALIGN16 HavranRayCaster(*this);
1125#endif
1126        }
1127        if (rayCastMethod == 3)
1128        {
1129#ifdef USE_HAVRAN_RAYCASTER
1130          cout << "ray cast method: havran - dyn" << endl <<flush;
1131          mRayCaster = new GALIGN16 HavranDynRayCaster(*this);
1132#endif
1133        }
1134
1135       
1136        /////////////////
1137        //-- reserve constant block of rays
1138       
1139        // hack: If we dont't use view cells loading, there must be at least as much rays
1140        // as are needed for the view cells construction
1141        bool loadViewCells;
1142        Environment::GetSingleton()->GetBoolValue("ViewCells.loadFromFile", loadViewCells);
1143
1144        int reserveRays;       
1145        int constructionSamples;
1146
1147        if (!loadViewCells)
1148        {
1149                cout << "hack: setting ray pool size to view cell construction or evaluation size" << endl;
1150
1151                constructionSamples = 1000000;
1152
1153                char buf[100];
1154                Environment::GetSingleton()->GetStringValue("ViewCells.type", buf);     
1155
1156                if (strcmp(buf, "vspBspTree") == 0)
1157                {
1158                        Environment::GetSingleton()->GetIntValue("VspBspTree.Construction.samples", constructionSamples);
1159                       
1160                }
1161                else if (strcmp(buf, "vspOspTree") == 0)
1162                {
1163                        Environment::GetSingleton()->GetIntValue("Hierarchy.Construction.samples", constructionSamples);               
1164                }
1165
1166                int evalSamplesPerPass;
1167
1168                Environment::GetSingleton()->GetIntValue("ViewCells.Evaluation.samplesPerPass", evalSamplesPerPass);
1169
1170                reserveRays = max(constructionSamples, evalSamplesPerPass);
1171                reserveRays *= 2;
1172        }
1173        else
1174        {
1175                const int n = 4;
1176                cout << "hack: setting ray pool size to multiple " << n << " of samples per pass" << endl;       
1177                reserveRays = mSamplesPerPass * n;
1178        }
1179
1180        cout << "======================" << endl;
1181        cout << "reserving " << reserveRays << " rays " << endl;
1182        mRayCaster->ReserveVssRayPool(reserveRays);
1183        cout<<"done."<<endl<<flush;
1184        return true;
1185}
1186
1187
1188void
1189Preprocessor::CastRays(
1190                                           SimpleRayContainer &rays,
1191                                           VssRayContainer &vssRays,
1192                                           const bool castDoubleRays,
1193                                           const bool pruneInvalidRays
1194                                           )
1195{
1196        const long t1 = GetTime();
1197
1198        // !!!!!!!!!!!!!!!! VH no sorting
1199        if (
1200                rays.size() > 10000
1201                )
1202        {
1203                mRayCaster->SortRays(rays);
1204                cout<<"Rays sorted in "<<TimeDiff(t1, GetTime())<<" ms."<<endl;
1205        }
1206
1207        int numTransformed = 0;
1208
1209
1210        if (mUseHwGlobalLines)
1211        {
1212                CastRaysWithHwGlobalLines(
1213                        rays,
1214                        vssRays,
1215                        castDoubleRays,
1216                        pruneInvalidRays
1217                        );
1218        }
1219        else
1220        {
1221                mRayCaster->CastRays(
1222                        rays,                           
1223                        vssRays,
1224                        mViewCellsManager->GetViewSpaceBox(),
1225                        castDoubleRays,
1226                        pruneInvalidRays);
1227
1228                // disabled not neccessary
1229                UpdateDynamicObjects();
1230        }
1231
1232       
1233        if (rays.size() > 10000)
1234        {
1235                cout << endl;
1236                long t2 = GetTime();
1237
1238#if SHOW_RAYCAST_TIMING
1239                if (castDoubleRays)
1240                        cout << 2 * rays.size() / (1e3f * TimeDiff(t1, t2)) << "M double rays/s" << endl;
1241                else
1242                        cout << rays.size() / (1e3f * TimeDiff(t1, t2)) << "M single rays/s" << endl;
1243#endif
1244
1245        }
1246
1247        DeterminePvsObjects(vssRays);
1248}
1249
1250 
1251void
1252Preprocessor::CastRaysWithHwGlobalLines(
1253                                                                                SimpleRayContainer &rays,
1254                                                                                VssRayContainer &vssRays,
1255                                                                                const bool castDoubleRays,
1256                                                                                const bool pruneInvalidRays)
1257{
1258  SimpleRayContainer::const_iterator rit, rit_end = rays.end();
1259  SimpleRayContainer rayBucket;
1260  int i = 0;
1261  for (rit = rays.begin(); rit != rit_end; ++ rit, ++ i)
1262        {
1263          SimpleRay ray = *rit;
1264#ifdef USE_CG
1265                // HACK: global lines must be treated special
1266          if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1267                {
1268                  mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1269                  continue;
1270                }
1271#endif
1272                rayBucket.push_back(ray);
1273
1274                // 16 rays gathered => do ray casting
1275                if (rayBucket.size() >= 16)
1276                {
1277                        mRayCaster->CastRays16(
1278                                rayBucket,                             
1279                                vssRays,
1280                                mViewCellsManager->GetViewSpaceBox(),
1281                                castDoubleRays,
1282                                pruneInvalidRays);
1283
1284                        rayBucket.clear();
1285                }
1286
1287                if (rays.size() > 100000 && i % 100000 == 0)
1288                        cout<<"\r"<<i<<"/"<<(int)rays.size()<<"\r";
1289        }
1290   
1291        // cast rest of rays
1292        SimpleRayContainer::const_iterator sit, sit_end = rayBucket.end();
1293
1294        for (sit = rayBucket.begin(); sit != sit_end; ++ sit)
1295        {
1296                SimpleRay ray = *sit;
1297
1298#ifdef USE_CG
1299                // HACK: global lines must be treated special
1300                if (ray.mDistribution == SamplingStrategy::HW_GLOBAL_LINES_DISTRIBUTION)
1301                {
1302                        mGlobalLinesRenderer->CastGlobalLines(ray, vssRays);
1303                        continue;
1304                }
1305#endif
1306                mRayCaster->CastRay(
1307                                                        ray,
1308                                                        vssRays,
1309                                                        mViewCellsManager->GetViewSpaceBox(),
1310                                                        castDoubleRays,
1311                                                        pruneInvalidRays);
1312               
1313        }
1314
1315}
1316
1317
1318bool Preprocessor::GenerateRayBundle(SimpleRayContainer &rayBundle,                                                                     
1319                                                                         const SimpleRay &mainRay,
1320                                                                         const int number,
1321                                                                         const int pertubType) const
1322{
1323        rayBundle.push_back(mainRay);
1324
1325        const float pertubOrigin = 0.0f;
1326        const float pertubDir = 0.2f;
1327
1328        for (int i = 0; i < number - 1; ++ i)
1329        {
1330                Vector3 pertub;
1331
1332                pertub.x = RandomValue(0.0f, pertubDir);
1333                pertub.y = RandomValue(0.0f, pertubDir);
1334                pertub.z = RandomValue(0.0f, pertubDir);
1335
1336                const Vector3 newDir = mainRay.mDirection + pertub;
1337                //const Vector3 newDir = mainRay.mDirection;
1338
1339                pertub.x = RandomValue(0.0f, pertubOrigin);
1340                pertub.y = RandomValue(0.0f, pertubOrigin);
1341                pertub.z = RandomValue(0.0f, pertubOrigin);
1342
1343                const Vector3 newOrigin = mainRay.mOrigin + pertub;
1344                //const Vector3 newOrigin = mainRay.mOrigin;
1345
1346                rayBundle.push_back(SimpleRay(newOrigin, newDir, 0, 1.0f));
1347        }
1348
1349        return true;
1350}
1351
1352
1353void Preprocessor::SetupRay(Ray &ray,
1354                                                        const Vector3 &point,
1355                                                        const Vector3 &direction) const
1356{
1357        ray.Clear();
1358        // do not store anything else then intersections at the ray
1359        ray.Init(point, direction, Ray::LOCAL_RAY);     
1360}
1361
1362
1363void Preprocessor::EvalViewCellHistogram()
1364{
1365        char filename[256];
1366        Environment::GetSingleton()->GetStringValue("Preprocessor.histogram.file", filename);
1367 
1368        // mViewCellsManager->EvalViewCellHistogram(filename, 1000000);
1369        mViewCellsManager->EvalViewCellHistogramForPvsSize(filename, 1000000);
1370}
1371
1372
1373bool
1374Preprocessor::ExportRays(const char *filename,
1375                                                 const VssRayContainer &vssRays,
1376                                                 const int number,
1377                                                 const bool exportScene
1378                                                 )
1379{
1380  cout<<"Exporting vss rays..."<<endl<<flush;
1381 
1382  Exporter *exporter = NULL;
1383  exporter = Exporter::GetExporter(filename);
1384
1385  if (0) {
1386        exporter->SetWireframe();
1387        exporter->ExportKdTree(*mKdTree);
1388  }
1389 
1390  exporter->SetFilled();
1391  // $$JB temporarily do not export the scene
1392  if (exportScene)
1393        exporter->ExportScene(mSceneGraph->GetRoot());
1394
1395  exporter->SetWireframe();
1396
1397  if (1) {
1398        exporter->SetForcedMaterial(RgbColor(1,0,1));
1399        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1400        exporter->ResetForcedMaterial();
1401  }
1402 
1403  VssRayContainer rays;
1404  vssRays.SelectRays(number, rays);
1405  exporter->ExportRays(rays, RgbColor(1, 0, 0));
1406  delete exporter;
1407  cout<<"done."<<endl<<flush;
1408
1409  return true;
1410}
1411
1412bool
1413Preprocessor::ExportRayAnimation(const char *filename,
1414                                                                 const vector<VssRayContainer> &vssRays
1415                                                                 )
1416{
1417  cout<<"Exporting vss rays..."<<endl<<flush;
1418       
1419  Exporter *exporter = NULL;
1420  exporter = Exporter::GetExporter(filename);
1421  if (0) {
1422        exporter->SetWireframe();
1423        exporter->ExportKdTree(*mKdTree);
1424  }
1425  exporter->SetFilled();
1426  // $$JB temporarily do not export the scene
1427  if (0)
1428        exporter->ExportScene(mSceneGraph->GetRoot());
1429  exporter->SetWireframe();
1430
1431  if (1) {
1432        exporter->SetForcedMaterial(RgbColor(1,0,1));
1433        exporter->ExportBox(mViewCellsManager->GetViewSpaceBox());
1434        exporter->ResetForcedMaterial();
1435  }
1436 
1437  exporter->ExportRaySets(vssRays, RgbColor(1, 0, 0));
1438       
1439  delete exporter;
1440
1441  cout<<"done."<<endl<<flush;
1442
1443  return true;
1444}
1445
1446void
1447Preprocessor::ComputeRenderError()
1448{
1449  // compute rendering error   
1450  if (renderer && renderer->mPvsStatFrames) {
1451       
1452        if (!mViewCellsManager->GetViewCellPointsList()->empty())
1453        {
1454         
1455          ViewCellPointsList *vcPoints = mViewCellsManager->GetViewCellPointsList();
1456         
1457          ViewCellPointsList::const_iterator
1458                vit = vcPoints->begin(),
1459                vit_end = vcPoints->end();
1460
1461          SimpleRayContainer viewPoints;
1462         
1463          for (; vit != vit_end; ++ vit) {
1464                ViewCellPoints *vp = *vit;
1465
1466                SimpleRayContainer::const_iterator rit = vp->second.begin(), rit_end = vp->second.end();
1467                for (; rit!=rit_end; ++rit)
1468                  viewPoints.push_back(*rit);
1469          }
1470         
1471          if (viewPoints.size() != renderer->mPvsErrorBuffer.size()) {
1472                renderer->mPvsErrorBuffer.resize(viewPoints.size());
1473                renderer->ClearErrorBuffer();
1474          }
1475
1476          cout << "evaluating list of " << viewPoints.size() << " pts" << endl;
1477          renderer->EvalPvsStat(viewPoints);
1478        } else
1479        {
1480                cout << "evaluating random points" << endl;
1481          renderer->EvalPvsStat();
1482        }
1483
1484        mStats <<
1485          "#AvgPvsRenderError\n" <<renderer->mPvsStat.GetAvgError()<<endl<<
1486          "#AvgPixelError\n" <<renderer->GetAvgPixelError()<<endl<<
1487          "#MaxPixelError\n" <<renderer->GetMaxPixelError()<<endl<<
1488          "#MaxPvsRenderError\n" <<renderer->mPvsStat.GetMaxError()<<endl<<
1489          "#ErrorFreeFrames\n" <<renderer->mPvsStat.GetErrorFreeFrames()<<endl<<
1490          "#AvgRenderPvs\n" <<renderer->mPvsStat.GetAvgPvs()<<endl;
1491  }
1492}
1493
1494
1495Intersectable *Preprocessor::GetObjectById(const int id)
1496{
1497#if 1
1498        // create a dummy mesh instance to be able to use stl
1499        MeshInstance object(NULL);
1500        object.SetId(id);
1501
1502        ObjectContainer::const_iterator oit =
1503                lower_bound(mObjects.begin(), mObjects.end(), &object, ilt);
1504                               
1505        // objects sorted by id
1506        if ((oit != mObjects.end()) && ((*oit)->GetId() == object.GetId()))
1507        {
1508                return (*oit);
1509        }
1510        else
1511        {
1512                return NULL;
1513        }
1514#else
1515        return mObjects[id];
1516#endif
1517}
1518
1519
1520void Preprocessor::PrepareHwGlobalLines()
1521{
1522        int texHeight, texWidth;
1523        float eps;
1524        int maxDepth;
1525        bool sampleReverse;
1526
1527        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texHeight", texHeight);
1528        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.texWidth", texWidth);
1529        Environment::GetSingleton()->GetFloatValue("Preprocessor.HwGlobalLines.stepSize", eps);
1530        Environment::GetSingleton()->GetIntValue("Preprocessor.HwGlobalLines.maxDepth", maxDepth);
1531        Environment::GetSingleton()->GetBoolValue("Preprocessor.HwGlobalLines.sampleReverse", sampleReverse);
1532
1533        Debug << "****** hw global line options *******" << endl;
1534        Debug << "texWidth: " << texWidth << endl;
1535        Debug << "texHeight: " << texHeight << endl;
1536        Debug << "sampleReverse: " << sampleReverse << endl;
1537        Debug << "max depth: " << maxDepth << endl;
1538        Debug << "step size: " << eps << endl;
1539        Debug << endl;
1540
1541#ifdef USE_CG
1542        globalLinesRenderer = mGlobalLinesRenderer =
1543                new GlobalLinesRenderer(this,
1544                                                                texHeight,
1545                                                                texWidth,
1546                                                                eps,
1547                                                                maxDepth,
1548                                                                sampleReverse);
1549
1550        mGlobalLinesRenderer->InitGl();
1551
1552#endif
1553}
1554
1555
1556void Preprocessor::DeterminePvsObjects(VssRayContainer &rays)
1557{
1558  mViewCellsManager->DeterminePvsObjects(rays, false);
1559}
1560
1561
1562bool Preprocessor::LoadObjects(const string &filename,
1563                                                           ObjectContainer &pvsObjects,
1564                                                           const ObjectContainer &preprocessorObjects)
1565{
1566        ObjectsParser parser;
1567
1568        const bool success = parser.ParseObjects(filename,
1569                                                                                         pvsObjects,
1570                                                                                         preprocessorObjects);
1571
1572        if (!success)
1573        {
1574                Debug << "Error: loading objects failed!" << endl;
1575        }
1576
1577        // hack: no bvh object could be found => take preprocessor objects
1578        if (pvsObjects.empty())
1579        {
1580                Debug << "no objects" << endl;
1581                pvsObjects = preprocessorObjects;
1582        }
1583
1584        return success;
1585}
1586
1587
1588void Preprocessor::RegisterDynamicObject(SceneGraphLeaf *leaf)
1589{       
1590        mDynamicObjects.push_back(leaf);
1591
1592        const int currentId = (int)mObjects.size() + sCurrentDynamicId;
1593
1594        leaf->GetIntersectable()->SetId(currentId);
1595
1596        for (size_t i = 0; i < leaf->mGeometry.size(); ++ i)
1597        {
1598                leaf->mGeometry[i]->SetId(currentId);
1599        }
1600
1601        cout << "\**************\n******* new object has id " << currentId << endl;
1602
1603        ++ sCurrentDynamicId;
1604
1605        // tell ray caster to update
1606        ScheduleUpdateDynamicObjects();
1607
1608        if (0)
1609        {
1610                // add to scene graph
1611                mSceneGraph->GetRoot()->mChildren.push_back(leaf);
1612                // add to ray caster
1613                if (mRayCaster)
1614                        mRayCaster->AddDynamicObjecs(leaf->mGeometry, leaf->GetTransformation());
1615        }
1616        // $$ JB in order to compile
1617        //return leaf;
1618}
1619
1620
1621SceneGraphLeaf *Preprocessor::LoadDynamicGeometry(const string &filename)
1622{
1623        const bool dynamic = true;
1624        SceneGraphLeaf *leaf = new SceneGraphLeaf(dynamic);
1625
1626        bool parsed = false;
1627
1628        if (strstr(filename.c_str(), ".obj"))
1629        {
1630                cout<<"parsing obj file.."<<endl;
1631                ObjParser *p = new ObjParser;
1632                parsed = p->ParseFile(filename, leaf, false);
1633        }
1634        else
1635        {
1636                cout<<"parsing binary obj file ... " << endl;
1637                parsed = LoadBinaryObj(filename, leaf, NULL, 100);
1638        }
1639
1640        if (parsed)
1641        {
1642                ObjectContainer::const_iterator it, it_end = leaf->mGeometry.end();
1643
1644                for (it = leaf->mGeometry.begin(); it != it_end; ++ it)
1645                {
1646                        TriangleIntersectable *tri = static_cast<TriangleIntersectable *>(*it);
1647
1648                        Triangle3 t = tri->GetItem();
1649
1650                        // hack: scale object appropriately
1651                        float scale = 0.01f;
1652
1653                        t.mVertices[0] *= scale;
1654                        t.mVertices[1] *= scale;
1655                        t.mVertices[2] *= scale;
1656
1657                        tri->SetItem(t);
1658                }
1659
1660                leaf->UpdateBox();
1661
1662                float offs = -leaf->GetOriginalBox().Min().y;
1663
1664                // scale so pivot is always on bottom
1665                for (it = leaf->mGeometry.begin(); it != it_end; ++ it)
1666                {
1667                        TriangleIntersectable *tri = static_cast<TriangleIntersectable *>(*it);
1668
1669                        Triangle3 t = tri->GetItem();
1670
1671                        // hack: scale object appropriately
1672                        t.mVertices[0].y += offs;
1673                        t.mVertices[1].y += offs;
1674                        t.mVertices[2].y += offs;
1675
1676                        tri->SetItem(t);
1677                }
1678
1679                leaf->UpdateBox();
1680
1681
1682                cout<<"Dynamic object loaded successfully: " << leaf->GetBox() << endl;
1683
1684                return leaf;
1685        }
1686               
1687
1688        cout<<"Dynamic object loading failed."<<endl;
1689        return NULL;
1690}
1691
1692
1693/** Object has moved - must dynamically update all affected PVSs */
1694void
1695Preprocessor::ObjectMoved(SceneGraphLeaf *leaf)
1696{
1697  // first invalidate all PVS from which this object is visible
1698  ViewCellContainer::const_iterator vit, vit_end = mViewCellsManager->GetViewCells().end();
1699 
1700  AxisAlignedBox3 box = leaf->GetBox();
1701  Intersectable *inter = leaf->GetIntersectable();
1702  int removedEntries = 0;
1703  int removedSelfEntries = 0;
1704  CSeparatingAxisTester shadowVolume;
1705  int maxPlanes = 0;
1706  int allEntries = 0;
1707  // now search for pvss which contained any mailed node
1708  for (vit = mViewCellsManager->GetViewCells().begin(); vit != vit_end; ++ vit) {
1709        ObjectPvs &pvs = (*vit)->GetPvs();
1710        if (Overlap(box, (*vit)->GetBox())) {
1711          pvs.Clear();
1712          removedEntries += pvs.GetSize();
1713        } else {
1714          //    cout<<(*vit)->GetBox()<<" "<<box<<endl;
1715          shadowVolume.Init((*vit)->GetBox(), box);
1716          if (shadowVolume.CntPlanes() > maxPlanes)
1717                maxPlanes = shadowVolume.CntPlanes();
1718         
1719          int j = 0;
1720          for (int i=0; i < pvs.mEntries.size(); i++) {
1721                allEntries++;
1722                Intersectable *o = pvs.mEntries[i].mObject;
1723                if (o == inter) {
1724                  removedSelfEntries++;
1725                } else {
1726                  if (!shadowVolume.TestIsInsideShaft(o->GetBox())) {
1727                        if (j != i)
1728                          pvs.mEntries[j] = pvs.mEntries[i];
1729                        j++;
1730                  } else {
1731                        removedEntries++;
1732                  }
1733                }
1734          }
1735          // now the pvs has to be resorted
1736          pvs.mLastSorted = 0;
1737          if (j==0)
1738                pvs.mEntries.clear();
1739          else {
1740                pvs.mEntries.resize(j);
1741                if (j>1)
1742                  pvs.SimpleSort();
1743          }
1744        }
1745  }
1746 
1747  cerr<<"Number of removed pvs entries = "<<removedEntries<<" ("<<
1748        100.0f*removedEntries/(float)allEntries<<"%)"<<endl;
1749  cerr<<"Number of removed pvs self-entries = "<<removedSelfEntries<<endl;
1750  cerr<<"Max shadow planes used:"<<maxPlanes<<endl;
1751  //    cout<<"Cleared "<<pvsCounter<<" PVSs ("<<mViewCellsManager->GetViewCells().size()/
1752  //      (float)pvsCounter*100.0f<<"%) "<<endl;
1753 
1754}
1755
1756
1757void Preprocessor::ObjectRemoved(SceneGraphLeaf *leaf)
1758{
1759        ObjectMoved(leaf);
1760}
1761
1762
1763void Preprocessor::UpdateDynamicObjects()
1764{
1765        if (mUpdateDynamicObjects)
1766        {
1767
1768          // delete ALL dynamic stuff and rebuild using the new trafos
1769          preprocessor->mRayCaster->DeleteDynamicObjects();
1770         
1771#define MULTIPLE_OBJECTS 0
1772#define CREATE_TRANSF_COPIES_OF_DYN_OBJECTS      1
1773
1774#if MULTIPLE_OBJECTS
1775#if CREATE_TRANSF_COPIES_OF_DYN_OBJECTS
1776          static ObjectContainer objects;
1777         
1778          if (objects.size()) {
1779                for (size_t i = 0; i < objects.size(); ++ i) {
1780                  delete objects[i];
1781                }
1782                objects.clear();
1783          }
1784         
1785          for (size_t i = 0; i < mDynamicObjects.size(); ++ i) {
1786                SceneGraphLeaf *l = mDynamicObjects[i];
1787                for (int j=0; j < l->mGeometry.size(); j++) {
1788                  if (l->mGeometry[j]->Type() == Intersectable::TRIANGLE_INTERSECTABLE) {
1789                        Triangle3 t(((TriangleIntersectable *)l->mGeometry[j])->GetItem());
1790                        t.ApplyTransformation(l->GetTransformation());
1791                        objects.push_back(new TriangleIntersectable(t));
1792                  }
1793                }
1794          }
1795          mRayCaster->AddDynamicObjecs(objects, IdentityMatrix());
1796#else
1797          mRayCaster->AddDynamicObjecs(objects, IdentityMatrix());
1798#endif
1799#endif   
1800
1801          SceneGraphLeaf *toUpdate = NULL;
1802         
1803          for (size_t i = 0; i < mDynamicObjects.size(); ++ i)
1804                {
1805                  SceneGraphLeaf *l = mDynamicObjects[i];
1806
1807#if  !MULTIPLE_OBJECTS
1808                  UpdateObjectInRayCaster(l);
1809#endif
1810
1811                  if (l->HasChanged())
1812                        {
1813                         
1814                          cout<<"Updating affected PVSs..."<<endl;
1815                          preprocessor->ObjectMoved(l);
1816                          cout<<"done."<<endl; 
1817                          l->SetHasChanged(false);
1818                        }
1819                }
1820
1821
1822          mUpdateDynamicObjects = false;
1823         
1824        }
1825}
1826
1827
1828void Preprocessor::ScheduleUpdateDynamicObjects()
1829{
1830        mUpdateDynamicObjects = true;
1831}
1832
1833
1834void Preprocessor::UpdateObjectInRayCaster(SceneGraphLeaf *l)
1835{
1836        cout<<"Updating dynamic objects in ray caster..."<<endl;
1837
1838        mRayCaster->AddDynamicObjecs(l->mGeometry, l->GetTransformation());
1839        cout<<"done."<<endl;
1840}
1841
1842}
Note: See TracBrowser for help on using the repository browser.