Subversion Repositories gelsvn

Rev

Rev 643 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
305 jab 1
#include <iostream>
2
#include <vector>
3
#include <algorithm>
4
#include <cmath>
5
 
596 jab 6
#include <GLGraphics/GLViewController.h>
653 janba 7
#include <GEL/GL/glew.h>
8
#ifdef __APPLE__
9
#include <GLUT/GLUT.h>
10
#else
11
#include <GL/glut.h>
12
#endif
305 jab 13
 
596 jab 14
#include <CGLA/Vec2f.h>
15
#include <CGLA/Vec3i.h>
16
#include <CGLA/Vec3f.h>
17
#include <CGLA/Vec3d.h>
18
#include <CGLA/Mat4x4f.h>
309 jab 19
 
596 jab 20
#include <HMesh/Manifold.h>
305 jab 21
 
596 jab 22
#include <Geometry/TriMesh.h>
23
#include <Geometry/obj_load.h>
24
#include <Geometry/Ray.h>
25
#include <Geometry/BSPTree.h>
26
#include <Geometry/build_bbtree.h>
27
#include <Geometry/AABox.h>
28
#include <Geometry/OBox.h>
29
 
30
#include <Util/Timer.h>
31
 
305 jab 32
#include "Camera.h"
33
 
643 janba 34
//#define USE_BSP
309 jab 35
 
305 jab 36
using namespace std;
37
using namespace CGLA;
38
using namespace Geometry;
309 jab 39
using namespace HMesh;
305 jab 40
using namespace GLGraphics;
41
 
309 jab 42
/*
43
 * TODO: 
44
 * - BBOX remove HMesh dependency - that is crazy.
45
 * - BBox visit child nodes in order of how far away the intersection point on
46
 *        the bbox is. Closest nodes visited first. Cull nodes farther than
47
 *        an actual intersection point.
48
 * - BBox Smooth interpolation of triangle normals. Straightforward.
49
 */
50
 
51
 
305 jab 52
namespace
53
{
310 jrf 54
  const int MAX_OBJECTS = 4;   // Maximum number of triangles in a BSP tree node
305 jab 55
  const int MAX_LEVEL = 20;    // Maximum number of BSP tree subdivisions
56
 
57
  const unsigned int TEX_SIZE = 512;
58
 
59
  bool raytrace = false;
60
  bool done = false;
61
  bool shadow = false;
62
 
63
  unsigned int winx = TEX_SIZE;     // Screen width
64
  unsigned int winy = TEX_SIZE;     // Screen height
65
 
66
  unsigned int PIXEL_SUBDIVS = 1;
67
 
68
  int mouse_state = GLUT_UP;
69
  int mouse_button = 0;
70
  int spin_timer = 20;
71
 
310 jrf 72
  GLViewController *vctrl;
305 jab 73
 
74
  TriMesh mesh;
322 jab 75
  vector<const TriMesh*> mesh_vector(1, &mesh);
305 jab 76
  vector<Mat4x4f> transforms(1, identity_Mat4x4f());
77
 
78
  double light_pow = 1.0;
79
  Vec3f light_dir = normalize(Vec3f(1.0, 1.0, 1.0));
80
  Vec3d background(0.8, 0.9, 1.0);
81
 
82
  BSPTree tree;
83
  Camera* cam;
84
 
85
  Vec3f image[TEX_SIZE][TEX_SIZE];
86
  unsigned int image_tex;
87
 
88
  // Function to generate a random number between 0 and 1.
417 jrf 89
  // gel_rand() returns a random number ranging from 0 to GEL_RAND_MAX.
305 jab 90
  inline double my_random()
91
  {
417 jrf 92
    return gel_rand()/static_cast<double>(GEL_RAND_MAX);
305 jab 93
  }
309 jab 94
 
310 jrf 95
  AABBTree bb_tree;		
305 jab 96
}
97
 
98
void spin(int x);
99
 
100
//////////////////////////////////////////////////////////////
101
//      I N I T I A L I Z A T I O N               
102
//////////////////////////////////////////////////////////////
103
 
104
void init_texture(unsigned int& tex)
105
{
322 jab 106
  glGenTextures(1, reinterpret_cast<GLuint*>(&tex));
305 jab 107
 
108
  glBindTexture(GL_TEXTURE_2D, tex);
109
 
110
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
111
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
112
 
113
  // load the texture image
114
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 
418 jrf 115
	             TEX_SIZE, TEX_SIZE,
116
	             0, GL_RGB, GL_FLOAT, image[0][0].get());
305 jab 117
}
118
 
