render_to_tga.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "render_to_tga.h"
  2. #include "tga.h"
  3. #if __APPLE__
  4. # include <OpenGL/gl.h>
  5. #elif defined(_WIN32)
  6. # define NOMINMAX
  7. # include <Windows.h>
  8. # undef NOMINMAX
  9. # include <GL/glew.h>
  10. # include <GL/gl.h>
  11. #else
  12. # define GL_GLEXT_PROTOTYPES
  13. # include <GL/gl.h>
  14. # include <GL/glext.h>
  15. #endif
  16. #include <cstdlib>
  17. IGL_INLINE bool igl::render_to_tga(
  18. const std::string tga_file,
  19. const int width,
  20. const int height,
  21. const bool alpha)
  22. {
  23. size_t components = 3;
  24. GLenum format = GL_BGR;
  25. if(alpha)
  26. {
  27. format = GL_BGRA;
  28. components = 4;
  29. }
  30. GLubyte * cmap = NULL;
  31. // OpenGL by default tries to read data in multiples of 4, if our data is
  32. // only RGB or BGR and the width is not divible by 4 then we need to alert
  33. // opengl
  34. if((width % 4) != 0 &&
  35. (format == GL_RGB ||
  36. format == GL_BGR))
  37. {
  38. glPixelStorei(GL_PACK_ALIGNMENT, 1);
  39. }
  40. GLubyte *pixels;
  41. pixels = (unsigned char *) malloc (width * height * components);
  42. glReadPixels(
  43. 0,
  44. 0,
  45. width,
  46. height,
  47. format,
  48. GL_UNSIGNED_BYTE,
  49. pixels);
  50. // set up generic image struct
  51. gliGenericImage * genericImage;
  52. genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
  53. genericImage->width = width;
  54. genericImage->height = height;
  55. genericImage->format = format;
  56. genericImage->components = components;
  57. genericImage->pixels = pixels;
  58. // CMAP is not supported, but we need to put something here
  59. genericImage->cmapEntries = 0;
  60. genericImage->cmapFormat = GL_BGR_EXT; // XXX fix me
  61. genericImage->cmap = cmap;
  62. // write pixels to tga file
  63. FILE * imgFile;
  64. // "-" as output file name is code for write to stdout
  65. if(tga_file.compare("-") == 0)
  66. {
  67. imgFile = stdout;
  68. }else{
  69. imgFile = fopen(tga_file.c_str(),"w");
  70. if(NULL==imgFile)
  71. {
  72. printf("IOError: %s could not be opened...\n",tga_file.c_str());
  73. return false;
  74. }
  75. }
  76. writeTGA(genericImage,imgFile);
  77. free(genericImage);
  78. return fclose(imgFile) == 0;
  79. }