Subversion Repositories gelsvn

Rev

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