🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

531 lines
16 KiB

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