Advertisement
Guest User

SDLTest testshader.c

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