texture_from_tga.cpp 1.8 KB

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