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

Revision 2017, 38.9 KB checked in by mattausch, 17 years ago (diff)

changed to static cast

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