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

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