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

Revision 2012, 38.7 KB checked in by bittner, 17 years ago (diff)

vss ray updates

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