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

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