Subversion Repositories gelsvn

Rev

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

Rev Author Line No. Line
82 jab 1
// ----------------------------------------
2
// A simple OBJ viewer.
178 bj 3
//
82 jab 4
// Controls:
5
// - left mouse down + mouse motion : rotate
6
// - Scroll button and +- buttons   : zoom
7
// - right mouse click              : centre trackball
8
// - esc                            : exits
178 bj 9
// - x,y,z buttons                  : switch trackball up axis
82 jab 10
// ----------------------------------------
11
 
102 bj 12
#if (_MSC_VER >= 1200)
82 jab 13
#pragma warning (disable: 4786)
102 bj 14
#endif
82 jab 15
 
16
#include <list>
17
#include <vector>
18
 
195 jrf 19
#include <assert.h>
20
#include <stdio.h>
21
#ifdef WIN32
22
#include <windows.h>
23
#include <io.h>
24
#endif
25
#include <string.h>
26
#include <stdlib.h>
27
 
28
#include <iostream>
337 jab 29
 
195 jrf 30
#include <IL/il.h>
31
#include <IL/ilu.h>
32
 
337 jab 33
#include <CGLA/Vec2i.h>
34
#include <CGLA/Vec2f.h>
82 jab 35
#include <CGLA/Vec3f.h>
36
#include <CGLA/Mat4x4f.h>
357 jab 37
#include "glsl_shader.h"
178 bj 38
#include "GLGraphics/gel_glut.h"
299 jrf 39
#include "GLGraphics/QuatTrackBall.h"
178 bj 40
#include "GLGraphics/draw.h"
82 jab 41
#include "Geometry/TriMesh.h"
42
#include "Geometry/obj_load.h"
43
 
337 jab 44
#include "ply_load.h"
45
 
82 jab 46
using namespace std;
47
using namespace CGLA;
48
using namespace Geometry;
178 bj 49
using namespace GLGraphics;
82 jab 50
 
51
namespace
52
{
337 jab 53
	int win_size_x = 800;
54
	int win_size_y = 800;
55
	QuatTrackBall* ball;
56
	int spin_timer = 20;
57
	void spin(int x);
58
	int main_window;
59
	TriMesh mesh;
60
 
61
 
62
	bool load_image_into_texture(const std::string& name, GLuint& id)
63
	{
64
		unsigned char* image = 0;
65
		unsigned int bpp = 0;
66
		unsigned int size_x = 0;
67
		unsigned int size_y = 0;
68
		unsigned int load_size_x = 0;
69
		unsigned int load_size_y = 0;
70
 
71
 
72
		ILenum Error;
73
		ILuint  ImgId;
74
 
75
		static bool washere = false;
76
		if(!washere)
77
		{
78
			ilInit();
79
			iluInit();
80
			washere=true;
81
		}
82
		ilEnable(IL_CONV_PAL);
83
		ilEnable(IL_ORIGIN_SET);
84
		ilOriginFunc(IL_ORIGIN_LOWER_LEFT);
85
		ilGenImages(1, &ImgId);
86
		ilBindImage(ImgId);
87
		char* name_cstr = const_cast<char*>(name.c_str());
88
		if(!ilLoadImage(name_cstr))
89
		{
90
			cout << "could not load <" << name_cstr  << ">" << endl;
91
			return false;
92
		}
93
 
94
		load_size_x = ilGetInteger(IL_IMAGE_WIDTH);
95
		load_size_y = ilGetInteger(IL_IMAGE_HEIGHT);
96
		bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
97
 
98
		if (bpp==24)
99
			ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
100
		else if (bpp==32)
101
			ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
102
		else if (bpp==8)
103
			ilConvertImage(IL_LUMINANCE, IL_UNSIGNED_BYTE);
104
		else
105
			assert(0);
106
 
107
		unsigned int i;
108
		for (i=2;i<=4096 ;i*=2)
109
			if (i>=load_size_x)
110
				break;
111
		size_x = i;
112
		for (i=2;i<=4096 ;i*=2)
113
			if (i>=load_size_y)
114
				break;
115
		size_y = i;
116
 
117
		if(size_x != load_size_x || size_y != load_size_y)
118
		{
119
			iluImageParameter(ILU_FILTER, ILU_BILINEAR);
120
			iluScale(size_x, size_y, 1);
121
		}
122
 
123
		const int image_size =size_x*size_y*ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
124
		image = new unsigned char[image_size];
125
		memcpy(image, ilGetData(), image_size);
126
		ilDeleteImages(1, &ImgId);
127
 
128
		bool any_errors=false;
129
		while ((Error = ilGetError())) {
130
			cout << __LINE__ << "Error: " << iluErrorString(Error) << endl;
131
			any_errors = true;
132
		}
133
		if(any_errors) return false;
134
 
135
		GLint internalFormat=0;
136
		GLenum format=0;
137
 
138
		glGenTextures(1, &id);
139
		switch (bpp)
140
		{
141
			case 8:
142
				internalFormat =  GL_LUMINANCE;
143
				format = GL_LUMINANCE;
144
				break;
145
			case 24:
146
				internalFormat =  GL_RGB;
147
				format = GL_RGB;
148
				break;
149
			case 32:
150
				internalFormat =  GL_RGBA;
151
				format = GL_RGBA;
152
				break;
153
			default:
154
				return false;
155
		}
156
 
157
		glBindTexture(GL_TEXTURE_2D, id);
158
		glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, size_x, size_y, 0,
159
					 format, GL_UNSIGNED_BYTE, image);
160
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
161
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
162
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
163
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
164
 
165
		return true;
166
	}
