texture_from_tga.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "texture_from_tga.h"
  9. #ifndef IGL_NO_OPENGL
  10. #include "tga.h"
  11. #include "report_gl_error.h"
  12. #include <cstring>
  13. IGL_INLINE bool igl::texture_from_tga(const std::string tga_file, GLuint & id)
  14. {
  15. using namespace std;
  16. using namespace igl;
  17. // read pixels to tga file
  18. FILE * imgFile;
  19. // "-" as input file name is code for read from stdin
  20. imgFile = fopen(tga_file.c_str(),"r");
  21. if(NULL==imgFile)
  22. {
  23. printf("IOError: %s could not be opened...",tga_file.c_str());
  24. return false;
  25. }
  26. // gliReadTGA annoyingly uses char * instead of const char *
  27. size_t len = tga_file.length();
  28. char* tga_file_char = new char [ len + 1 ];
  29. strcpy( tga_file_char, tga_file.c_str() );
  30. // read image
  31. gliGenericImage* img = gliReadTGA(imgFile, tga_file_char, 0, 0);
  32. // clean up filename buffer
  33. delete[] tga_file_char;
  34. fclose( imgFile );
  35. // set up texture mapping parameters and generate texture id
  36. glGenTextures(1,&id);
  37. glBindTexture(GL_TEXTURE_2D, id);
  38. // Texture parameters
  39. float empty[] = {1.0f,1.0f,1.0f,0.0f};
  40. glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,empty);
  41. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  42. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  43. //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
  44. // GL_LINEAR_MIPMAP_NEAREST);
  45. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
  46. GL_LINEAR);
  47. // OpenGL by default tries to read data in multiples of 4, if our data is
  48. // only RGB or BGR and the width is not divible by 4 then we need to alert
  49. // opengl
  50. if((img->width % 4) != 0 &&
  51. (img->format == GL_RGB ||
  52. img->format == GL_BGR))
  53. {
  54. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  55. igl::report_gl_error();
  56. }
  57. // Load texture
  58. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img->width,
  59. img->height, 0, img->format, GL_UNSIGNED_BYTE,
  60. img->pixels);
  61. return id;
  62. }
  63. #endif