1 /*
2  * Copyright (C) 1999-2001  Brian Paul   All Rights Reserved.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
18  * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20  */
21 
22 /*
23  * Ported to GLES2.
24  * Kristian Høgsberg <krh@bitplanet.net>
25  * May 3, 2010
26  *
27  * Improve GLES2 port:
28  *   * Refactor gear drawing.
29  *   * Use correct normals for surfaces.
30  *   * Improve shader.
31  *   * Use perspective projection transformation.
32  *   * Add FPS count.
33  *   * Add comments.
34  * Alexandros Frantzis <alexandros.frantzis@linaro.org>
35  * Jul 13, 2010
36  */
37 
38 #define GL_GLEXT_PROTOTYPES
39 #define EGL_EGLEXT_PROTOTYPES
40 
41 #define _GNU_SOURCE
42 
43 #include <math.h>
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <sys/time.h>
48 #include <unistd.h>
49 #ifdef __APPLE__
50 #include <OpenGL/gl.h>
51 #include <Glut/glut.h>
52 #else
53 #include <GL/gl.h>
54 #include <GL/glut.h>
55 #endif
56 
57 #define STRIPS_PER_TOOTH 7
58 #define VERTICES_PER_TOOTH 34
59 #define GEAR_VERTEX_STRIDE 6
60 
61 #ifndef HAVE_BUILTIN_SINCOS
62 #define sincos _sincos
63 static void
sincos(double a,double * s,double * c)64 sincos (double a, double *s, double *c)
65 {
66   *s = sin (a);
67   *c = cos (a);
68 }
69 #endif
70 
71 /**
72  * Struct describing the vertices in triangle strip
73  */
74 struct vertex_strip {
75    /** The first vertex in the strip */
76    GLint first;
77    /** The number of consecutive vertices in the strip after the first */
78    GLint count;
79 };
80 
81 /* Each vertex consist of GEAR_VERTEX_STRIDE GLfloat attributes */
82 typedef GLfloat GearVertex[GEAR_VERTEX_STRIDE];
83 
84 /**
85  * Struct representing a gear.
86  */
87 struct gear {
88    /** The array of vertices comprising the gear */
89    GearVertex *vertices;
90    /** The number of vertices comprising the gear */
91    int nvertices;
92    /** The array of triangle strips comprising the gear */
93    struct vertex_strip *strips;
94    /** The number of triangle strips comprising the gear */
95    int nstrips;
96    /** The Vertex Buffer Object holding the vertices in the graphics card */
97    GLuint vbo;
98 };
99 
100 /** The view rotation [x, y, z] */
101 static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
102 /** The gears */
103 static struct gear *gear1, *gear2, *gear3;
104 /** The current gear rotation angle */
105 static GLfloat angle = 0.0;
106 /** The location of the shader uniforms */
107 static GLuint ModelViewProjectionMatrix_location,
108               NormalMatrix_location,
109               LightSourcePosition_location,
110               MaterialColor_location;
111 /** The projection matrix */
112 static GLfloat ProjectionMatrix[16];
113 /** The direction of the directional light for the scene */
114 static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0};
115 
116 /**
117  * Fills a gear vertex.
118  *
119  * @param v the vertex to fill
120  * @param x the x coordinate
121  * @param y the y coordinate
122  * @param z the z coortinate
123  * @param n pointer to the normal table
124  *
125  * @return the operation error code
126  */
127 static GearVertex *
vert(GearVertex * v,GLfloat x,GLfloat y,GLfloat z,GLfloat n[3])128 vert(GearVertex *v, GLfloat x, GLfloat y, GLfloat z, GLfloat n[3])
129 {
130    v[0][0] = x;
131    v[0][1] = y;
132    v[0][2] = z;
133    v[0][3] = n[0];
134    v[0][4] = n[1];
135    v[0][5] = n[2];
136 
137    return v + 1;
138 }
139 
140 /**
141  *  Create a gear wheel.
142  *
143  *  @param inner_radius radius of hole at center
144  *  @param outer_radius radius at center of teeth
145  *  @param width width of gear
146  *  @param teeth number of teeth
147  *  @param tooth_depth depth of tooth
148  *
149  *  @return pointer to the constructed struct gear
150  */
151 static struct gear *
create_gear(GLfloat inner_radius,GLfloat outer_radius,GLfloat width,GLint teeth,GLfloat tooth_depth)152 create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
153       GLint teeth, GLfloat tooth_depth)
154 {
155    GLfloat r0, r1, r2;
156    GLfloat da;
157    GearVertex *v;
158    struct gear *gear;
159    double s[5], c[5];
160    GLfloat normal[3];
161    int cur_strip = 0;
162    int i;
163 
164    /* Allocate memory for the gear */
165    gear = malloc(sizeof *gear);
166    if (gear == NULL)
167       return NULL;
168 
169    /* Calculate the radii used in the gear */
170    r0 = inner_radius;
171    r1 = outer_radius - tooth_depth / 2.0;
172    r2 = outer_radius + tooth_depth / 2.0;
173 
174    da = 2.0 * M_PI / teeth / 4.0;
175 
176    /* Allocate memory for the triangle strip information */
177    gear->nstrips = STRIPS_PER_TOOTH * teeth;
178    gear->strips = calloc(gear->nstrips, sizeof (*gear->strips));
179 
180    /* Allocate memory for the vertices */
181    gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices));
182    v = gear->vertices;
183 
184    for (i = 0; i < teeth; i++) {
185       /* Calculate needed sin/cos for varius angles */
186       sincos(i * 2.0 * M_PI / teeth, &s[0], &c[0]);
187       sincos(i * 2.0 * M_PI / teeth + da, &s[1], &c[1]);
188       sincos(i * 2.0 * M_PI / teeth + da * 2, &s[2], &c[2]);
189       sincos(i * 2.0 * M_PI / teeth + da * 3, &s[3], &c[3]);
190       sincos(i * 2.0 * M_PI / teeth + da * 4, &s[4], &c[4]);
191 
192       /* A set of macros for making the creation of the gears easier */
193 #define  GEAR_POINT(r, da) { (r) * c[(da)], (r) * s[(da)] }
194 #define  SET_NORMAL(x, y, z) do { \
195    normal[0] = (x); normal[1] = (y); normal[2] = (z); \
196 } while(0)
197 
198 #define  GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal)
199 
200 #define START_STRIP do { \
201    gear->strips[cur_strip].first = v - gear->vertices; \
202 } while(0);
203 
204 #define END_STRIP do { \
205    int _tmp = (v - gear->vertices); \
206    gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \
207    cur_strip++; \
208 } while (0)
209 
210 #define QUAD_WITH_NORMAL(p1, p2) do { \
211    SET_NORMAL((p[(p1)].y - p[(p2)].y), -(p[(p1)].x - p[(p2)].x), 0); \
212    v = GEAR_VERT(v, (p1), -1); \
213    v = GEAR_VERT(v, (p1), 1); \
214    v = GEAR_VERT(v, (p2), -1); \
215    v = GEAR_VERT(v, (p2), 1); \
216 } while(0)
217 
218       struct point {
219          GLfloat x;
220          GLfloat y;
221       };
222 
223       /* Create the 7 points (only x,y coords) used to draw a tooth */
224       struct point p[7] = {
225          GEAR_POINT(r2, 1), // 0
226          GEAR_POINT(r2, 2), // 1
227          GEAR_POINT(r1, 0), // 2
228          GEAR_POINT(r1, 3), // 3
229          GEAR_POINT(r0, 0), // 4
230          GEAR_POINT(r1, 4), // 5
231          GEAR_POINT(r0, 4), // 6
232       };
233 
234       /* Front face */
235       START_STRIP;
236       SET_NORMAL(0, 0, 1.0);
237       v = GEAR_VERT(v, 0, +1);
238       v = GEAR_VERT(v, 1, +1);
239       v = GEAR_VERT(v, 2, +1);
240       v = GEAR_VERT(v, 3, +1);
241       v = GEAR_VERT(v, 4, +1);
242       v = GEAR_VERT(v, 5, +1);
243       v = GEAR_VERT(v, 6, +1);
244       END_STRIP;
245 
246       /* Inner face */
247       START_STRIP;
248       QUAD_WITH_NORMAL(4, 6);
249       END_STRIP;
250 
251       /* Back face */
252       START_STRIP;
253       SET_NORMAL(0, 0, -1.0);
254       v = GEAR_VERT(v, 6, -1);
255       v = GEAR_VERT(v, 5, -1);
256       v = GEAR_VERT(v, 4, -1);
257       v = GEAR_VERT(v, 3, -1);
258       v = GEAR_VERT(v, 2, -1);
259       v = GEAR_VERT(v, 1, -1);
260       v = GEAR_VERT(v, 0, -1);
261       END_STRIP;
262 
263       /* Outer face */
264       START_STRIP;
265       QUAD_WITH_NORMAL(0, 2);
266       END_STRIP;
267 
268       START_STRIP;
269       QUAD_WITH_NORMAL(1, 0);
270       END_STRIP;
271 
272       START_STRIP;
273       QUAD_WITH_NORMAL(3, 1);
274       END_STRIP;
275 
276       START_STRIP;
277       QUAD_WITH_NORMAL(5, 3);
278       END_STRIP;
279    }
280 
281    gear->nvertices = (v - gear->vertices);
282 
283    /* Store the vertices in a vertex buffer object (VBO) */
284    glGenBuffers(1, &gear->vbo);
285    glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
286    glBufferData(GL_ARRAY_BUFFER, gear->nvertices * sizeof(GearVertex),
287          gear->vertices, GL_STATIC_DRAW);
288 
289    return gear;
290 }
291 
292 /**
293  * Multiplies two 4x4 matrices.
294  *
295  * The result is stored in matrix m.
296  *
297  * @param m the first matrix to multiply
298  * @param n the second matrix to multiply
299  */
300 static void
multiply(GLfloat * m,const GLfloat * n)301 multiply(GLfloat *m, const GLfloat *n)
302 {
303    GLfloat tmp[16];
304    const GLfloat *row, *column;
305    div_t d;
306    int i, j;
307 
308    for (i = 0; i < 16; i++) {
309       tmp[i] = 0;
310       d = div(i, 4);
311       row = n + d.quot * 4;
312       column = m + d.rem;
313       for (j = 0; j < 4; j++)
314          tmp[i] += row[j] * column[j * 4];
315    }
316    memcpy(m, &tmp, sizeof tmp);
317 }
318 
319 /**
320  * Rotates a 4x4 matrix.
321  *
322  * @param[in,out] m the matrix to rotate
323  * @param angle the angle to rotate
324  * @param x the x component of the direction to rotate to
325  * @param y the y component of the direction to rotate to
326  * @param z the z component of the direction to rotate to
327  */
328 static void
rotate(GLfloat * m,GLfloat angle,GLfloat x,GLfloat y,GLfloat z)329 rotate(GLfloat *m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
330 {
331    double s, c;
332 
333    sincos(angle, &s, &c);
334    GLfloat r[16] = {
335       x * x * (1 - c) + c,     y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
336       x * y * (1 - c) - z * s, y * y * (1 - c) + c,     y * z * (1 - c) + x * s, 0,
337       x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c,     0,
338       0, 0, 0, 1
339    };
340 
341    multiply(m, r);
342 }
343 
344 
345 /**
346  * Translates a 4x4 matrix.
347  *
348  * @param[in,out] m the matrix to translate
349  * @param x the x component of the direction to translate to
350  * @param y the y component of the direction to translate to
351  * @param z the z component of the direction to translate to
352  */
353 static void
translate(GLfloat * m,GLfloat x,GLfloat y,GLfloat z)354 translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
355 {
356    GLfloat t[16] = { 1, 0, 0, 0,  0, 1, 0, 0,  0, 0, 1, 0,  x, y, z, 1 };
357 
358    multiply(m, t);
359 }
360 
361 /**
362  * Creates an identity 4x4 matrix.
363  *
364  * @param m the matrix make an identity matrix
365  */
366 static void
identity(GLfloat * m)367 identity(GLfloat *m)
368 {
369    GLfloat t[16] = {
370       1.0, 0.0, 0.0, 0.0,
371       0.0, 1.0, 0.0, 0.0,
372       0.0, 0.0, 1.0, 0.0,
373       0.0, 0.0, 0.0, 1.0,
374    };
375 
376    memcpy(m, t, sizeof(t));
377 }
378 
379 /**
380  * Transposes a 4x4 matrix.
381  *
382  * @param m the matrix to transpose
383  */
384 static void
transpose(GLfloat * m)385 transpose(GLfloat *m)
386 {
387    GLfloat t[16] = {
388       m[0], m[4], m[8],  m[12],
389       m[1], m[5], m[9],  m[13],
390       m[2], m[6], m[10], m[14],
391       m[3], m[7], m[11], m[15]};
392 
393    memcpy(m, t, sizeof(t));
394 }
395 
396 /**
397  * Inverts a 4x4 matrix.
398  *
399  * This function can currently handle only pure translation-rotation matrices.
400  * Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
401  * for an explanation.
402  */
403 static void
invert(GLfloat * m)404 invert(GLfloat *m)
405 {
406    GLfloat t[16];
407    identity(t);
408 
409    // Extract and invert the translation part 't'. The inverse of a
410    // translation matrix can be calculated by negating the translation
411    // coordinates.
412    t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
413 
414    // Invert the rotation part 'r'. The inverse of a rotation matrix is
415    // equal to its transpose.
416    m[12] = m[13] = m[14] = 0;
417    transpose(m);
418 
419    // inv(m) = inv(r) * inv(t)
420    multiply(m, t);
421 }
422 
423 /**
424  * Calculate a perspective projection transformation.
425  *
426  * @param m the matrix to save the transformation in
427  * @param fovy the field of view in the y direction
428  * @param aspect the view aspect ratio
429  * @param zNear the near clipping plane
430  * @param zFar the far clipping plane
431  */
perspective(GLfloat * m,GLfloat fovy,GLfloat aspect,GLfloat zNear,GLfloat zFar)432 void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
433 {
434    GLfloat tmp[16];
435    identity(tmp);
436 
437    double sine, cosine, cotangent, deltaZ;
438    GLfloat radians = fovy / 2 * M_PI / 180;
439 
440    deltaZ = zFar - zNear;
441    sincos(radians, &sine, &cosine);
442 
443    if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
444       return;
445 
446    cotangent = cosine / sine;
447 
448    tmp[0] = cotangent / aspect;
449    tmp[5] = cotangent;
450    tmp[10] = -(zFar + zNear) / deltaZ;
451    tmp[11] = -1;
452    tmp[14] = -2 * zNear * zFar / deltaZ;
453    tmp[15] = 0;
454 
455    memcpy(m, tmp, sizeof(tmp));
456 }
457 
458 /**
459  * Draws a gear.
460  *
461  * @param gear the gear to draw
462  * @param transform the current transformation matrix
463  * @param x the x position to draw the gear at
464  * @param y the y position to draw the gear at
465  * @param angle the rotation angle of the gear
466  * @param color the color of the gear
467  */
468 static void
draw_gear(struct gear * gear,GLfloat * transform,GLfloat x,GLfloat y,GLfloat angle,const GLfloat color[4])469 draw_gear(struct gear *gear, GLfloat *transform,
470       GLfloat x, GLfloat y, GLfloat angle, const GLfloat color[4])
471 {
472    GLfloat model_view[16];
473    GLfloat normal_matrix[16];
474    GLfloat model_view_projection[16];
475 
476    /* Translate and rotate the gear */
477    memcpy(model_view, transform, sizeof (model_view));
478    translate(model_view, x, y, 0);
479    rotate(model_view, 2 * M_PI * angle / 360.0, 0, 0, 1);
480 
481    /* Create and set the ModelViewProjectionMatrix */
482    memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
483    multiply(model_view_projection, model_view);
484 
485    glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
486                       model_view_projection);
487 
488    /*
489     * Create and set the NormalMatrix. It's the inverse transpose of the
490     * ModelView matrix.
491     */
492    memcpy(normal_matrix, model_view, sizeof (normal_matrix));
493    invert(normal_matrix);
494    transpose(normal_matrix);
495    glUniformMatrix4fv(NormalMatrix_location, 1, GL_FALSE, normal_matrix);
496 
497    /* Set the gear color */
498    glUniform4fv(MaterialColor_location, 1, color);
499 
500    /* Set the vertex buffer object to use */
501    glBindBuffer(GL_ARRAY_BUFFER, 0);
502 
503    /* Set up the position of the attributes in the vertex buffer object */
504    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
505          6 * sizeof(GLfloat), *gear->vertices);
506 
507    glBindBuffer(GL_ARRAY_BUFFER, gear->vbo); // second is not clientside
508    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
509          6 * sizeof(GLfloat), (GLfloat *) 0 + 3);
510    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, // third is not clientside either, but not enabled
511          6 * sizeof(GLfloat), ((float*)*gear->vertices) + 6*4);
512    glBindBuffer(GL_ARRAY_BUFFER, 0);
513 
514    glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, // also never enabled
515          6 * sizeof(GLfloat), ((float*)*gear->vertices) + 9*4);
516 
517    /* Enable the attributes */
518    glEnableVertexAttribArray(0);
519    glEnableVertexAttribArray(1);
520 
521    /* Draw the triangle strips that comprise the gear */
522    int n;
523    for (n = 0; n < gear->nstrips; n++)
524       glDrawArrays(GL_TRIANGLE_STRIP, gear->strips[n].first, gear->strips[n].count);
525 
526    /* Disable the attributes */
527    glDisableVertexAttribArray(1);
528    glDisableVertexAttribArray(0);
529 }
530 
531 /**
532  * Draws the gears.
533  */
534 static void
gears_draw(void)535 gears_draw(void)
536 {
537    const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
538    const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
539    const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
540    GLfloat transform[16];
541    identity(transform);
542 
543    glClearColor(0.0, 0.0, 0.0, 0.0);
544    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
545 
546    /* Translate and rotate the view */
547    translate(transform, 0, 0, -20);
548    rotate(transform, 2 * M_PI * view_rot[0] / 360.0, 1, 0, 0);
549    rotate(transform, 2 * M_PI * view_rot[1] / 360.0, 0, 1, 0);
550    rotate(transform, 2 * M_PI * view_rot[2] / 360.0, 0, 0, 1);
551 
552    /* Draw the gears */
553    draw_gear(gear1, transform, -3.0, -2.0, angle, red);
554    draw_gear(gear2, transform, 3.1, -2.0, -2 * angle - 9.0, green);
555    draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
556 
557    glutSwapBuffers();
558 }
559 
560 /**
561  * Handles a new window size or exposure.
562  *
563  * @param width the window width
564  * @param height the window height
565  */
566 static void
gears_reshape(int width,int height)567 gears_reshape(int width, int height)
568 {
569    /* Update the projection matrix */
570    perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
571 
572    /* Set the viewport */
573    glViewport(0, 0, (GLint) width, (GLint) height);
574 }
575 
576 /**
577  * Handles special glut events.
578  *
579  * @param special the event to handle.
580  */
581 static void
gears_special(int special,int crap,int morecrap)582 gears_special(int special, int crap, int morecrap)
583 {
584    switch (special) {
585       case GLUT_KEY_LEFT:
586          view_rot[1] += 5.0;
587          break;
588       case GLUT_KEY_RIGHT:
589          view_rot[1] -= 5.0;
590          break;
591       case GLUT_KEY_UP:
592          view_rot[0] += 5.0;
593          break;
594       case GLUT_KEY_DOWN:
595          view_rot[0] -= 5.0;
596          break;
597       case GLUT_KEY_F11:
598          glutFullScreen();
599          break;
600    }
601 }
602 
603 static void
gears_idle(void)604 gears_idle(void)
605 {
606    static int frames = 0;
607    static double tRot0 = -1.0, tRate0 = -1.0;
608    double dt, t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
609 
610    if (tRot0 < 0.0)
611       tRot0 = t;
612    dt = t - tRot0;
613    tRot0 = t;
614 
615    /* advance rotation for next frame */
616    angle += 70.0 * dt;  /* 70 degrees per second */
617    if (angle > 3600.0)
618       angle -= 3600.0;
619 
620    glutPostRedisplay();
621    frames++;
622 
623    if (tRate0 < 0.0)
624       tRate0 = t;
625    if (t - tRate0 >= 5.0) {
626       GLfloat seconds = t - tRate0;
627       GLfloat fps = frames / seconds;
628       printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
629             fps);
630       tRate0 = t;
631       frames = 0;
632    }
633 }
634 
635 static const char vertex_shader[] =
636 "attribute vec3 position;\n"
637 "attribute vec3 normal;\n"
638 "\n"
639 "uniform mat4 ModelViewProjectionMatrix;\n"
640 "uniform mat4 NormalMatrix;\n"
641 "uniform vec4 LightSourcePosition;\n"
642 "uniform vec4 MaterialColor;\n"
643 "\n"
644 "varying vec4 Color;\n"
645 "\n"
646 "void main(void)\n"
647 "{\n"
648 "    // Transform the normal to eye coordinates\n"
649 "    vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
650 "\n"
651 "    // The LightSourcePosition is actually its direction for directional light\n"
652 "    vec3 L = normalize(LightSourcePosition.xyz);\n"
653 "\n"
654 "    // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
655 "    // to get the actual color that we will use to draw this vertex with\n"
656 "    float diffuse = max(dot(N, L), 0.0);\n"
657 "    Color = diffuse * MaterialColor;\n"
658 "\n"
659 "    // Transform the position to clip coordinates\n"
660 "    gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
661 "}";
662 
663 static const char fragment_shader[] =
664 "#ifdef GL_ES\n"
665 "precision mediump float;\n"
666 "#endif\n"
667 "varying vec4 Color;\n"
668 "\n"
669 "void main(void)\n"
670 "{\n"
671 "    gl_FragColor = Color;\n"
672 "}";
673 
674 static void
gears_init(void)675 gears_init(void)
676 {
677    GLuint v, f, program;
678    const char *p;
679    char msg[512];
680 
681    glEnable(GL_CULL_FACE);
682    glEnable(GL_DEPTH_TEST);
683 
684    /* Compile the vertex shader */
685    p = vertex_shader;
686    v = glCreateShader(GL_VERTEX_SHADER);
687    glShaderSource(v, 1, &p, NULL);
688    glCompileShader(v);
689    glGetShaderInfoLog(v, sizeof msg, NULL, msg);
690    printf("vertex shader info: %s\n", msg);
691 
692    /* Compile the fragment shader */
693    p = fragment_shader;
694    f = glCreateShader(GL_FRAGMENT_SHADER);
695    glShaderSource(f, 1, &p, NULL);
696    glCompileShader(f);
697    glGetShaderInfoLog(f, sizeof msg, NULL, msg);
698    printf("fragment shader info: %s\n", msg);
699 
700    /* Create and link the shader program */
701    program = glCreateProgram();
702    glAttachShader(program, v);
703    glAttachShader(program, f);
704    glBindAttribLocation(program, 0, "position");
705    glBindAttribLocation(program, 1, "normal");
706 
707    glLinkProgram(program);
708    glGetProgramInfoLog(program, sizeof msg, NULL, msg);
709    printf("info: %s\n", msg);
710 
711    /* Enable the shaders */
712    glUseProgram(program);
713 
714    /* Get the locations of the uniforms so we can access them */
715    ModelViewProjectionMatrix_location = glGetUniformLocation(program, "ModelViewProjectionMatrix");
716    NormalMatrix_location = glGetUniformLocation(program, "NormalMatrix");
717    LightSourcePosition_location = glGetUniformLocation(program, "LightSourcePosition");
718    MaterialColor_location = glGetUniformLocation(program, "MaterialColor");
719 
720    /* Set the LightSourcePosition uniform which is constant throught the program */
721    glUniform4fv(LightSourcePosition_location, 1, LightSourcePosition);
722 
723    /* make the gears */
724    gear1 = create_gear(1.0, 4.0, 1.0, 20, 0.7);
725    gear2 = create_gear(0.5, 2.0, 2.0, 10, 0.7);
726    gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
727 }
728 
729 int
main(int argc,char * argv[])730 main(int argc, char *argv[])
731 {
732    /* Initialize the window */
733    glutInit(&argc, argv);
734    glutInitWindowSize(300, 300);
735    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
736 
737    glutCreateWindow("es2gears");
738 
739    /* Set up glut callback functions */
740    glutIdleFunc (gears_idle);
741    glutReshapeFunc(gears_reshape);
742    glutDisplayFunc(gears_draw);
743    glutSpecialFunc(gears_special);
744 
745    /* Initialize the gears */
746    gears_init();
747 
748    glutMainLoop();
749 
750    return 0;
751 }
752