167
 
168
	void enable_textures(TriMesh& tm)
169
	{
170
		for(unsigned int i=0;i<tm.materials.size(); ++i)
171
		{
172
			Material& mat = tm.materials[i];
173
			if(mat.tex_name != "")
174
			{
175
				string name = mat.tex_path + mat.tex_name;
176
 
177
				GLuint tex_id;
178
				if(load_image_into_texture(name, tex_id))
179
					mat.tex_id = tex_id;
180
			}
181
		}
182
	}
183
 
357 jab 184
	void toggle_wire()
185
	{
186
		static bool wire= false;
187
		static string shader_path = "/Users/jab/SrcTree/Appsrc/wireframepaper/";
188
		static GLhandleARB prog_P0;
189
 
190
		wire = !wire;
191
		static bool washere = false;
192
		if(!washere)
193
		{
194
			washere = true;
195
 
196
			// Create s	haders directly from file
197
			GLuint vs = create_glsl_shader(GL_VERTEX_SHADER, shader_path, "tri.vert");
198
			GLuint gs = create_glsl_shader(GL_GEOMETRY_SHADER_EXT, shader_path, "tri.geom");
199
			GLuint fs = create_glsl_shader(GL_FRAGMENT_SHADER, shader_path, "tri.frag");
200
 
201
			// Create the program
202
			prog_P0 = glCreateProgram();
203
 
204
			// Attach all shaders
205
			if(vs) glAttachShader(prog_P0, vs);
206
			if(gs) glAttachShader(prog_P0, gs);
207
			if(fs) glAttachShader(prog_P0, fs);
208
 
209
			// Specify input and output for the geometry shader. Note that this must be
210
			// done before linking the program.
211
			glProgramParameteriEXT(prog_P0,GL_GEOMETRY_INPUT_TYPE_EXT,GL_TRIANGLES);
212
			glProgramParameteriEXT(prog_P0,GL_GEOMETRY_VERTICES_OUT_EXT,3);
213
			glProgramParameteriEXT(prog_P0,GL_GEOMETRY_OUTPUT_TYPE_EXT,GL_TRIANGLE_STRIP);
214
 
215
			// Link the program object and print out the info log
216
			glLinkProgram(prog_P0);
217
		}
218
		if(wire)
219
		{
220
			glUseProgram(prog_P0);
221
			// Set the value of a uniform
222
			glUniform2f(glGetUniformLocation(prog_P0,"WIN_SCALE"), win_size_x/2.0, win_size_y/2.0);
223
		}
224
		else
225
			glUseProgram(0);		
226
	}
227
 
337 jab 228
	bool depth_pick(int x, int y,Vec3f& wp)
229
	{
230
		// Enquire about the viewport dimensions
231
		GLint viewport[4];
232
		glGetIntegerv(GL_VIEWPORT, viewport);
233
 
234
		// Get the minimum and maximum depth values.
235
		float minmax_depth[2];
236
		glGetFloatv(GL_DEPTH_RANGE, minmax_depth);
237
 
238
		// Read a single pixel at the position of the mouse cursor.
239
		float depth;
240
		glReadPixels(x, viewport[3]-y, 1,1, GL_DEPTH_COMPONENT,
241
					 GL_FLOAT, (void*) &depth);
242
 
243
		// If the depth corresponds to the far plane, we clicked on the
244
		// background.
245
		if(depth == minmax_depth[1])
246
			return false;
247
 
248
		// The lines below copy the viewing transformation from OpenGL
249
		// to local variables. The call to gluLookAt must have exactly
250
		// the same parameters as when the scene is drawn.
251
		glLoadIdentity();
252
		ball->set_gl_modelview();
253
		double mvmat[16];
254
		glGetDoublev(GL_MODELVIEW_MATRIX, mvmat);
255
 
256
		// Copy the projection matrix. We assume it is unchanged.
257
		double prjmat[16];
258
		glGetDoublev(GL_PROJECTION_MATRIX, prjmat);
259
 
260
		// Now unproject the point from screen to world coordinates.
261
		double ox, oy, oz;
262
		gluUnProject(x,viewport[3]-y,depth,
263
					 mvmat,prjmat,viewport,
264
					 &ox, &oy, &oz);
265
 
266
		wp = Vec3f(ox,oy,oz);
267
 
268
		return true;
269
	}
