InitShader.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #include "Angel.h"
  2. namespace Angel {
  3. // Create a NULL-terminated string by reading the provided file
  4. static char*
  5. readShaderSource(const char* shaderFile)
  6. {
  7. FILE* fp = fopen(shaderFile, "r");
  8. if ( fp == NULL ) { return NULL; }
  9. fseek(fp, 0L, SEEK_END);
  10. long size = ftell(fp);
  11. fseek(fp, 0L, SEEK_SET);
  12. char* buf = new char[size + 1];
  13. fread(buf, 1, size, fp);
  14. buf[size] = '\0';
  15. fclose(fp);
  16. return buf;
  17. }
  18. // Create a GLSL program object from vertex and fragment shader files
  19. GLuint
  20. InitShader(const char* vShaderFile, const char* fShaderFile)
  21. {
  22. struct Shader {
  23. const char* filename;
  24. GLenum type;
  25. GLchar* source;
  26. } shaders[2] = {
  27. { vShaderFile, GL_VERTEX_SHADER, NULL },
  28. { fShaderFile, GL_FRAGMENT_SHADER, NULL }
  29. };
  30. GLuint program = glCreateProgram();
  31. for ( int i = 0; i < 2; ++i ) {
  32. Shader& s = shaders[i];
  33. s.source = readShaderSource( s.filename );
  34. if ( shaders[i].source == NULL ) {
  35. std::cerr << "Failed to read " << s.filename << std::endl;
  36. exit( EXIT_FAILURE );
  37. }
  38. GLuint shader = glCreateShader( s.type );
  39. glShaderSource( shader, 1, (const GLchar**) &s.source, NULL );
  40. glCompileShader( shader );
  41. GLint compiled;
  42. glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
  43. if ( !compiled ) {
  44. std::cerr << s.filename << " failed to compile:" << std::endl;
  45. GLint logSize;
  46. glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
  47. char* logMsg = new char[logSize];
  48. glGetShaderInfoLog( shader, logSize, NULL, logMsg );
  49. std::cerr << logMsg << std::endl;
  50. delete [] logMsg;
  51. exit( EXIT_FAILURE );
  52. }
  53. delete [] s.source;
  54. glAttachShader( program, shader );
  55. }
  56. /* link and error check */
  57. glLinkProgram(program);
  58. GLint linked;
  59. glGetProgramiv( program, GL_LINK_STATUS, &linked );
  60. if ( !linked ) {
  61. std::cerr << "Shader program failed to link" << std::endl;
  62. GLint logSize;
  63. glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize);
  64. char* logMsg = new char[logSize];
  65. glGetProgramInfoLog( program, logSize, NULL, logMsg );
  66. std::cerr << logMsg << std::endl;
  67. delete [] logMsg;
  68. exit( EXIT_FAILURE );
  69. }
  70. /* use program object */
  71. glUseProgram(program);
  72. return program;
  73. }
  74. } // Close namespace Angel block