Debian Codegraph @

test/testshader.c

raw
1 /*
2 Copyright (C) 1997-2026 Sam Lantinga <[email protected]>
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely.
11 */
12 /* This is a simple example of using GLSL shaders with SDL */
13
14 #include <stdlib.h>
15 #include "SDL.h"
16
17 #ifdef HAVE_OPENGL
18
19 #include "SDL_opengl.h"
20
21 static SDL_bool shaders_supported;
22 static int current_shader = 0;
23
24 enum
25 {
26 SHADER_COLOR,
27 SHADER_TEXTURE,
28 SHADER_TEXCOORDS,
29 NUM_SHADERS
30 };
31
32 typedef struct
33 {
34 GLhandleARB program;
35 GLhandleARB vert_shader;
36 GLhandleARB frag_shader;
37 const char *vert_source;
38 const char *frag_source;
39 } ShaderData;
40
41 static ShaderData shaders[NUM_SHADERS] = {
42
43 /* SHADER_COLOR */
44 { 0, 0, 0,
45 /* vertex shader */
46 "varying vec4 v_color;\n"
47 "\n"
48 "void main()\n"
49 "{\n"
50 " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
51 " v_color = gl_Color;\n"
52 "}",
53 /* fragment shader */
54 "varying vec4 v_color;\n"
55 "\n"
56 "void main()\n"
57 "{\n"
58 " gl_FragColor = v_color;\n"
59 "}" },
60
61 /* SHADER_TEXTURE */
62 { 0, 0, 0,
63 /* vertex shader */
64 "varying vec4 v_color;\n"
65 "varying vec2 v_texCoord;\n"
66 "\n"
67 "void main()\n"
68 "{\n"
69 " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
70 " v_color = gl_Color;\n"
71 " v_texCoord = vec2(gl_MultiTexCoord0);\n"
72 "}",
73 /* fragment shader */
74 "varying vec4 v_color;\n"
75 "varying vec2 v_texCoord;\n"
76 "uniform sampler2D tex0;\n"
77 "\n"
78 "void main()\n"
79 "{\n"
80 " gl_FragColor = texture2D(tex0, v_texCoord) * v_color;\n"
81 "}" },
82
83 /* SHADER_TEXCOORDS */
84 { 0, 0, 0,
85 /* vertex shader */
86 "varying vec2 v_texCoord;\n"
87 "\n"
88 "void main()\n"
89 "{\n"
90 " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
91 " v_texCoord = vec2(gl_MultiTexCoord0);\n"
92 "}",
93 /* fragment shader */
94 "varying vec2 v_texCoord;\n"
95 "\n"
96 "void main()\n"
97 "{\n"
98 " vec4 color;\n"
99 " vec2 delta;\n"
100 " float dist;\n"
101 "\n"
102 " delta = vec2(0.5, 0.5) - v_texCoord;\n"
103 " dist = dot(delta, delta);\n"
104 "\n"
105 " color.r = v_texCoord.x;\n"
106 " color.g = v_texCoord.x * v_texCoord.y;\n"
107 " color.b = v_texCoord.y;\n"
108 " color.a = 1.0 - (dist * 4.0);\n"
109 " gl_FragColor = color;\n"
110 "}" },
111 };
112
113 static PFNGLATTACHOBJECTARBPROC pglAttachObjectARB;
114 static PFNGLCOMPILESHADERARBPROC pglCompileShaderARB;
115 static PFNGLCREATEPROGRAMOBJECTARBPROC pglCreateProgramObjectARB;
116 static PFNGLCREATESHADEROBJECTARBPROC pglCreateShaderObjectARB;
117 static PFNGLDELETEOBJECTARBPROC pglDeleteObjectARB;
118 static PFNGLGETINFOLOGARBPROC pglGetInfoLogARB;
119 static PFNGLGETOBJECTPARAMETERIVARBPROC pglGetObjectParameterivARB;
120 static PFNGLGETUNIFORMLOCATIONARBPROC pglGetUniformLocationARB;
121 static PFNGLLINKPROGRAMARBPROC pglLinkProgramARB;
122 static PFNGLSHADERSOURCEARBPROC pglShaderSourceARB;
123 static PFNGLUNIFORM1IARBPROC pglUniform1iARB;
124 static PFNGLUSEPROGRAMOBJECTARBPROC pglUseProgramObjectARB;
125
126 static SDL_bool CompileShader(GLhandleARB shader, const char *source)
127 {
128 GLint status = 0;
129
130 pglShaderSourceARB(shader, 1, &source, NULL);
131 pglCompileShaderARB(shader);
132 pglGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &status);
133 if (status == 0) {
134 GLint length = 0;
135 char *info;
136
137 pglGetObjectParameterivARB(shader, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length);
138 info = (char *)SDL_malloc((size_t)length + 1);
139 if (!info) {
140 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!");
141 } else {
142 pglGetInfoLogARB(shader, length, NULL, info);
143 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to compile shader:\n%s\n%s", source, info);
144 SDL_free(info);
145 }
146 return SDL_FALSE;
147 } else {
148 return SDL_TRUE;
149 }
150 }
151
152 static SDL_bool LinkProgram(ShaderData *data)
153 {
154 GLint status = 0;
155
156 pglAttachObjectARB(data->program, data->vert_shader);
157 pglAttachObjectARB(data->program, data->frag_shader);
158 pglLinkProgramARB(data->program);
159
160 pglGetObjectParameterivARB(data->program, GL_OBJECT_LINK_STATUS_ARB, &status);
161 if (status == 0) {
162 GLint length = 0;
163 char *info;
164
165 pglGetObjectParameterivARB(data->program, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length);
166 info = (char *)SDL_malloc((size_t)length + 1);
167 if (!info) {
168 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!");
169 } else {
170 pglGetInfoLogARB(data->program, length, NULL, info);
171 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to link program:\n%s", info);
172 SDL_free(info);
173 }
174 return SDL_FALSE;
175 } else {
176 return SDL_TRUE;
177 }
178 }
179
180 static SDL_bool CompileShaderProgram(ShaderData *data)
181 {
182 const int num_tmus_bound = 4;
183 int i;
184 GLint location;
185
186 glGetError();
187
188 /* Create one program object to rule them all */
189 data->program = pglCreateProgramObjectARB();
190
191 /* Create the vertex shader */
192 data->vert_shader = pglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
193 if (!CompileShader(data->vert_shader, data->vert_source)) {
194 return SDL_FALSE;
195 }
196
197 /* Create the fragment shader */
198 data->frag_shader = pglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
199 if (!CompileShader(data->frag_shader, data->frag_source)) {
200 return SDL_FALSE;
201 }
202
203 /* ... and in the darkness bind them */
204 if (!LinkProgram(data)) {
205 return SDL_FALSE;
206 }
207
208 /* Set up some uniform variables */
209 pglUseProgramObjectARB(data->program);
210 for (i = 0; i < num_tmus_bound; ++i) {
211 char tex_name[5];
212 (void)SDL_snprintf(tex_name, SDL_arraysize(tex_name), "tex%d", i);
213 location = pglGetUniformLocationARB(data->program, tex_name);
214 if (location >= 0) {
215 pglUniform1iARB(location, i);
216 }
217 }
218 pglUseProgramObjectARB(0);
219
220 return (glGetError() == GL_NO_ERROR) ? SDL_TRUE : SDL_FALSE;
221 }
222
223 static void DestroyShaderProgram(ShaderData *data)
224 {
225 if (shaders_supported) {
226 pglDeleteObjectARB(data->vert_shader);
227 pglDeleteObjectARB(data->frag_shader);
228 pglDeleteObjectARB(data->program);
229 }
230 }
231
232 static SDL_bool InitShaders(void)
233 {
234 int i;
235
236 /* Check for shader support */
237 shaders_supported = SDL_FALSE;
238 if (SDL_GL_ExtensionSupported("GL_ARB_shader_objects") &&
239 SDL_GL_ExtensionSupported("GL_ARB_shading_language_100") &&
240 SDL_GL_ExtensionSupported("GL_ARB_vertex_shader") &&
241 SDL_GL_ExtensionSupported("GL_ARB_fragment_shader")) {
242 pglAttachObjectARB = (PFNGLATTACHOBJECTARBPROC)SDL_GL_GetProcAddress("glAttachObjectARB");
243 pglCompileShaderARB = (PFNGLCOMPILESHADERARBPROC)SDL_GL_GetProcAddress("glCompileShaderARB");
244 pglCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glCreateProgramObjectARB");
245 pglCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC)SDL_GL_GetProcAddress("glCreateShaderObjectARB");
246 pglDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC)SDL_GL_GetProcAddress("glDeleteObjectARB");
247 pglGetInfoLogARB = (PFNGLGETINFOLOGARBPROC)SDL_GL_GetProcAddress("glGetInfoLogARB");
248 pglGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC)SDL_GL_GetProcAddress("glGetObjectParameterivARB");
249 pglGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC)SDL_GL_GetProcAddress("glGetUniformLocationARB");
250 pglLinkProgramARB = (PFNGLLINKPROGRAMARBPROC)SDL_GL_GetProcAddress("glLinkProgramARB");
251 pglShaderSourceARB = (PFNGLSHADERSOURCEARBPROC)SDL_GL_GetProcAddress("glShaderSourceARB");
252 pglUniform1iARB = (PFNGLUNIFORM1IARBPROC)SDL_GL_GetProcAddress("glUniform1iARB");
253 pglUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC)SDL_GL_GetProcAddress("glUseProgramObjectARB");
254 if (pglAttachObjectARB &&
255 pglCompileShaderARB &&
256 pglCreateProgramObjectARB &&
257 pglCreateShaderObjectARB &&
258 pglDeleteObjectARB &&
259 pglGetInfoLogARB &&
260 pglGetObjectParameterivARB &&
261 pglGetUniformLocationARB &&
262 pglLinkProgramARB &&
263 pglShaderSourceARB &&
264 pglUniform1iARB &&
265 pglUseProgramObjectARB) {
266 shaders_supported = SDL_TRUE;
267 }
268 }
269
270 if (!shaders_supported) {
271 return SDL_FALSE;
272 }
273
274 /* Compile all the shaders */
275 for (i = 0; i < NUM_SHADERS; ++i) {
276 if (!CompileShaderProgram(&shaders[i])) {
277 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to compile shader!\n");
278 return SDL_FALSE;
279 }
280 }
281
282 /* We're done! */
283 return SDL_TRUE;
284 }
285
286 static void QuitShaders(void)
287 {
288 int i;
289
290 for (i = 0; i < NUM_SHADERS; ++i) {
291 DestroyShaderProgram(&shaders[i]);
292 }
293 }
294
295 /* Quick utility function for texture creation */
296 static int
297 power_of_two(int input)
298 {
299 int value = 1;
300
301 while (value < input) {
302 value <<= 1;
303 }
304 return value;
305 }
306
307 GLuint
308 SDL_GL_LoadTexture(SDL_Surface *surface, GLfloat *texcoord)
309 {
310 GLuint texture;
311 int w, h;
312 SDL_Surface *image;
313 SDL_Rect area;
314 SDL_BlendMode saved_mode;
315
316 /* Use the surface width and height expanded to powers of 2 */
317 w = power_of_two(surface->w);
318 h = power_of_two(surface->h);
319 texcoord[0] = 0.0f; /* Min X */
320 texcoord[1] = 0.0f; /* Min Y */
321 texcoord[2] = (GLfloat)surface->w / w; /* Max X */
322 texcoord[3] = (GLfloat)surface->h / h; /* Max Y */
323
324 image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32,
325 #if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
326 0x000000FF,
327 0x0000FF00, 0x00FF0000, 0xFF000000
328 #else
329 0xFF000000,
330 0x00FF0000, 0x0000FF00, 0x000000FF
331 #endif
332 );
333 if (!image) {
334 return 0;
335 }
336
337 /* Save the alpha blending attributes */
338 SDL_GetSurfaceBlendMode(surface, &saved_mode);
339 SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);
340
341 /* Copy the surface into the GL texture image */
342 area.x = 0;
343 area.y = 0;
344 area.w = surface->w;
345 area.h = surface->h;
346 SDL_BlitSurface(surface, &area, image, &area);
347
348 /* Restore the alpha blending attributes */
349 SDL_SetSurfaceBlendMode(surface, saved_mode);
350
351 /* Create an OpenGL texture for the image */
352 glGenTextures(1, &texture);
353 glBindTexture(GL_TEXTURE_2D, texture);
354 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
355 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
356 glTexImage2D(GL_TEXTURE_2D,
357 0,
358 GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);
359 SDL_FreeSurface(image); /* No longer needed */
360
361 return texture;
362 }
363
364 /* A general OpenGL initialization function. Sets all of the initial parameters. */
365 void InitGL(int Width, int Height) /* We call this right after our OpenGL window is created. */
366 {
367 GLdouble aspect;
368
369 glViewport(0, 0, Width, Height);
370 glClearColor(0.0f, 0.0f, 0.0f, 0.0f); /* This Will Clear The Background Color To Black */
371 glClearDepth(1.0); /* Enables Clearing Of The Depth Buffer */
372 glDepthFunc(GL_LESS); /* The Type Of Depth Test To Do */
373 glEnable(GL_DEPTH_TEST); /* Enables Depth Testing */
374 glShadeModel(GL_SMOOTH); /* Enables Smooth Color Shading */
375
376 glMatrixMode(GL_PROJECTION);
377 glLoadIdentity(); /* Reset The Projection Matrix */
378
379 aspect = (GLdouble)Width / Height;
380 glOrtho(-3.0, 3.0, -3.0 / aspect, 3.0 / aspect, 0.0, 1.0);
381
382 glMatrixMode(GL_MODELVIEW);
383 }
384
385 /* The main drawing function. */
386 void DrawGLScene(SDL_Window *window, GLuint texture, GLfloat *texcoord)
387 {
388 /* Texture coordinate lookup, to make it simple */
389 enum
390 {
391 MINX,
392 MINY,
393 MAXX,
394 MAXY
395 };
396
397 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Clear The Screen And The Depth Buffer */
398 glLoadIdentity(); /* Reset The View */
399
400 glTranslatef(-1.5f, 0.0f, 0.0f); /* Move Left 1.5 Units */
401
402 /* draw a triangle (in smooth coloring mode) */
403 glBegin(GL_POLYGON); /* start drawing a polygon */
404 glColor3f(1.0f, 0.0f, 0.0f); /* Set The Color To Red */
405 glVertex3f(0.0f, 1.0f, 0.0f); /* Top */
406 glColor3f(0.0f, 1.0f, 0.0f); /* Set The Color To Green */
407 glVertex3f(1.0f, -1.0f, 0.0f); /* Bottom Right */
408 glColor3f(0.0f, 0.0f, 1.0f); /* Set The Color To Blue */
409 glVertex3f(-1.0f, -1.0f, 0.0f); /* Bottom Left */
410 glEnd(); /* we're done with the polygon (smooth color interpolation) */
411
412 glTranslatef(3.0f, 0.0f, 0.0f); /* Move Right 3 Units */
413
414 /* Enable blending */
415 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
416 glEnable(GL_BLEND);
417 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
418
419 /* draw a textured square (quadrilateral) */
420 glEnable(GL_TEXTURE_2D);
421 glBindTexture(GL_TEXTURE_2D, texture);
422 glColor3f(1.0f, 1.0f, 1.0f);
423 if (shaders_supported) {
424 pglUseProgramObjectARB(shaders[current_shader].program);
425 }
426
427 glBegin(GL_QUADS); /* start drawing a polygon (4 sided) */
428 glTexCoord2f(texcoord[MINX], texcoord[MINY]);
429 glVertex3f(-1.0f, 1.0f, 0.0f); /* Top Left */
430 glTexCoord2f(texcoord[MAXX], texcoord[MINY]);
431 glVertex3f(1.0f, 1.0f, 0.0f); /* Top Right */
432 glTexCoord2f(texcoord[MAXX], texcoord[MAXY]);
433 glVertex3f(1.0f, -1.0f, 0.0f); /* Bottom Right */
434 glTexCoord2f(texcoord[MINX], texcoord[MAXY]);
435 glVertex3f(-1.0f, -1.0f, 0.0f); /* Bottom Left */
436 glEnd(); /* done with the polygon */
437
438 if (shaders_supported) {
439 pglUseProgramObjectARB(0);
440 }
441 glDisable(GL_TEXTURE_2D);
442
443 /* swap buffers to display, since we're double buffered. */
444 SDL_GL_SwapWindow(window);
445 }
446
447 int main(int argc, char **argv)
448 {
449 int done;
450 SDL_Window *window;
451 SDL_Surface *surface;
452 GLuint texture;
453 GLfloat texcoords[4];
454
455 /* Enable standard application logging */
456 SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
457
458 /* Initialize SDL for video output */
459 if (SDL_Init(SDL_INIT_VIDEO) < 0) {
460 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL: %s\n", SDL_GetError());
461 exit(1);
462 }
463
464 /* Create a 640x480 OpenGL screen */
465 window = SDL_CreateWindow("Shader Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL);
466 if (!window) {
467 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create OpenGL window: %s\n", SDL_GetError());
468 SDL_Quit();
469 exit(2);
470 }
471
472 if (!SDL_GL_CreateContext(window)) {
473 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create OpenGL context: %s\n", SDL_GetError());
474 SDL_Quit();
475 exit(2);
476 }
477
478 surface = SDL_LoadBMP("icon.bmp");
479 if (!surface) {
480 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load icon.bmp: %s\n", SDL_GetError());
481 SDL_Quit();
482 exit(3);
483 }
484 texture = SDL_GL_LoadTexture(surface, texcoords);
485 SDL_FreeSurface(surface);
486
487 /* Loop, drawing and checking events */
488 InitGL(640, 480);
489 if (InitShaders()) {
490 SDL_Log("Shaders supported, press SPACE to cycle them.\n");
491 } else {
492 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shaders not supported!\n");
493 }
494 done = 0;
495 while (!done) {
496 DrawGLScene(window, texture, texcoords);
497
498 /* This could go in a separate function */
499 {
500 SDL_Event event;
501 while (SDL_PollEvent(&event)) {
502 if (event.type == SDL_QUIT) {
503 done = 1;
504 }
505 if (event.type == SDL_KEYDOWN) {
506 if (event.key.keysym.sym == SDLK_SPACE) {
507 current_shader = (current_shader + 1) % NUM_SHADERS;
508 }
509 if (event.key.keysym.sym == SDLK_ESCAPE) {
510 done = 1;
511 }
512 }
513 }
514 }
515 }
516 QuitShaders();
517 SDL_Quit();
518 return 1;
519 }
520
521 #else /* HAVE_OPENGL */
522
523 int main(int argc, char *argv[])
524 {
525 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No OpenGL support on this system\n");
526 return 1;
527 }
528
529 #endif /* HAVE_OPENGL */
530
531 /* vi: set ts=4 sw=4 expandtab: */