270
 
82 jab 271
 
272
 
178 bj 273
void mouse_motion(int x, int y)
274
{
299 jrf 275
    ball->roll_ball(Vec2i(x,y));
178 bj 276
}
277
 
299 jrf 278
void mouse(int btn, int state, int x, int y)
178 bj 279
{
337 jab 280
	if(state == GLUT_DOWN) 
281
	{
282
		if(btn == GLUT_LEFT_BUTTON) 
283
			ball->grab_ball(ROTATE_ACTION, Vec2i(x,y));
284
		else if(btn == GLUT_MIDDLE_BUTTON) 
285
			ball->grab_ball(ZOOM_ACTION, Vec2i(x, y));
286
		else if(btn == GLUT_RIGHT_BUTTON) 
287
			ball->grab_ball(PAN_ACTION, Vec2i(x, y));
288
	}
289
	else if(state == GLUT_UP)
290
		ball->release_ball();	
178 bj 291
}
292
 
299 jrf 293
void spin(int x)
294
{
337 jab 295
	ball->do_spin();
296
	glutTimerFunc(spin_timer, spin, 0);  
297
	glutPostRedisplay();
299 jrf 298
}
337 jab 299
 
178 bj 300
void display()
301
{
302
    static bool washere = false;
303
    static unsigned int l;
304
    if(!washere)
305
    {
306
        cout << "Creating display list" << endl;
307
        l = glGenLists(1);
308
        glNewList(l, GL_COMPILE);
309
        draw(mesh);
310
        glEndList();
311
        washere = true;
337 jab 312
		glutTimerFunc(spin_timer, spin, 0);	
299 jrf 313
	}
178 bj 314
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
315
    glLoadIdentity();
299 jrf 316
    ball->set_gl_modelview();
178 bj 317
    glCallList(l);
318
    glutSwapBuffers();
319
}
320
 
321
void keyboard(unsigned char key, int x, int y)
322
{
323
    switch(key)
324
    {
337 jab 325
		case '\033': exit(0); break;
357 jab 326
		case 'w': toggle_wire(); break;
178 bj 327
    }
328
}
329
}
330
 
82 jab 331
int main(int argc, char** argv)
178 bj 332
{
333
    // GLUT INIT
334
    glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH);
335
    glutInitWindowSize(win_size_x, win_size_y);
336
    glutInit(&argc, argv);
337
    main_window = glutCreateWindow("OBJ Viewer");
338
    glutDisplayFunc(display);
339
    glutKeyboardFunc(keyboard);
340
    glutMotionFunc(mouse_motion);
341
    glutMouseFunc(mouse);
299 jrf 342
    //glutIdleFunc(idle);
337 jab 343
 
357 jab 344
	glewInit();
345
 
178 bj 346
    // GL INIT
347
    glClearColor(.8f, 0.9f, 1.0f, 0.f);
348
    glEnable(GL_DEPTH_TEST);
349
    glEnable(GL_LIGHTING);
350
    glEnable(GL_LIGHT0);
351
    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);
352
    glShadeModel(GL_SMOOTH);
337 jab 353
 
178 bj 354
    // LOAD OBJ
355
    string fn;
356
    if(argc>1)
357
        fn = argv[1];
358
    else
359
        fn = "../../data/head.obj";
337 jab 360
 
361
	if(fn.substr(fn.length()-4,fn.length())==".obj")
362
	{
363
		obj_load(fn, mesh);
364
	}
365
	else if(fn.substr(fn.length()-4,fn.length())==".ply")
366
	{
367
		ply_load(fn, mesh);
368
	}	
369
	else
370
	{
371
		cout << "Either the format was unrecognized or the file did not have the appropriate extension" << endl;
372
		exit(0);
373
	}		
341 jab 374
    enable_textures(mesh);	
178 bj 375
    if(!mesh.has_normals())
376
    {
377
        cout << "Computing normals" << endl;
378
        mesh.compute_normals();
379
    }
341 jab 380
 
178 bj 381
    // Initialize Trackball
382
    Vec3f c;
383
    float r;
384
    mesh.get_bsphere(c,r);
385
    r *= 1.5;
299 jrf 386
    ball = new QuatTrackBall(c,r,800,800);
337 jab 387
 
178 bj 388
    // Setup projection
389
    glMatrixMode(GL_PROJECTION);
390
    glLoadIdentity();
299 jrf 391
    gluPerspective(53,1.0f,r/100.0,r*3.0);
178 bj 392
    glMatrixMode(GL_MODELVIEW);
337 jab 393
 
178 bj 394
    // Pass control to GLUT
395
    glutMainLoop();
337 jab 396
 
178 bj 397
    return 0;
82 jab 398
}