texture_from_tga.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #ifndef IGL_TEXTURE_FROM_TGA
  2. #define IGL_TEXTURE_FROM_TGA
  3. #if __APPLE__
  4. # include <OpenGL/gl.h>
  5. #else
  6. # ifdef _WIN32
  7. # define NOMINMAX
  8. # include <Windows.h>
  9. # undef NOMINMAX
  10. # endif
  11. # include <GL/gl.h>
  12. #endif
  13. namespace igl
  14. {
  15. // Read an image from a .tga file and use it as a texture
  16. //
  17. // Input:
  18. // tga_file path to .tga file
  19. // Output:
  20. // id of generated openGL texture
  21. // Returns true on success, false on failure
  22. inline bool texture_from_tga(const std::string tga_file, GLuint & id);
  23. }
  24. // Implementation
  25. #include "tga.h"
  26. inline bool igl::texture_from_tga(const std::string tga_file, GLuint & id)
  27. {
  28. using namespace std;
  29. using namespace igl;
  30. // read pixels to tga file
  31. FILE * imgFile;
  32. // "-" as input file name is code for read from stdin
  33. imgFile = fopen(tga_file.c_str(),"r");
  34. if(NULL==imgFile)
  35. {
  36. printf("IOError: %s could not be opened...",tga_file.c_str());
  37. return false;
  38. }
  39. // gliReadTGA annoyingly uses char * instead of const char *
  40. size_t len = tga_file.length();
  41. char* tga_file_char = new char [ len + 1 ];
  42. strcpy( tga_file_char, tga_file.c_str() );
  43. // read image
  44. gliGenericImage* img = gliReadTGA(imgFile, tga_file_char, 0, 0);
  45. // clean up filename buffer
  46. delete[] tga_file_char;
  47. fclose( imgFile );
  48. // set up texture mapping parameters and generate texture id
  49. glGenTextures(1,&id);
  50. glBindTexture(GL_TEXTURE_2D, id);
  51. // Texture parameters
  52. float empty[] = {1.0f,1.0f,1.0f,0.0f};
  53. glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,empty);
  54. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  55. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  56. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
  57. // GL_LINEAR_MIPMAP_NEAREST);
  58. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  59. GL_LINEAR);
  60. // OpenGL by default tries to read data in multiples of 4, if our data is
  61. // only RGB or BGR and the width is not divible by 4 then we need to alert
  62. // opengl
  63. if((img->width % 4) != 0 &&
  64. (img->format == GL_RGB ||
  65. img->format == GL_BGR))
  66. {
  67. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  68. }
  69. // Load texture
  70. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->width,
  71. img->height, 0, img->format, GL_UNSIGNED_BYTE,
  72. img->pixels);
  73. return id;
  74. }
  75. #endif