texture_from_tga.cpp 2.2 KB

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