119
void initRaytracer()
120
{
121
  Vec3f c;
122
  float r;
123
  mesh.get_bsphere(c, r);
124
  r *= 1.5;
125
 
126
  // Initialize track ball
310 jrf 127
  vctrl = new GLViewController(winx, winy, c, r);
305 jab 128
 
129
  // Initialize corresponding camera
418 jrf 130
  cam = new Camera(c - Vec3f(r), c, Vec3f(0.0f, 1.0f, 0.0f), 1.0f);
305 jab 131
 
312 jrf 132
#ifdef USE_BSP
309 jab 133
   cout << "Constructing BSP tree..." << endl;
134
   tree.init(mesh_vector, transforms, MAX_OBJECTS, MAX_LEVEL);
135
   tree.build();
136
#else
137
	// AABB TREE
138
	Manifold m;
139
	vector<int> faces(mesh.geometry.no_faces(), 3);
140
	cout << "Creating manifold" << endl;
643 janba 141
    m.build(mesh.geometry.no_vertices(),
142
            reinterpret_cast<const float*>(&mesh.geometry.vertex(0)),
143
            faces.size(),
144
            &faces[0],
145
            reinterpret_cast<const int*>(&mesh.geometry.face(0)));
309 jab 146
	cout << "Building tree" << endl;
147
	build_AABBTree(m, bb_tree);
148
#endif
305 jab 149
}
150
 
151
void initGL()
152
{
153
  glShadeModel(GL_SMOOTH); 
309 jab 154
  glDisable(GL_CULL_FACE);
305 jab 155
  glFrontFace(GL_CCW);
156
 
157
  glClearColor(1.0, 1.0, 1.0, 1.0);
158
  glColor3f(0.0, 0.0, 0.0);
159
}
160
 
161
 
162
//////////////////////////////////////////////////////////////
163
//      S H A D E   F U N C T I O N S
164
//////////////////////////////////////////////////////////////
165
 
166
double shadow_shade(Ray& r)
167
{
168
  r.compute_position();
169
  Ray shadow(r.hit_pos, light_dir);
170
  double s = tree.intersect(shadow) ? 0.0 : 1.0;
171
 
172
  r.compute_normal();
173
  return s*light_pow*dot(r.hit_normal, light_dir);
174
}
175
 
176
double lambertian_shade(Ray& r)
177
{
312 jrf 178
#ifdef USE_BSP
418 jrf 179
	r.compute_normal();
309 jab 180
#endif
305 jab 181
  return light_pow*dot(r.hit_normal, light_dir);
182
}
183
 
184
double (*shade_ray[2])(Ray&) = { lambertian_shade,
418 jrf 185
				                         shadow_shade      };
305 jab 186
 
187
//////////////////////////////////////////////////////////////
188
//      D R A W   F U N C T I O N S
189
//////////////////////////////////////////////////////////////
190
 
191
/*
192
void enable_textures(TriMesh& tm)
193
{
194
  for(unsigned int i=0;i<tm.materials.size(); ++i)
195
  {
196
    Material& mat = tm.materials[i];
197
    if(mat.tex_name != "")
198
    {
199
      string name = mat.tex_path + mat.tex_name;
200
 
201
      GLuint tex_id;
202
      if(load_image_into_texture(name, tex_id))
203
	mat.tex_id = tex_id;
204
    }
205
  }
206
}
207
*/
208
 
209
void set_perspective_proj()
210
{
211
  glMatrixMode(GL_PROJECTION);	 
212
  glLoadIdentity();            
213
 
214
  gluPerspective(64.0, 1.0, 0.1, 1000.0);
215
 
216
  glMatrixMode(GL_MODELVIEW);
217
}
218
 
219
void set_ortho_proj()
220
{
221
  glMatrixMode(GL_PROJECTION);	 
222
  glLoadIdentity();             
223
 
224
  glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
225
 
226
  glMatrixMode(GL_MODELVIEW);  
227
}
228
 
