Subversion Repositories gelsvn

Rev

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

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