Browse Source

render to tga

Former-commit-id: f4d352d143dedd5aa0361628cead3c82a8ea60e8
jalec 13 years ago
parent
commit
5c3a8ff977
2 changed files with 98 additions and 0 deletions
  1. 72 0
      include/igl/render_to_tga.cpp
  2. 26 0
      include/igl/render_to_tga.h

+ 72 - 0
include/igl/render_to_tga.cpp

@@ -0,0 +1,72 @@
+#include "render_to_tga.h"
+#include "tga.h"
+
+IGL_INLINE bool igl::render_to_tga(
+  const std::string tga_file,
+  const int width,
+  const int height,
+  const bool alpha)
+{
+
+  size_t components = 3;
+  GLenum format = GL_BGR;
+  if(alpha)
+  {
+    format = GL_BGRA;
+    components = 4;
+  }
+  GLubyte * cmap = NULL;
+
+  // OpenGL by default tries to read data in multiples of 4, if our data is
+  // only RGB or BGR and the width is not divible by 4 then we need to alert
+  // opengl
+  if((width % 4) != 0 && 
+   (format == GL_RGB || 
+    format == GL_BGR))
+  {
+    glPixelStorei(GL_PACK_ALIGNMENT, 1);
+  }
+  GLubyte *pixels;
+  pixels = (unsigned char *) malloc (width * height * components);
+  glReadPixels(
+    0,
+    0,
+    width,
+    height,
+    format,
+    GL_UNSIGNED_BYTE,
+    pixels);
+
+  // set up generic image struct
+  gliGenericImage * genericImage;
+  genericImage = (gliGenericImage*) malloc(sizeof(gliGenericImage));
+  genericImage->width = width;
+  genericImage->height = height;
+  genericImage->format = format;
+  genericImage->components = components;
+  genericImage->pixels = pixels;
+  // CMAP is not supported, but we need to put something here
+  genericImage->cmapEntries = 0;
+  genericImage->cmapFormat = GL_BGR_EXT;  // XXX fix me
+  genericImage->cmap = cmap;
+
+  // write pixels to tga file
+  FILE * imgFile;
+  // "-" as output file name is code for write to stdout
+  if(tga_file.compare("-") == 0)
+  {
+    imgFile = stdout;
+  }else{
+    imgFile = fopen(tga_file.c_str(),"w");
+    if(NULL==imgFile)
+    {
+      printf("IOError: %s could not be opened...",tga_file.c_str());
+      return false;
+    }
+  }
+
+  writeTGA(genericImage,imgFile);
+
+  free(genericImage);
+  return true;
+}

+ 26 - 0
include/igl/render_to_tga.h

@@ -0,0 +1,26 @@
+#ifndef IGL_RENDER_TO_TGA_H
+#define IGL_RENDER_TO_TGA_H
+#include "igl_inline.h"
+
+#include <string>
+namespace igl
+{
+  // Render current open GL image to .tga file
+  // Inputs:
+  //   tga_file  path to output .tga file
+  //   width  width of scene and resulting image
+  //   height height of scene and resulting image
+  ///  alpha  whether to include alpha channel
+  // Returns true only if no errors occured
+  IGL_INLINE bool render_to_tga(
+    const std::string tga_file,
+    const int width,
+    const int height,
+    const bool alpha);
+}
+
+#ifdef IGL_HEADER_ONLY
+#  include "render_to_tga.cpp"
+#endif
+
+#endif