229
void draw_texture(unsigned int tex)
230
{
231
  static GLfloat verts[] = { 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
232
 
233
  glColor4f(1.0, 1.0, 1.0, 1.0);
234
 
235
  glBindTexture(GL_TEXTURE_2D, tex);
236
  glEnable(GL_TEXTURE_2D);
237
 
238
  glEnableClientState(GL_VERTEX_ARRAY);
239
  glEnableClientState(GL_TEXTURE_COORD_ARRAY);
240
 
241
  glVertexPointer(2, GL_FLOAT, 0, verts);
242
  glTexCoordPointer(2, GL_FLOAT, 0, verts);
243
 
244
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
245
 
246
  glDisableClientState(GL_VERTEX_ARRAY);
247
  glDisableClientState(GL_TEXTURE_COORD_ARRAY);
248
 
249
  glDisable(GL_TEXTURE_2D);
250
}
251
 
252
void drawOBJ()
253
{
254
  static bool washere = false;
255
  static unsigned int disp_list;
256
 
257
  if(!washere)
258
  {
259
    disp_list = glGenLists(1);
260
    glNewList(disp_list, GL_COMPILE);
261
 
262
    glBegin(GL_TRIANGLES);
418 jrf 263
    for(int i = 0; i < mesh.geometry.no_faces(); ++i)
264
    {
265
      Vec3i n_face = mesh.normals.face(i);
266
      Vec3i g_face = mesh.geometry.face(i);
267
      for(int j=0;j<3;j++)
305 jab 268
      {
418 jrf 269
        double shade = 0.5;
305 jab 270
 
418 jrf 271
        if(n_face != Geometry::NULL_FACE)
272
        {
273
          Vec3f norm = normalize(mesh.normals.vertex(n_face[j]));
274
          glNormal3fv(norm.get());
275
          shade = light_pow*dot(norm, light_dir);
276
        }
305 jab 277
 
418 jrf 278
        glColor3d(shade, shade, shade);
279
        Vec3f vert = mesh.geometry.vertex(g_face[j]);	  
280
        glVertex3fv(vert.get());
305 jab 281
      }
418 jrf 282
    }
305 jab 283
    glEnd();
284
 
285
    glEndList();
286
    washere = true;
287
  }
288
  glCallList(disp_list);
289
}
290
 
291
 
292
//////////////////////////////////////////////////////////////
293
//      G L U T   C A L L B A C K   F U N C T I O N S                 
294
//////////////////////////////////////////////////////////////
295
 
296
void display()
297
{
298
  static bool first = true;
299
 
300
  if(first)
301
  {
302
    first = false;
303
    glutTimerFunc(spin_timer, spin, 0);
304
  }
305
 
306
  Vec3f eye, focus, up;
309 jab 307
	vctrl->get_view_param(eye, focus, up);
308
	cam->set(eye, focus, up, cam->get_focal_dist());
309
 
305 jab 310
  if(raytrace)
311
  {
312
    raytrace = false;
313
 
314
    cout << "Raytracing";
315
    float win_to_vp = 1.0f/static_cast<float>(TEX_SIZE);
316
    float lowerleft = 0.5 + win_to_vp*0.5;
317
    float step = win_to_vp/static_cast<float>(PIXEL_SUBDIVS);
318
 
319
    vector<Vec2f> jitter(PIXEL_SUBDIVS*PIXEL_SUBDIVS); 
320
    for(unsigned int i = 0; i < PIXEL_SUBDIVS; ++i)
321
      for(unsigned int j = 0; j < PIXEL_SUBDIVS; ++j)
322
      {
418 jrf 323
	      jitter[i*PIXEL_SUBDIVS + j][0] = (my_random() + (j%PIXEL_SUBDIVS))*step; 
324
	      jitter[i*PIXEL_SUBDIVS + j][1] = (my_random() + (i%PIXEL_SUBDIVS))*step; 
305 jab 325
      }
326
 
418 jrf 327
    Util::Timer tim;
328
    tim.start();
305 jab 329
    for(unsigned int i = 0; i < TEX_SIZE; ++i)
330
    {
418 jrf 331
	    for(unsigned int j = 0; j < TEX_SIZE; ++j)
332
	    {
333
		    Vec3d sum(0.0f);
334
		    Vec2f vp_pos(j*win_to_vp - lowerleft, i*win_to_vp - lowerleft);
335
 
336
		    for(unsigned int ky = 0; ky < PIXEL_SUBDIVS; ++ky)
337
		      for(unsigned int kx = 0; kx < PIXEL_SUBDIVS; ++kx)
338
		      {
339
			      Ray r = cam->get_ray(vp_pos + jitter[ky*PIXEL_SUBDIVS + kx]);
305 jab 340
 
312 jrf 341
#ifdef USE_BSP
418 jrf 342
			      if(tree.intersect(r))
343
			        sum += Vec3d(shade_ray[shadow](r));
344
			      else
345
			        sum += background;
309 jab 346
#else
418 jrf 347
			      float t = FLT_MAX;
348
			      bb_tree.intersect(r);
349
			      if(r.has_hit)
350
			        sum += Vec3d(shade_ray[0](r));
351
			      else 
352
			        sum += background;
309 jab 353
#endif		
418 jrf 354
		      }
355
	      image[i][j] = Vec3f(sum/static_cast<double>(PIXEL_SUBDIVS*PIXEL_SUBDIVS));
356
      }
357
      if(((i + 1) % 50) == 0) cerr << ".";
358
    }
359
	  cout << " - " << tim.get_secs() << " secs " << endl;
305 jab 360
    cout << endl;
361
 
362
    init_texture(image_tex);
363
 
364
    done = true;
365
  }
366
 
367
  if(done)
368
  {
369
    set_ortho_proj();
370
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
371
    glLoadIdentity();
372
 
373
    draw_texture(image_tex);
374
  }
375
  else
376
  {
377
    glEnable(GL_DEPTH_TEST);
378
 
379
    cam->glSetPerspective(winx, winy);
380
 
381
    glClearColor(background[0], background[1], background[2], 1.0);
382
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
383
    glLoadIdentity();
384
 
418 jrf 385
	  cam->glSetCamera();
305 jab 386
 
387
    glColor3f(0.5, 0.5, 0.5);
388
    drawOBJ();
389
 
390
    glDisable(GL_DEPTH_TEST);
391
  }
392
 
393
  glutSwapBuffers();  
394
}
395
 
396
void reshape(int w, int h)
397
{
398
  winx = w; winy = h;
399
 
309 jab 400
  vctrl->reshape(winx, winy);
305 jab 401
 
402
  glViewport(0, 0, winx, winy);
403
}
404
 
405
void keyboard(unsigned char key, int x, int y)
406
{
407
  switch(key)
408
  {
409
  case '+':
410
    ++PIXEL_SUBDIVS;
411
    cout << "Rays per pixel: " << PIXEL_SUBDIVS*PIXEL_SUBDIVS << endl;
412
    break;
413
  case '-':
414
    if(PIXEL_SUBDIVS > 1)
415
      --PIXEL_SUBDIVS;
416
    cout << "Rays per pixel: " << PIXEL_SUBDIVS*PIXEL_SUBDIVS << endl;
417
    break;
418
  case 'r':
419
    if(done) done = false;
420
    else raytrace = true;
421
    break;
422
  case 's':
423
    shadow = !shadow;
424
    cout << "Shadow " << (shadow ? "on." : "off.") << endl;
425
    break;
426
  case 27:
309 jab 427
    delete vctrl;
305 jab 428
    delete cam;
429
    exit(0);
430
  }
431
}
432
 
433
void mouse(int btn, int state, int x, int y)
434
{
435
  if(state == GLUT_DOWN) 
436
  {
437
    if(btn == GLUT_LEFT_BUTTON) 
309 jab 438
      vctrl->grab_ball(ROTATE_ACTION, Vec2i(x, y));
305 jab 439
    else if(btn == GLUT_MIDDLE_BUTTON) 
309 jab 440
      vctrl->grab_ball(ZOOM_ACTION, Vec2i(x, y));
305 jab 441
    else if(btn == GLUT_RIGHT_BUTTON) 
309 jab 442
      vctrl->grab_ball(PAN_ACTION, Vec2i(x, y));
305 jab 443
  }
444
  else if(state == GLUT_UP)
309 jab 445
			vctrl->release_ball();
305 jab 446
 
447
  mouse_state = state;
448
  mouse_button = btn;
449
 
450
  glutPostRedisplay();
451
}
452
 
453
void move(int x, int y)
454
{
309 jab 455
    vctrl->roll_ball(Vec2i(x, y));
305 jab 456
 
457
  glutPostRedisplay();
458
}
459
 
460
void spin(int x)
461
{
309 jab 462
  vctrl->try_spin();
305 jab 463
  glutTimerFunc(spin_timer, spin, 0);  
464
  glutPostRedisplay();
465
}
466
 
467
 
468
//////////////////////////////////////////////////////////////
469
//                        M A I N
470
//////////////////////////////////////////////////////////////
471
 
472
int main(int argc, char** argv)
473
{
474
#ifdef __BORLANDC__
475
  _control87(MCW_EM, MCW_EM);  // Borland C++ will crash OpenGL if this
476
                               // magic line is not inserted
477
#endif
478
 
479
  glutInit(&argc, argv);
480
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
481
  glutInitWindowSize(winx, winy);
482
  glutCreateWindow("Press 'r' to raytrace");
483
  glutDisplayFunc(display);
484
  glutReshapeFunc(reshape);
485
  glutKeyboardFunc(keyboard);
486
  glutMouseFunc(mouse);
487
  glutMotionFunc(move);
488
 
489
  // LOAD OBJ
490
  string filename;
491
  if(argc > 1)
492
  {
493
    filename = argv[1];
494
    cout << "Loading " << filename << endl;
495
 
496
    obj_load(filename, mesh);
497
    //if(!mesh.has_normals())
498
    //{
499
      cout << "Computing normals" << endl;
500
      mesh.compute_normals();
501
    //}
502
 
503
    cout << "No. of triangles: " << mesh.geometry.no_faces() << endl;
504
  }
505
  else
506
  {
653 janba 507
    obj_load("../../data/dolphins.obj", mesh);
305 jab 508
 
418 jrf 509
  	cout << "Computing normals" << endl;
305 jab 510
    mesh.compute_normals();
511
 
418 jrf 512
    //cout << "Usage: raytrace any_object.obj";
305 jab 513
    //exit(0);
514
  }
515
 
516
  initRaytracer();
517
  initGL();    
518
 
519
  glutMainLoop();
520
 
521
  return 0;
522
}
523