texture_from_tga.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "texture_from_tga.h"
  2. #ifndef IGL_NO_OPENGL
  3. #include "tga.h"
  4. #include "report_gl_error.h"
  5. #include <cstring>
  6. IGL_INLINE bool igl::texture_from_tga(const std::string tga_file, GLuint & id)
  7. {
  8. using namespace std;
  9. using namespace igl;
  10. // read pixels to tga file
  11. FILE * imgFile;
  12. // "-" as input file name is code for read from stdin
  13. imgFile = fopen(tga_file.c_str(),"r");
  14. if(NULL==imgFile)
  15. {
  16. printf("IOError: %s could not be opened...",tga_file.c_str());
  17. return false;
  18. }
  19. // gliReadTGA annoyingly uses char * instead of const char *
  20. size_t len = tga_file.length();
  21. char* tga_file_char = new char [ len + 1 ];
  22. strcpy( tga_file_char, tga_file.c_str() );
  23. // read image
  24. gliGenericImage* img = gliReadTGA(imgFile, tga_file_char, 0, 0);
  25. // clean up filename buffer
  26. delete[] tga_file_char;
  27. fclose( imgFile );
  28. // set up texture mapping parameters and generate texture id
  29. glGenTextures(1,&id);
  30. glBindTexture(GL_TEXTURE_2D, id);
  31. // Texture parameters
  32. float empty[] = {1.0f,1.0f,1.0f,0.0f};
  33. glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,empty);
  34. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  35. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  36. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
  37. // GL_LINEAR_MIPMAP_NEAREST);
  38. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  39. GL_LINEAR);
  40. // OpenGL by default tries to read data in multiples of 4, if our data is
  41. // only RGB or BGR and the width is not divible by 4 then we need to alert
  42. // opengl
  43. if((img->width % 4) != 0 &&
  44. (img->format == GL_RGB ||
  45. img->format == GL_BGR))
  46. {
  47. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  48. igl::report_gl_error();
  49. }
  50. // Load texture
  51. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->width,
  52. img->height, 0, img->format, GL_UNSIGNED_BYTE,
  53. img->pixels);
  54. return id;
  55. }
  56. #endif