source: GTP/trunk/Lib/Vis/Preprocessing/src/GlRenderer.cpp @ 1581

Revision 1581, 12.5 KB checked in by bittner, 18 years ago (diff)

Qtglwidget changes - second view + trackball - ray casting seems not functional

  • Property svn:executable set to *
Line 
1#include "Mesh.h"
2#include "glInterface.h"
3#include "OcclusionQuery.h"
4#include "GlRenderer.h"
5#include "ViewCellsManager.h"
6#include "SceneGraph.h"
7#include "Pvs.h"
8#include "Viewcell.h"
9#include "Beam.h"
10#include "KdTree.h"
11#include "Environment.h"
12#include "Triangle3.h"
13#include "IntersectableWrapper.h"
14
15//#include <Cg/cg.h>
16//#include <Cg/cgGL.h>
17
18
19namespace GtpVisibilityPreprocessor {
20
21
22static bool arbQuerySupport = false;
23static bool nvQuerySupport = false;
24
25
26static void InitExtensions()
27{
28        GLenum err = glewInit();
29
30        if (GLEW_OK != err)
31        {
32                // problem: glewInit failed, something is seriously wrong
33                cerr << "Error: " << glewGetErrorString(err) << endl;
34                exit(1);
35        }
36
37        if (GLEW_ARB_occlusion_query)
38                arbQuerySupport = true;
39       
40        if (GLEW_NV_occlusion_query)
41                nvQuerySupport = true;
42       
43
44        if  (!arbQuerySupport && !nvQuerySupport)
45        {
46                cout << "I require the GL_ARB_occlusion_query or the GL_NV_occlusion_query OpenGL extension to work.\n";
47                exit(1);
48        }
49}
50
51
52GlRenderer::GlRenderer(SceneGraph *sceneGraph,
53                                           ViewCellsManager *viewCellsManager,
54                                           KdTree *tree):
55  Renderer(sceneGraph, viewCellsManager),
56  mKdTree(tree)
57{
58  mSceneGraph->CollectObjects(&mObjects);
59
60  //  mViewCellsManager->GetViewPoint(mViewPoint);
61
62  mViewPoint = mSceneGraph->GetBox().Center();
63  mViewDirection = Vector3(0,0,1);
64
65  //  mViewPoint = Vector3(991.7, 187.8, -271);
66  //  mViewDirection = Vector3(0.9, 0, -0.4);
67
68  //  timerId = startTimer(10);
69  // debug coords for atlanta
70  //  mViewPoint = Vector3(3473, 6.778, -1699);
71  //  mViewDirection = Vector3(-0.2432, 0, 0.97);
72 
73  mFrame = 0;
74  mWireFrame = false;
75  Environment::GetSingleton()->GetBoolValue("Preprocessor.detectEmptyViewSpace", mDetectEmptyViewSpace);
76  mSnapErrorFrames = true;
77  mSnapPrefix = "snap/";
78  mUseForcedColors = false;
79
80  mUseGlLists = true;
81  //mUseGlLists = false;
82}
83
84GlRenderer::~GlRenderer()
85{
86  cerr<<"gl renderer destructor..\n";
87 
88  //CLEAR_CONTAINER(sQueries);
89  CLEAR_CONTAINER(mOcclusionQueries);
90
91  cerr<<"done."<<endl;
92}
93
94
95void
96GlRenderer::RenderTriangle(TriangleIntersectable *object)
97{
98  Triangle3 &t = object->GetItem();
99  glBegin(GL_TRIANGLES);
100  glVertex3f(t.mVertices[0].x, t.mVertices[0].y, t.mVertices[0].z);
101  glVertex3f(t.mVertices[1].x, t.mVertices[1].y, t.mVertices[1].z);
102  glVertex3f(t.mVertices[2].x, t.mVertices[2].y, t.mVertices[2].z);
103  glEnd();
104}
105
106void
107GlRenderer::RenderIntersectable(Intersectable *object)
108{
109
110  glPushAttrib(GL_CURRENT_BIT);
111  if (mUseFalseColors)
112        SetupFalseColor(object->mId);
113 
114
115  switch (object->Type()) {
116  case Intersectable::MESH_INSTANCE:
117        RenderMeshInstance((MeshInstance *)object);
118        break;
119  case Intersectable::VIEW_CELL:
120        RenderViewCell(dynamic_cast<ViewCell *>(object));
121        break;
122  case Intersectable::TRANSFORMED_MESH_INSTANCE:
123        RenderTransformedMeshInstance(dynamic_cast<TransformedMeshInstance *>(object));
124        break;
125  case Intersectable::TRIANGLE_INTERSECTABLE:
126        RenderTriangle(dynamic_cast<TriangleIntersectable *>(object));
127        break;
128  default:
129        cerr<<"Rendering this object not yet implemented\n";
130        break;
131  }
132
133  glPopAttrib();
134}
135
136void
137GlRenderer::RenderRays(const VssRayContainer &rays)
138{
139  VssRayContainer::const_iterator it = rays.begin(), it_end = rays.end();
140
141  glBegin(GL_LINES);
142  for (; it != it_end; ++it) {
143        VssRay *ray = *it;
144        float importance = log10(1e3*ray->mWeightedPvsContribution)/3.0f;
145        //      cout<<"w="<<ray->mWeightedPvsContribution<<" r="<<ray->mWeightedPvsContribution;
146        glColor3f(importance, importance, importance);
147        glVertex3fv(&ray->mOrigin.x);
148        glVertex3fv(&ray->mTermination.x);
149  }
150  glEnd();
151}
152
153void
154GlRenderer::RenderViewCell(ViewCell *vc)
155{
156  if (vc->GetMesh()) {
157
158        if (!mUseFalseColors) {
159          if (vc->GetValid())
160                glColor3f(0,1,0);
161          else
162                glColor3f(0,0,1);
163        }
164       
165        RenderMesh(vc->GetMesh());
166  } else {
167        // render viewcells in the subtree
168        if (!vc->IsLeaf()) {
169          ViewCellInterior *vci = (ViewCellInterior *) vc;
170
171          ViewCellContainer::iterator it = vci->mChildren.begin();
172          for (; it != vci->mChildren.end(); ++it) {
173                RenderViewCell(*it);
174          }
175        } else {
176          //      cerr<<"Empty viewcell mesh\n";
177        }
178  }
179}
180
181
182void
183GlRenderer::RenderMeshInstance(MeshInstance *mi)
184{
185  RenderMesh(mi->GetMesh());
186}
187
188
189void
190GlRenderer::RenderTransformedMeshInstance(TransformedMeshInstance *mi)
191{
192        // apply world transform before rendering
193        Matrix4x4 m;
194        mi->GetWorldTransform(m);
195
196        glPushMatrix();
197/* cout << "\n";
198        for (int i = 0; i < 4; ++ i)
199                for (int j = 0; j < 4; ++ j)
200                        cout << m.x[i][j] << " "; cout << "\n"*/
201
202        glMultMatrixf((float *)m.x);
203
204        /*GLfloat dummy[16];
205        glGetFloatv(GL_MODELVIEW_MATRIX, dummy);
206        for (int i = 0; i < 16; ++ i)
207                cout << dummy[i] << " ";
208        cout << endl;*/
209        RenderMesh(mi->GetMesh());
210       
211        glPopMatrix();
212}
213
214
215void
216GlRenderer::SetupFalseColor(const int id)
217{
218  // swap bits of the color
219  glColor3ub(id&255, (id>>8)&255, (id>>16)&255);
220}
221
222
223int GlRenderer::GetId(int r, int g, int b) const
224{
225        return r + (g << 8) + (b << 16);
226}
227
228void
229GlRenderer::SetupMaterial(Material *m)
230{
231  if (m)
232        glColor3fv(&(m->mDiffuseColor.r));
233}
234
235void
236GlRenderer::RenderMesh(Mesh *mesh)
237{
238  int i = 0;
239
240  if (!mUseFalseColors && !mUseForcedColors)
241        SetupMaterial(mesh->mMaterial);
242 
243  for (i=0; i < mesh->mFaces.size(); i++) {
244        if (mWireFrame)
245          glBegin(GL_LINE_LOOP);
246        else
247          glBegin(GL_POLYGON);
248
249        Face *face = mesh->mFaces[i];
250        for (int j = 0; j < face->mVertexIndices.size(); j++) {
251          glVertex3fv(&mesh->mVertices[face->mVertexIndices[j]].x);
252        }
253        glEnd();
254  }
255}
256       
257void
258GlRenderer::InitGL()
259{
260  glMatrixMode(GL_PROJECTION);
261  glLoadIdentity();
262 
263  glMatrixMode(GL_MODELVIEW);
264  glLoadIdentity();
265
266  glEnable(GL_CULL_FACE);
267  glShadeModel(GL_FLAT);
268  glEnable(GL_DEPTH_TEST);
269  glEnable(GL_CULL_FACE);
270 
271  InitExtensions();
272 
273#if 0
274  GLfloat mat_ambient[]   = {  0.5, 0.5, 0.5, 1.0  };
275  /*  mat_specular and mat_shininess are NOT default values     */
276  GLfloat mat_diffuse[]   = {  1.0, 1.0, 1.0, 1.0  };
277  GLfloat mat_specular[]  = {  0.3, 0.3, 0.3, 1.0  };
278  GLfloat mat_shininess[] = {  1.0  };
279 
280  GLfloat light_ambient[]  = {  0.2, 0.2, 0.2, 1.0  };
281  GLfloat light_diffuse[]  = {  0.4, 0.4, 0.4, 1.0  };
282  GLfloat light_specular[] = {  0.3, 0.3, 0.3, 1.0  };
283 
284  GLfloat lmodel_ambient[] = {  0.3, 0.3, 0.3, 1.0  };
285 
286 
287  // default Material
288  glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
289  glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
290  glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
291  glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
292
293  // a light
294  glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
295  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
296  glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
297 
298  glLightfv(GL_LIGHT1, GL_AMBIENT, light_ambient);
299  glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
300  glLightfv(GL_LIGHT1, GL_SPECULAR, light_specular);
301 
302  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
303 
304  glEnable(GL_LIGHTING);
305  glEnable(GL_LIGHT0);
306  glEnable(GL_LIGHT1);
307 
308 
309  // set position of the light
310  GLfloat infinite_light[] = {  1.0, 0.8, 1.0, 0.0  };
311  glLightfv (GL_LIGHT0, GL_POSITION, infinite_light);
312 
313  // set position of the light2
314  GLfloat infinite_light2[] = {  -0.3, 1.5, 1.0, 0.0  };
315  glLightfv (GL_LIGHT1, GL_POSITION, infinite_light2);
316 
317  glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
318  //   glColorMaterial( GL_FRONT_AND_BACK, GL_SPECULAR);
319  glEnable(GL_COLOR_MATERIAL);
320 
321  glShadeModel( GL_FLAT );
322 
323  glDepthFunc( GL_LESS );
324  glEnable( GL_DEPTH_TEST );
325#endif
326
327  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
328
329  glEnable( GL_NORMALIZE );
330 
331  glClearColor(0.0f, 0.0f, 1.0f, 1.0f);
332}
333
334
335void
336GlRenderer::SetupProjection(const int w, const int h, const float angle)
337{
338  glViewport(0, 0, w, h);
339  glMatrixMode(GL_PROJECTION);
340  glLoadIdentity();
341  gluPerspective(angle, 1.0, 0.1, 2.0*Magnitude(mSceneGraph->GetBox().Diagonal()));
342  glMatrixMode(GL_MODELVIEW);
343}
344
345
346
347void
348GlRenderer::SetupCamera()
349{
350  Vector3 target = mViewPoint + mViewDirection;
351
352  Vector3 up(0,1,0);
353 
354  if (abs(DotProd(mViewDirection, up)) > 0.99f)
355        up = Vector3(1, 0, 0);
356 
357  glLoadIdentity();
358  gluLookAt(mViewPoint.x, mViewPoint.y, mViewPoint.z,
359                        target.x, target.y, target.z,
360                        up.x, up.y, up.z);
361}
362
363void
364GlRenderer::_RenderScene()
365{
366  ObjectContainer::const_iterator oi = mObjects.begin();
367
368  for (; oi != mObjects.end(); oi++)
369        RenderIntersectable(*oi);
370}
371
372bool
373GlRenderer::RenderScene()
374{
375  static int glList = -1;
376  if (mUseGlLists) {
377        if (glList == -1) {
378          glList = glGenLists(1);
379          glNewList(glList, GL_COMPILE);
380          _RenderScene();
381          glEndList();
382        }
383        glCallList(glList);
384  } else
385        _RenderScene();
386       
387 
388  return true;
389}
390
391
392void
393GlRendererBuffer::EvalQueryWithItemBuffer(
394                                                                                  //RenderCostSample &sample
395                                                                           )
396{
397        // read back the texture
398        glReadPixels(0, 0,
399                                GetWidth(), GetHeight(),
400                                GL_RGBA,
401                                GL_UNSIGNED_BYTE,
402                                mPixelBuffer);
403               
404                       
405        unsigned int *p = mPixelBuffer;
406                       
407        for (int y = 0; y < GetHeight(); y++)
408        {
409                for (int x = 0; x < GetWidth(); x++, p++)
410                {
411                        unsigned int id = (*p) & 0xFFFFFF;
412
413                        if (id != 0xFFFFFF)
414                                ++ mObjects[id]->mCounter;
415                }
416        }
417}
418
419
420
421/****************************************************************/
422/*               GlRendererBuffer implementation                */
423/****************************************************************/
424
425
426
427GlRendererBuffer::GlRendererBuffer(SceneGraph *sceneGraph,
428                                                                   ViewCellsManager *viewcells,
429                                                                   KdTree *tree):
430GlRenderer(sceneGraph, viewcells, tree) 
431{
432        mPixelBuffer = NULL;
433
434        // implement width and height in subclasses
435}
436
437
438void
439GlRendererBuffer::EvalQueryWithOcclusionQueries(
440                                                                           //RenderCostSample &sample
441                                                                           )
442{
443        glDepthFunc(GL_LEQUAL);
444               
445        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
446        glDepthMask(GL_FALSE);
447
448
449        // simulate detectemptyviewspace using backface culling
450        if (mDetectEmptyViewSpace)
451        {
452                glEnable(GL_CULL_FACE);
453                //cout << "culling" << endl;
454        }
455        else
456        {
457                //cout << "not culling" << endl;
458                glDisable(GL_CULL_FACE);
459        }
460
461       
462        //const int numQ = 1;
463        const int numQ = (int)mOcclusionQueries.size();
464       
465        //glFinish();
466#if 0
467        //-- now issue queries for all objects
468        for (int j = 0; j < (int)mObjects.size(); ++ j)
469        {
470                mOcclusionQueries[j]->BeginQuery();
471                RenderIntersectable(mObjects[j]);
472                mOcclusionQueries[j]->EndQuery();
473
474                unsigned int pixelCount;
475
476                pixelCount = mOcclusionQueries[j]->GetQueryResult();
477                mObjects[j]->mCounter += pixelCount;
478        }
479#else
480
481        int q = 0;
482
483        //-- now issue queries for all objects
484        for (int j = 0; j < (int)mObjects.size(); j += q)
485        {       
486                for (q = 0; ((j + q) < (int)mObjects.size()) && (q < numQ); ++ q)
487                {
488                        //glFinish();
489                        mOcclusionQueries[q]->BeginQuery();
490                       
491                        RenderIntersectable(mObjects[j + q]);
492               
493                        mOcclusionQueries[q]->EndQuery();
494                        //glFinish();
495                }
496                //cout << "q: " << q << endl;
497                // collect results of the queries
498                for (int t = 0; t < q; ++ t)
499                {
500                        unsigned int pixelCount;
501               
502                        //-- reenable other state
503#if 0
504                        bool available;
505
506                        do
507                        {
508                                available = mOcclusionQueries[t]->ResultAvailable();
509                               
510                                if (!available) cout << "W";
511                        }
512                        while (!available);
513#endif
514
515                        pixelCount = mOcclusionQueries[t]->GetQueryResult();
516
517                        //if (pixelCount > 0)
518                        //      cout <<"o="<<j+q<<" q="<<mOcclusionQueries[q]->GetQueryId()<<" pc="<<pixelCount<<" ";
519                        mObjects[j + t]->mCounter += pixelCount;
520                }
521
522                //j += q;
523        }
524#endif
525        //glFinish();
526        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
527        glDepthMask(GL_TRUE);
528       
529        glEnable(GL_CULL_FACE);
530}
531
532
533void
534GlRendererBuffer::RandomViewPoint()
535{
536  // do not use this function since it could return different viewpoints for
537  // different executions of the algorithm
538
539  //  mViewCellsManager->GetViewPoint(mViewPoint);
540
541  while (1) {
542        Vector3 pVector = Vector3(halton.GetNumber(1),
543                                                          halton.GetNumber(2),
544                                                          halton.GetNumber(3));
545       
546        mViewPoint =  mViewCellsManager->GetViewSpaceBox().GetPoint(pVector);
547        ViewCell *v = mViewCellsManager->GetViewCell(mViewPoint);
548        if (v && v->GetValid())
549          break;
550        // generate a new vector
551        halton.GenerateNext();
552  }
553 
554  Vector3 dVector = Vector3(2*M_PI*halton.GetNumber(4),
555                                                        M_PI*halton.GetNumber(5),
556                                                        0.0f);
557 
558  mViewDirection = Normalize(Vector3(sin(dVector.x),
559                                                                         //                                                                      cos(dVector.y),
560                                                                         0.0f,
561                                                                         cos(dVector.x)));
562  halton.GenerateNext();
563}
564
565
566}
Note: See TracBrowser for help on using the repository browser.