1/**
2 * Test using a geometry shader to implement polygon outlining.
3 * Using GLSL 1.50 (or any later version)
4 *
5 * Based on the technique "Single-Pass Wireframe Rendering" by Andreas
6 * Bærentzen, Steen Lund Nielsen, Mikkel Gjael, Bent D. Larsen & Niels
7 * Jaergen Christensen, SIGGRAPH 2006
8 *
9 * Brian Paul
10 * May 2012
11 */
12
13#include <assert.h>
14#include <string.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <math.h>
18#include <GL/glew.h>
19#include "glut_wrap.h"
20#include "shaderutil.h"
21#include "trackball.h"
22
23static GLint WinWidth = 500, WinHeight = 500;
24static GLint Win = 0;
25static GLuint VertShader, GeomShader, FragShader, Program;
26static GLuint vao, vbo;
27static GLboolean Anim = GL_TRUE;
28static int uViewportSize = -1, uModelViewProj = -1, uColor = -1;
29
30static const GLfloat Orange[4] = {1.0, 0.6, 0.0, 1};
31
32static float CurQuat[4] = { 0, 0, 0, 1 };
33static GLboolean ButtonDown = GL_FALSE;
34static GLint ButtonX, ButtonY;
35
36static GLfloat Projection[16];
37
38
39static void
40CheckError(int line)
41{
42   GLenum err = glGetError();
43   if (err) {
44      printf("GL Error %s (0x%x) at line %d\n",
45             gluErrorString(err), (int) err, line);
46   }
47}
48
49
50static void
51mat_identity(GLfloat mat[16])
52{
53   memset(mat, 0, 16*sizeof(GLfloat));
54   mat[0] = mat[5] = mat[10] = mat[15] = 1.0;
55}
56
57
58static void
59mat_translate(GLfloat mat[16], float tx, float ty, float tz)
60{
61   mat_identity(mat);
62   mat[12] = tx;
63   mat[13] = ty;
64   mat[14] = tx;
65}
66
67
68static void
69mat_frustum(GLfloat mat[16],
70              GLfloat left, GLfloat right,
71              GLfloat bottom, GLfloat top,
72              GLfloat nearval, GLfloat farval)
73{
74   GLfloat x, y, a, b, c, d;
75
76   x = (2.0F*nearval) / (right-left);
77   y = (2.0F*nearval) / (top-bottom);
78   a = (right+left) / (right-left);
79   b = (top+bottom) / (top-bottom);
80   c = -(farval+nearval) / ( farval-nearval);
81   d = -(2.0F*farval*nearval) / (farval-nearval);  /* error? */
82
83#define M(row,col)  mat[col*4+row]
84   M(0,0) = x;     M(0,1) = 0.0F;  M(0,2) = a;      M(0,3) = 0.0F;
85   M(1,0) = 0.0F;  M(1,1) = y;     M(1,2) = b;      M(1,3) = 0.0F;
86   M(2,0) = 0.0F;  M(2,1) = 0.0F;  M(2,2) = c;      M(2,3) = d;
87   M(3,0) = 0.0F;  M(3,1) = 0.0F;  M(3,2) = -1.0F;  M(3,3) = 0.0F;
88#undef M
89}
90
91
92static void
93mat_multiply(GLfloat product[16], const GLfloat a[16], const GLfloat b[16])
94{
95#define A(row,col)  a[(col<<2)+row]
96#define B(row,col)  b[(col<<2)+row]
97#define P(row,col)  product[(col<<2)+row]
98   GLint i;
99   for (i = 0; i < 4; i++) {
100      const GLfloat ai0=A(i,0),  ai1=A(i,1),  ai2=A(i,2),  ai3=A(i,3);
101      P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
102      P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
103      P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
104      P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
105   }
106#undef A
107#undef B
108#undef P
109}
110
111
112
113static void
114Redisplay(void)
115{
116   GLfloat rot[4][4];
117   GLfloat trans[16], mvp[16];
118
119   glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
120
121   /* Build the modelview * projection matrix */
122   build_rotmatrix(rot, CurQuat);
123   mat_translate(trans, 0, 0, -10);
124   mat_multiply(mvp, trans, (GLfloat *) rot);
125   mat_multiply(mvp, Projection, mvp);
126   /* Set the MVP matrix */
127   glUniformMatrix4fv(uModelViewProj, 1, GL_FALSE, (float *) mvp);
128
129   /* Draw */
130   glDrawArrays(GL_TRIANGLES, 0, 3);
131
132   glutSwapBuffers();
133}
134
135
136static void
137Idle(void)
138{
139   static const float yAxis[3] = {0, 1, 0};
140   static double t0 = -1.;
141   float quat[4];
142   double dt, t = glutGet(GLUT_ELAPSED_TIME) / 2000.0;
143   if (t0 < 0.0)
144      t0 = t;
145   dt = t - t0;
146   t0 = t;
147
148   axis_to_quat(yAxis, 2.0 * dt, quat);
149   add_quats(quat, CurQuat, CurQuat);
150
151   glutPostRedisplay();
152}
153
154
155static void
156Reshape(int width, int height)
157{
158   float ar = (float) width / height;
159   WinWidth = width;
160   WinHeight = height;
161   glViewport(0, 0, width, height);
162   mat_frustum(Projection, -ar, ar, -1, 1, 3, 25);
163
164   /* pass viewport dims to the shader */
165   {
166      GLfloat viewport[4];
167      glGetFloatv(GL_VIEWPORT, viewport);
168      glUniform2f(uViewportSize, viewport[2], viewport[3]);
169   }
170}
171
172
173static void
174MouseMotion(int x, int y)
175{
176   if (ButtonDown) {
177      float x0 = (2.0 * ButtonX - WinWidth) / WinWidth;
178      float y0 = (WinHeight - 2.0 * ButtonY) / WinHeight;
179      float x1 = (2.0 * x - WinWidth) / WinWidth;
180      float y1 = (WinHeight - 2.0 * y) / WinHeight;
181      float q[4];
182
183      trackball(q, x0, y0, x1, y1);
184      ButtonX = x;
185      ButtonY = y;
186      add_quats(q, CurQuat, CurQuat);
187
188      glutPostRedisplay();
189   }
190}
191
192
193static void
194MouseButton(int button, int state, int x, int y)
195{
196  if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
197     ButtonDown = GL_TRUE;
198     ButtonX = x;
199     ButtonY = y;
200  }
201  else if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
202     ButtonDown = GL_FALSE;
203  }
204}
205
206
207static void
208CleanUp(void)
209{
210   glDeleteShader(FragShader);
211   glDeleteShader(VertShader);
212   glDeleteShader(GeomShader);
213   glDeleteProgram(Program);
214   glDeleteVertexArrays(1, &vao);
215   glDeleteBuffers(1, &vbo);
216   glutDestroyWindow(Win);
217}
218
219
220static void
221Key(unsigned char key, int x, int y)
222{
223  (void) x;
224  (void) y;
225
226   switch(key) {
227   case ' ':
228   case 'a':
229      Anim = !Anim;
230      if (Anim) {
231         glutIdleFunc(Idle);
232      }
233      else
234         glutIdleFunc(NULL);
235      break;
236   case 27:
237      CleanUp();
238      exit(0);
239      break;
240   }
241   glutPostRedisplay();
242}
243
244
245static void
246Init(void)
247{
248   const GLubyte *version;
249   static const char *vertShaderText =
250      "#version 150 \n"
251      "uniform mat4 ModelViewProjection; \n"
252      "in vec4 Vertex; \n"
253      "void main() \n"
254      "{ \n"
255      "   gl_Position = ModelViewProjection * Vertex; \n"
256      "} \n";
257   static const char *geomShaderText =
258      "#version 150 \n"
259      "layout(triangles) in; \n"
260      "layout(triangle_strip, max_vertices = 3) out; \n"
261      "uniform vec2 ViewportSize; \n"
262      "out vec2 Vert0, Vert1, Vert2; \n"
263      "\n"
264      "// Transform NDC coord to window coord \n"
265      "vec2 vpxform(vec4 p) \n"
266      "{ \n"
267      "   return (p.xy / p.w + 1.0) * 0.5 * ViewportSize; \n"
268      "} \n"
269      "\n"
270      "void main() \n"
271      "{ \n"
272      "   Vert0 = vpxform(gl_in[0].gl_Position); \n"
273      "   Vert1 = vpxform(gl_in[1].gl_Position); \n"
274      "   Vert2 = vpxform(gl_in[2].gl_Position); \n"
275      "   gl_Position = gl_in[0].gl_Position; \n"
276      "   EmitVertex(); \n"
277      "   gl_Position = gl_in[1].gl_Position; \n"
278      "   EmitVertex(); \n"
279      "   gl_Position = gl_in[2].gl_Position; \n"
280      "   EmitVertex(); \n"
281      "} \n";
282   static const char *fragShaderText =
283      "#version 150 \n"
284      "#define LINE_WIDTH 2.5 \n"
285      "uniform vec4 Color; \n"
286      "in vec2 Vert0, Vert1, Vert2; \n"
287      "out vec4 FragColor; \n"
288      "// Compute distance from a point to a line \n"
289      "float point_line_dist(vec2 p, vec2 v1, vec2 v2) \n"
290      "{ \n"
291      "   float s = (v2.x - v1.x) * (v1.y - p.y) - (v1.x - p.x) * (v2.y - v1.y); \n"
292      "   float t = length(v2 - v1); \n"
293      "   return abs(s) / t; \n"
294      "} \n"
295      "\n"
296      "void main() \n"
297      "{ \n"
298      "   float d0 = point_line_dist(gl_FragCoord.xy, Vert0, Vert1); \n"
299      "   float d1 = point_line_dist(gl_FragCoord.xy, Vert1, Vert2); \n"
300      "   float d2 = point_line_dist(gl_FragCoord.xy, Vert2, Vert0); \n"
301      "   float m = min(d0, min(d1, d2)); \n"
302      "   FragColor = Color * smoothstep(0.0, LINE_WIDTH, m); \n"
303      "} \n";
304   static const GLfloat verts[3][2] = {
305      { -1, -1 },
306      {  1, -1 },
307      {  0,  1 }
308   };
309
310   if (!ShadersSupported())
311      exit(1);
312
313   if (!GLEW_VERSION_3_2) {
314      fprintf(stderr, "Sorry, OpenGL 3.2 or later required.\n");
315      exit(1);
316   }
317
318   VertShader = CompileShaderText(GL_VERTEX_SHADER, vertShaderText);
319   FragShader = CompileShaderText(GL_FRAGMENT_SHADER, fragShaderText);
320   GeomShader = CompileShaderText(GL_GEOMETRY_SHADER, geomShaderText);
321
322   Program = LinkShaders3(VertShader, GeomShader, FragShader);
323   assert(Program);
324   CheckError(__LINE__);
325
326   glBindAttribLocation(Program, 0, "Vertex");
327   glBindFragDataLocation(Program, 0, "FragColor");
328
329   /* relink */
330   glLinkProgram(Program);
331
332   assert(glIsProgram(Program));
333   assert(glIsShader(FragShader));
334   assert(glIsShader(VertShader));
335   assert(glIsShader(GeomShader));
336
337   glUseProgram(Program);
338
339   uViewportSize = glGetUniformLocation(Program, "ViewportSize");
340   uModelViewProj = glGetUniformLocation(Program, "ModelViewProjection");
341   uColor = glGetUniformLocation(Program, "Color");
342
343   glUniform4fv(uColor, 1, Orange);
344
345   glGenBuffers(1, &vbo);
346   glBindBuffer(GL_ARRAY_BUFFER, vbo);
347   glBufferData(GL_ARRAY_BUFFER, sizeof(verts), verts, GL_STATIC_DRAW);
348
349   glGenVertexArrays(1, &vao);
350   glBindVertexArray(vao);
351
352   glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
353   glEnableVertexAttribArray(0);
354
355   glClearColor(0.3f, 0.3f, 0.3f, 0.0f);
356   glEnable(GL_DEPTH_TEST);
357
358   printf("GL_RENDERER = %s\n",(const char *) glGetString(GL_RENDERER));
359}
360
361
362int
363main(int argc, char *argv[])
364{
365   glutInit(&argc, argv);
366   glutInitWindowSize(WinWidth, WinHeight);
367#ifdef HAVE_FREEGLUT
368   glutInitContextVersion(3, 2);
369   glutInitContextProfile(GLUT_CORE_PROFILE);
370   glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
371#elif defined __APPLE__
372   glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
373#else
374   glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
375#endif
376   Win = glutCreateWindow(argv[0]);
377   /* glewInit requires glewExperimentel set to true for core profiles.
378    * Depending on the glew version it also generates a GL_INVALID_ENUM.
379    */
380   glewExperimental = GL_TRUE;
381   glewInit();
382   glGetError();
383   glutReshapeFunc(Reshape);
384   glutKeyboardFunc(Key);
385   glutDisplayFunc(Redisplay);
386   glutMotionFunc(MouseMotion);
387   glutMouseFunc(MouseButton);
388   if (Anim)
389      glutIdleFunc(Idle);
390
391   Init();
392   glutMainLoop();
393   return 0;
394}
395