]> code.bitgloo.com Git - clyne/gamedev2.git/commitdiff
Added SOIL for OpenGL texture loading
authorAndy Belle-Isle <drumsetmonkey@gmail.com>
Sun, 1 Sep 2019 23:02:29 +0000 (19:02 -0400)
committerAndy Belle-Isle <drumsetmonkey@gmail.com>
Sun, 1 Sep 2019 23:02:29 +0000 (19:02 -0400)
14 files changed:
lib/libSOIL.a [new file with mode: 0644]
lib/soil/soil/SOIL.c [new file with mode: 0644]
lib/soil/soil/SOIL.h [new file with mode: 0644]
lib/soil/soil/image_DXT.c [new file with mode: 0644]
lib/soil/soil/image_DXT.h [new file with mode: 0644]
lib/soil/soil/image_helper.c [new file with mode: 0644]
lib/soil/soil/image_helper.h [new file with mode: 0644]
lib/soil/soil/original/stb_image-1.09.c [new file with mode: 0644]
lib/soil/soil/original/stb_image-1.16.c [new file with mode: 0644]
lib/soil/soil/stb_image_aug.c [new file with mode: 0644]
lib/soil/soil/stb_image_aug.h [new file with mode: 0644]
lib/soil/soil/stbi_DDS_aug.h [new file with mode: 0644]
lib/soil/soil/stbi_DDS_aug_c.h [new file with mode: 0644]
lib/soil/soil/test_SOIL.cpp [new file with mode: 0644]

diff --git a/lib/libSOIL.a b/lib/libSOIL.a
new file mode 100644 (file)
index 0000000..45ae424
Binary files /dev/null and b/lib/libSOIL.a differ
diff --git a/lib/soil/soil/SOIL.c b/lib/soil/soil/SOIL.c
new file mode 100644 (file)
index 0000000..44d62db
--- /dev/null
@@ -0,0 +1,2024 @@
+/*\r
+       Jonathan Dummer\r
+       2007-07-26-10.36\r
+\r
+       Simple OpenGL Image Library\r
+\r
+       Public Domain\r
+       using Sean Barret's stb_image as a base\r
+\r
+       Thanks to:\r
+       * Sean Barret - for the awesome stb_image\r
+       * Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts\r
+       * everybody at gamedev.net\r
+*/\r
+\r
+#define SOIL_CHECK_FOR_GL_ERRORS 0\r
+\r
+#ifdef WIN32\r
+       #define WIN32_LEAN_AND_MEAN\r
+       #include <windows.h>\r
+       #include <wingdi.h>\r
+       #include <GL/gl.h>\r
+#elif defined(__APPLE__) || defined(__APPLE_CC__)\r
+       /*      I can't test this Apple stuff!  */\r
+       #include <OpenGL/gl.h>\r
+       #include <Carbon/Carbon.h>\r
+       #define APIENTRY\r
+#else\r
+       #include <GL/gl.h>\r
+       #include <GL/glx.h>\r
+#endif\r
+\r
+#include "SOIL.h"\r
+#include "stb_image_aug.h"\r
+#include "image_helper.h"\r
+#include "image_DXT.h"\r
+\r
+#include <stdlib.h>\r
+#include <string.h>\r
+\r
+/*     error reporting */\r
+char *result_string_pointer = "SOIL initialized";\r
+\r
+/*     for loading cube maps   */\r
+enum{\r
+       SOIL_CAPABILITY_UNKNOWN = -1,\r
+       SOIL_CAPABILITY_NONE = 0,\r
+       SOIL_CAPABILITY_PRESENT = 1\r
+};\r
+static int has_cubemap_capability = SOIL_CAPABILITY_UNKNOWN;\r
+int query_cubemap_capability( void );\r
+#define SOIL_TEXTURE_WRAP_R                                    0x8072\r
+#define SOIL_CLAMP_TO_EDGE                                     0x812F\r
+#define SOIL_NORMAL_MAP                                                0x8511\r
+#define SOIL_REFLECTION_MAP                                    0x8512\r
+#define SOIL_TEXTURE_CUBE_MAP                          0x8513\r
+#define SOIL_TEXTURE_BINDING_CUBE_MAP          0x8514\r
+#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_X       0x8515\r
+#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X       0x8516\r
+#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y       0x8517\r
+#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y       0x8518\r
+#define SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z       0x8519\r
+#define SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z       0x851A\r
+#define SOIL_PROXY_TEXTURE_CUBE_MAP                    0x851B\r
+#define SOIL_MAX_CUBE_MAP_TEXTURE_SIZE         0x851C\r
+/*     for non-power-of-two texture    */\r
+static int has_NPOT_capability = SOIL_CAPABILITY_UNKNOWN;\r
+int query_NPOT_capability( void );\r
+/*     for texture rectangles  */\r
+static int has_tex_rectangle_capability = SOIL_CAPABILITY_UNKNOWN;\r
+int query_tex_rectangle_capability( void );\r
+#define SOIL_TEXTURE_RECTANGLE_ARB                             0x84F5\r
+#define SOIL_MAX_RECTANGLE_TEXTURE_SIZE_ARB            0x84F8\r
+/*     for using DXT compression       */\r
+static int has_DXT_capability = SOIL_CAPABILITY_UNKNOWN;\r
+int query_DXT_capability( void );\r
+#define SOIL_RGB_S3TC_DXT1             0x83F0\r
+#define SOIL_RGBA_S3TC_DXT1            0x83F1\r
+#define SOIL_RGBA_S3TC_DXT3            0x83F2\r
+#define SOIL_RGBA_S3TC_DXT5            0x83F3\r
+typedef void (APIENTRY * P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid * data);\r
+P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC soilGlCompressedTexImage2D = NULL;\r
+unsigned int SOIL_direct_load_DDS(\r
+               const char *filename,\r
+               unsigned int reuse_texture_ID,\r
+               int flags,\r
+               int loading_as_cubemap );\r
+unsigned int SOIL_direct_load_DDS_from_memory(\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               unsigned int reuse_texture_ID,\r
+               int flags,\r
+               int loading_as_cubemap );\r
+/*     other functions */\r
+unsigned int\r
+       SOIL_internal_create_OGL_texture\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags,\r
+               unsigned int opengl_texture_type,\r
+               unsigned int opengl_texture_target,\r
+               unsigned int texture_check_size_enum\r
+       );\r
+\r
+/*     and the code magic begins here [8^)     */\r
+unsigned int\r
+       SOIL_load_OGL_texture\r
+       (\r
+               const char *filename,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels;\r
+       unsigned int tex_id;\r
+       /*      does the user want direct uploading of the image as a DDS file? */\r
+       if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )\r
+       {\r
+               /*      1st try direct loading of the image as a DDS file\r
+                       note: direct uploading will only load what is in the\r
+                       DDS file, no MIPmaps will be generated, the image will\r
+                       not be flipped, etc.    */\r
+               tex_id = SOIL_direct_load_DDS( filename, reuse_texture_ID, flags, 0 );\r
+               if( tex_id )\r
+               {\r
+                       /*      hey, it worked!!        */\r
+                       return tex_id;\r
+               }\r
+       }\r
+       /*      try to load the image   */\r
+       img = SOIL_load_image( filename, &width, &height, &channels, force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      OK, make it a texture!  */\r
+       tex_id = SOIL_internal_create_OGL_texture(\r
+                       img, width, height, channels,\r
+                       reuse_texture_ID, flags,\r
+                       GL_TEXTURE_2D, GL_TEXTURE_2D,\r
+                       GL_MAX_TEXTURE_SIZE );\r
+       /*      and nuke the image data */\r
+       SOIL_free_image_data( img );\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_HDR_texture\r
+       (\r
+               const char *filename,\r
+               int fake_HDR_format,\r
+               int rescale_to_max,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels;\r
+       unsigned int tex_id;\r
+       /*      no direct uploading of the image as a DDS file  */\r
+       /* error check */\r
+       if( (fake_HDR_format != SOIL_HDR_RGBE) &&\r
+               (fake_HDR_format != SOIL_HDR_RGBdivA) &&\r
+               (fake_HDR_format != SOIL_HDR_RGBdivA2) )\r
+       {\r
+               result_string_pointer = "Invalid fake HDR format specified";\r
+               return 0;\r
+       }\r
+       /*      try to load the image (only the HDR type) */\r
+       img = stbi_hdr_load_rgbe( filename, &width, &height, &channels, 4 );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /* the load worked, do I need to convert it? */\r
+       if( fake_HDR_format == SOIL_HDR_RGBdivA )\r
+       {\r
+               RGBE_to_RGBdivA( img, width, height, rescale_to_max );\r
+       } else if( fake_HDR_format == SOIL_HDR_RGBdivA2 )\r
+       {\r
+               RGBE_to_RGBdivA2( img, width, height, rescale_to_max );\r
+       }\r
+       /*      OK, make it a texture!  */\r
+       tex_id = SOIL_internal_create_OGL_texture(\r
+                       img, width, height, channels,\r
+                       reuse_texture_ID, flags,\r
+                       GL_TEXTURE_2D, GL_TEXTURE_2D,\r
+                       GL_MAX_TEXTURE_SIZE );\r
+       /*      and nuke the image data */\r
+       SOIL_free_image_data( img );\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_texture_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels;\r
+       unsigned int tex_id;\r
+       /*      does the user want direct uploading of the image as a DDS file? */\r
+       if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )\r
+       {\r
+               /*      1st try direct loading of the image as a DDS file\r
+                       note: direct uploading will only load what is in the\r
+                       DDS file, no MIPmaps will be generated, the image will\r
+                       not be flipped, etc.    */\r
+               tex_id = SOIL_direct_load_DDS_from_memory(\r
+                               buffer, buffer_length,\r
+                               reuse_texture_ID, flags, 0 );\r
+               if( tex_id )\r
+               {\r
+                       /*      hey, it worked!!        */\r
+                       return tex_id;\r
+               }\r
+       }\r
+       /*      try to load the image   */\r
+       img = SOIL_load_image_from_memory(\r
+                                       buffer, buffer_length,\r
+                                       &width, &height, &channels,\r
+                                       force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      OK, make it a texture!  */\r
+       tex_id = SOIL_internal_create_OGL_texture(\r
+                       img, width, height, channels,\r
+                       reuse_texture_ID, flags,\r
+                       GL_TEXTURE_2D, GL_TEXTURE_2D,\r
+                       GL_MAX_TEXTURE_SIZE );\r
+       /*      and nuke the image data */\r
+       SOIL_free_image_data( img );\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_cubemap\r
+       (\r
+               const char *x_pos_file,\r
+               const char *x_neg_file,\r
+               const char *y_pos_file,\r
+               const char *y_neg_file,\r
+               const char *z_pos_file,\r
+               const char *z_neg_file,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels;\r
+       unsigned int tex_id;\r
+       /*      error checking  */\r
+       if( (x_pos_file == NULL) ||\r
+               (x_neg_file == NULL) ||\r
+               (y_pos_file == NULL) ||\r
+               (y_neg_file == NULL) ||\r
+               (z_pos_file == NULL) ||\r
+               (z_neg_file == NULL) )\r
+       {\r
+               result_string_pointer = "Invalid cube map files list";\r
+               return 0;\r
+       }\r
+       /*      capability checking     */\r
+       if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+       {\r
+               result_string_pointer = "No cube map capability present";\r
+               return 0;\r
+       }\r
+       /*      1st face: try to load the image */\r
+       img = SOIL_load_image( x_pos_file, &width, &height, &channels, force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      upload the texture, and create a texture ID if necessary        */\r
+       tex_id = SOIL_internal_create_OGL_texture(\r
+                       img, width, height, channels,\r
+                       reuse_texture_ID, flags,\r
+                       SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_X,\r
+                       SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+       /*      and nuke the image data */\r
+       SOIL_free_image_data( img );\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image( x_neg_file, &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image( y_pos_file, &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image( y_neg_file, &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image( z_pos_file, &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image( z_neg_file, &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_cubemap_from_memory\r
+       (\r
+               const unsigned char *const x_pos_buffer,\r
+               int x_pos_buffer_length,\r
+               const unsigned char *const x_neg_buffer,\r
+               int x_neg_buffer_length,\r
+               const unsigned char *const y_pos_buffer,\r
+               int y_pos_buffer_length,\r
+               const unsigned char *const y_neg_buffer,\r
+               int y_neg_buffer_length,\r
+               const unsigned char *const z_pos_buffer,\r
+               int z_pos_buffer_length,\r
+               const unsigned char *const z_neg_buffer,\r
+               int z_neg_buffer_length,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels;\r
+       unsigned int tex_id;\r
+       /*      error checking  */\r
+       if( (x_pos_buffer == NULL) ||\r
+               (x_neg_buffer == NULL) ||\r
+               (y_pos_buffer == NULL) ||\r
+               (y_neg_buffer == NULL) ||\r
+               (z_pos_buffer == NULL) ||\r
+               (z_neg_buffer == NULL) )\r
+       {\r
+               result_string_pointer = "Invalid cube map buffers list";\r
+               return 0;\r
+       }\r
+       /*      capability checking     */\r
+       if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+       {\r
+               result_string_pointer = "No cube map capability present";\r
+               return 0;\r
+       }\r
+       /*      1st face: try to load the image */\r
+       img = SOIL_load_image_from_memory(\r
+                       x_pos_buffer, x_pos_buffer_length,\r
+                       &width, &height, &channels, force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      upload the texture, and create a texture ID if necessary        */\r
+       tex_id = SOIL_internal_create_OGL_texture(\r
+                       img, width, height, channels,\r
+                       reuse_texture_ID, flags,\r
+                       SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_X,\r
+                       SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+       /*      and nuke the image data */\r
+       SOIL_free_image_data( img );\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image_from_memory(\r
+                               x_neg_buffer, x_neg_buffer_length,\r
+                               &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image_from_memory(\r
+                               y_pos_buffer, y_pos_buffer_length,\r
+                               &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image_from_memory(\r
+                               y_neg_buffer, y_neg_buffer_length,\r
+                               &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image_from_memory(\r
+                               z_pos_buffer, z_pos_buffer_length,\r
+                               &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      continue?       */\r
+       if( tex_id != 0 )\r
+       {\r
+               /*      1st face: try to load the image */\r
+               img = SOIL_load_image_from_memory(\r
+                               z_neg_buffer, z_neg_buffer_length,\r
+                               &width, &height, &channels, force_channels );\r
+               /*      channels holds the original number of channels, which may have been forced      */\r
+               if( (force_channels >= 1) && (force_channels <= 4) )\r
+               {\r
+                       channels = force_channels;\r
+               }\r
+               if( NULL == img )\r
+               {\r
+                       /*      image loading failed    */\r
+                       result_string_pointer = stbi_failure_reason();\r
+                       return 0;\r
+               }\r
+               /*      upload the texture, but reuse the assigned texture ID   */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               img, width, height, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP, SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+               /*      and nuke the image data */\r
+               SOIL_free_image_data( img );\r
+       }\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_single_cubemap\r
+       (\r
+               const char *filename,\r
+               const char face_order[6],\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels, i;\r
+       unsigned int tex_id = 0;\r
+       /*      error checking  */\r
+       if( filename == NULL )\r
+       {\r
+               result_string_pointer = "Invalid single cube map file name";\r
+               return 0;\r
+       }\r
+       /*      does the user want direct uploading of the image as a DDS file? */\r
+       if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )\r
+       {\r
+               /*      1st try direct loading of the image as a DDS file\r
+                       note: direct uploading will only load what is in the\r
+                       DDS file, no MIPmaps will be generated, the image will\r
+                       not be flipped, etc.    */\r
+               tex_id = SOIL_direct_load_DDS( filename, reuse_texture_ID, flags, 1 );\r
+               if( tex_id )\r
+               {\r
+                       /*      hey, it worked!!        */\r
+                       return tex_id;\r
+               }\r
+       }\r
+       /*      face order checking     */\r
+       for( i = 0; i < 6; ++i )\r
+       {\r
+               if( (face_order[i] != 'N') &&\r
+                       (face_order[i] != 'S') &&\r
+                       (face_order[i] != 'W') &&\r
+                       (face_order[i] != 'E') &&\r
+                       (face_order[i] != 'U') &&\r
+                       (face_order[i] != 'D') )\r
+               {\r
+                       result_string_pointer = "Invalid single cube map face order";\r
+                       return 0;\r
+               };\r
+       }\r
+       /*      capability checking     */\r
+       if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+       {\r
+               result_string_pointer = "No cube map capability present";\r
+               return 0;\r
+       }\r
+       /*      1st off, try to load the full image     */\r
+       img = SOIL_load_image( filename, &width, &height, &channels, force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      now, does this image have the right dimensions? */\r
+       if( (width != 6*height) &&\r
+               (6*width != height) )\r
+       {\r
+               SOIL_free_image_data( img );\r
+               result_string_pointer = "Single cubemap image must have a 6:1 ratio";\r
+               return 0;\r
+       }\r
+       /*      try the image split and create  */\r
+       tex_id = SOIL_create_OGL_single_cubemap(\r
+                       img, width, height, channels,\r
+                       face_order, reuse_texture_ID, flags\r
+                       );\r
+       /*      nuke the temporary image data and return the texture handle     */\r
+       SOIL_free_image_data( img );\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_load_OGL_single_cubemap_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               const char face_order[6],\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       int width, height, channels, i;\r
+       unsigned int tex_id = 0;\r
+       /*      error checking  */\r
+       if( buffer == NULL )\r
+       {\r
+               result_string_pointer = "Invalid single cube map buffer";\r
+               return 0;\r
+       }\r
+       /*      does the user want direct uploading of the image as a DDS file? */\r
+       if( flags & SOIL_FLAG_DDS_LOAD_DIRECT )\r
+       {\r
+               /*      1st try direct loading of the image as a DDS file\r
+                       note: direct uploading will only load what is in the\r
+                       DDS file, no MIPmaps will be generated, the image will\r
+                       not be flipped, etc.    */\r
+               tex_id = SOIL_direct_load_DDS_from_memory(\r
+                               buffer, buffer_length,\r
+                               reuse_texture_ID, flags, 1 );\r
+               if( tex_id )\r
+               {\r
+                       /*      hey, it worked!!        */\r
+                       return tex_id;\r
+               }\r
+       }\r
+       /*      face order checking     */\r
+       for( i = 0; i < 6; ++i )\r
+       {\r
+               if( (face_order[i] != 'N') &&\r
+                       (face_order[i] != 'S') &&\r
+                       (face_order[i] != 'W') &&\r
+                       (face_order[i] != 'E') &&\r
+                       (face_order[i] != 'U') &&\r
+                       (face_order[i] != 'D') )\r
+               {\r
+                       result_string_pointer = "Invalid single cube map face order";\r
+                       return 0;\r
+               };\r
+       }\r
+       /*      capability checking     */\r
+       if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+       {\r
+               result_string_pointer = "No cube map capability present";\r
+               return 0;\r
+       }\r
+       /*      1st off, try to load the full image     */\r
+       img = SOIL_load_image_from_memory(\r
+                       buffer, buffer_length,\r
+                       &width, &height, &channels,\r
+                       force_channels );\r
+       /*      channels holds the original number of channels, which may have been forced      */\r
+       if( (force_channels >= 1) && (force_channels <= 4) )\r
+       {\r
+               channels = force_channels;\r
+       }\r
+       if( NULL == img )\r
+       {\r
+               /*      image loading failed    */\r
+               result_string_pointer = stbi_failure_reason();\r
+               return 0;\r
+       }\r
+       /*      now, does this image have the right dimensions? */\r
+       if( (width != 6*height) &&\r
+               (6*width != height) )\r
+       {\r
+               SOIL_free_image_data( img );\r
+               result_string_pointer = "Single cubemap image must have a 6:1 ratio";\r
+               return 0;\r
+       }\r
+       /*      try the image split and create  */\r
+       tex_id = SOIL_create_OGL_single_cubemap(\r
+                       img, width, height, channels,\r
+                       face_order, reuse_texture_ID, flags\r
+                       );\r
+       /*      nuke the temporary image data and return the texture handle     */\r
+       SOIL_free_image_data( img );\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_create_OGL_single_cubemap\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               const char face_order[6],\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* sub_img;\r
+       int dw, dh, sz, i;\r
+       unsigned int tex_id;\r
+       /*      error checking  */\r
+       if( data == NULL )\r
+       {\r
+               result_string_pointer = "Invalid single cube map image data";\r
+               return 0;\r
+       }\r
+       /*      face order checking     */\r
+       for( i = 0; i < 6; ++i )\r
+       {\r
+               if( (face_order[i] != 'N') &&\r
+                       (face_order[i] != 'S') &&\r
+                       (face_order[i] != 'W') &&\r
+                       (face_order[i] != 'E') &&\r
+                       (face_order[i] != 'U') &&\r
+                       (face_order[i] != 'D') )\r
+               {\r
+                       result_string_pointer = "Invalid single cube map face order";\r
+                       return 0;\r
+               };\r
+       }\r
+       /*      capability checking     */\r
+       if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+       {\r
+               result_string_pointer = "No cube map capability present";\r
+               return 0;\r
+       }\r
+       /*      now, does this image have the right dimensions? */\r
+       if( (width != 6*height) &&\r
+               (6*width != height) )\r
+       {\r
+               result_string_pointer = "Single cubemap image must have a 6:1 ratio";\r
+               return 0;\r
+       }\r
+       /*      which way am I stepping?        */\r
+       if( width > height )\r
+       {\r
+               dw = height;\r
+               dh = 0;\r
+       } else\r
+       {\r
+               dw = 0;\r
+               dh = width;\r
+       }\r
+       sz = dw+dh;\r
+       sub_img = (unsigned char *)malloc( sz*sz*channels );\r
+       /*      do the splitting and uploading  */\r
+       tex_id = reuse_texture_ID;\r
+       for( i = 0; i < 6; ++i )\r
+       {\r
+               int x, y, idx = 0;\r
+               unsigned int cubemap_target = 0;\r
+               /*      copy in the sub-image   */\r
+               for( y = i*dh; y < i*dh+sz; ++y )\r
+               {\r
+                       for( x = i*dw*channels; x < (i*dw+sz)*channels; ++x )\r
+                       {\r
+                               sub_img[idx++] = data[y*width*channels+x];\r
+                       }\r
+               }\r
+               /*      what is my texture target?\r
+                       remember, this coordinate system is\r
+                       LHS if viewed from inside the cube!     */\r
+               switch( face_order[i] )\r
+               {\r
+               case 'N':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_Z;\r
+                       break;\r
+               case 'S':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z;\r
+                       break;\r
+               case 'W':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_X;\r
+                       break;\r
+               case 'E':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_X;\r
+                       break;\r
+               case 'U':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_POSITIVE_Y;\r
+                       break;\r
+               case 'D':\r
+                       cubemap_target = SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Y;\r
+                       break;\r
+               }\r
+               /*      upload it as a texture  */\r
+               tex_id = SOIL_internal_create_OGL_texture(\r
+                               sub_img, sz, sz, channels,\r
+                               tex_id, flags,\r
+                               SOIL_TEXTURE_CUBE_MAP,\r
+                               cubemap_target,\r
+                               SOIL_MAX_CUBE_MAP_TEXTURE_SIZE );\r
+       }\r
+       /*      and nuke the image and sub-image data   */\r
+       SOIL_free_image_data( sub_img );\r
+       /*      and return the handle, such as it is    */\r
+       return tex_id;\r
+}\r
+\r
+unsigned int\r
+       SOIL_create_OGL_texture\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       )\r
+{\r
+       /*      wrapper function for 2D textures        */\r
+       return SOIL_internal_create_OGL_texture(\r
+                               data, width, height, channels,\r
+                               reuse_texture_ID, flags,\r
+                               GL_TEXTURE_2D, GL_TEXTURE_2D,\r
+                               GL_MAX_TEXTURE_SIZE );\r
+}\r
+\r
+#if SOIL_CHECK_FOR_GL_ERRORS\r
+void check_for_GL_errors( const char *calling_location )\r
+{\r
+       /*      check for errors        */\r
+       GLenum err_code = glGetError();\r
+       while( GL_NO_ERROR != err_code )\r
+       {\r
+               printf( "OpenGL Error @ %s: %i", calling_location, err_code );\r
+               err_code = glGetError();\r
+       }\r
+}\r
+#else\r
+void check_for_GL_errors( const char *calling_location )\r
+{\r
+       /*      no check for errors     */\r
+}\r
+#endif\r
+\r
+unsigned int\r
+       SOIL_internal_create_OGL_texture\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags,\r
+               unsigned int opengl_texture_type,\r
+               unsigned int opengl_texture_target,\r
+               unsigned int texture_check_size_enum\r
+       )\r
+{\r
+       /*      variables       */\r
+       unsigned char* img;\r
+       unsigned int tex_id;\r
+       unsigned int internal_texture_format = 0, original_texture_format = 0;\r
+       int DXT_mode = SOIL_CAPABILITY_UNKNOWN;\r
+       int max_supported_size;\r
+       /*      If the user wants to use the texture rectangle I kill a few flags       */\r
+       if( flags & SOIL_FLAG_TEXTURE_RECTANGLE )\r
+       {\r
+               /*      well, the user asked for it, can we do that?    */\r
+               if( query_tex_rectangle_capability() == SOIL_CAPABILITY_PRESENT )\r
+               {\r
+                       /*      only allow this if the user in _NOT_ trying to do a cubemap!    */\r
+                       if( opengl_texture_type == GL_TEXTURE_2D )\r
+                       {\r
+                               /*      clean out the flags that cannot be used with texture rectangles */\r
+                               flags &= ~(\r
+                                               SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS |\r
+                                               SOIL_FLAG_TEXTURE_REPEATS\r
+                                       );\r
+                               /*      and change my target    */\r
+                               opengl_texture_target = SOIL_TEXTURE_RECTANGLE_ARB;\r
+                               opengl_texture_type = SOIL_TEXTURE_RECTANGLE_ARB;\r
+                       } else\r
+                       {\r
+                               /*      not allowed for any other uses (yes, I'm looking at you, cubemaps!)     */\r
+                               flags &= ~SOIL_FLAG_TEXTURE_RECTANGLE;\r
+                       }\r
+\r
+               } else\r
+               {\r
+                       /*      can't do it, and that is a breakable offense (uv coords use pixels instead of [0,1]!)   */\r
+                       result_string_pointer = "Texture Rectangle extension unsupported";\r
+                       return 0;\r
+               }\r
+       }\r
+       /*      create a copy the image data    */\r
+       img = (unsigned char*)malloc( width*height*channels );\r
+       memcpy( img, data, width*height*channels );\r
+       /*      does the user want me to invert the image?      */\r
+       if( flags & SOIL_FLAG_INVERT_Y )\r
+       {\r
+               int i, j;\r
+               for( j = 0; j*2 < height; ++j )\r
+               {\r
+                       int index1 = j * width * channels;\r
+                       int index2 = (height - 1 - j) * width * channels;\r
+                       for( i = width * channels; i > 0; --i )\r
+                       {\r
+                               unsigned char temp = img[index1];\r
+                               img[index1] = img[index2];\r
+                               img[index2] = temp;\r
+                               ++index1;\r
+                               ++index2;\r
+                       }\r
+               }\r
+       }\r
+       /*      does the user want me to scale the colors into the NTSC safe RGB range? */\r
+       if( flags & SOIL_FLAG_NTSC_SAFE_RGB )\r
+       {\r
+               scale_image_RGB_to_NTSC_safe( img, width, height, channels );\r
+       }\r
+       /*      does the user want me to convert from straight to pre-multiplied alpha?\r
+               (and do we even _have_ alpha?)  */\r
+       if( flags & SOIL_FLAG_MULTIPLY_ALPHA )\r
+       {\r
+               int i;\r
+               switch( channels )\r
+               {\r
+               case 2:\r
+                       for( i = 0; i < 2*width*height; i += 2 )\r
+                       {\r
+                               img[i] = (img[i] * img[i+1] + 128) >> 8;\r
+                       }\r
+                       break;\r
+               case 4:\r
+                       for( i = 0; i < 4*width*height; i += 4 )\r
+                       {\r
+                               img[i+0] = (img[i+0] * img[i+3] + 128) >> 8;\r
+                               img[i+1] = (img[i+1] * img[i+3] + 128) >> 8;\r
+                               img[i+2] = (img[i+2] * img[i+3] + 128) >> 8;\r
+                       }\r
+                       break;\r
+               default:\r
+                       /*      no other number of channels contains alpha data */\r
+                       break;\r
+               }\r
+       }\r
+       /*      if the user can't support NPOT textures, make sure we force the POT option      */\r
+       if( (query_NPOT_capability() == SOIL_CAPABILITY_NONE) &&\r
+               !(flags & SOIL_FLAG_TEXTURE_RECTANGLE) )\r
+       {\r
+               /*      add in the POT flag */\r
+               flags |= SOIL_FLAG_POWER_OF_TWO;\r
+       }\r
+       /*      how large of a texture can this OpenGL implementation handle?   */\r
+       /*      texture_check_size_enum will be GL_MAX_TEXTURE_SIZE or SOIL_MAX_CUBE_MAP_TEXTURE_SIZE   */\r
+       glGetIntegerv( texture_check_size_enum, &max_supported_size );\r
+       /*      do I need to make it a power of 2?      */\r
+       if(\r
+               (flags & SOIL_FLAG_POWER_OF_TWO) ||     /*      user asked for it       */\r
+               (flags & SOIL_FLAG_MIPMAPS) ||          /*      need it for the MIP-maps        */\r
+               (width > max_supported_size) ||         /*      it's too big, (make sure it's   */\r
+               (height > max_supported_size) )         /*      2^n for later down-sampling)    */\r
+       {\r
+               int new_width = 1;\r
+               int new_height = 1;\r
+               while( new_width < width )\r
+               {\r
+                       new_width *= 2;\r
+               }\r
+               while( new_height < height )\r
+               {\r
+                       new_height *= 2;\r
+               }\r
+               /*      still?  */\r
+               if( (new_width != width) || (new_height != height) )\r
+               {\r
+                       /*      yep, resize     */\r
+                       unsigned char *resampled = (unsigned char*)malloc( channels*new_width*new_height );\r
+                       up_scale_image(\r
+                                       img, width, height, channels,\r
+                                       resampled, new_width, new_height );\r
+                       /*      OJO     this is for debug only! */\r
+                       /*\r
+                       SOIL_save_image( "\\showme.bmp", SOIL_SAVE_TYPE_BMP,\r
+                                                       new_width, new_height, channels,\r
+                                                       resampled );\r
+                       */\r
+                       /*      nuke the old guy, then point it at the new guy  */\r
+                       SOIL_free_image_data( img );\r
+                       img = resampled;\r
+                       width = new_width;\r
+                       height = new_height;\r
+               }\r
+       }\r
+       /*      now, if it is too large...      */\r
+       if( (width > max_supported_size) || (height > max_supported_size) )\r
+       {\r
+               /*      I've already made it a power of two, so simply use the MIPmapping\r
+                       code to reduce its size to the allowable maximum.       */\r
+               unsigned char *resampled;\r
+               int reduce_block_x = 1, reduce_block_y = 1;\r
+               int new_width, new_height;\r
+               if( width > max_supported_size )\r
+               {\r
+                       reduce_block_x = width / max_supported_size;\r
+               }\r
+               if( height > max_supported_size )\r
+               {\r
+                       reduce_block_y = height / max_supported_size;\r
+               }\r
+               new_width = width / reduce_block_x;\r
+               new_height = height / reduce_block_y;\r
+               resampled = (unsigned char*)malloc( channels*new_width*new_height );\r
+               /*      perform the actual reduction    */\r
+               mipmap_image(   img, width, height, channels,\r
+                                               resampled, reduce_block_x, reduce_block_y );\r
+               /*      nuke the old guy, then point it at the new guy  */\r
+               SOIL_free_image_data( img );\r
+               img = resampled;\r
+               width = new_width;\r
+               height = new_height;\r
+       }\r
+       /*      does the user want us to use YCoCg color space? */\r
+       if( flags & SOIL_FLAG_CoCg_Y )\r
+       {\r
+               /*      this will only work with RGB and RGBA images */\r
+               convert_RGB_to_YCoCg( img, width, height, channels );\r
+               /*\r
+               save_image_as_DDS( "CoCg_Y.dds", width, height, channels, img );\r
+               */\r
+       }\r
+       /*      create the OpenGL texture ID handle\r
+       (note: allowing a forced texture ID lets me reload a texture)   */\r
+    tex_id = reuse_texture_ID;\r
+    if( tex_id == 0 )\r
+    {\r
+               glGenTextures( 1, &tex_id );\r
+    }\r
+       check_for_GL_errors( "glGenTextures" );\r
+       /* Note: sometimes glGenTextures fails (usually no OpenGL context)      */\r
+       if( tex_id )\r
+       {\r
+               /*      and what type am I using as the internal texture format?        */\r
+               switch( channels )\r
+               {\r
+               case 1:\r
+                       original_texture_format = GL_LUMINANCE;\r
+                       break;\r
+               case 2:\r
+                       original_texture_format = GL_LUMINANCE_ALPHA;\r
+                       break;\r
+               case 3:\r
+                       original_texture_format = GL_RGB;\r
+                       break;\r
+               case 4:\r
+                       original_texture_format = GL_RGBA;\r
+                       break;\r
+               }\r
+               internal_texture_format = original_texture_format;\r
+               /*      does the user want me to, and can I, save as DXT?       */\r
+               if( flags & SOIL_FLAG_COMPRESS_TO_DXT )\r
+               {\r
+                       DXT_mode = query_DXT_capability();\r
+                       if( DXT_mode == SOIL_CAPABILITY_PRESENT )\r
+                       {\r
+                               /*      I can use DXT, whether I compress it or OpenGL does     */\r
+                               if( (channels & 1) == 1 )\r
+                               {\r
+                                       /*      1 or 3 channels = DXT1  */\r
+                                       internal_texture_format = SOIL_RGB_S3TC_DXT1;\r
+                               } else\r
+                               {\r
+                                       /*      2 or 4 channels = DXT5  */\r
+                                       internal_texture_format = SOIL_RGBA_S3TC_DXT5;\r
+                               }\r
+                       }\r
+               }\r
+               /*  bind an OpenGL texture ID   */\r
+               glBindTexture( opengl_texture_type, tex_id );\r
+               check_for_GL_errors( "glBindTexture" );\r
+               /*  upload the main image       */\r
+               if( DXT_mode == SOIL_CAPABILITY_PRESENT )\r
+               {\r
+                       /*      user wants me to do the DXT conversion! */\r
+                       int DDS_size;\r
+                       unsigned char *DDS_data = NULL;\r
+                       if( (channels & 1) == 1 )\r
+                       {\r
+                               /*      RGB, use DXT1   */\r
+                               DDS_data = convert_image_to_DXT1( img, width, height, channels, &DDS_size );\r
+                       } else\r
+                       {\r
+                               /*      RGBA, use DXT5  */\r
+                               DDS_data = convert_image_to_DXT5( img, width, height, channels, &DDS_size );\r
+                       }\r
+                       if( DDS_data )\r
+                       {\r
+                               soilGlCompressedTexImage2D(\r
+                                       opengl_texture_target, 0,\r
+                                       internal_texture_format, width, height, 0,\r
+                                       DDS_size, DDS_data );\r
+                               check_for_GL_errors( "glCompressedTexImage2D" );\r
+                               SOIL_free_image_data( DDS_data );\r
+                               /*      printf( "Internal DXT compressor\n" );  */\r
+                       } else\r
+                       {\r
+                               /*      my compression failed, try the OpenGL driver's version  */\r
+                               glTexImage2D(\r
+                                       opengl_texture_target, 0,\r
+                                       internal_texture_format, width, height, 0,\r
+                                       original_texture_format, GL_UNSIGNED_BYTE, img );\r
+                               check_for_GL_errors( "glTexImage2D" );\r
+                               /*      printf( "OpenGL DXT compressor\n" );    */\r
+                       }\r
+               } else\r
+               {\r
+                       /*      user want OpenGL to do all the work!    */\r
+                       glTexImage2D(\r
+                               opengl_texture_target, 0,\r
+                               internal_texture_format, width, height, 0,\r
+                               original_texture_format, GL_UNSIGNED_BYTE, img );\r
+                       check_for_GL_errors( "glTexImage2D" );\r
+                       /*printf( "OpenGL DXT compressor\n" );  */\r
+               }\r
+               /*      are any MIPmaps desired?        */\r
+               if( flags & SOIL_FLAG_MIPMAPS )\r
+               {\r
+                       int MIPlevel = 1;\r
+                       int MIPwidth = (width+1) / 2;\r
+                       int MIPheight = (height+1) / 2;\r
+                       unsigned char *resampled = (unsigned char*)malloc( channels*MIPwidth*MIPheight );\r
+                       while( ((1<<MIPlevel) <= width) || ((1<<MIPlevel) <= height) )\r
+                       {\r
+                               /*      do this MIPmap level    */\r
+                               mipmap_image(\r
+                                               img, width, height, channels,\r
+                                               resampled,\r
+                                               (1 << MIPlevel), (1 << MIPlevel) );\r
+                               /*  upload the MIPmaps  */\r
+                               if( DXT_mode == SOIL_CAPABILITY_PRESENT )\r
+                               {\r
+                                       /*      user wants me to do the DXT conversion! */\r
+                                       int DDS_size;\r
+                                       unsigned char *DDS_data = NULL;\r
+                                       if( (channels & 1) == 1 )\r
+                                       {\r
+                                               /*      RGB, use DXT1   */\r
+                                               DDS_data = convert_image_to_DXT1(\r
+                                                               resampled, MIPwidth, MIPheight, channels, &DDS_size );\r
+                                       } else\r
+                                       {\r
+                                               /*      RGBA, use DXT5  */\r
+                                               DDS_data = convert_image_to_DXT5(\r
+                                                               resampled, MIPwidth, MIPheight, channels, &DDS_size );\r
+                                       }\r
+                                       if( DDS_data )\r
+                                       {\r
+                                               soilGlCompressedTexImage2D(\r
+                                                       opengl_texture_target, MIPlevel,\r
+                                                       internal_texture_format, MIPwidth, MIPheight, 0,\r
+                                                       DDS_size, DDS_data );\r
+                                               check_for_GL_errors( "glCompressedTexImage2D" );\r
+                                               SOIL_free_image_data( DDS_data );\r
+                                       } else\r
+                                       {\r
+                                               /*      my compression failed, try the OpenGL driver's version  */\r
+                                               glTexImage2D(\r
+                                                       opengl_texture_target, MIPlevel,\r
+                                                       internal_texture_format, MIPwidth, MIPheight, 0,\r
+                                                       original_texture_format, GL_UNSIGNED_BYTE, resampled );\r
+                                               check_for_GL_errors( "glTexImage2D" );\r
+                                       }\r
+                               } else\r
+                               {\r
+                                       /*      user want OpenGL to do all the work!    */\r
+                                       glTexImage2D(\r
+                                               opengl_texture_target, MIPlevel,\r
+                                               internal_texture_format, MIPwidth, MIPheight, 0,\r
+                                               original_texture_format, GL_UNSIGNED_BYTE, resampled );\r
+                                       check_for_GL_errors( "glTexImage2D" );\r
+                               }\r
+                               /*      prep for the next level */\r
+                               ++MIPlevel;\r
+                               MIPwidth = (MIPwidth + 1) / 2;\r
+                               MIPheight = (MIPheight + 1) / 2;\r
+                       }\r
+                       SOIL_free_image_data( resampled );\r
+                       /*      instruct OpenGL to use the MIPmaps      */\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\r
+                       check_for_GL_errors( "GL_TEXTURE_MIN/MAG_FILTER" );\r
+               } else\r
+               {\r
+                       /*      instruct OpenGL _NOT_ to use the MIPmaps        */\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\r
+                       check_for_GL_errors( "GL_TEXTURE_MIN/MAG_FILTER" );\r
+               }\r
+               /*      does the user want clamping, or wrapping?       */\r
+               if( flags & SOIL_FLAG_TEXTURE_REPEATS )\r
+               {\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT );\r
+                       if( opengl_texture_type == SOIL_TEXTURE_CUBE_MAP )\r
+                       {\r
+                               /*      SOIL_TEXTURE_WRAP_R is invalid if cubemaps aren't supported     */\r
+                               glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, GL_REPEAT );\r
+                       }\r
+                       check_for_GL_errors( "GL_TEXTURE_WRAP_*" );\r
+               } else\r
+               {\r
+                       /*      unsigned int clamp_mode = SOIL_CLAMP_TO_EDGE;   */\r
+                       unsigned int clamp_mode = GL_CLAMP;\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, clamp_mode );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, clamp_mode );\r
+                       if( opengl_texture_type == SOIL_TEXTURE_CUBE_MAP )\r
+                       {\r
+                               /*      SOIL_TEXTURE_WRAP_R is invalid if cubemaps aren't supported     */\r
+                               glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, clamp_mode );\r
+                       }\r
+                       check_for_GL_errors( "GL_TEXTURE_WRAP_*" );\r
+               }\r
+               /*      done    */\r
+               result_string_pointer = "Image loaded as an OpenGL texture";\r
+       } else\r
+       {\r
+               /*      failed  */\r
+               result_string_pointer = "Failed to generate an OpenGL texture name; missing OpenGL context?";\r
+       }\r
+       SOIL_free_image_data( img );\r
+       return tex_id;\r
+}\r
+\r
+int\r
+       SOIL_save_screenshot\r
+       (\r
+               const char *filename,\r
+               int image_type,\r
+               int x, int y,\r
+               int width, int height\r
+       )\r
+{\r
+       unsigned char *pixel_data;\r
+       int i, j;\r
+       int save_result;\r
+\r
+       /*      error checks    */\r
+       if( (width < 1) || (height < 1) )\r
+       {\r
+               result_string_pointer = "Invalid screenshot dimensions";\r
+               return 0;\r
+       }\r
+       if( (x < 0) || (y < 0) )\r
+       {\r
+               result_string_pointer = "Invalid screenshot location";\r
+               return 0;\r
+       }\r
+       if( filename == NULL )\r
+       {\r
+               result_string_pointer = "Invalid screenshot filename";\r
+               return 0;\r
+       }\r
+\r
+    /*  Get the data from OpenGL       */\r
+    pixel_data = (unsigned char*)malloc( 3*width*height );\r
+    glReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixel_data);\r
+\r
+    /* invert the image        */\r
+    for( j = 0; j*2 < height; ++j )\r
+       {\r
+               int index1 = j * width * 3;\r
+               int index2 = (height - 1 - j) * width * 3;\r
+               for( i = width * 3; i > 0; --i )\r
+               {\r
+                       unsigned char temp = pixel_data[index1];\r
+                       pixel_data[index1] = pixel_data[index2];\r
+                       pixel_data[index2] = temp;\r
+                       ++index1;\r
+                       ++index2;\r
+               }\r
+       }\r
+\r
+    /* save the image  */\r
+    save_result = SOIL_save_image( filename, image_type, width, height, 3, pixel_data);\r
+\r
+    /*  And free the memory    */\r
+    SOIL_free_image_data( pixel_data );\r
+       return save_result;\r
+}\r
+\r
+unsigned char*\r
+       SOIL_load_image\r
+       (\r
+               const char *filename,\r
+               int *width, int *height, int *channels,\r
+               int force_channels\r
+       )\r
+{\r
+       unsigned char *result = stbi_load( filename,\r
+                       width, height, channels, force_channels );\r
+       if( result == NULL )\r
+       {\r
+               result_string_pointer = stbi_failure_reason();\r
+       } else\r
+       {\r
+               result_string_pointer = "Image loaded";\r
+       }\r
+       return result;\r
+}\r
+\r
+unsigned char*\r
+       SOIL_load_image_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               int *width, int *height, int *channels,\r
+               int force_channels\r
+       )\r
+{\r
+       unsigned char *result = stbi_load_from_memory(\r
+                               buffer, buffer_length,\r
+                               width, height, channels,\r
+                               force_channels );\r
+       if( result == NULL )\r
+       {\r
+               result_string_pointer = stbi_failure_reason();\r
+       } else\r
+       {\r
+               result_string_pointer = "Image loaded from memory";\r
+       }\r
+       return result;\r
+}\r
+\r
+int\r
+       SOIL_save_image\r
+       (\r
+               const char *filename,\r
+               int image_type,\r
+               int width, int height, int channels,\r
+               const unsigned char *const data\r
+       )\r
+{\r
+       int save_result;\r
+\r
+       /*      error check     */\r
+       if( (width < 1) || (height < 1) ||\r
+               (channels < 1) || (channels > 4) ||\r
+               (data == NULL) ||\r
+               (filename == NULL) )\r
+       {\r
+               return 0;\r
+       }\r
+       if( image_type == SOIL_SAVE_TYPE_BMP )\r
+       {\r
+               save_result = stbi_write_bmp( filename,\r
+                               width, height, channels, (void*)data );\r
+       } else\r
+       if( image_type == SOIL_SAVE_TYPE_TGA )\r
+       {\r
+               save_result = stbi_write_tga( filename,\r
+                               width, height, channels, (void*)data );\r
+       } else\r
+       if( image_type == SOIL_SAVE_TYPE_DDS )\r
+       {\r
+               save_result = save_image_as_DDS( filename,\r
+                               width, height, channels, (const unsigned char *const)data );\r
+       } else\r
+       {\r
+               save_result = 0;\r
+       }\r
+       if( save_result == 0 )\r
+       {\r
+               result_string_pointer = "Saving the image failed";\r
+       } else\r
+       {\r
+               result_string_pointer = "Image saved";\r
+       }\r
+       return save_result;\r
+}\r
+\r
+void\r
+       SOIL_free_image_data\r
+       (\r
+               unsigned char *img_data\r
+       )\r
+{\r
+       free( (void*)img_data );\r
+}\r
+\r
+const char*\r
+       SOIL_last_result\r
+       (\r
+               void\r
+       )\r
+{\r
+       return result_string_pointer;\r
+}\r
+\r
+unsigned int SOIL_direct_load_DDS_from_memory(\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               unsigned int reuse_texture_ID,\r
+               int flags,\r
+               int loading_as_cubemap )\r
+{\r
+       /*      variables       */\r
+       DDS_header header;\r
+       unsigned int buffer_index = 0;\r
+       unsigned int tex_ID = 0;\r
+       /*      file reading variables  */\r
+       unsigned int S3TC_type = 0;\r
+       unsigned char *DDS_data;\r
+       unsigned int DDS_main_size;\r
+       unsigned int DDS_full_size;\r
+       unsigned int width, height;\r
+       int mipmaps, cubemap, uncompressed, block_size = 16;\r
+       unsigned int flag;\r
+       unsigned int cf_target, ogl_target_start, ogl_target_end;\r
+       unsigned int opengl_texture_type;\r
+       int i;\r
+       /*      1st off, does the filename even exist?  */\r
+       if( NULL == buffer )\r
+       {\r
+               /*      we can't do it! */\r
+               result_string_pointer = "NULL buffer";\r
+               return 0;\r
+       }\r
+       if( buffer_length < sizeof( DDS_header ) )\r
+       {\r
+               /*      we can't do it! */\r
+               result_string_pointer = "DDS file was too small to contain the DDS header";\r
+               return 0;\r
+       }\r
+       /*      try reading in the header       */\r
+       memcpy ( (void*)(&header), (const void *)buffer, sizeof( DDS_header ) );\r
+       buffer_index = sizeof( DDS_header );\r
+       /*      guilty until proven innocent    */\r
+       result_string_pointer = "Failed to read a known DDS header";\r
+       /*      validate the header (warning, "goto"'s ahead, shield your eyes!!)       */\r
+       flag = ('D'<<0)|('D'<<8)|('S'<<16)|(' '<<24);\r
+       if( header.dwMagic != flag ) {goto quick_exit;}\r
+       if( header.dwSize != 124 ) {goto quick_exit;}\r
+       /*      I need all of these     */\r
+       flag = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;\r
+       if( (header.dwFlags & flag) != flag ) {goto quick_exit;}\r
+       /*      According to the MSDN spec, the dwFlags should contain\r
+               DDSD_LINEARSIZE if it's compressed, or DDSD_PITCH if\r
+               uncompressed.  Some DDS writers do not conform to the\r
+               spec, so I need to make my reader more tolerant */\r
+       /*      I need one of these     */\r
+       flag = DDPF_FOURCC | DDPF_RGB;\r
+       if( (header.sPixelFormat.dwFlags & flag) == 0 ) {goto quick_exit;}\r
+       if( header.sPixelFormat.dwSize != 32 ) {goto quick_exit;}\r
+       if( (header.sCaps.dwCaps1 & DDSCAPS_TEXTURE) == 0 ) {goto quick_exit;}\r
+       /*      make sure it is a type we can upload    */\r
+       if( (header.sPixelFormat.dwFlags & DDPF_FOURCC) &&\r
+               !(\r
+               (header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('1'<<24))) ||\r
+               (header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('3'<<24))) ||\r
+               (header.sPixelFormat.dwFourCC == (('D'<<0)|('X'<<8)|('T'<<16)|('5'<<24)))\r
+               ) )\r
+       {\r
+               goto quick_exit;\r
+       }\r
+       /*      OK, validated the header, let's load the image data     */\r
+       result_string_pointer = "DDS header loaded and validated";\r
+       width = header.dwWidth;\r
+       height = header.dwHeight;\r
+       uncompressed = 1 - (header.sPixelFormat.dwFlags & DDPF_FOURCC) / DDPF_FOURCC;\r
+       cubemap = (header.sCaps.dwCaps2 & DDSCAPS2_CUBEMAP) / DDSCAPS2_CUBEMAP;\r
+       if( uncompressed )\r
+       {\r
+               S3TC_type = GL_RGB;\r
+               block_size = 3;\r
+               if( header.sPixelFormat.dwFlags & DDPF_ALPHAPIXELS )\r
+               {\r
+                       S3TC_type = GL_RGBA;\r
+                       block_size = 4;\r
+               }\r
+               DDS_main_size = width * height * block_size;\r
+       } else\r
+       {\r
+               /*      can we even handle direct uploading to OpenGL DXT compressed images?    */\r
+               if( query_DXT_capability() != SOIL_CAPABILITY_PRESENT )\r
+               {\r
+                       /*      we can't do it! */\r
+                       result_string_pointer = "Direct upload of S3TC images not supported by the OpenGL driver";\r
+                       return 0;\r
+               }\r
+               /*      well, we know it is DXT1/3/5, because we checked above  */\r
+               switch( (header.sPixelFormat.dwFourCC >> 24) - '0' )\r
+               {\r
+               case 1:\r
+                       S3TC_type = SOIL_RGBA_S3TC_DXT1;\r
+                       block_size = 8;\r
+                       break;\r
+               case 3:\r
+                       S3TC_type = SOIL_RGBA_S3TC_DXT3;\r
+                       block_size = 16;\r
+                       break;\r
+               case 5:\r
+                       S3TC_type = SOIL_RGBA_S3TC_DXT5;\r
+                       block_size = 16;\r
+                       break;\r
+               }\r
+               DDS_main_size = ((width+3)>>2)*((height+3)>>2)*block_size;\r
+       }\r
+       if( cubemap )\r
+       {\r
+               /* does the user want a cubemap?        */\r
+               if( !loading_as_cubemap )\r
+               {\r
+                       /*      we can't do it! */\r
+                       result_string_pointer = "DDS image was a cubemap";\r
+                       return 0;\r
+               }\r
+               /*      can we even handle cubemaps with the OpenGL driver?     */\r
+               if( query_cubemap_capability() != SOIL_CAPABILITY_PRESENT )\r
+               {\r
+                       /*      we can't do it! */\r
+                       result_string_pointer = "Direct upload of cubemap images not supported by the OpenGL driver";\r
+                       return 0;\r
+               }\r
+               ogl_target_start = SOIL_TEXTURE_CUBE_MAP_POSITIVE_X;\r
+               ogl_target_end =   SOIL_TEXTURE_CUBE_MAP_NEGATIVE_Z;\r
+               opengl_texture_type = SOIL_TEXTURE_CUBE_MAP;\r
+       } else\r
+       {\r
+               /* does the user want a non-cubemap?    */\r
+               if( loading_as_cubemap )\r
+               {\r
+                       /*      we can't do it! */\r
+                       result_string_pointer = "DDS image was not a cubemap";\r
+                       return 0;\r
+               }\r
+               ogl_target_start = GL_TEXTURE_2D;\r
+               ogl_target_end =   GL_TEXTURE_2D;\r
+               opengl_texture_type = GL_TEXTURE_2D;\r
+       }\r
+       if( (header.sCaps.dwCaps1 & DDSCAPS_MIPMAP) && (header.dwMipMapCount > 1) )\r
+       {\r
+               int shift_offset;\r
+               mipmaps = header.dwMipMapCount - 1;\r
+               DDS_full_size = DDS_main_size;\r
+               if( uncompressed )\r
+               {\r
+                       /*      uncompressed DDS, simple MIPmap size calculation        */\r
+                       shift_offset = 0;\r
+               } else\r
+               {\r
+                       /*      compressed DDS, MIPmap size calculation is block based  */\r
+                       shift_offset = 2;\r
+               }\r
+               for( i = 1; i <= mipmaps; ++ i )\r
+               {\r
+                       int w, h;\r
+                       w = width >> (shift_offset + i);\r
+                       h = height >> (shift_offset + i);\r
+                       if( w < 1 )\r
+                       {\r
+                               w = 1;\r
+                       }\r
+                       if( h < 1 )\r
+                       {\r
+                               h = 1;\r
+                       }\r
+                       DDS_full_size += w*h*block_size;\r
+               }\r
+       } else\r
+       {\r
+               mipmaps = 0;\r
+               DDS_full_size = DDS_main_size;\r
+       }\r
+       DDS_data = (unsigned char*)malloc( DDS_full_size );\r
+       /*      got the image data RAM, create or use an existing OpenGL texture handle */\r
+       tex_ID = reuse_texture_ID;\r
+       if( tex_ID == 0 )\r
+       {\r
+               glGenTextures( 1, &tex_ID );\r
+       }\r
+       /*  bind an OpenGL texture ID   */\r
+       glBindTexture( opengl_texture_type, tex_ID );\r
+       /*      do this for each face of the cubemap!   */\r
+       for( cf_target = ogl_target_start; cf_target <= ogl_target_end; ++cf_target )\r
+       {\r
+               if( buffer_index + DDS_full_size <= buffer_length )\r
+               {\r
+                       unsigned int byte_offset = DDS_main_size;\r
+                       memcpy( (void*)DDS_data, (const void*)(&buffer[buffer_index]), DDS_full_size );\r
+                       buffer_index += DDS_full_size;\r
+                       /*      upload the main chunk   */\r
+                       if( uncompressed )\r
+                       {\r
+                               /*      and remember, DXT uncompressed uses BGR(A),\r
+                                       so swap to RGB(A) for ALL MIPmap levels */\r
+                               for( i = 0; i < DDS_full_size; i += block_size )\r
+                               {\r
+                                       unsigned char temp = DDS_data[i];\r
+                                       DDS_data[i] = DDS_data[i+2];\r
+                                       DDS_data[i+2] = temp;\r
+                               }\r
+                               glTexImage2D(\r
+                                       cf_target, 0,\r
+                                       S3TC_type, width, height, 0,\r
+                                       S3TC_type, GL_UNSIGNED_BYTE, DDS_data );\r
+                       } else\r
+                       {\r
+                               soilGlCompressedTexImage2D(\r
+                                       cf_target, 0,\r
+                                       S3TC_type, width, height, 0,\r
+                                       DDS_main_size, DDS_data );\r
+                       }\r
+                       /*      upload the mipmaps, if we have them     */\r
+                       for( i = 1; i <= mipmaps; ++i )\r
+                       {\r
+                               int w, h, mip_size;\r
+                               w = width >> i;\r
+                               h = height >> i;\r
+                               if( w < 1 )\r
+                               {\r
+                                       w = 1;\r
+                               }\r
+                               if( h < 1 )\r
+                               {\r
+                                       h = 1;\r
+                               }\r
+                               /*      upload this mipmap      */\r
+                               if( uncompressed )\r
+                               {\r
+                                       mip_size = w*h*block_size;\r
+                                       glTexImage2D(\r
+                                               cf_target, i,\r
+                                               S3TC_type, w, h, 0,\r
+                                               S3TC_type, GL_UNSIGNED_BYTE, &DDS_data[byte_offset] );\r
+                               } else\r
+                               {\r
+                                       mip_size = ((w+3)/4)*((h+3)/4)*block_size;\r
+                                       soilGlCompressedTexImage2D(\r
+                                               cf_target, i,\r
+                                               S3TC_type, w, h, 0,\r
+                                               mip_size, &DDS_data[byte_offset] );\r
+                               }\r
+                               /*      and move to the next mipmap     */\r
+                               byte_offset += mip_size;\r
+                       }\r
+                       /*      it worked!      */\r
+                       result_string_pointer = "DDS file loaded";\r
+               } else\r
+               {\r
+                       glDeleteTextures( 1, & tex_ID );\r
+                       tex_ID = 0;\r
+                       cf_target = ogl_target_end + 1;\r
+                       result_string_pointer = "DDS file was too small for expected image data";\r
+               }\r
+       }/* end reading each face */\r
+       SOIL_free_image_data( DDS_data );\r
+       if( tex_ID )\r
+       {\r
+               /*      did I have MIPmaps?     */\r
+               if( mipmaps > 0 )\r
+               {\r
+                       /*      instruct OpenGL to use the MIPmaps      */\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );\r
+               } else\r
+               {\r
+                       /*      instruct OpenGL _NOT_ to use the MIPmaps        */\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\r
+               }\r
+               /*      does the user want clamping, or wrapping?       */\r
+               if( flags & SOIL_FLAG_TEXTURE_REPEATS )\r
+               {\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, GL_REPEAT );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, GL_REPEAT );\r
+                       glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, GL_REPEAT );\r
+               } else\r
+               {\r
+                       /*      unsigned int clamp_mode = SOIL_CLAMP_TO_EDGE;   */\r
+                       unsigned int clamp_mode = GL_CLAMP;\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_S, clamp_mode );\r
+                       glTexParameteri( opengl_texture_type, GL_TEXTURE_WRAP_T, clamp_mode );\r
+                       glTexParameteri( opengl_texture_type, SOIL_TEXTURE_WRAP_R, clamp_mode );\r
+               }\r
+       }\r
+\r
+quick_exit:\r
+       /*      report success or failure       */\r
+       return tex_ID;\r
+}\r
+\r
+unsigned int SOIL_direct_load_DDS(\r
+               const char *filename,\r
+               unsigned int reuse_texture_ID,\r
+               int flags,\r
+               int loading_as_cubemap )\r
+{\r
+       FILE *f;\r
+       unsigned char *buffer;\r
+       size_t buffer_length, bytes_read;\r
+       unsigned int tex_ID = 0;\r
+       /*      error checks    */\r
+       if( NULL == filename )\r
+       {\r
+               result_string_pointer = "NULL filename";\r
+               return 0;\r
+       }\r
+       f = fopen( filename, "rb" );\r
+       if( NULL == f )\r
+       {\r
+               /*      the file doesn't seem to exist (or be open-able)        */\r
+               result_string_pointer = "Can not find DDS file";\r
+               return 0;\r
+       }\r
+       fseek( f, 0, SEEK_END );\r
+       buffer_length = ftell( f );\r
+       fseek( f, 0, SEEK_SET );\r
+       buffer = (unsigned char *) malloc( buffer_length );\r
+       if( NULL == buffer )\r
+       {\r
+               result_string_pointer = "malloc failed";\r
+               fclose( f );\r
+               return 0;\r
+       }\r
+       bytes_read = fread( (void*)buffer, 1, buffer_length, f );\r
+       fclose( f );\r
+       if( bytes_read < buffer_length )\r
+       {\r
+               /*      huh?    */\r
+               buffer_length = bytes_read;\r
+       }\r
+       /*      now try to do the loading       */\r
+       tex_ID = SOIL_direct_load_DDS_from_memory(\r
+               (const unsigned char *const)buffer, buffer_length,\r
+               reuse_texture_ID, flags, loading_as_cubemap );\r
+       SOIL_free_image_data( buffer );\r
+       return tex_ID;\r
+}\r
+\r
+int query_NPOT_capability( void )\r
+{\r
+       /*      check for the capability        */\r
+       if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN )\r
+       {\r
+               /*      we haven't yet checked for the capability, do so        */\r
+               if(\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_ARB_texture_non_power_of_two" ) )\r
+                       )\r
+               {\r
+                       /*      not there, flag the failure     */\r
+                       has_NPOT_capability = SOIL_CAPABILITY_NONE;\r
+               } else\r
+               {\r
+                       /*      it's there!     */\r
+                       has_NPOT_capability = SOIL_CAPABILITY_PRESENT;\r
+               }\r
+       }\r
+       /*      let the user know if we can do non-power-of-two textures or not */\r
+       return has_NPOT_capability;\r
+}\r
+\r
+int query_tex_rectangle_capability( void )\r
+{\r
+       /*      check for the capability        */\r
+       if( has_tex_rectangle_capability == SOIL_CAPABILITY_UNKNOWN )\r
+       {\r
+               /*      we haven't yet checked for the capability, do so        */\r
+               if(\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_ARB_texture_rectangle" ) )\r
+               &&\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_EXT_texture_rectangle" ) )\r
+               &&\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_NV_texture_rectangle" ) )\r
+                       )\r
+               {\r
+                       /*      not there, flag the failure     */\r
+                       has_tex_rectangle_capability = SOIL_CAPABILITY_NONE;\r
+               } else\r
+               {\r
+                       /*      it's there!     */\r
+                       has_tex_rectangle_capability = SOIL_CAPABILITY_PRESENT;\r
+               }\r
+       }\r
+       /*      let the user know if we can do texture rectangles or not        */\r
+       return has_tex_rectangle_capability;\r
+}\r
+\r
+int query_cubemap_capability( void )\r
+{\r
+       /*      check for the capability        */\r
+       if( has_cubemap_capability == SOIL_CAPABILITY_UNKNOWN )\r
+       {\r
+               /*      we haven't yet checked for the capability, do so        */\r
+               if(\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_ARB_texture_cube_map" ) )\r
+               &&\r
+                       (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_EXT_texture_cube_map" ) )\r
+                       )\r
+               {\r
+                       /*      not there, flag the failure     */\r
+                       has_cubemap_capability = SOIL_CAPABILITY_NONE;\r
+               } else\r
+               {\r
+                       /*      it's there!     */\r
+                       has_cubemap_capability = SOIL_CAPABILITY_PRESENT;\r
+               }\r
+       }\r
+       /*      let the user know if we can do cubemaps or not  */\r
+       return has_cubemap_capability;\r
+}\r
+\r
+int query_DXT_capability( void )\r
+{\r
+       /*      check for the capability        */\r
+       if( has_DXT_capability == SOIL_CAPABILITY_UNKNOWN )\r
+       {\r
+               /*      we haven't yet checked for the capability, do so        */\r
+               if( NULL == strstr(\r
+                               (char const*)glGetString( GL_EXTENSIONS ),\r
+                               "GL_EXT_texture_compression_s3tc" ) )\r
+               {\r
+                       /*      not there, flag the failure     */\r
+                       has_DXT_capability = SOIL_CAPABILITY_NONE;\r
+               } else\r
+               {\r
+                       /*      and find the address of the extension function  */\r
+                       P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC ext_addr = NULL;\r
+                       #ifdef WIN32\r
+                               ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)\r
+                                               wglGetProcAddress\r
+                                               (\r
+                                                       "glCompressedTexImage2DARB"\r
+                                               );\r
+                       #elif defined(__APPLE__) || defined(__APPLE_CC__)\r
+                               /*      I can't test this Apple stuff!  */\r
+                               CFBundleRef bundle;\r
+                               CFURLRef bundleURL =\r
+                                       CFURLCreateWithFileSystemPath(\r
+                                               kCFAllocatorDefault,\r
+                                               CFSTR("/System/Library/Frameworks/OpenGL.framework"),\r
+                                               kCFURLPOSIXPathStyle,\r
+                                               true );\r
+                               CFStringRef extensionName =\r
+                                       CFStringCreateWithCString(\r
+                                               kCFAllocatorDefault,\r
+                                               "glCompressedTexImage2DARB",\r
+                                               kCFStringEncodingASCII );\r
+                               bundle = CFBundleCreate( kCFAllocatorDefault, bundleURL );\r
+                               assert( bundle != NULL );\r
+                               ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)\r
+                                               CFBundleGetFunctionPointerForName\r
+                                               (\r
+                                                       bundle, extensionName\r
+                                               );\r
+                               CFRelease( bundleURL );\r
+                               CFRelease( extensionName );\r
+                               CFRelease( bundle );\r
+                       #else\r
+                               ext_addr = (P_SOIL_GLCOMPRESSEDTEXIMAGE2DPROC)\r
+                                               glXGetProcAddressARB\r
+                                               (\r
+                                                       (const GLubyte *)"glCompressedTexImage2DARB"\r
+                                               );\r
+                       #endif\r
+                       /*      Flag it so no checks needed later       */\r
+                       if( NULL == ext_addr )\r
+                       {\r
+                               /*      hmm, not good!!  This should not happen, but does on my\r
+                                       laptop's VIA chipset.  The GL_EXT_texture_compression_s3tc\r
+                                       spec requires that ARB_texture_compression be present too.\r
+                                       this means I can upload and have the OpenGL drive do the\r
+                                       conversion, but I can't use my own routines or load DDS files\r
+                                       from disk and upload them directly [8^( */\r
+                               has_DXT_capability = SOIL_CAPABILITY_NONE;\r
+                       } else\r
+                       {\r
+                               /*      all's well!     */\r
+                               soilGlCompressedTexImage2D = ext_addr;\r
+                               has_DXT_capability = SOIL_CAPABILITY_PRESENT;\r
+                       }\r
+               }\r
+       }\r
+       /*      let the user know if we can do DXT or not       */\r
+       return has_DXT_capability;\r
+}\r
diff --git a/lib/soil/soil/SOIL.h b/lib/soil/soil/SOIL.h
new file mode 100644 (file)
index 0000000..57f375b
--- /dev/null
@@ -0,0 +1,433 @@
+/**\r
+       @mainpage SOIL\r
+\r
+       Jonathan Dummer\r
+       2007-07-26-10.36\r
+\r
+       Simple OpenGL Image Library\r
+\r
+       A tiny c library for uploading images as\r
+       textures into OpenGL.  Also saving and\r
+       loading of images is supported.\r
+\r
+       I'm using Sean's Tool Box image loader as a base:\r
+       http://www.nothings.org/\r
+\r
+       I'm upgrading it to load TGA and DDS files, and a direct\r
+       path for loading DDS files straight into OpenGL textures,\r
+       when applicable.\r
+\r
+       Image Formats:\r
+       - BMP           load & save\r
+       - TGA           load & save\r
+       - DDS           load & save\r
+       - PNG           load\r
+       - JPG           load\r
+\r
+       OpenGL Texture Features:\r
+       - resample to power-of-two sizes\r
+       - MIPmap generation\r
+       - compressed texture S3TC formats (if supported)\r
+       - can pre-multiply alpha for you, for better compositing\r
+       - can flip image about the y-axis (except pre-compressed DDS files)\r
+\r
+       Thanks to:\r
+       * Sean Barret - for the awesome stb_image\r
+       * Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts\r
+       * everybody at gamedev.net\r
+**/\r
+\r
+#ifndef HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY\r
+#define HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/**\r
+       The format of images that may be loaded (force_channels).\r
+       SOIL_LOAD_AUTO leaves the image in whatever format it was found.\r
+       SOIL_LOAD_L forces the image to load as Luminous (greyscale)\r
+       SOIL_LOAD_LA forces the image to load as Luminous with Alpha\r
+       SOIL_LOAD_RGB forces the image to load as Red Green Blue\r
+       SOIL_LOAD_RGBA forces the image to load as Red Green Blue Alpha\r
+**/\r
+enum\r
+{\r
+       SOIL_LOAD_AUTO = 0,\r
+       SOIL_LOAD_L = 1,\r
+       SOIL_LOAD_LA = 2,\r
+       SOIL_LOAD_RGB = 3,\r
+       SOIL_LOAD_RGBA = 4\r
+};\r
+\r
+/**\r
+       Passed in as reuse_texture_ID, will cause SOIL to\r
+       register a new texture ID using glGenTextures().\r
+       If the value passed into reuse_texture_ID > 0 then\r
+       SOIL will just re-use that texture ID (great for\r
+       reloading image assets in-game!)\r
+**/\r
+enum\r
+{\r
+       SOIL_CREATE_NEW_ID = 0\r
+};\r
+\r
+/**\r
+       flags you can pass into SOIL_load_OGL_texture()\r
+       and SOIL_create_OGL_texture().\r
+       (note that if SOIL_FLAG_DDS_LOAD_DIRECT is used\r
+       the rest of the flags with the exception of\r
+       SOIL_FLAG_TEXTURE_REPEATS will be ignored while\r
+       loading already-compressed DDS files.)\r
+\r
+       SOIL_FLAG_POWER_OF_TWO: force the image to be POT\r
+       SOIL_FLAG_MIPMAPS: generate mipmaps for the texture\r
+       SOIL_FLAG_TEXTURE_REPEATS: otherwise will clamp\r
+       SOIL_FLAG_MULTIPLY_ALPHA: for using (GL_ONE,GL_ONE_MINUS_SRC_ALPHA) blending\r
+       SOIL_FLAG_INVERT_Y: flip the image vertically\r
+       SOIL_FLAG_COMPRESS_TO_DXT: if the card can display them, will convert RGB to DXT1, RGBA to DXT5\r
+       SOIL_FLAG_DDS_LOAD_DIRECT: will load DDS files directly without _ANY_ additional processing\r
+       SOIL_FLAG_NTSC_SAFE_RGB: clamps RGB components to the range [16,235]\r
+       SOIL_FLAG_CoCg_Y: Google YCoCg; RGB=>CoYCg, RGBA=>CoCgAY\r
+       SOIL_FLAG_TEXTURE_RECTANGE: uses ARB_texture_rectangle ; pixel indexed & no repeat or MIPmaps or cubemaps\r
+**/\r
+enum\r
+{\r
+       SOIL_FLAG_POWER_OF_TWO = 1,\r
+       SOIL_FLAG_MIPMAPS = 2,\r
+       SOIL_FLAG_TEXTURE_REPEATS = 4,\r
+       SOIL_FLAG_MULTIPLY_ALPHA = 8,\r
+       SOIL_FLAG_INVERT_Y = 16,\r
+       SOIL_FLAG_COMPRESS_TO_DXT = 32,\r
+       SOIL_FLAG_DDS_LOAD_DIRECT = 64,\r
+       SOIL_FLAG_NTSC_SAFE_RGB = 128,\r
+       SOIL_FLAG_CoCg_Y = 256,\r
+       SOIL_FLAG_TEXTURE_RECTANGLE = 512\r
+};\r
+\r
+/**\r
+       The types of images that may be saved.\r
+       (TGA supports uncompressed RGB / RGBA)\r
+       (BMP supports uncompressed RGB)\r
+       (DDS supports DXT1 and DXT5)\r
+**/\r
+enum\r
+{\r
+       SOIL_SAVE_TYPE_TGA = 0,\r
+       SOIL_SAVE_TYPE_BMP = 1,\r
+       SOIL_SAVE_TYPE_DDS = 2\r
+};\r
+\r
+/**\r
+       Defines the order of faces in a DDS cubemap.\r
+       I recommend that you use the same order in single\r
+       image cubemap files, so they will be interchangeable\r
+       with DDS cubemaps when using SOIL.\r
+**/\r
+#define SOIL_DDS_CUBEMAP_FACE_ORDER "EWUDNS"\r
+\r
+/**\r
+       The types of internal fake HDR representations\r
+\r
+       SOIL_HDR_RGBE:          RGB * pow( 2.0, A - 128.0 )\r
+       SOIL_HDR_RGBdivA:       RGB / A\r
+       SOIL_HDR_RGBdivA2:      RGB / (A*A)\r
+**/\r
+enum\r
+{\r
+       SOIL_HDR_RGBE = 0,\r
+       SOIL_HDR_RGBdivA = 1,\r
+       SOIL_HDR_RGBdivA2 = 2\r
+};\r
+\r
+/**\r
+       Loads an image from disk into an OpenGL texture.\r
+       \param filename the name of the file to upload as a texture\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_texture\r
+       (\r
+               const char *filename,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads 6 images from disk into an OpenGL cubemap texture.\r
+       \param x_pos_file the name of the file to upload as the +x cube face\r
+       \param x_neg_file the name of the file to upload as the -x cube face\r
+       \param y_pos_file the name of the file to upload as the +y cube face\r
+       \param y_neg_file the name of the file to upload as the -y cube face\r
+       \param z_pos_file the name of the file to upload as the +z cube face\r
+       \param z_neg_file the name of the file to upload as the -z cube face\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_cubemap\r
+       (\r
+               const char *x_pos_file,\r
+               const char *x_neg_file,\r
+               const char *y_pos_file,\r
+               const char *y_neg_file,\r
+               const char *z_pos_file,\r
+               const char *z_neg_file,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads 1 image from disk and splits it into an OpenGL cubemap texture.\r
+       \param filename the name of the file to upload as a texture\r
+       \param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_single_cubemap\r
+       (\r
+               const char *filename,\r
+               const char face_order[6],\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads an HDR image from disk into an OpenGL texture.\r
+       \param filename the name of the file to upload as a texture\r
+       \param fake_HDR_format SOIL_HDR_RGBE, SOIL_HDR_RGBdivA, SOIL_HDR_RGBdivA2\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_HDR_texture\r
+       (\r
+               const char *filename,\r
+               int fake_HDR_format,\r
+               int rescale_to_max,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads an image from RAM into an OpenGL texture.\r
+       \param buffer the image data in RAM just as if it were still in a file\r
+       \param buffer_length the size of the buffer in bytes\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_texture_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads 6 images from memory into an OpenGL cubemap texture.\r
+       \param x_pos_buffer the image data in RAM to upload as the +x cube face\r
+       \param x_pos_buffer_length the size of the above buffer\r
+       \param x_neg_buffer the image data in RAM to upload as the +x cube face\r
+       \param x_neg_buffer_length the size of the above buffer\r
+       \param y_pos_buffer the image data in RAM to upload as the +x cube face\r
+       \param y_pos_buffer_length the size of the above buffer\r
+       \param y_neg_buffer the image data in RAM to upload as the +x cube face\r
+       \param y_neg_buffer_length the size of the above buffer\r
+       \param z_pos_buffer the image data in RAM to upload as the +x cube face\r
+       \param z_pos_buffer_length the size of the above buffer\r
+       \param z_neg_buffer the image data in RAM to upload as the +x cube face\r
+       \param z_neg_buffer_length the size of the above buffer\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_cubemap_from_memory\r
+       (\r
+               const unsigned char *const x_pos_buffer,\r
+               int x_pos_buffer_length,\r
+               const unsigned char *const x_neg_buffer,\r
+               int x_neg_buffer_length,\r
+               const unsigned char *const y_pos_buffer,\r
+               int y_pos_buffer_length,\r
+               const unsigned char *const y_neg_buffer,\r
+               int y_neg_buffer_length,\r
+               const unsigned char *const z_pos_buffer,\r
+               int z_pos_buffer_length,\r
+               const unsigned char *const z_neg_buffer,\r
+               int z_neg_buffer_length,\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Loads 1 image from RAM and splits it into an OpenGL cubemap texture.\r
+       \param buffer the image data in RAM just as if it were still in a file\r
+       \param buffer_length the size of the buffer in bytes\r
+       \param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.\r
+       \param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_load_OGL_single_cubemap_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               const char face_order[6],\r
+               int force_channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Creates a 2D OpenGL texture from raw image data.  Note that the raw data is\r
+       _NOT_ freed after the upload (so the user can load various versions).\r
+       \param data the raw data to be uploaded as an OpenGL texture\r
+       \param width the width of the image in pixels\r
+       \param height the height of the image in pixels\r
+       \param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_create_OGL_texture\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Creates an OpenGL cubemap texture by splitting up 1 image into 6 parts.\r
+       \param data the raw data to be uploaded as an OpenGL texture\r
+       \param width the width of the image in pixels\r
+       \param height the height of the image in pixels\r
+       \param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA\r
+       \param face_order the order of the faces in the file, and combination of NSWEUD, for North, South, Up, etc.\r
+       \param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)\r
+       \param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT\r
+       \return 0-failed, otherwise returns the OpenGL texture handle\r
+**/\r
+unsigned int\r
+       SOIL_create_OGL_single_cubemap\r
+       (\r
+               const unsigned char *const data,\r
+               int width, int height, int channels,\r
+               const char face_order[6],\r
+               unsigned int reuse_texture_ID,\r
+               unsigned int flags\r
+       );\r
+\r
+/**\r
+       Captures the OpenGL window (RGB) and saves it to disk\r
+       \return 0 if it failed, otherwise returns 1\r
+**/\r
+int\r
+       SOIL_save_screenshot\r
+       (\r
+               const char *filename,\r
+               int image_type,\r
+               int x, int y,\r
+               int width, int height\r
+       );\r
+\r
+/**\r
+       Loads an image from disk into an array of unsigned chars.\r
+       Note that *channels return the original channel count of the\r
+       image.  If force_channels was other than SOIL_LOAD_AUTO,\r
+       the resulting image has force_channels, but *channels may be\r
+       different (if the original image had a different channel\r
+       count).\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+unsigned char*\r
+       SOIL_load_image\r
+       (\r
+               const char *filename,\r
+               int *width, int *height, int *channels,\r
+               int force_channels\r
+       );\r
+\r
+/**\r
+       Loads an image from memory into an array of unsigned chars.\r
+       Note that *channels return the original channel count of the\r
+       image.  If force_channels was other than SOIL_LOAD_AUTO,\r
+       the resulting image has force_channels, but *channels may be\r
+       different (if the original image had a different channel\r
+       count).\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+unsigned char*\r
+       SOIL_load_image_from_memory\r
+       (\r
+               const unsigned char *const buffer,\r
+               int buffer_length,\r
+               int *width, int *height, int *channels,\r
+               int force_channels\r
+       );\r
+\r
+/**\r
+       Saves an image from an array of unsigned chars (RGBA) to disk\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+int\r
+       SOIL_save_image\r
+       (\r
+               const char *filename,\r
+               int image_type,\r
+               int width, int height, int channels,\r
+               const unsigned char *const data\r
+       );\r
+\r
+/**\r
+       Frees the image data (note, this is just C's "free()"...this function is\r
+       present mostly so C++ programmers don't forget to use "free()" and call\r
+       "delete []" instead [8^)\r
+**/\r
+void\r
+       SOIL_free_image_data\r
+       (\r
+               unsigned char *img_data\r
+       );\r
+\r
+/**\r
+       This function resturn a pointer to a string describing the last thing\r
+       that happened inside SOIL.  It can be used to determine why an image\r
+       failed to load.\r
+**/\r
+const char*\r
+       SOIL_last_result\r
+       (\r
+               void\r
+       );\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY   */\r
diff --git a/lib/soil/soil/image_DXT.c b/lib/soil/soil/image_DXT.c
new file mode 100644 (file)
index 0000000..eb90be6
--- /dev/null
@@ -0,0 +1,632 @@
+/*\r
+       Jonathan Dummer\r
+       2007-07-31-10.32\r
+\r
+       simple DXT compression / decompression code\r
+\r
+       public domain\r
+*/\r
+\r
+#include "image_DXT.h"\r
+#include <math.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+#include <stdio.h>\r
+\r
+/*     set this =1 if you want to use the covarince matrix method...\r
+       which is better than my method of using standard deviations\r
+       overall, except on the infintesimal chance that the power\r
+       method fails for finding the largest eigenvector        */\r
+#define USE_COV_MAT    1\r
+\r
+/********* Function Prototypes *********/\r
+/*\r
+       Takes a 4x4 block of pixels and compresses it into 8 bytes\r
+       in DXT1 format (color only, no alpha).  Speed is valued\r
+       over prettyness, at least for now.\r
+*/\r
+void compress_DDS_color_block(\r
+                               int channels,\r
+                               const unsigned char *const uncompressed,\r
+                               unsigned char compressed[8] );\r
+/*\r
+       Takes a 4x4 block of pixels and compresses the alpha\r
+       component it into 8 bytes for use in DXT5 DDS files.\r
+       Speed is valued over prettyness, at least for now.\r
+*/\r
+void compress_DDS_alpha_block(\r
+                               const unsigned char *const uncompressed,\r
+                               unsigned char compressed[8] );\r
+\r
+/********* Actual Exposed Functions *********/\r
+int\r
+       save_image_as_DDS\r
+       (\r
+               const char *filename,\r
+               int width, int height, int channels,\r
+               const unsigned char *const data\r
+       )\r
+{\r
+       /*      variables       */\r
+       FILE *fout;\r
+       unsigned char *DDS_data;\r
+       DDS_header header;\r
+       int DDS_size;\r
+       /*      error check     */\r
+       if( (NULL == filename) ||\r
+               (width < 1) || (height < 1) ||\r
+               (channels < 1) || (channels > 4) ||\r
+               (data == NULL ) )\r
+       {\r
+               return 0;\r
+       }\r
+       /*      Convert the image       */\r
+       if( (channels & 1) == 1 )\r
+       {\r
+               /*      no alpha, just use DXT1 */\r
+               DDS_data = convert_image_to_DXT1( data, width, height, channels, &DDS_size );\r
+       } else\r
+       {\r
+               /*      has alpha, so use DXT5  */\r
+               DDS_data = convert_image_to_DXT5( data, width, height, channels, &DDS_size );\r
+       }\r
+       /*      save it */\r
+       memset( &header, 0, sizeof( DDS_header ) );\r
+       header.dwMagic = ('D' << 0) | ('D' << 8) | ('S' << 16) | (' ' << 24);\r
+       header.dwSize = 124;\r
+       header.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | DDSD_LINEARSIZE;\r
+       header.dwWidth = width;\r
+       header.dwHeight = height;\r
+       header.dwPitchOrLinearSize = DDS_size;\r
+       header.sPixelFormat.dwSize = 32;\r
+       header.sPixelFormat.dwFlags = DDPF_FOURCC;\r
+       if( (channels & 1) == 1 )\r
+       {\r
+               header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('1' << 24);\r
+       } else\r
+       {\r
+               header.sPixelFormat.dwFourCC = ('D' << 0) | ('X' << 8) | ('T' << 16) | ('5' << 24);\r
+       }\r
+       header.sCaps.dwCaps1 = DDSCAPS_TEXTURE;\r
+       /*      write it out    */\r
+       fout = fopen( filename, "wb");\r
+       fwrite( &header, sizeof( DDS_header ), 1, fout );\r
+       fwrite( DDS_data, 1, DDS_size, fout );\r
+       fclose( fout );\r
+       /*      done    */\r
+       free( DDS_data );\r
+       return 1;\r
+}\r
+\r
+unsigned char* convert_image_to_DXT1(\r
+               const unsigned char *const uncompressed,\r
+               int width, int height, int channels,\r
+               int *out_size )\r
+{\r
+       unsigned char *compressed;\r
+       int i, j, x, y;\r
+       unsigned char ublock[16*3];\r
+       unsigned char cblock[8];\r
+       int index = 0, chan_step = 1;\r
+       int block_count = 0;\r
+       /*      error check     */\r
+       *out_size = 0;\r
+       if( (width < 1) || (height < 1) ||\r
+               (NULL == uncompressed) ||\r
+               (channels < 1) || (channels > 4) )\r
+       {\r
+               return NULL;\r
+       }\r
+       /*      for channels == 1 or 2, I do not step forward for R,G,B values  */\r
+       if( channels < 3 )\r
+       {\r
+               chan_step = 0;\r
+       }\r
+       /*      get the RAM for the compressed image\r
+               (8 bytes per 4x4 pixel block)   */\r
+       *out_size = ((width+3) >> 2) * ((height+3) >> 2) * 8;\r
+       compressed = (unsigned char*)malloc( *out_size );\r
+       /*      go through each block   */\r
+       for( j = 0; j < height; j += 4 )\r
+       {\r
+               for( i = 0; i < width; i += 4 )\r
+               {\r
+                       /*      copy this block into a new one  */\r
+                       int idx = 0;\r
+                       int mx = 4, my = 4;\r
+                       if( j+4 >= height )\r
+                       {\r
+                               my = height - j;\r
+                       }\r
+                       if( i+4 >= width )\r
+                       {\r
+                               mx = width - i;\r
+                       }\r
+                       for( y = 0; y < my; ++y )\r
+                       {\r
+                               for( x = 0; x < mx; ++x )\r
+                               {\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];\r
+                               }\r
+                               for( x = mx; x < 4; ++x )\r
+                               {\r
+                                       ublock[idx++] = ublock[0];\r
+                                       ublock[idx++] = ublock[1];\r
+                                       ublock[idx++] = ublock[2];\r
+                               }\r
+                       }\r
+                       for( y = my; y < 4; ++y )\r
+                       {\r
+                               for( x = 0; x < 4; ++x )\r
+                               {\r
+                                       ublock[idx++] = ublock[0];\r
+                                       ublock[idx++] = ublock[1];\r
+                                       ublock[idx++] = ublock[2];\r
+                               }\r
+                       }\r
+                       /*      compress the block      */\r
+                       ++block_count;\r
+                       compress_DDS_color_block( 3, ublock, cblock );\r
+                       /*      copy the data from the block into the main block        */\r
+                       for( x = 0; x < 8; ++x )\r
+                       {\r
+                               compressed[index++] = cblock[x];\r
+                       }\r
+               }\r
+       }\r
+       return compressed;\r
+}\r
+\r
+unsigned char* convert_image_to_DXT5(\r
+               const unsigned char *const uncompressed,\r
+               int width, int height, int channels,\r
+               int *out_size )\r
+{\r
+       unsigned char *compressed;\r
+       int i, j, x, y;\r
+       unsigned char ublock[16*4];\r
+       unsigned char cblock[8];\r
+       int index = 0, chan_step = 1;\r
+       int block_count = 0, has_alpha;\r
+       /*      error check     */\r
+       *out_size = 0;\r
+       if( (width < 1) || (height < 1) ||\r
+               (NULL == uncompressed) ||\r
+               (channels < 1) || ( channels > 4) )\r
+       {\r
+               return NULL;\r
+       }\r
+       /*      for channels == 1 or 2, I do not step forward for R,G,B vales   */\r
+       if( channels < 3 )\r
+       {\r
+               chan_step = 0;\r
+       }\r
+       /*      # channels = 1 or 3 have no alpha, 2 & 4 do have alpha  */\r
+       has_alpha = 1 - (channels & 1);\r
+       /*      get the RAM for the compressed image\r
+               (16 bytes per 4x4 pixel block)  */\r
+       *out_size = ((width+3) >> 2) * ((height+3) >> 2) * 16;\r
+       compressed = (unsigned char*)malloc( *out_size );\r
+       /*      go through each block   */\r
+       for( j = 0; j < height; j += 4 )\r
+       {\r
+               for( i = 0; i < width; i += 4 )\r
+               {\r
+                       /*      local variables, and my block counter   */\r
+                       int idx = 0;\r
+                       int mx = 4, my = 4;\r
+                       if( j+4 >= height )\r
+                       {\r
+                               my = height - j;\r
+                       }\r
+                       if( i+4 >= width )\r
+                       {\r
+                               mx = width - i;\r
+                       }\r
+                       for( y = 0; y < my; ++y )\r
+                       {\r
+                               for( x = 0; x < mx; ++x )\r
+                               {\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels];\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step];\r
+                                       ublock[idx++] = uncompressed[(j+y)*width*channels+(i+x)*channels+chan_step+chan_step];\r
+                                       ublock[idx++] =\r
+                                               has_alpha * uncompressed[(j+y)*width*channels+(i+x)*channels+channels-1]\r
+                                               + (1-has_alpha)*255;\r
+                               }\r
+                               for( x = mx; x < 4; ++x )\r
+                               {\r
+                                       ublock[idx++] = ublock[0];\r
+                                       ublock[idx++] = ublock[1];\r
+                                       ublock[idx++] = ublock[2];\r
+                                       ublock[idx++] = ublock[3];\r
+                               }\r
+                       }\r
+                       for( y = my; y < 4; ++y )\r
+                       {\r
+                               for( x = 0; x < 4; ++x )\r
+                               {\r
+                                       ublock[idx++] = ublock[0];\r
+                                       ublock[idx++] = ublock[1];\r
+                                       ublock[idx++] = ublock[2];\r
+                                       ublock[idx++] = ublock[3];\r
+                               }\r
+                       }\r
+                       /*      now compress the alpha block    */\r
+                       compress_DDS_alpha_block( ublock, cblock );\r
+                       /*      copy the data from the compressed alpha block into the main buffer      */\r
+                       for( x = 0; x < 8; ++x )\r
+                       {\r
+                               compressed[index++] = cblock[x];\r
+                       }\r
+                       /*      then compress the color block   */\r
+                       ++block_count;\r
+                       compress_DDS_color_block( 4, ublock, cblock );\r
+                       /*      copy the data from the compressed color block into the main buffer      */\r
+                       for( x = 0; x < 8; ++x )\r
+                       {\r
+                               compressed[index++] = cblock[x];\r
+                       }\r
+               }\r
+       }\r
+       return compressed;\r
+}\r
+\r
+/********* Helper Functions *********/\r
+int convert_bit_range( int c, int from_bits, int to_bits )\r
+{\r
+       int b = (1 << (from_bits - 1)) + c * ((1 << to_bits) - 1);\r
+       return (b + (b >> from_bits)) >> from_bits;\r
+}\r
+\r
+int rgb_to_565( int r, int g, int b )\r
+{\r
+       return\r
+               (convert_bit_range( r, 8, 5 ) << 11) |\r
+               (convert_bit_range( g, 8, 6 ) << 05) |\r
+               (convert_bit_range( b, 8, 5 ) << 00);\r
+}\r
+\r
+void rgb_888_from_565( unsigned int c, int *r, int *g, int *b )\r
+{\r
+       *r = convert_bit_range( (c >> 11) & 31, 5, 8 );\r
+       *g = convert_bit_range( (c >> 05) & 63, 6, 8 );\r
+       *b = convert_bit_range( (c >> 00) & 31, 5, 8 );\r
+}\r
+\r
+void compute_color_line_STDEV(\r
+               const unsigned char *const uncompressed,\r
+               int channels,\r
+               float point[3], float direction[3] )\r
+{\r
+       const float inv_16 = 1.0f / 16.0f;\r
+       int i;\r
+       float sum_r = 0.0f, sum_g = 0.0f, sum_b = 0.0f;\r
+       float sum_rr = 0.0f, sum_gg = 0.0f, sum_bb = 0.0f;\r
+       float sum_rg = 0.0f, sum_rb = 0.0f, sum_gb = 0.0f;\r
+       /*      calculate all data needed for the covariance matrix\r
+               ( to compare with _rygdxt code) */\r
+       for( i = 0; i < 16*channels; i += channels )\r
+       {\r
+               sum_r += uncompressed[i+0];\r
+               sum_rr += uncompressed[i+0] * uncompressed[i+0];\r
+               sum_g += uncompressed[i+1];\r
+               sum_gg += uncompressed[i+1] * uncompressed[i+1];\r
+               sum_b += uncompressed[i+2];\r
+               sum_bb += uncompressed[i+2] * uncompressed[i+2];\r
+               sum_rg += uncompressed[i+0] * uncompressed[i+1];\r
+               sum_rb += uncompressed[i+0] * uncompressed[i+2];\r
+               sum_gb += uncompressed[i+1] * uncompressed[i+2];\r
+       }\r
+       /*      convert the sums to averages    */\r
+       sum_r *= inv_16;\r
+       sum_g *= inv_16;\r
+       sum_b *= inv_16;\r
+       /*      and convert the squares to the squares of the value - avg_value */\r
+       sum_rr -= 16.0f * sum_r * sum_r;\r
+       sum_gg -= 16.0f * sum_g * sum_g;\r
+       sum_bb -= 16.0f * sum_b * sum_b;\r
+       sum_rg -= 16.0f * sum_r * sum_g;\r
+       sum_rb -= 16.0f * sum_r * sum_b;\r
+       sum_gb -= 16.0f * sum_g * sum_b;\r
+       /*      the point on the color line is the average      */\r
+       point[0] = sum_r;\r
+       point[1] = sum_g;\r
+       point[2] = sum_b;\r
+       #if USE_COV_MAT\r
+       /*\r
+               The following idea was from ryg.\r
+               (https://mollyrocket.com/forums/viewtopic.php?t=392)\r
+               The method worked great (less RMSE than mine) most of\r
+               the time, but had some issues handling some simple\r
+               boundary cases, like full green next to full red,\r
+               which would generate a covariance matrix like this:\r
+\r
+               | 1  -1  0 |\r
+               | -1  1  0 |\r
+               | 0   0  0 |\r
+\r
+               For a given starting vector, the power method can\r
+               generate all zeros!  So no starting with {1,1,1}\r
+               as I was doing!  This kind of error is still a\r
+               slight posibillity, but will be very rare.\r
+       */\r
+       /*      use the covariance matrix directly\r
+               (1st iteration, don't use all 1.0 values!)      */\r
+       sum_r = 1.0f;\r
+       sum_g = 2.718281828f;\r
+       sum_b = 3.141592654f;\r
+       direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;\r
+       direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;\r
+       direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;\r
+       /*      2nd iteration, use results from the 1st guy     */\r
+       sum_r = direction[0];\r
+       sum_g = direction[1];\r
+       sum_b = direction[2];\r
+       direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;\r
+       direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;\r
+       direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;\r
+       /*      3rd iteration, use results from the 2nd guy     */\r
+       sum_r = direction[0];\r
+       sum_g = direction[1];\r
+       sum_b = direction[2];\r
+       direction[0] = sum_r*sum_rr + sum_g*sum_rg + sum_b*sum_rb;\r
+       direction[1] = sum_r*sum_rg + sum_g*sum_gg + sum_b*sum_gb;\r
+       direction[2] = sum_r*sum_rb + sum_g*sum_gb + sum_b*sum_bb;\r
+       #else\r
+       /*      use my standard deviation method\r
+               (very robust, a tiny bit slower and less accurate)      */\r
+       direction[0] = sqrt( sum_rr );\r
+       direction[1] = sqrt( sum_gg );\r
+       direction[2] = sqrt( sum_bb );\r
+       /*      which has a greater component   */\r
+       if( sum_gg > sum_rr )\r
+       {\r
+               /*      green has greater component, so base the other signs off of green       */\r
+               if( sum_rg < 0.0f )\r
+               {\r
+                       direction[0] = -direction[0];\r
+               }\r
+               if( sum_gb < 0.0f )\r
+               {\r
+                       direction[2] = -direction[2];\r
+               }\r
+       } else\r
+       {\r
+               /*      red has a greater component     */\r
+               if( sum_rg < 0.0f )\r
+               {\r
+                       direction[1] = -direction[1];\r
+               }\r
+               if( sum_rb < 0.0f )\r
+               {\r
+                       direction[2] = -direction[2];\r
+               }\r
+       }\r
+       #endif\r
+}\r
+\r
+void LSE_master_colors_max_min(\r
+               int *cmax, int *cmin,\r
+               int channels,\r
+               const unsigned char *const uncompressed )\r
+{\r
+       int i, j;\r
+       /*      the master colors       */\r
+       int c0[3], c1[3];\r
+       /*      used for fitting the line       */\r
+       float sum_x[] = { 0.0f, 0.0f, 0.0f };\r
+       float sum_x2[] = { 0.0f, 0.0f, 0.0f };\r
+       float dot_max = 1.0f, dot_min = -1.0f;\r
+       float vec_len2 = 0.0f;\r
+       float dot;\r
+       /*      error check     */\r
+       if( (channels < 3) || (channels > 4) )\r
+       {\r
+               return;\r
+       }\r
+       compute_color_line_STDEV( uncompressed, channels, sum_x, sum_x2 );\r
+       vec_len2 = 1.0f / ( 0.00001f +\r
+                       sum_x2[0]*sum_x2[0] + sum_x2[1]*sum_x2[1] + sum_x2[2]*sum_x2[2] );\r
+       /*      finding the max and min vector values   */\r
+       dot_max =\r
+                       (\r
+                               sum_x2[0] * uncompressed[0] +\r
+                               sum_x2[1] * uncompressed[1] +\r
+                               sum_x2[2] * uncompressed[2]\r
+                       );\r
+       dot_min = dot_max;\r
+       for( i = 1; i < 16; ++i )\r
+       {\r
+               dot =\r
+                       (\r
+                               sum_x2[0] * uncompressed[i*channels+0] +\r
+                               sum_x2[1] * uncompressed[i*channels+1] +\r
+                               sum_x2[2] * uncompressed[i*channels+2]\r
+                       );\r
+               if( dot < dot_min )\r
+               {\r
+                       dot_min = dot;\r
+               } else if( dot > dot_max )\r
+               {\r
+                       dot_max = dot;\r
+               }\r
+       }\r
+       /*      and the offset (from the average location)      */\r
+       dot = sum_x2[0]*sum_x[0] + sum_x2[1]*sum_x[1] + sum_x2[2]*sum_x[2];\r
+       dot_min -= dot;\r
+       dot_max -= dot;\r
+       /*      post multiply by the scaling factor     */\r
+       dot_min *= vec_len2;\r
+       dot_max *= vec_len2;\r
+       /*      OK, build the master colors     */\r
+       for( i = 0; i < 3; ++i )\r
+       {\r
+               /*      color 0 */\r
+               c0[i] = (int)(0.5f + sum_x[i] + dot_max * sum_x2[i]);\r
+               if( c0[i] < 0 )\r
+               {\r
+                       c0[i] = 0;\r
+               } else if( c0[i] > 255 )\r
+               {\r
+                       c0[i] = 255;\r
+               }\r
+               /*      color 1 */\r
+               c1[i] = (int)(0.5f + sum_x[i] + dot_min * sum_x2[i]);\r
+               if( c1[i] < 0 )\r
+               {\r
+                       c1[i] = 0;\r
+               } else if( c1[i] > 255 )\r
+               {\r
+                       c1[i] = 255;\r
+               }\r
+       }\r
+       /*      down_sample (with rounding?)    */\r
+       i = rgb_to_565( c0[0], c0[1], c0[2] );\r
+       j = rgb_to_565( c1[0], c1[1], c1[2] );\r
+       if( i > j )\r
+       {\r
+               *cmax = i;\r
+               *cmin = j;\r
+       } else\r
+       {\r
+               *cmax = j;\r
+               *cmin = i;\r
+       }\r
+}\r
+\r
+void\r
+       compress_DDS_color_block\r
+       (\r
+               int channels,\r
+               const unsigned char *const uncompressed,\r
+               unsigned char compressed[8]\r
+       )\r
+{\r
+       /*      variables       */\r
+       int i;\r
+       int next_bit;\r
+       int enc_c0, enc_c1;\r
+       int c0[4], c1[4];\r
+       float color_line[] = { 0.0f, 0.0f, 0.0f, 0.0f };\r
+       float vec_len2 = 0.0f, dot_offset = 0.0f;\r
+       /*      stupid order    */\r
+       int swizzle4[] = { 0, 2, 3, 1 };\r
+       /*      get the master colors   */\r
+       LSE_master_colors_max_min( &enc_c0, &enc_c1, channels, uncompressed );\r
+       /*      store the 565 color 0 and color 1       */\r
+       compressed[0] = (enc_c0 >> 0) & 255;\r
+       compressed[1] = (enc_c0 >> 8) & 255;\r
+       compressed[2] = (enc_c1 >> 0) & 255;\r
+       compressed[3] = (enc_c1 >> 8) & 255;\r
+       /*      zero out the compressed data    */\r
+       compressed[4] = 0;\r
+       compressed[5] = 0;\r
+       compressed[6] = 0;\r
+       compressed[7] = 0;\r
+       /*      reconstitute the master color vectors   */\r
+       rgb_888_from_565( enc_c0, &c0[0], &c0[1], &c0[2] );\r
+       rgb_888_from_565( enc_c1, &c1[0], &c1[1], &c1[2] );\r
+       /*      the new vector  */\r
+       vec_len2 = 0.0f;\r
+       for( i = 0; i < 3; ++i )\r
+       {\r
+               color_line[i] = (float)(c1[i] - c0[i]);\r
+               vec_len2 += color_line[i] * color_line[i];\r
+       }\r
+       if( vec_len2 > 0.0f )\r
+       {\r
+               vec_len2 = 1.0f / vec_len2;\r
+       }\r
+       /*      pre-proform the scaling */\r
+       color_line[0] *= vec_len2;\r
+       color_line[1] *= vec_len2;\r
+       color_line[2] *= vec_len2;\r
+       /*      compute the offset (constant) portion of the dot product        */\r
+       dot_offset = color_line[0]*c0[0] + color_line[1]*c0[1] + color_line[2]*c0[2];\r
+       /*      store the rest of the bits      */\r
+       next_bit = 8*4;\r
+       for( i = 0; i < 16; ++i )\r
+       {\r
+               /*      find the dot product of this color, to place it on the line\r
+                       (should be [-1,1])      */\r
+               int next_value = 0;\r
+               float dot_product =\r
+                       color_line[0] * uncompressed[i*channels+0] +\r
+                       color_line[1] * uncompressed[i*channels+1] +\r
+                       color_line[2] * uncompressed[i*channels+2] -\r
+                       dot_offset;\r
+               /*      map to [0,3]    */\r
+               next_value = (int)( dot_product * 3.0f + 0.5f );\r
+               if( next_value > 3 )\r
+               {\r
+                       next_value = 3;\r
+               } else if( next_value < 0 )\r
+               {\r
+                       next_value = 0;\r
+               }\r
+               /*      OK, store this value    */\r
+               compressed[next_bit >> 3] |= swizzle4[ next_value ] << (next_bit & 7);\r
+               next_bit += 2;\r
+       }\r
+       /*      done compressing to DXT1        */\r
+}\r
+\r
+void\r
+       compress_DDS_alpha_block\r
+       (\r
+               const unsigned char *const uncompressed,\r
+               unsigned char compressed[8]\r
+       )\r
+{\r
+       /*      variables       */\r
+       int i;\r
+       int next_bit;\r
+       int a0, a1;\r
+       float scale_me;\r
+       /*      stupid order    */\r
+       int swizzle8[] = { 1, 7, 6, 5, 4, 3, 2, 0 };\r
+       /*      get the alpha limits (a0 > a1)  */\r
+       a0 = a1 = uncompressed[3];\r
+       for( i = 4+3; i < 16*4; i += 4 )\r
+       {\r
+               if( uncompressed[i] > a0 )\r
+               {\r
+                       a0 = uncompressed[i];\r
+               } else if( uncompressed[i] < a1 )\r
+               {\r
+                       a1 = uncompressed[i];\r
+               }\r
+       }\r
+       /*      store those limits, and zero the rest of the compressed dataset */\r
+       compressed[0] = a0;\r
+       compressed[1] = a1;\r
+       /*      zero out the compressed data    */\r
+       compressed[2] = 0;\r
+       compressed[3] = 0;\r
+       compressed[4] = 0;\r
+       compressed[5] = 0;\r
+       compressed[6] = 0;\r
+       compressed[7] = 0;\r
+       /*      store the all of the alpha values       */\r
+       next_bit = 8*2;\r
+       scale_me = 7.9999f / (a0 - a1);\r
+       for( i = 3; i < 16*4; i += 4 )\r
+       {\r
+               /*      convert this alpha value to a 3 bit number      */\r
+               int svalue;\r
+               int value = (int)((uncompressed[i] - a1) * scale_me);\r
+               svalue = swizzle8[ value&7 ];\r
+               /*      OK, store this value, start with the 1st byte   */\r
+               compressed[next_bit >> 3] |= svalue << (next_bit & 7);\r
+               if( (next_bit & 7) > 5 )\r
+               {\r
+                       /*      spans 2 bytes, fill in the start of the 2nd byte        */\r
+                       compressed[1 + (next_bit >> 3)] |= svalue >> (8 - (next_bit & 7) );\r
+               }\r
+               next_bit += 3;\r
+       }\r
+       /*      done compressing to DXT1        */\r
+}\r
diff --git a/lib/soil/soil/image_DXT.h b/lib/soil/soil/image_DXT.h
new file mode 100644 (file)
index 0000000..ce77164
--- /dev/null
@@ -0,0 +1,123 @@
+/*\r
+       Jonathan Dummer\r
+       2007-07-31-10.32\r
+\r
+       simple DXT compression / decompression code\r
+\r
+       public domain\r
+*/\r
+\r
+#ifndef HEADER_IMAGE_DXT\r
+#define HEADER_IMAGE_DXT\r
+\r
+/**\r
+       Converts an image from an array of unsigned chars (RGB or RGBA) to\r
+       DXT1 or DXT5, then saves the converted image to disk.\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+int\r
+save_image_as_DDS\r
+(\r
+    const char *filename,\r
+    int width, int height, int channels,\r
+    const unsigned char *const data\r
+);\r
+\r
+/**\r
+       take an image and convert it to DXT1 (no alpha)\r
+**/\r
+unsigned char*\r
+convert_image_to_DXT1\r
+(\r
+    const unsigned char *const uncompressed,\r
+    int width, int height, int channels,\r
+    int *out_size\r
+);\r
+\r
+/**\r
+       take an image and convert it to DXT5 (with alpha)\r
+**/\r
+unsigned char*\r
+convert_image_to_DXT5\r
+(\r
+    const unsigned char *const uncompressed,\r
+    int width, int height, int channels,\r
+    int *out_size\r
+);\r
+\r
+/**    A bunch of DirectDraw Surface structures and flags **/\r
+typedef struct\r
+{\r
+    unsigned int    dwMagic;\r
+    unsigned int    dwSize;\r
+    unsigned int    dwFlags;\r
+    unsigned int    dwHeight;\r
+    unsigned int    dwWidth;\r
+    unsigned int    dwPitchOrLinearSize;\r
+    unsigned int    dwDepth;\r
+    unsigned int    dwMipMapCount;\r
+    unsigned int    dwReserved1[ 11 ];\r
+\r
+    /*  DDPIXELFORMAT  */\r
+    struct\r
+    {\r
+        unsigned int    dwSize;\r
+        unsigned int    dwFlags;\r
+        unsigned int    dwFourCC;\r
+        unsigned int    dwRGBBitCount;\r
+        unsigned int    dwRBitMask;\r
+        unsigned int    dwGBitMask;\r
+        unsigned int    dwBBitMask;\r
+        unsigned int    dwAlphaBitMask;\r
+    }\r
+    sPixelFormat;\r
+\r
+    /*  DDCAPS2        */\r
+    struct\r
+    {\r
+        unsigned int    dwCaps1;\r
+        unsigned int    dwCaps2;\r
+        unsigned int    dwDDSX;\r
+        unsigned int    dwReserved;\r
+    }\r
+    sCaps;\r
+    unsigned int    dwReserved2;\r
+}\r
+DDS_header ;\r
+\r
+/*     the following constants were copied directly off the MSDN website       */\r
+\r
+/*     The dwFlags member of the original DDSURFACEDESC2 structure\r
+       can be set to one or more of the following values.      */\r
+#define DDSD_CAPS      0x00000001\r
+#define DDSD_HEIGHT    0x00000002\r
+#define DDSD_WIDTH     0x00000004\r
+#define DDSD_PITCH     0x00000008\r
+#define DDSD_PIXELFORMAT       0x00001000\r
+#define DDSD_MIPMAPCOUNT       0x00020000\r
+#define DDSD_LINEARSIZE        0x00080000\r
+#define DDSD_DEPTH     0x00800000\r
+\r
+/*     DirectDraw Pixel Format */\r
+#define DDPF_ALPHAPIXELS       0x00000001\r
+#define DDPF_FOURCC    0x00000004\r
+#define DDPF_RGB       0x00000040\r
+\r
+/*     The dwCaps1 member of the DDSCAPS2 structure can be\r
+       set to one or more of the following values.     */\r
+#define DDSCAPS_COMPLEX        0x00000008\r
+#define DDSCAPS_TEXTURE        0x00001000\r
+#define DDSCAPS_MIPMAP 0x00400000\r
+\r
+/*     The dwCaps2 member of the DDSCAPS2 structure can be\r
+       set to one or more of the following values.             */\r
+#define DDSCAPS2_CUBEMAP       0x00000200\r
+#define DDSCAPS2_CUBEMAP_POSITIVEX     0x00000400\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEX     0x00000800\r
+#define DDSCAPS2_CUBEMAP_POSITIVEY     0x00001000\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEY     0x00002000\r
+#define DDSCAPS2_CUBEMAP_POSITIVEZ     0x00004000\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEZ     0x00008000\r
+#define DDSCAPS2_VOLUME        0x00200000\r
+\r
+#endif /* HEADER_IMAGE_DXT     */\r
diff --git a/lib/soil/soil/image_helper.c b/lib/soil/soil/image_helper.c
new file mode 100644 (file)
index 0000000..445f6bb
--- /dev/null
@@ -0,0 +1,435 @@
+/*\r
+    Jonathan Dummer\r
+\r
+    image helper functions\r
+\r
+    MIT license\r
+*/\r
+\r
+#include "image_helper.h"\r
+#include <stdlib.h>\r
+#include <math.h>\r
+\r
+/*     Upscaling the image uses simple bilinear interpolation  */\r
+int\r
+       up_scale_image\r
+       (\r
+               const unsigned char* const orig,\r
+               int width, int height, int channels,\r
+               unsigned char* resampled,\r
+               int resampled_width, int resampled_height\r
+       )\r
+{\r
+       float dx, dy;\r
+       int x, y, c;\r
+\r
+    /* error(s) check  */\r
+    if (       (width < 1) || (height < 1) ||\r
+            (resampled_width < 2) || (resampled_height < 2) ||\r
+            (channels < 1) ||\r
+            (NULL == orig) || (NULL == resampled) )\r
+    {\r
+        /*     signify badness */\r
+        return 0;\r
+    }\r
+    /*\r
+               for each given pixel in the new map, find the exact location\r
+               from the original map which would contribute to this guy\r
+       */\r
+    dx = (width - 1.0f) / (resampled_width - 1.0f);\r
+    dy = (height - 1.0f) / (resampled_height - 1.0f);\r
+    for ( y = 0; y < resampled_height; ++y )\r
+    {\r
+       /* find the base y index and fractional offset from that        */\r
+       float sampley = y * dy;\r
+       int inty = (int)sampley;\r
+       /*      if( inty < 0 ) { inty = 0; } else       */\r
+               if( inty > height - 2 ) { inty = height - 2; }\r
+               sampley -= inty;\r
+        for ( x = 0; x < resampled_width; ++x )\r
+        {\r
+                       float samplex = x * dx;\r
+                       int intx = (int)samplex;\r
+                       int base_index;\r
+                       /* find the base x index and fractional offset from that        */\r
+                       /*      if( intx < 0 ) { intx = 0; } else       */\r
+                       if( intx > width - 2 ) { intx = width - 2; }\r
+                       samplex -= intx;\r
+                       /*      base index into the original image      */\r
+                       base_index = (inty * width + intx) * channels;\r
+            for ( c = 0; c < channels; ++c )\r
+            {\r
+               /*      do the sampling */\r
+                               float value = 0.5f;\r
+                               value += orig[base_index]\r
+                                                       *(1.0f-samplex)*(1.0f-sampley);\r
+                               value += orig[base_index+channels]\r
+                                                       *(samplex)*(1.0f-sampley);\r
+                               value += orig[base_index+width*channels]\r
+                                                       *(1.0f-samplex)*(sampley);\r
+                               value += orig[base_index+width*channels+channels]\r
+                                                       *(samplex)*(sampley);\r
+                               /*      move to the next channel        */\r
+                               ++base_index;\r
+               /*      save the new value      */\r
+               resampled[y*resampled_width*channels+x*channels+c] =\r
+                                               (unsigned char)(value);\r
+            }\r
+        }\r
+    }\r
+    /* done    */\r
+    return 1;\r
+}\r
+\r
+int\r
+       mipmap_image\r
+       (\r
+               const unsigned char* const orig,\r
+               int width, int height, int channels,\r
+               unsigned char* resampled,\r
+               int block_size_x, int block_size_y\r
+       )\r
+{\r
+       int mip_width, mip_height;\r
+       int i, j, c;\r
+\r
+       /*      error check     */\r
+       if( (width < 1) || (height < 1) ||\r
+               (channels < 1) || (orig == NULL) ||\r
+               (resampled == NULL) ||\r
+               (block_size_x < 1) || (block_size_y < 1) )\r
+       {\r
+               /*      nothing to do   */\r
+               return 0;\r
+       }\r
+       mip_width = width / block_size_x;\r
+       mip_height = height / block_size_y;\r
+       if( mip_width < 1 )\r
+       {\r
+               mip_width = 1;\r
+       }\r
+       if( mip_height < 1 )\r
+       {\r
+               mip_height = 1;\r
+       }\r
+       for( j = 0; j < mip_height; ++j )\r
+       {\r
+               for( i = 0; i < mip_width; ++i )\r
+               {\r
+                       for( c = 0; c < channels; ++c )\r
+                       {\r
+                               const int index = (j*block_size_y)*width*channels + (i*block_size_x)*channels + c;\r
+                               int sum_value;\r
+                               int u,v;\r
+                               int u_block = block_size_x;\r
+                               int v_block = block_size_y;\r
+                               int block_area;\r
+                               /*      do a bit of checking so we don't over-run the boundaries\r
+                                       (necessary for non-square textures!)    */\r
+                               if( block_size_x * (i+1) > width )\r
+                               {\r
+                                       u_block = width - i*block_size_y;\r
+                               }\r
+                               if( block_size_y * (j+1) > height )\r
+                               {\r
+                                       v_block = height - j*block_size_y;\r
+                               }\r
+                               block_area = u_block*v_block;\r
+                               /*      for this pixel, see what the average\r
+                                       of all the values in the block are.\r
+                                       note: start the sum at the rounding value, not at 0     */\r
+                               sum_value = block_area >> 1;\r
+                               for( v = 0; v < v_block; ++v )\r
+                               for( u = 0; u < u_block; ++u )\r
+                               {\r
+                                       sum_value += orig[index + v*width*channels + u*channels];\r
+                               }\r
+                               resampled[j*mip_width*channels + i*channels + c] = sum_value / block_area;\r
+                       }\r
+               }\r
+       }\r
+       return 1;\r
+}\r
+\r
+int\r
+       scale_image_RGB_to_NTSC_safe\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       )\r
+{\r
+       const float scale_lo = 16.0f - 0.499f;\r
+       const float scale_hi = 235.0f + 0.499f;\r
+       int i, j;\r
+       int nc = channels;\r
+       unsigned char scale_LUT[256];\r
+       /*      error check     */\r
+       if( (width < 1) || (height < 1) ||\r
+               (channels < 1) || (orig == NULL) )\r
+       {\r
+               /*      nothing to do   */\r
+               return 0;\r
+       }\r
+       /*      set up the scaling Look Up Table        */\r
+       for( i = 0; i < 256; ++i )\r
+       {\r
+               scale_LUT[i] = (unsigned char)((scale_hi - scale_lo) * i / 255.0f + scale_lo);\r
+       }\r
+       /*      for channels = 2 or 4, ignore the alpha component       */\r
+       nc -= 1 - (channels & 1);\r
+       /*      OK, go through the image and scale any non-alpha components     */\r
+       for( i = 0; i < width*height*channels; i += channels )\r
+       {\r
+               for( j = 0; j < nc; ++j )\r
+               {\r
+                       orig[i+j] = scale_LUT[orig[i+j]];\r
+               }\r
+       }\r
+       return 1;\r
+}\r
+\r
+unsigned char clamp_byte( int x ) { return ( (x) < 0 ? (0) : ( (x) > 255 ? 255 : (x) ) ); }\r
+\r
+/*\r
+       This function takes the RGB components of the image\r
+       and converts them into YCoCg.  3 components will be\r
+       re-ordered to CoYCg (for optimum DXT1 compression),\r
+       while 4 components will be ordered CoCgAY (for DXT5\r
+       compression).\r
+*/\r
+int\r
+       convert_RGB_to_YCoCg\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       )\r
+{\r
+       int i;\r
+       /*      error check     */\r
+       if( (width < 1) || (height < 1) ||\r
+               (channels < 3) || (channels > 4) ||\r
+               (orig == NULL) )\r
+       {\r
+               /*      nothing to do   */\r
+               return -1;\r
+       }\r
+       /*      do the conversion       */\r
+       if( channels == 3 )\r
+       {\r
+               for( i = 0; i < width*height*3; i += 3 )\r
+               {\r
+                       int r = orig[i+0];\r
+                       int g = (orig[i+1] + 1) >> 1;\r
+                       int b = orig[i+2];\r
+                       int tmp = (2 + r + b) >> 2;\r
+                       /*      Co      */\r
+                       orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );\r
+                       /*      Y       */\r
+                       orig[i+1] = clamp_byte( g + tmp );\r
+                       /*      Cg      */\r
+                       orig[i+2] = clamp_byte( 128 + g - tmp );\r
+               }\r
+       } else\r
+       {\r
+               for( i = 0; i < width*height*4; i += 4 )\r
+               {\r
+                       int r = orig[i+0];\r
+                       int g = (orig[i+1] + 1) >> 1;\r
+                       int b = orig[i+2];\r
+                       unsigned char a = orig[i+3];\r
+                       int tmp = (2 + r + b) >> 2;\r
+                       /*      Co      */\r
+                       orig[i+0] = clamp_byte( 128 + ((r - b + 1) >> 1) );\r
+                       /*      Cg      */\r
+                       orig[i+1] = clamp_byte( 128 + g - tmp );\r
+                       /*      Alpha   */\r
+                       orig[i+2] = a;\r
+                       /*      Y       */\r
+                       orig[i+3] = clamp_byte( g + tmp );\r
+               }\r
+       }\r
+       /*      done    */\r
+       return 0;\r
+}\r
+\r
+/*\r
+       This function takes the YCoCg components of the image\r
+       and converts them into RGB.  See above.\r
+*/\r
+int\r
+       convert_YCoCg_to_RGB\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       )\r
+{\r
+       int i;\r
+       /*      error check     */\r
+       if( (width < 1) || (height < 1) ||\r
+               (channels < 3) || (channels > 4) ||\r
+               (orig == NULL) )\r
+       {\r
+               /*      nothing to do   */\r
+               return -1;\r
+       }\r
+       /*      do the conversion       */\r
+       if( channels == 3 )\r
+       {\r
+               for( i = 0; i < width*height*3; i += 3 )\r
+               {\r
+                       int co = orig[i+0] - 128;\r
+                       int y  = orig[i+1];\r
+                       int cg = orig[i+2] - 128;\r
+                       /*      R       */\r
+                       orig[i+0] = clamp_byte( y + co - cg );\r
+                       /*      G       */\r
+                       orig[i+1] = clamp_byte( y + cg );\r
+                       /*      B       */\r
+                       orig[i+2] = clamp_byte( y - co - cg );\r
+               }\r
+       } else\r
+       {\r
+               for( i = 0; i < width*height*4; i += 4 )\r
+               {\r
+                       int co = orig[i+0] - 128;\r
+                       int cg = orig[i+1] - 128;\r
+                       unsigned char a  = orig[i+2];\r
+                       int y  = orig[i+3];\r
+                       /*      R       */\r
+                       orig[i+0] = clamp_byte( y + co - cg );\r
+                       /*      G       */\r
+                       orig[i+1] = clamp_byte( y + cg );\r
+                       /*      B       */\r
+                       orig[i+2] = clamp_byte( y - co - cg );\r
+                       /*      A       */\r
+                       orig[i+3] = a;\r
+               }\r
+       }\r
+       /*      done    */\r
+       return 0;\r
+}\r
+\r
+float\r
+find_max_RGBE\r
+(\r
+       unsigned char *image,\r
+    int width, int height\r
+)\r
+{\r
+       float max_val = 0.0f;\r
+       unsigned char *img = image;\r
+       int i, j;\r
+       for( i = width * height; i > 0; --i )\r
+       {\r
+               /* float scale = powf( 2.0f, img[3] - 128.0f ) / 255.0f; */\r
+               float scale = ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );\r
+               for( j = 0; j < 3; ++j )\r
+               {\r
+                       if( img[j] * scale > max_val )\r
+                       {\r
+                               max_val = img[j] * scale;\r
+                       }\r
+               }\r
+               /* next pixel */\r
+               img += 4;\r
+       }\r
+       return max_val;\r
+}\r
+\r
+int\r
+RGBE_to_RGBdivA\r
+(\r
+    unsigned char *image,\r
+    int width, int height,\r
+    int rescale_to_max\r
+)\r
+{\r
+       /* local variables */\r
+       int i, iv;\r
+       unsigned char *img = image;\r
+       float scale = 1.0f;\r
+       /* error check */\r
+       if( (!image) || (width < 1) || (height < 1) )\r
+       {\r
+               return 0;\r
+       }\r
+       /* convert (note: no negative numbers, but 0.0 is possible) */\r
+       if( rescale_to_max )\r
+       {\r
+               scale = 255.0f / find_max_RGBE( image, width, height );\r
+       }\r
+       for( i = width * height; i > 0; --i )\r
+       {\r
+               /* decode this pixel, and find the max */\r
+               float r,g,b,e, m;\r
+               /* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */\r
+               e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );\r
+               r = e * img[0];\r
+               g = e * img[1];\r
+               b = e * img[2];\r
+               m = (r > g) ? r : g;\r
+               m = (b > m) ? b : m;\r
+               /* and encode it into RGBdivA */\r
+               iv = (m != 0.0f) ? (int)(255.0f / m) : 1.0f;\r
+               iv = (iv < 1) ? 1 : iv;\r
+               img[3] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * r + 0.5f);\r
+               img[0] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * g + 0.5f);\r
+               img[1] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * b + 0.5f);\r
+               img[2] = (iv > 255) ? 255 : iv;\r
+               /* and on to the next pixel */\r
+               img += 4;\r
+       }\r
+       return 1;\r
+}\r
+\r
+int\r
+RGBE_to_RGBdivA2\r
+(\r
+    unsigned char *image,\r
+    int width, int height,\r
+    int rescale_to_max\r
+)\r
+{\r
+       /* local variables */\r
+       int i, iv;\r
+       unsigned char *img = image;\r
+       float scale = 1.0f;\r
+       /* error check */\r
+       if( (!image) || (width < 1) || (height < 1) )\r
+       {\r
+               return 0;\r
+       }\r
+       /* convert (note: no negative numbers, but 0.0 is possible) */\r
+       if( rescale_to_max )\r
+       {\r
+               scale = 255.0f * 255.0f / find_max_RGBE( image, width, height );\r
+       }\r
+       for( i = width * height; i > 0; --i )\r
+       {\r
+               /* decode this pixel, and find the max */\r
+               float r,g,b,e, m;\r
+               /* e = scale * powf( 2.0f, img[3] - 128.0f ) / 255.0f; */\r
+               e = scale * ldexp( 1.0f / 255.0f, (int)(img[3]) - 128 );\r
+               r = e * img[0];\r
+               g = e * img[1];\r
+               b = e * img[2];\r
+               m = (r > g) ? r : g;\r
+               m = (b > m) ? b : m;\r
+               /* and encode it into RGBdivA */\r
+               iv = (m != 0.0f) ? (int)sqrtf( 255.0f * 255.0f / m ) : 1.0f;\r
+               iv = (iv < 1) ? 1 : iv;\r
+               img[3] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * img[3] * r / 255.0f + 0.5f);\r
+               img[0] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * img[3] * g / 255.0f + 0.5f);\r
+               img[1] = (iv > 255) ? 255 : iv;\r
+               iv = (int)(img[3] * img[3] * b / 255.0f + 0.5f);\r
+               img[2] = (iv > 255) ? 255 : iv;\r
+               /* and on to the next pixel */\r
+               img += 4;\r
+       }\r
+       return 1;\r
+}\r
diff --git a/lib/soil/soil/image_helper.h b/lib/soil/soil/image_helper.h
new file mode 100644 (file)
index 0000000..abb257c
--- /dev/null
@@ -0,0 +1,115 @@
+/*\r
+    Jonathan Dummer\r
+\r
+    Image helper functions\r
+\r
+    MIT license\r
+*/\r
+\r
+#ifndef HEADER_IMAGE_HELPER\r
+#define HEADER_IMAGE_HELPER\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+/**\r
+       This function upscales an image.\r
+       Not to be used to create MIPmaps,\r
+       but to make it square,\r
+       or to make it a power-of-two sized.\r
+**/\r
+int\r
+       up_scale_image\r
+       (\r
+               const unsigned char* const orig,\r
+               int width, int height, int channels,\r
+               unsigned char* resampled,\r
+               int resampled_width, int resampled_height\r
+       );\r
+\r
+/**\r
+       This function downscales an image.\r
+       Used for creating MIPmaps,\r
+       the incoming image should be a\r
+       power-of-two sized.\r
+**/\r
+int\r
+       mipmap_image\r
+       (\r
+               const unsigned char* const orig,\r
+               int width, int height, int channels,\r
+               unsigned char* resampled,\r
+               int block_size_x, int block_size_y\r
+       );\r
+\r
+/**\r
+       This function takes the RGB components of the image\r
+       and scales each channel from [0,255] to [16,235].\r
+       This makes the colors "Safe" for display on NTSC\r
+       displays.  Note that this is _NOT_ a good idea for\r
+       loading images like normal- or height-maps!\r
+**/\r
+int\r
+       scale_image_RGB_to_NTSC_safe\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       );\r
+\r
+/**\r
+       This function takes the RGB components of the image\r
+       and converts them into YCoCg.  3 components will be\r
+       re-ordered to CoYCg (for optimum DXT1 compression),\r
+       while 4 components will be ordered CoCgAY (for DXT5\r
+       compression).\r
+**/\r
+int\r
+       convert_RGB_to_YCoCg\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       );\r
+\r
+/**\r
+       This function takes the YCoCg components of the image\r
+       and converts them into RGB.  See above.\r
+**/\r
+int\r
+       convert_YCoCg_to_RGB\r
+       (\r
+               unsigned char* orig,\r
+               int width, int height, int channels\r
+       );\r
+\r
+/**\r
+       Converts an HDR image from an array\r
+       of unsigned chars (RGBE) to RGBdivA\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+int\r
+       RGBE_to_RGBdivA\r
+       (\r
+               unsigned char *image,\r
+               int width, int height,\r
+               int rescale_to_max\r
+       );\r
+\r
+/**\r
+       Converts an HDR image from an array\r
+       of unsigned chars (RGBE) to RGBdivA2\r
+       \return 0 if failed, otherwise returns 1\r
+**/\r
+int\r
+       RGBE_to_RGBdivA2\r
+       (\r
+               unsigned char *image,\r
+               int width, int height,\r
+               int rescale_to_max\r
+       );\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif /* HEADER_IMAGE_HELPER  */\r
diff --git a/lib/soil/soil/original/stb_image-1.09.c b/lib/soil/soil/original/stb_image-1.09.c
new file mode 100644 (file)
index 0000000..a30c7da
--- /dev/null
@@ -0,0 +1,3632 @@
+/* stbi-1.09 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r
+                      when you control the images you're loading\r
+\r
+   QUICK NOTES:\r
+      Primarily of interest to game developers and other people who can\r
+          avoid problematic images and only need the trivial interface\r
+\r
+      JPEG baseline (no JPEG progressive, no oddball channel decimations)\r
+      PNG non-interlaced\r
+      BMP non-1bpp, non-RLE\r
+      TGA (not sure what subset, if a subset)\r
+      PSD (composited view only, no extra channels)\r
+      HDR (radiance rgbE format)\r
+      writes BMP,TGA (define STBI_NO_WRITE to remove code)\r
+      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)\r
+        \r
+   TODO:\r
+      stbi_info_*\r
+  \r
+   history:\r
+      1.09   Fix format-conversion for PSD code (bad global variables!)\r
+      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz\r
+      1.07   attempt to fix C++ warning/errors again\r
+      1.06   attempt to fix C++ warning/errors again\r
+      1.05   fix TGA loading to return correct *comp and use good luminance calc\r
+      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free\r
+      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR\r
+      1.02   support for (subset of) HDR files, float interface for preferred access to them\r
+      1.01   fix bug: possible bug in handling right-side up bmps... not sure\r
+             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all\r
+      1.00   interface to zlib that skips zlib header\r
+      0.99   correct handling of alpha in palette\r
+      0.98   TGA loader by lonesock; dynamically add loaders (untested)\r
+      0.97   jpeg errors on too large a file; also catch another malloc failure\r
+      0.96   fix detection of invalid v value - particleman@mollyrocket forum\r
+      0.95   during header scan, seek to markers in case of padding\r
+      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same\r
+      0.93   handle jpegtran output; verbose errors\r
+      0.92   read 4,8,16,24,32-bit BMP files of several formats\r
+      0.91   output 24-bit Windows 3.0 BMP files\r
+      0.90   fix a few more warnings; bump version number to approach 1.0\r
+      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd\r
+      0.60   fix compiling as c++\r
+      0.59   fix warnings: merge Dave Moore's -Wall fixes\r
+      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian\r
+      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less\r
+                      than 16 available\r
+      0.56   fix bug: zlib uncompressed mode len vs. nlen\r
+      0.55   fix bug: restart_interval not initialized to 0\r
+      0.54   allow NULL for 'int *comp'\r
+      0.53   fix bug in png 3->4; speedup png decoding\r
+      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments\r
+      0.51   obey req_comp requests, 1-component jpegs return as 1-component,\r
+             on 'test' only check type, not whether we support this variant\r
+*/\r
+\r
+\r
+////   begin header file  ////////////////////////////////////////////////////\r
+//\r
+// Limitations:\r
+//    - no progressive/interlaced support (jpeg, png)\r
+//    - 8-bit samples only (jpeg, png)\r
+//    - not threadsafe\r
+//    - channel subsampling of at most 2 in each dimension (jpeg)\r
+//    - no delayed line count (jpeg) -- IJG doesn't support either\r
+//\r
+// Basic usage (see HDR discussion below):\r
+//    int x,y,n;\r
+//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);\r
+//    // ... process data if not NULL ... \r
+//    // ... x = width, y = height, n = # 8-bit components per pixel ...\r
+//    // ... replace '0' with '1'..'4' to force that many components per pixel\r
+//    stbi_image_free(data)\r
+//\r
+// Standard parameters:\r
+//    int *x       -- outputs image width in pixels\r
+//    int *y       -- outputs image height in pixels\r
+//    int *comp    -- outputs # of image components in image file\r
+//    int req_comp -- if non-zero, # of image components requested in result\r
+//\r
+// The return value from an image loader is an 'unsigned char *' which points\r
+// to the pixel data. The pixel data consists of *y scanlines of *x pixels,\r
+// with each pixel consisting of N interleaved 8-bit components; the first\r
+// pixel pointed to is top-left-most in the image. There is no padding between\r
+// image scanlines or between pixels, regardless of format. The number of\r
+// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.\r
+// If req_comp is non-zero, *comp has the number of components that _would_\r
+// have been output otherwise. E.g. if you set req_comp to 4, you will always\r
+// get RGBA output, but you can check *comp to easily see if it's opaque.\r
+//\r
+// An output image with N components has the following components interleaved\r
+// in this order in each pixel:\r
+//\r
+//     N=#comp     components\r
+//       1           grey\r
+//       2           grey, alpha\r
+//       3           red, green, blue\r
+//       4           red, green, blue, alpha\r
+//\r
+// If image loading fails for any reason, the return value will be NULL,\r
+// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()\r
+// can be queried for an extremely brief, end-user unfriendly explanation\r
+// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid\r
+// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly\r
+// more user-friendly ones.\r
+//\r
+// Paletted PNG and BMP images are automatically depalettized.\r
+//\r
+//\r
+// ===========================================================================\r
+//\r
+// HDR image support   (disable by defining STBI_NO_HDR)\r
+//\r
+// stb_image now supports loading HDR images in general, and currently\r
+// the Radiance .HDR file format, although the support is provided\r
+// generically. You can still load any file through the existing interface;\r
+// if you attempt to load an HDR file, it will be automatically remapped to\r
+// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;\r
+// both of these constants can be reconfigured through this interface:\r
+//\r
+//     stbi_hdr_to_ldr_gamma(2.2f);\r
+//     stbi_hdr_to_ldr_scale(1.0f);\r
+//\r
+// (note, do not use _inverse_ constants; stbi_image will invert them\r
+// appropriately).\r
+//\r
+// Additionally, there is a new, parallel interface for loading files as\r
+// (linear) floats to preserve the full dynamic range:\r
+//\r
+//    float *data = stbi_loadf(filename, &x, &y, &n, 0);\r
+// \r
+// If you load LDR images through this interface, those images will\r
+// be promoted to floating point values, run through the inverse of\r
+// constants corresponding to the above:\r
+//\r
+//     stbi_ldr_to_hdr_scale(1.0f);\r
+//     stbi_ldr_to_hdr_gamma(2.2f);\r
+//\r
+// Finally, given a filename (or an open file or memory block--see header\r
+// file for details) containing image data, you can query for the "most\r
+// appropriate" interface to use (that is, whether the image is HDR or\r
+// not), using:\r
+//\r
+//     stbi_is_hdr(char *filename);\r
+\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+\r
+#ifndef STBI_NO_HDR\r
+#include <math.h>  // ldexp\r
+#include <string.h> // strcmp\r
+#endif\r
+\r
+enum\r
+{\r
+   STBI_default = 0, // only used for req_comp\r
+\r
+   STBI_grey       = 1,\r
+   STBI_grey_alpha = 2,\r
+   STBI_rgb        = 3,\r
+   STBI_rgb_alpha  = 4,\r
+};\r
+\r
+typedef unsigned char stbi_uc;\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+// WRITING API\r
+\r
+#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)\r
+// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)\r
+// (you must include the appropriate extension in the filename).\r
+// returns TRUE on success, FALSE if couldn't open file, error writing file\r
+extern int      stbi_write_bmp       (char *filename,           int x, int y, int comp, void *data);\r
+extern int      stbi_write_tga       (char *filename,           int x, int y, int comp, void *data);\r
+#endif\r
+\r
+// PRIMARY API - works on images of any type\r
+\r
+// load image by filename, open file, or memory buffer\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_load            (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern stbi_uc *stbi_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+// for stbi_load_from_file, file pointer is left pointing immediately after image\r
+\r
+#ifndef STBI_NO_HDR\r
+#ifndef STBI_NO_STDIO\r
+extern float *stbi_loadf            (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern float *stbi_loadf_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+extern float *stbi_loadf_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+\r
+extern void   stbi_hdr_to_ldr_gamma(float gamma);\r
+extern void   stbi_hdr_to_ldr_scale(float scale);\r
+\r
+extern void   stbi_ldr_to_hdr_gamma(float gamma);\r
+extern void   stbi_ldr_to_hdr_scale(float scale);\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+// get a VERY brief reason for failure\r
+extern char    *stbi_failure_reason  (void);\r
+\r
+// free the loaded image -- this is just free()\r
+extern void     stbi_image_free      (void *retval_from_stbi_load);\r
+\r
+// get image dimensions & components without fully decoding\r
+extern int      stbi_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr_from_memory(stbi_uc *buffer, int len);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr          (char *filename);\r
+extern int      stbi_is_hdr_from_file(FILE *f);\r
+#endif\r
+\r
+// ZLIB client - used by PNG, available for other purposes\r
+\r
+extern char *stbi_zlib_decode_malloc_guesssize(int initial_size, int *outlen);\r
+extern char *stbi_zlib_decode_malloc(char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, char *ibuffer, int ilen);\r
+\r
+extern char *stbi_zlib_decode_noheader_malloc(char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, char *ibuffer, int ilen);\r
+\r
+\r
+// TYPE-SPECIFIC ACCESS\r
+\r
+// is it a jpeg?\r
+extern int      stbi_jpeg_test_memory     (stbi_uc *buffer, int len);\r
+extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_jpeg_load            (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_test_file       (FILE *f);\r
+extern stbi_uc *stbi_jpeg_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+\r
+extern int      stbi_jpeg_info            (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+extern int      stbi_jpeg_dc_only; // only decode DC component\r
+\r
+// is it a png?\r
+extern int      stbi_png_test_memory      (stbi_uc *buffer, int len);\r
+extern stbi_uc *stbi_png_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_png_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info             (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_png_test_file        (FILE *f);\r
+extern stbi_uc *stbi_png_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+// is it a bmp?\r
+extern int      stbi_bmp_test_memory      (stbi_uc *buffer, int len);\r
+\r
+extern stbi_uc *stbi_bmp_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_bmp_test_file        (FILE *f);\r
+extern stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a tga?\r
+extern int      stbi_tga_test_memory      (stbi_uc *buffer, int len);\r
+\r
+extern stbi_uc *stbi_tga_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_tga_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_tga_test_file        (FILE *f);\r
+extern stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a psd?\r
+extern int      stbi_psd_test_memory      (stbi_uc *buffer, int len);\r
+\r
+extern stbi_uc *stbi_psd_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_psd_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_psd_test_file        (FILE *f);\r
+extern stbi_uc *stbi_psd_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it an hdr?\r
+extern int      stbi_hdr_test_memory      (stbi_uc *buffer, int len);\r
+\r
+extern float *  stbi_hdr_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern float *  stbi_hdr_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_hdr_test_file        (FILE *f);\r
+extern float *  stbi_hdr_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// define new loaders\r
+typedef struct\r
+{\r
+   int       (*test_memory)(stbi_uc *buffer, int len);\r
+   stbi_uc * (*load_from_memory)(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+   #ifndef STBI_NO_STDIO\r
+   int       (*test_file)(FILE *f);\r
+   stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);\r
+   #endif\r
+} stbi_loader;\r
+\r
+// register a loader by filling out the above structure (you must defined ALL functions)\r
+// returns 1 if added or already added, 0 if not added (too many loaders)\r
+extern int stbi_register_loader(stbi_loader *loader);\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+//\r
+//\r
+////   end header file   /////////////////////////////////////////////////////\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+#include <stdlib.h>\r
+#include <memory.h>\r
+#include <assert.h>\r
+#include <stdarg.h>\r
+\r
+#ifndef _MSC_VER\r
+#define __forceinline\r
+#endif\r
+\r
+// implementation:\r
+typedef unsigned char uint8;\r
+typedef unsigned short uint16;\r
+typedef   signed short  int16;\r
+typedef unsigned int   uint32;\r
+typedef   signed int    int32;\r
+typedef unsigned int   uint;\r
+\r
+// should produce compiler error if size is wrong\r
+typedef unsigned char validate_uint32[sizeof(uint32)==4];\r
+\r
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)\r
+#define STBI_NO_WRITE\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Generic API that works on all image types\r
+//\r
+\r
+static char *failure_reason;\r
+\r
+char *stbi_failure_reason(void)\r
+{\r
+   return failure_reason;\r
+}\r
+\r
+static int e(char *str)\r
+{\r
+   failure_reason = str;\r
+   return 0;\r
+}\r
+\r
+#ifdef STBI_NO_FAILURE_STRINGS\r
+   #define e(x,y)  0\r
+#elif defined(STBI_FAILURE_USERMSG)\r
+   #define e(x,y)  e(y)\r
+#else\r
+   #define e(x,y)  e(x)\r
+#endif\r
+\r
+#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))\r
+#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))\r
+\r
+void stbi_image_free(void *retval_from_stbi_load)\r
+{\r
+   free(retval_from_stbi_load);\r
+}\r
+\r
+#define MAX_LOADERS  32\r
+stbi_loader *loaders[MAX_LOADERS];\r
+static int max_loaders = 0;\r
+\r
+int stbi_register_loader(stbi_loader *loader)\r
+{\r
+   int i;\r
+   for (i=0; i < MAX_LOADERS; ++i) {\r
+      // already present?\r
+      if (loaders[i] == loader)\r
+         return 1;\r
+      // end of the list?\r
+      if (loaders[i] == NULL) {\r
+         loaders[i] = loader;\r
+         max_loaders = i+1;\r
+         return 1;\r
+      }\r
+   }\r
+   // no room for it\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);\r
+#endif\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_load(char *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   unsigned char *result;\r
+   if (!f) return epuc("can't fopen", "Unable to open file");\r
+   result = stbi_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_file(f))\r
+      return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_png_test_file(f))\r
+      return stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_file(f))\r
+      return stbi_bmp_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_psd_test_file(f))\r
+      return stbi_psd_load_from_file(f,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f)) {\r
+      float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_file(f))\r
+         return loaders[i]->load_from_file(f,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_file(f))\r
+      return stbi_tga_load_from_file(f,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_memory(buffer,len))\r
+      return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_png_test_memory(buffer,len))\r
+      return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_memory(buffer,len))\r
+      return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_psd_test_memory(buffer,len))\r
+      return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len)) {\r
+      float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_memory(buffer,len))\r
+         return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_memory(buffer,len))\r
+      return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_loadf(char *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   float *result;\r
+   if (!f) return epf("can't fopen", "Unable to open file");\r
+   result = stbi_loadf_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f))\r
+      return stbi_hdr_load_from_file(f,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_file(f, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+float *stbi_loadf_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len))\r
+      return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is\r
+// defined, for API simplicity; if STBI_NO_HDR is defined, it always\r
+// reports false!\r
+\r
+extern int      stbi_is_hdr_from_memory(stbi_uc *buffer, int len)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_memory(buffer, len);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_is_hdr          (char *filename)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   int result=0;\r
+   if (f) {\r
+      result = stbi_is_hdr_from_file(f);\r
+      fclose(f);\r
+   }\r
+   return result;\r
+}\r
+\r
+extern int      stbi_is_hdr_from_file(FILE *f)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_file(f);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#endif\r
+\r
+// @TODO: get image dimensions & components without fully decoding\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_HDR\r
+static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;\r
+static float l2h_gamma=2.2f, l2h_scale=1.0f;\r
+\r
+void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }\r
+void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }\r
+\r
+void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }\r
+void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }\r
+#endif\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Common code used by all image loaders\r
+//\r
+\r
+// image width, height, # components\r
+static uint32 img_x, img_y;\r
+static int img_n, img_out_n;\r
+\r
+enum\r
+{\r
+   SCAN_load=0,\r
+   SCAN_type,\r
+   SCAN_header,\r
+};\r
+\r
+// An API for reading either from memory or file.\r
+#ifndef STBI_NO_STDIO\r
+static FILE  *img_file;\r
+#endif\r
+static uint8 *img_buffer, *img_buffer_end;\r
+\r
+#ifndef STBI_NO_STDIO\r
+static void start_file(FILE *f)\r
+{\r
+   img_file = f;\r
+}\r
+#endif\r
+\r
+static void start_mem(uint8 *buffer, int len)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   img_file = NULL;\r
+#endif\r
+   img_buffer = buffer;\r
+   img_buffer_end = buffer+len;\r
+}\r
+\r
+static int get8(void)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (img_file) {\r
+      int c = fgetc(img_file);\r
+      return c == EOF ? 0 : c;\r
+   }\r
+#endif\r
+   if (img_buffer < img_buffer_end)\r
+      return *img_buffer++;\r
+   return 0;\r
+}\r
+\r
+static int at_eof(void)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (img_file)\r
+      return feof(img_file);\r
+#endif\r
+   return img_buffer >= img_buffer_end;   \r
+}\r
+\r
+static uint8 get8u(void)\r
+{\r
+   return (uint8) get8();\r
+}\r
+\r
+static void skip(int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (img_file)\r
+      fseek(img_file, n, SEEK_CUR);\r
+   else\r
+#endif\r
+      img_buffer += n;\r
+}\r
+\r
+static int get16(void)\r
+{\r
+   int z = get8();\r
+   return (z << 8) + get8();\r
+}\r
+\r
+static uint32 get32(void)\r
+{\r
+   uint32 z = get16();\r
+   return (z << 16) + get16();\r
+}\r
+\r
+static int get16le(void)\r
+{\r
+   int z = get8();\r
+   return z + (get8() << 8);\r
+}\r
+\r
+static uint32 get32le(void)\r
+{\r
+   uint32 z = get16le();\r
+   return z + (get16le() << 16);\r
+}\r
+\r
+static void getn(stbi_uc *buffer, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (img_file) {\r
+      fread(buffer, 1, n, img_file);\r
+      return;\r
+   }\r
+#endif\r
+   memcpy(buffer, img_buffer, n);\r
+   img_buffer += n;\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  generic converter from built-in img_n to req_comp\r
+//    individual types do this automatically as much as possible (e.g. jpeg\r
+//    does all cases internally since it needs to colorspace convert anyway,\r
+//    and it never has alpha, so very few cases ). png can automatically\r
+//    interleave an alpha=255 channel, but falls back to this for other cases\r
+//\r
+//  assume data buffer is malloced, so malloc a new one and free that one\r
+//  only failure mode is malloc failing\r
+\r
+static uint8 compute_y(int r, int g, int b)\r
+{\r
+   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);\r
+}\r
+\r
+static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp)\r
+{\r
+   uint i,j;\r
+   unsigned char *good;\r
+\r
+   if (req_comp == img_n) return data;\r
+   assert(req_comp >= 1 && req_comp <= 4);\r
+\r
+   good = (unsigned char *) malloc(req_comp * img_x * img_y);\r
+   if (good == NULL) {\r
+      free(data);\r
+      return epuc("outofmem", "Out of memory");\r
+   }\r
+\r
+   for (j=0; j < img_y; ++j) {\r
+      unsigned char *src  = data + j * img_x * img_n   ;\r
+      unsigned char *dest = good + j * img_x * req_comp;\r
+\r
+      #define COMBO(a,b)  ((a)*8+(b))\r
+      #define CASE(a,b)   case COMBO(a,b): for(i=0; i < img_x; ++i, src += a, dest += b)\r
+\r
+      // convert source image with img_n components to one with req_comp components;\r
+      // avoid switch per pixel, so use switch per scanline and massive macros\r
+      switch(COMBO(img_n, req_comp)) {\r
+         CASE(1,2) dest[0]=src[0], dest[1]=255; break;\r
+         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;\r
+         CASE(2,1) dest[0]=src[0]; break;\r
+         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;\r
+         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;\r
+         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;\r
+         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;\r
+         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;\r
+         default: assert(0);\r
+      }\r
+      #undef CASE\r
+   }\r
+\r
+   free(data);\r
+   img_out_n = req_comp;\r
+   return good;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   float *output = (float *) malloc(x * y * comp * sizeof(float));\r
+   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;\r
+      }\r
+      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+\r
+#define float2int(x)   ((int) (x))\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);\r
+   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+      if (k < comp) {\r
+         float z = data[i*comp+k] * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)\r
+//\r
+//    simple implementation\r
+//      - channel subsampling of at most 2 in each dimension\r
+//      - doesn't support delayed output of y-dimension\r
+//      - simple interface (only one output format: 8-bit interleaved RGB)\r
+//      - doesn't try to recover corrupt jpegs\r
+//      - doesn't allow partial loading, loading multiple at once\r
+//      - still fast on x86 (copying globals into locals doesn't help x86)\r
+//      - allocates lots of intermediate memory (full size of all components)\r
+//        - non-interleaved case requires this anyway\r
+//        - allows good upsampling (see next)\r
+//    high-quality\r
+//      - upsampled channels are bilinearly interpolated, even across blocks\r
+//      - quality integer IDCT derived from IJG's 'slow'\r
+//    performance\r
+//      - fast huffman; reasonable integer IDCT\r
+//      - uses a lot of intermediate memory, could cache poorly\r
+//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4\r
+//          stb_jpeg:   1.34 seconds (MSVC6, default release build)\r
+//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)\r
+//          IJL11.dll:  1.08 seconds (compiled by intel)\r
+//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)\r
+//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)\r
+\r
+int stbi_jpeg_dc_only;\r
+\r
+// huffman decoding acceleration\r
+#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache\r
+\r
+typedef struct\r
+{\r
+   uint8  fast[1 << FAST_BITS];\r
+   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win\r
+   uint16 code[256];\r
+   uint8  values[256];\r
+   uint8  size[257];\r
+   unsigned int maxcode[18];\r
+   int    delta[17];   // old 'firstsymbol' - old 'firstcode'\r
+} huffman;\r
+\r
+static huffman huff_dc[4];  // baseline is 2 tables, extended is 4\r
+static huffman huff_ac[4];\r
+static uint8 dequant[4][64];\r
+\r
+static int build_huffman(huffman *h, int *count)\r
+{\r
+   int i,j,k=0,code;\r
+   // build size list for each symbol (from JPEG spec)\r
+   for (i=0; i < 16; ++i)\r
+      for (j=0; j < count[i]; ++j)\r
+         h->size[k++] = (uint8) (i+1);\r
+   h->size[k] = 0;\r
+\r
+   // compute actual symbols (from jpeg spec)\r
+   code = 0;\r
+   k = 0;\r
+   for(j=1; j <= 16; ++j) {\r
+      // compute delta to add to code to compute symbol id\r
+      h->delta[j] = k - code;\r
+      if (h->size[k] == j) {\r
+         while (h->size[k] == j)\r
+            h->code[k++] = (uint16) (code++);\r
+         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");\r
+      }\r
+      // compute largest code + 1 for this size, preshifted as needed later\r
+      h->maxcode[j] = code << (16-j);\r
+      code <<= 1;\r
+   }\r
+   h->maxcode[j] = 0xffffffff;\r
+\r
+   // build non-spec acceleration table; 255 is flag for not-accelerated\r
+   memset(h->fast, 255, 1 << FAST_BITS);\r
+   for (i=0; i < k; ++i) {\r
+      int s = h->size[i];\r
+      if (s <= FAST_BITS) {\r
+         int c = h->code[i] << (FAST_BITS-s);\r
+         int m = 1 << (FAST_BITS-s);\r
+         for (j=0; j < m; ++j) {\r
+            h->fast[c+j] = (uint8) i;\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+// sizes for components, interleaved MCUs\r
+static int img_h_max, img_v_max;\r
+static int img_mcu_x, img_mcu_y;\r
+static int img_mcu_w, img_mcu_h;\r
+\r
+// definition of jpeg image component\r
+static struct\r
+{\r
+   int id;\r
+   int h,v;\r
+   int tq;\r
+   int hd,ha;\r
+   int dc_pred;\r
+\r
+   int x,y,w2,h2;\r
+   uint8 *data;\r
+} img_comp[4];\r
+\r
+static unsigned long  code_buffer; // jpeg entropy-coded buffer\r
+static int            code_bits;   // number of valid bits\r
+static unsigned char  marker;      // marker seen while filling entropy buffer\r
+static int            nomore;      // flag if we saw a marker so must stop\r
\r
+static void grow_buffer_unsafe(void)\r
+{\r
+   do {\r
+      int b = nomore ? 0 : get8();\r
+      if (b == 0xff) {\r
+         int c = get8();\r
+         if (c != 0) {\r
+            marker = (unsigned char) c;\r
+            nomore = 1;\r
+            return;\r
+         }\r
+      }\r
+      code_buffer = (code_buffer << 8) | b;\r
+      code_bits += 8;\r
+   } while (code_bits <= 24);\r
+}\r
+\r
+// (1 << n) - 1\r
+static unsigned long bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};\r
+\r
+// decode a jpeg huffman value from the bitstream\r
+__forceinline static int decode(huffman *h)\r
+{\r
+   unsigned int temp;\r
+   int c,k;\r
+\r
+   if (code_bits < 16) grow_buffer_unsafe();\r
+\r
+   // look at the top FAST_BITS and determine what symbol ID it is,\r
+   // if the code is <= FAST_BITS\r
+   c = (code_buffer >> (code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);\r
+   k = h->fast[c];\r
+   if (k < 255) {\r
+      if (h->size[k] > code_bits)\r
+         return -1;\r
+      code_bits -= h->size[k];\r
+      return h->values[k];\r
+   }\r
+\r
+   // naive test is to shift the code_buffer down so k bits are\r
+   // valid, then test against maxcode. To speed this up, we've\r
+   // preshifted maxcode left so that it has (16-k) 0s at the\r
+   // end; in other words, regardless of the number of bits, it\r
+   // wants to be compared against something shifted to have 16;\r
+   // that way we don't need to shift inside the loop.\r
+   if (code_bits < 16)\r
+      temp = (code_buffer << (16 - code_bits)) & 0xffff;\r
+   else\r
+      temp = (code_buffer >> (code_bits - 16)) & 0xffff;\r
+   for (k=FAST_BITS+1 ; ; ++k)\r
+      if (temp < h->maxcode[k])\r
+         break;\r
+   if (k == 17) {\r
+      // error! code not found\r
+      code_bits -= 16;\r
+      return -1;\r
+   }\r
+\r
+   if (k > code_bits)\r
+      return -1;\r
+\r
+   // convert the huffman code to the symbol id\r
+   c = ((code_buffer >> (code_bits - k)) & bmask[k]) + h->delta[k];\r
+   assert((((code_buffer) >> (code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);\r
+\r
+   // convert the id to a symbol\r
+   code_bits -= k;\r
+   return h->values[c];\r
+}\r
+\r
+// combined JPEG 'receive' and JPEG 'extend', since baseline\r
+// always extends everything it receives.\r
+__forceinline static int extend_receive(int n)\r
+{\r
+   unsigned int m = 1 << (n-1);\r
+   unsigned int k;\r
+   if (code_bits < n) grow_buffer_unsafe();\r
+   k = (code_buffer >> (code_bits - n)) & bmask[n];\r
+   code_bits -= n;\r
+   // the following test is probably a random branch that won't\r
+   // predict well. I tried to table accelerate it but failed.\r
+   // maybe it's compiling as a conditional move?\r
+   if (k < m)\r
+      return (-1 << n) + k + 1;\r
+   else\r
+      return k;\r
+}\r
+\r
+// given a value that's at position X in the zigzag stream,\r
+// where does it appear in the 8x8 matrix coded as row-major?\r
+static uint8 dezigzag[64+15] =\r
+{\r
+    0,  1,  8, 16,  9,  2,  3, 10,\r
+   17, 24, 32, 25, 18, 11,  4,  5,\r
+   12, 19, 26, 33, 40, 48, 41, 34,\r
+   27, 20, 13,  6,  7, 14, 21, 28,\r
+   35, 42, 49, 56, 57, 50, 43, 36,\r
+   29, 22, 15, 23, 30, 37, 44, 51,\r
+   58, 59, 52, 45, 38, 31, 39, 46,\r
+   53, 60, 61, 54, 47, 55, 62, 63,\r
+   // let corrupt input sample past end\r
+   63, 63, 63, 63, 63, 63, 63, 63,\r
+   63, 63, 63, 63, 63, 63, 63\r
+};\r
+\r
+// decode one 64-entry block--\r
+static int decode_block(short data[64], huffman *hdc, huffman *hac, int b)\r
+{\r
+   int diff,dc,k;\r
+   int t = decode(hdc);\r
+   if (t < 0) return e("bad huffman code","Corrupt JPEG");\r
+\r
+   // 0 all the ac values now so we can do it 32-bits at a time\r
+   memset(data,0,64*sizeof(data[0]));\r
+\r
+   diff = t ? extend_receive(t) : 0;\r
+   dc = img_comp[b].dc_pred + diff;\r
+   img_comp[b].dc_pred = dc;\r
+   data[0] = (short) dc;\r
+\r
+   // decode AC components, see JPEG spec\r
+   k = 1;\r
+   do {\r
+      int r,s;\r
+      int rs = decode(hac);\r
+      if (rs < 0) return e("bad huffman code","Corrupt JPEG");\r
+      s = rs & 15;\r
+      r = rs >> 4;\r
+      if (s == 0) {\r
+         if (rs != 0xf0) break; // end block\r
+         k += 16;\r
+      } else {\r
+         k += r;\r
+         // decode into unzigzag'd location\r
+         data[dezigzag[k++]] = (short) extend_receive(s);\r
+      }\r
+   } while (k < 64);\r
+   return 1;\r
+}\r
+\r
+// take a -128..127 value and clamp it and convert to 0..255\r
+__forceinline static uint8 clamp(int x)\r
+{\r
+   x += 128;\r
+   // trick to use a single test to catch both cases\r
+   if ((unsigned int) x > 255) {\r
+      if (x < 0) return 0;\r
+      if (x > 255) return 255;\r
+   }\r
+   return (uint8) x;\r
+}\r
+\r
+#define f2f(x)  (int) (((x) * 4096 + 0.5))\r
+#define fsh(x)  ((x) << 12)\r
+\r
+// derived from jidctint -- DCT_ISLOW\r
+#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \\r
+   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \\r
+   p2 = s2;                                    \\r
+   p3 = s6;                                    \\r
+   p1 = (p2+p3) * f2f(0.5411961f);             \\r
+   t2 = p1 + p3*f2f(-1.847759065f);            \\r
+   t3 = p1 + p2*f2f( 0.765366865f);            \\r
+   p2 = s0;                                    \\r
+   p3 = s4;                                    \\r
+   t0 = fsh(p2+p3);                            \\r
+   t1 = fsh(p2-p3);                            \\r
+   x0 = t0+t3;                                 \\r
+   x3 = t0-t3;                                 \\r
+   x1 = t1+t2;                                 \\r
+   x2 = t1-t2;                                 \\r
+   t0 = s7;                                    \\r
+   t1 = s5;                                    \\r
+   t2 = s3;                                    \\r
+   t3 = s1;                                    \\r
+   p3 = t0+t2;                                 \\r
+   p4 = t1+t3;                                 \\r
+   p1 = t0+t3;                                 \\r
+   p2 = t1+t2;                                 \\r
+   p5 = (p3+p4)*f2f( 1.175875602f);            \\r
+   t0 = t0*f2f( 0.298631336f);                 \\r
+   t1 = t1*f2f( 2.053119869f);                 \\r
+   t2 = t2*f2f( 3.072711026f);                 \\r
+   t3 = t3*f2f( 1.501321110f);                 \\r
+   p1 = p5 + p1*f2f(-0.899976223f);            \\r
+   p2 = p5 + p2*f2f(-2.562915447f);            \\r
+   p3 = p3*f2f(-1.961570560f);                 \\r
+   p4 = p4*f2f(-0.390180644f);                 \\r
+   t3 += p1+p4;                                \\r
+   t2 += p2+p3;                                \\r
+   t1 += p2+p4;                                \\r
+   t0 += p1+p3;\r
+\r
+// .344 seconds on 3*anemones.jpg\r
+static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)\r
+{\r
+   int i,val[64],*v=val;\r
+   uint8 *o,*dq = dequantize;\r
+   short *d = data;\r
+\r
+   if (stbi_jpeg_dc_only) {\r
+      // ok, I don't really know why this is right, but it seems to be:\r
+      int z = 128 + ((d[0] * dq[0]) >> 3);\r
+      for (i=0; i < 8; ++i) {\r
+         out[0] = out[1] = out[2] = out[3] = out[4] = out[5] = out[6] = out[7] = z;\r
+         out += out_stride;\r
+      }\r
+      return;\r
+   }\r
+\r
+   // columns\r
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {\r
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\r
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\r
+           && d[40]==0 && d[48]==0 && d[56]==0) {\r
+         //    no shortcut                 0     seconds\r
+         //    (1|2|3|4|5|6|7)==0          0     seconds\r
+         //    all separate               -0.047 seconds\r
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\r
+         int dcterm = d[0] * dq[0] << 2;\r
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\r
+      } else {\r
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\r
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\r
+         // constants scaled things up by 1<<12; let's bring them back\r
+         // down, but keep 2 extra bits of precision\r
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\r
+         v[ 0] = (x0+t3) >> 10;\r
+         v[56] = (x0-t3) >> 10;\r
+         v[ 8] = (x1+t2) >> 10;\r
+         v[48] = (x1-t2) >> 10;\r
+         v[16] = (x2+t1) >> 10;\r
+         v[40] = (x2-t1) >> 10;\r
+         v[24] = (x3+t0) >> 10;\r
+         v[32] = (x3-t0) >> 10;\r
+      }\r
+   }\r
+\r
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\r
+      // no fast case since the first 1D IDCT spread components out\r
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\r
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first\r
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together\r
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.\r
+      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;\r
+      o[0] = clamp((x0+t3) >> 17);\r
+      o[7] = clamp((x0-t3) >> 17);\r
+      o[1] = clamp((x1+t2) >> 17);\r
+      o[6] = clamp((x1-t2) >> 17);\r
+      o[2] = clamp((x2+t1) >> 17);\r
+      o[5] = clamp((x2-t1) >> 17);\r
+      o[3] = clamp((x3+t0) >> 17);\r
+      o[4] = clamp((x3-t0) >> 17);\r
+   }\r
+}\r
+\r
+#define MARKER_none  0xff\r
+// if there's a pending marker from the entropy stream, return that\r
+// otherwise, fetch from the stream and get a marker. if there's no\r
+// marker, return 0xff, which is never a valid marker value\r
+static uint8 get_marker(void)\r
+{\r
+   uint8 x;\r
+   if (marker != MARKER_none) { x = marker; marker = MARKER_none; return x; }\r
+   x = get8u();\r
+   if (x != 0xff) return MARKER_none;\r
+   while (x == 0xff)\r
+      x = get8u();\r
+   return x;\r
+}\r
+\r
+// in each scan, we'll have scan_n components, and the order\r
+// of the components is specified by order[]\r
+static int scan_n, order[4];\r
+static int restart_interval, todo;\r
+#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)\r
+\r
+// after a restart interval, reset the entropy decoder and\r
+// the dc prediction\r
+static void reset(void)\r
+{\r
+   code_bits = 0;\r
+   code_buffer = 0;\r
+   nomore = 0;\r
+   img_comp[0].dc_pred = img_comp[1].dc_pred = img_comp[2].dc_pred = 0;\r
+   marker = MARKER_none;\r
+   todo = restart_interval ? restart_interval : 0x7fffffff;\r
+   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,\r
+   // since we don't even allow 1<<30 pixels\r
+}\r
+\r
+static int parse_entropy_coded_data(void)\r
+{\r
+   reset();\r
+   if (scan_n == 1) {\r
+      int i,j;\r
+      short data[64];\r
+      int n = order[0];\r
+      // non-interleaved data, we just need to process one block at a time,\r
+      // in trivial scanline order\r
+      // number of blocks to do just depends on how many actual "pixels" this\r
+      // component has, independent of interleaved MCU blocking and such\r
+      int w = (img_comp[n].x+7) >> 3;\r
+      int h = (img_comp[n].y+7) >> 3;\r
+      for (j=0; j < h; ++j) {\r
+         for (i=0; i < w; ++i) {\r
+            if (!decode_block(data, huff_dc+img_comp[n].hd, huff_ac+img_comp[n].ha, n)) return 0;\r
+            idct_block(img_comp[n].data+img_comp[n].w2*j*8+i*8, img_comp[n].w2, data, dequant[img_comp[n].tq]);\r
+            // every data block is an MCU, so countdown the restart interval\r
+            if (--todo <= 0) {\r
+               if (code_bits < 24) grow_buffer_unsafe();\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(marker)) return 1;\r
+               reset();\r
+            }\r
+         }\r
+      }\r
+   } else { // interleaved!\r
+      int i,j,k,x,y;\r
+      short data[64];\r
+      for (j=0; j < img_mcu_y; ++j) {\r
+         for (i=0; i < img_mcu_x; ++i) {\r
+            // scan an interleaved mcu... process scan_n components in order\r
+            for (k=0; k < scan_n; ++k) {\r
+               int n = order[k];\r
+               // scan out an mcu's worth of this component; that's just determined\r
+               // by the basic H and V specified for the component\r
+               for (y=0; y < img_comp[n].v; ++y) {\r
+                  for (x=0; x < img_comp[n].h; ++x) {\r
+                     int x2 = (i*img_comp[n].h + x)*8;\r
+                     int y2 = (j*img_comp[n].v + y)*8;\r
+                     if (!decode_block(data, huff_dc+img_comp[n].hd, huff_ac+img_comp[n].ha, n)) return 0;\r
+                     idct_block(img_comp[n].data+img_comp[n].w2*y2+x2, img_comp[n].w2, data, dequant[img_comp[n].tq]);\r
+                  }\r
+               }\r
+            }\r
+            // after all interleaved components, that's an interleaved MCU,\r
+            // so now count down the restart interval\r
+            if (--todo <= 0) {\r
+               if (code_bits < 24) grow_buffer_unsafe();\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(marker)) return 1;\r
+               reset();\r
+            }\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int process_marker(int m)\r
+{\r
+   int L;\r
+   switch (m) {\r
+      case MARKER_none: // no marker found\r
+         return e("expected marker","Corrupt JPEG");\r
+\r
+      case 0xC2: // SOF - progressive\r
+         return e("progressive jpeg","JPEG format not supported (progressive)");\r
+\r
+      case 0xDD: // DRI - specify restart interval\r
+         if (get16() != 4) return e("bad DRI len","Corrupt JPEG");\r
+         restart_interval = get16();\r
+         return 1;\r
+\r
+      case 0xDB: // DQT - define quantization table\r
+         L = get16()-2;\r
+         while (L > 0) {\r
+            int z = get8();\r
+            int p = z >> 4;\r
+            int t = z & 15,i;\r
+            if (p != 0) return e("bad DQT type","Corrupt JPEG");\r
+            if (t > 3) return e("bad DQT table","Corrupt JPEG");\r
+            for (i=0; i < 64; ++i)\r
+               dequant[t][dezigzag[i]] = get8u();\r
+            L -= 65;\r
+         }\r
+         return L==0;\r
+\r
+      case 0xC4: // DHT - define huffman table\r
+         L = get16()-2;\r
+         while (L > 0) {\r
+            uint8 *v;\r
+            int sizes[16],i,m=0;\r
+            int z = get8();\r
+            int tc = z >> 4;\r
+            int th = z & 15;\r
+            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");\r
+            for (i=0; i < 16; ++i) {\r
+               sizes[i] = get8();\r
+               m += sizes[i];\r
+            }\r
+            L -= 17;\r
+            if (tc == 0) {\r
+               if (!build_huffman(huff_dc+th, sizes)) return 0;\r
+               v = huff_dc[th].values;\r
+            } else {\r
+               if (!build_huffman(huff_ac+th, sizes)) return 0;\r
+               v = huff_ac[th].values;\r
+            }\r
+            for (i=0; i < m; ++i)\r
+               v[i] = get8u();\r
+            L -= m;\r
+         }\r
+         return L==0;\r
+   }\r
+   // check for comment block or APP blocks\r
+   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {\r
+      skip(get16()-2);\r
+      return 1;\r
+   }\r
+   return 0;\r
+}\r
+\r
+// after we see SOS\r
+static int process_scan_header(void)\r
+{\r
+   int i;\r
+   int Ls = get16();\r
+   scan_n = get8();\r
+   if (scan_n < 1 || scan_n > 4 || scan_n > (int) img_n) return e("bad SOS component count","Corrupt JPEG");\r
+   if (Ls != 6+2*scan_n) return e("bad SOS len","Corrupt JPEG");\r
+   for (i=0; i < scan_n; ++i) {\r
+      int id = get8(), which;\r
+      int z = get8();\r
+      for (which = 0; which < img_n; ++which)\r
+         if (img_comp[which].id == id)\r
+            break;\r
+      if (which == img_n) return 0;\r
+      img_comp[which].hd = z >> 4;   if (img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");\r
+      img_comp[which].ha = z & 15;   if (img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");\r
+      order[i] = which;\r
+   }\r
+   if (get8() != 0) return e("bad SOS","Corrupt JPEG");\r
+   get8(); // should be 63, but might be 0\r
+   if (get8() != 0) return e("bad SOS","Corrupt JPEG");\r
+\r
+   return 1;\r
+}\r
+\r
+static int process_frame_header(int scan)\r
+{\r
+   int Lf,p,i,z, h_max=1,v_max=1;\r
+   Lf = get16();         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG\r
+   p  = get8();          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline\r
+   img_y = get16();      if (img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG\r
+   img_x = get16();      if (img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires\r
+   img_n = get8();\r
+   if (img_n != 3 && img_n != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires\r
+\r
+   if (Lf != 8+3*img_n) return e("bad SOF len","Corrupt JPEG");\r
+\r
+   for (i=0; i < img_n; ++i) {\r
+      img_comp[i].id = get8();\r
+      if (img_comp[i].id != i+1)   // JFIF requires\r
+         if (img_comp[i].id != i)  // jpegtran outputs non-JFIF-compliant files!\r
+            return e("bad component ID","Corrupt JPEG");\r
+      z = get8();\r
+      img_comp[i].h = (z >> 4);  if (!img_comp[i].h || img_comp[i].h > 4) return e("bad H","Corrupt JPEG");\r
+      img_comp[i].v = z & 15;    if (!img_comp[i].v || img_comp[i].v > 4) return e("bad V","Corrupt JPEG");\r
+      img_comp[i].tq = get8();   if (img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");\r
+   }\r
+\r
+   if (scan != SCAN_load) return 1;\r
+\r
+   if ((1 << 30) / img_x / img_n < img_y) return e("too large", "Image too large to decode");\r
+\r
+   for (i=0; i < img_n; ++i) {\r
+      if (img_comp[i].h > h_max) h_max = img_comp[i].h;\r
+      if (img_comp[i].v > v_max) v_max = img_comp[i].v;\r
+   }\r
+\r
+   // compute interleaved mcu info\r
+   img_h_max = h_max;\r
+   img_v_max = v_max;\r
+   img_mcu_w = h_max * 8;\r
+   img_mcu_h = v_max * 8;\r
+   img_mcu_x = (img_x + img_mcu_w-1) / img_mcu_w;\r
+   img_mcu_y = (img_y + img_mcu_h-1) / img_mcu_h;\r
+\r
+   for (i=0; i < img_n; ++i) {\r
+      // number of effective pixels (e.g. for non-interleaved MCU)\r
+      img_comp[i].x = (img_x * img_comp[i].h + h_max-1) / h_max;\r
+      img_comp[i].y = (img_y * img_comp[i].v + v_max-1) / v_max;\r
+      // to simplify generation, we'll allocate enough memory to decode\r
+      // the bogus oversized data from using interleaved MCUs and their\r
+      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't\r
+      // discard the extra data until colorspace conversion\r
+      img_comp[i].w2 = img_mcu_x * img_comp[i].h * 8;\r
+      img_comp[i].h2 = img_mcu_y * img_comp[i].v * 8;\r
+      img_comp[i].data = (uint8 *) malloc(img_comp[i].w2 * img_comp[i].h2);\r
+      if (img_comp[i].data == NULL) {\r
+         for(--i; i >= 0; --i)\r
+            free(img_comp[i].data);\r
+         return e("outofmem", "Out of memory");\r
+      }\r
+   }\r
+\r
+   return 1;\r
+}\r
+\r
+// use comparisons since in some cases we handle more than one case (e.g. SOF)\r
+#define DNL(x)         ((x) == 0xdc)\r
+#define SOI(x)         ((x) == 0xd8)\r
+#define EOI(x)         ((x) == 0xd9)\r
+#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)\r
+#define SOS(x)         ((x) == 0xda)\r
+\r
+static int decode_jpeg_header(int scan)\r
+{\r
+   int m;\r
+   marker = MARKER_none; // initialize cached marker to empty\r
+   m = get_marker();\r
+   if (!SOI(m)) return e("no SOI","Corrupt JPEG");\r
+   if (scan == SCAN_type) return 1;\r
+   m = get_marker();\r
+   while (!SOF(m)) {\r
+      if (!process_marker(m)) return 0;\r
+      m = get_marker();\r
+      while (m == MARKER_none) {\r
+         // some files have extra padding after their blocks, so ok, we'll scan\r
+         if (at_eof()) return e("no SOF", "Corrupt JPEG");\r
+         m = get_marker();\r
+      }\r
+   }\r
+   if (!process_frame_header(scan)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int decode_jpeg_image(void)\r
+{\r
+   int m;\r
+   restart_interval = 0;\r
+   if (!decode_jpeg_header(SCAN_load)) return 0;\r
+   m = get_marker();\r
+   while (!EOI(m)) {\r
+      if (SOS(m)) {\r
+         if (!process_scan_header()) return 0;\r
+         if (!parse_entropy_coded_data()) return 0;\r
+      } else {\r
+         if (!process_marker(m)) return 0;\r
+      }\r
+      m = get_marker();\r
+   }\r
+   return 1;\r
+}\r
+\r
+// static jfif-centered resampling with cross-block smoothing\r
+// here by cross-block smoothing what I mean is that the resampling\r
+// is bilerp and crosses blocks; I dunno what IJG means\r
+\r
+#define div4(x) ((uint8) ((x) >> 2))\r
+\r
+static void resample_v_2(uint8 *out1, uint8 *input, int w, int h, int s)\r
+{\r
+   // need to generate two samples vertically for every one in input\r
+   uint8 *above;\r
+   uint8 *below;\r
+   uint8 *source;\r
+   uint8 *out2;\r
+   int i,j;\r
+   source = input;\r
+   out2 = out1+w;\r
+   for (j=0; j < h; ++j) {\r
+      above = source;\r
+      source = input + j*s;\r
+      below = source + s; if (j == h-1) below = source;\r
+      for (i=0; i < w; ++i) {\r
+         int n = source[i]*3;\r
+         out1[i] = div4(above[i] + n);\r
+         out2[i] = div4(below[i] + n);\r
+      }\r
+      out1 += w*2;\r
+      out2 += w*2;\r
+   }\r
+}\r
+\r
+static void resample_h_2(uint8 *out, uint8 *input, int w, int h, int s)\r
+{\r
+   // need to generate two samples horizontally for every one in input\r
+   int i,j;\r
+   if (w == 1) {\r
+      for (j=0; j < h; ++j)\r
+         out[j*2+0] = out[j*2+1] = input[j*s];\r
+      return;\r
+   }\r
+   for (j=0; j < h; ++j) {\r
+      out[0] = input[0];\r
+      out[1] = div4(input[0]*3 + input[1]);\r
+      for (i=1; i < w-1; ++i) {\r
+         int n = input[i]*3;\r
+         out[i*2-2] = div4(input[i-1] + n);\r
+         out[i*2-1] = div4(input[i+1] + n);\r
+      }\r
+      out[w*2-2] = div4(input[w-2]*3 + input[w-1]);\r
+      out[w*2-1] = input[w-1];\r
+      out += w*2;\r
+      input += s;\r
+   }\r
+}\r
+\r
+// .172 seconds on 3*anemones.jpg\r
+static void resample_hv_2(uint8 *out, uint8 *input, int w, int h, int s)\r
+{\r
+   // need to generate 2x2 samples for every one in input\r
+   int i,j;\r
+   int os = w*2;\r
+   // generate edge samples... @TODO lerp them!\r
+   for (i=0; i < w; ++i) {\r
+      out[i*2+0] = out[i*2+1] = input[i];\r
+      out[i*2+(2*h-1)*os+0] = out[i*2+(2*h-1)*os+1] = input[i+(h-1)*w];\r
+   }\r
+   for (j=0; j < h; ++j) {\r
+      out[j*os*2+0] = out[j*os*2+os+0] = input[j*w];\r
+      out[j*os*2+os-1] = out[j*os*2+os+os-1] = input[j*w+i-1];\r
+   }\r
+   // now generate interior samples; i & j point to top left of input\r
+   for (j=0; j < h-1; ++j) {\r
+      uint8 *in1 = input+j*s;\r
+      uint8 *in2 = in1 + s;\r
+      uint8 *out1 = out + (j*2+1)*os + 1;\r
+      uint8 *out2 = out1 + os;\r
+      for (i=0; i < w-1; ++i) {\r
+         int p00 = in1[0], p01=in1[1], p10=in2[0], p11=in2[1];\r
+         int p00_3 = p00*3, p01_3 = p01*3, p10_3 = p10*3, p11_3 = p11*3;\r
+\r
+         #define div16(x)  ((uint8) ((x) >> 4))\r
+\r
+         out1[0] = div16(p00*9 + p01_3 + p10_3 + p11);\r
+         out1[1] = div16(p01*9 + p00_3 + p01_3 + p10);\r
+         out2[0] = div16(p10*9 + p11_3 + p00_3 + p01);\r
+         out2[1] = div16(p11*9 + p10_3 + p01_3 + p00);\r
+         out1 += 2;\r
+         out2 += 2;                                                         \r
+         ++in1;\r
+         ++in2;\r
+      }\r
+   }\r
+}\r
+\r
+#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))\r
+\r
+// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)\r
+// VC6 without processor=Pro is generating multiple LEAs per multiply!\r
+static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pcr, int count, int step)\r
+{\r
+   int i;\r
+   for (i=0; i < count; ++i) {\r
+      int y_fixed = (y[i] << 16) + 32768; // rounding\r
+      int r,g,b;\r
+      int cr = pcr[i] - 128;\r
+      int cb = pcb[i] - 128;\r
+      r = y_fixed + cr*float2fixed(1.40200f);\r
+      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);\r
+      b = y_fixed                            + cb*float2fixed(1.77200f);\r
+      r >>= 16;\r
+      g >>= 16;\r
+      b >>= 16;\r
+      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\r
+      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\r
+      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\r
+      out[0] = (uint8)r;\r
+      out[1] = (uint8)g;\r
+      out[2] = (uint8)b;\r
+      if (step == 4) out[3] = 255;\r
+      out += step;\r
+   }\r
+}\r
+\r
+// clean up the temporary component buffers\r
+static void cleanup_jpeg(void)\r
+{\r
+   int i;\r
+   for (i=0; i < img_n; ++i) {\r
+      if (img_comp[i].data) {\r
+         free(img_comp[i].data);\r
+         img_comp[i].data = NULL;\r
+      }\r
+   }\r
+}\r
+\r
+static uint8 *load_jpeg_image(int *out_x, int *out_y, int *comp, int req_comp)\r
+{\r
+   int i, n;\r
+   // validate req_comp\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+\r
+   // load a jpeg image from whichever source\r
+   if (!decode_jpeg_image()) { cleanup_jpeg(); return NULL; }\r
+\r
+   // determine actual number of components to generate\r
+   n = req_comp ? req_comp : img_n;\r
+\r
+   // resample components to full size... memory wasteful, but this\r
+   // lets us bilerp across blocks while upsampling\r
+   for (i=0; i < img_n; ++i) {\r
+      // if we're outputting fewer than 3 components, we're grey not RGB;\r
+      // in that case, don't bother upsampling Cb or Cr\r
+      if (n < 3 && i) continue;\r
+\r
+      // check if the component scale is less than max; if so it needs upsampling\r
+      if (img_comp[i].h != img_h_max || img_comp[i].v != img_v_max) {\r
+         int stride = img_x;\r
+         // allocate final size; make sure it's big enough for upsampling off\r
+         // the edges with upsample up to 4x4 (although we only support 2x2\r
+         // currently)\r
+         uint8 *new_data = (uint8 *) malloc((img_x+3)*(img_y+3));\r
+         if (new_data == NULL) {\r
+            cleanup_jpeg();\r
+            return epuc("outofmem", "Out of memory (image too large?)");\r
+         }\r
+         if (img_comp[i].h*2 == img_h_max && img_comp[i].v*2 == img_v_max) {\r
+            int tx = (img_x+1)>>1;\r
+            resample_hv_2(new_data, img_comp[i].data, tx,(img_y+1)>>1, img_comp[i].w2);\r
+            stride = tx*2;\r
+         } else if (img_comp[i].h == img_h_max && img_comp[i].v*2 == img_v_max) {\r
+            resample_v_2(new_data, img_comp[i].data, img_x,(img_y+1)>>1, img_comp[i].w2);\r
+         } else if (img_comp[i].h*2 == img_h_max && img_comp[i].v == img_v_max) {\r
+            int tx = (img_x+1)>>1;\r
+            resample_h_2(new_data, img_comp[i].data, tx,img_y, img_comp[i].w2);\r
+            stride = tx*2;\r
+         } else {\r
+            // @TODO resample uncommon sampling pattern with nearest neighbor\r
+            free(new_data);\r
+            cleanup_jpeg();\r
+            return epuc("uncommon H or V", "JPEG not supported: atypical downsampling mode");\r
+         }\r
+         img_comp[i].w2 = stride;\r
+         free(img_comp[i].data);\r
+         img_comp[i].data = new_data;\r
+      }\r
+   }\r
+\r
+   // now convert components to output image\r
+   {\r
+      uint32 i,j;\r
+      uint8 *output = (uint8 *) malloc(n * img_x * img_y + 1);\r
+      if (n >= 3) { // output STBI_rgb_*\r
+         for (j=0; j < img_y; ++j) {\r
+            uint8 *y  = img_comp[0].data + j*img_comp[0].w2;\r
+            uint8 *out = output + n * img_x * j;\r
+            if (img_n == 3) {\r
+               uint8 *cb = img_comp[1].data + j*img_comp[1].w2;\r
+               uint8 *cr = img_comp[2].data + j*img_comp[2].w2;\r
+               YCbCr_to_RGB_row(out, y, cb, cr, img_x, n);\r
+            } else {\r
+               for (i=0; i < img_x; ++i) {\r
+                  out[0] = out[1] = out[2] = y[i];\r
+                  out[3] = 255; // not used if n == 3\r
+                  out += n;\r
+               }\r
+            }\r
+         }\r
+      } else {      // output STBI_grey_*\r
+         for (j=0; j < img_y; ++j) {\r
+            uint8 *y  = img_comp[0].data + j*img_comp[0].w2;\r
+            uint8 *out = output + n * img_x * j;\r
+            if (n == 1)\r
+               for (i=0; i < img_x; ++i) *out++ = *y++;\r
+            else\r
+               for (i=0; i < img_x; ++i) *out++ = *y++, *out++ = 255;\r
+         }\r
+      }\r
+      cleanup_jpeg();\r
+      *out_x = img_x;\r
+      *out_y = img_y;\r
+      if (comp) *comp  = img_n; // report original components, not output\r
+      return output;\r
+   }\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return load_jpeg_image(x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_jpeg_load(char *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_jpeg_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer,len);\r
+   return load_jpeg_image(x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_jpeg_test_file(FILE *f)\r
+{\r
+   int n,r;\r
+   n = ftell(f);\r
+   start_file(f);\r
+   r = decode_jpeg_header(SCAN_type);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_jpeg_test_memory(unsigned char *buffer, int len)\r
+{\r
+   start_mem(buffer,len);\r
+   return decode_jpeg_header(SCAN_type);\r
+}\r
+\r
+// @TODO:\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_jpeg_info            (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// public domain zlib decode    v0.2  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - all input must be provided in an upfront buffer\r
+//      - all output is written to a single output buffer (can malloc/realloc)\r
+//    performance\r
+//      - fast huffman\r
+\r
+// fast-way is faster to check than jpeg huffman, but slow way is slower\r
+#define ZFAST_BITS  9 // accelerate all cases in default tables\r
+#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)\r
+\r
+// zlib-style huffman encoding\r
+// (jpegs packs from left, zlib from right, so can't share code)\r
+typedef struct\r
+{\r
+   uint16 fast[1 << ZFAST_BITS];\r
+   uint16 firstcode[16];\r
+   int maxcode[17];\r
+   uint16 firstsymbol[16];\r
+   uint8  size[288];\r
+   uint16 value[288]; \r
+} zhuffman;\r
+\r
+__forceinline static int bitreverse16(int n)\r
+{\r
+  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);\r
+  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);\r
+  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);\r
+  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);\r
+  return n;\r
+}\r
+\r
+__forceinline static int bit_reverse(int v, int bits)\r
+{\r
+   assert(bits <= 16);\r
+   // to bit reverse n bits, reverse 16 and shift\r
+   // e.g. 11 bits, bit reverse and shift away 5\r
+   return bitreverse16(v) >> (16-bits);\r
+}\r
+\r
+static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)\r
+{\r
+   int i,k=0;\r
+   int code, next_code[16], sizes[17];\r
+\r
+   // DEFLATE spec for generating codes\r
+   memset(sizes, 0, sizeof(sizes));\r
+   memset(z->fast, 255, sizeof(z->fast));\r
+   for (i=0; i < num; ++i) \r
+      ++sizes[sizelist[i]];\r
+   sizes[0] = 0;\r
+   for (i=1; i < 16; ++i)\r
+      assert(sizes[i] <= (1 << i));\r
+   code = 0;\r
+   for (i=1; i < 16; ++i) {\r
+      next_code[i] = code;\r
+      z->firstcode[i] = (uint16) code;\r
+      z->firstsymbol[i] = (uint16) k;\r
+      code = (code + sizes[i]);\r
+      if (sizes[i])\r
+         if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");\r
+      z->maxcode[i] = code << (16-i); // preshift for inner loop\r
+      code <<= 1;\r
+      k += sizes[i];\r
+   }\r
+   z->maxcode[16] = 0x10000; // sentinel\r
+   for (i=0; i < num; ++i) {\r
+      int s = sizelist[i];\r
+      if (s) {\r
+         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];\r
+         z->size[c] = (uint8)s;\r
+         z->value[c] = (uint16)i;\r
+         if (s <= ZFAST_BITS) {\r
+            int k = bit_reverse(next_code[s],s);\r
+            while (k < (1 << ZFAST_BITS)) {\r
+               z->fast[k] = (uint16) c;\r
+               k += (1 << s);\r
+            }\r
+         }\r
+         ++next_code[s];\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+// zlib-from-memory implementation for PNG reading\r
+//    because PNG allows splitting the zlib stream arbitrarily,\r
+//    and it's annoying structurally to have PNG call ZLIB call PNG,\r
+//    we require PNG read all the IDATs and combine them into a single\r
+//    memory buffer\r
+\r
+static uint8 *zbuffer, *zbuffer_end;\r
+\r
+__forceinline static int zget8(void)\r
+{\r
+   if (zbuffer >= zbuffer_end) return 0;\r
+   return *zbuffer++;\r
+}\r
+\r
+//static unsigned long code_buffer;\r
+static int           num_bits;\r
+\r
+static void fill_bits(void)\r
+{\r
+   do {\r
+      assert(code_buffer < (1U << num_bits));\r
+      code_buffer |= zget8() << num_bits;\r
+      num_bits += 8;\r
+   } while (num_bits <= 24);\r
+}\r
+\r
+__forceinline static unsigned int zreceive(int n)\r
+{\r
+   unsigned int k;\r
+   if (num_bits < n) fill_bits();\r
+   k = code_buffer & ((1 << n) - 1);\r
+   code_buffer >>= n;\r
+   num_bits -= n;\r
+   return k;   \r
+}\r
+\r
+__forceinline static int zhuffman_decode(zhuffman *z)\r
+{\r
+   int b,s,k;\r
+   if (num_bits < 16) fill_bits();\r
+   b = z->fast[code_buffer & ZFAST_MASK];\r
+   if (b < 0xffff) {\r
+      s = z->size[b];\r
+      code_buffer >>= s;\r
+      num_bits -= s;\r
+      return z->value[b];\r
+   }\r
+\r
+   // not resolved by fast table, so compute it the slow way\r
+   // use jpeg approach, which requires MSbits at top\r
+   k = bit_reverse(code_buffer, 16);\r
+   for (s=ZFAST_BITS+1; ; ++s)\r
+      if (k < z->maxcode[s])\r
+         break;\r
+   if (s == 16) return -1; // invalid code!\r
+   // code size is s, so:\r
+   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];\r
+   assert(z->size[b] == s);\r
+   code_buffer >>= s;\r
+   num_bits -= s;\r
+   return z->value[b];\r
+}\r
+\r
+static char *zout;\r
+static char *zout_start;\r
+static char *zout_end;\r
+static int   z_expandable;\r
+\r
+static int expand(int n)  // need to make room for n bytes\r
+{\r
+   char *q;\r
+   int cur, limit;\r
+   if (!z_expandable) return e("output buffer limit","Corrupt PNG");\r
+   cur   = (int) (zout     - zout_start);\r
+   limit = (int) (zout_end - zout_start);\r
+   while (cur + n > limit)\r
+      limit *= 2;\r
+   q = (char *) realloc(zout_start, limit);\r
+   if (q == NULL) return e("outofmem", "Out of memory");\r
+   zout_start = q;\r
+   zout       = q + cur;\r
+   zout_end   = q + limit;\r
+   return 1;\r
+}\r
+\r
+static zhuffman z_length, z_distance;\r
+\r
+static int length_base[31] = {\r
+   3,4,5,6,7,8,9,10,11,13,\r
+   15,17,19,23,27,31,35,43,51,59,\r
+   67,83,99,115,131,163,195,227,258,0,0 };\r
+\r
+static int length_extra[31]= \r
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\r
+\r
+static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,\r
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\r
+\r
+static int dist_extra[32] =\r
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\r
+\r
+static int parse_huffman_block(void)\r
+{\r
+   for(;;) {\r
+      int z = zhuffman_decode(&z_length);\r
+      if (z < 256) {\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes\r
+         if (zout >= zout_end) if (!expand(1)) return 0;\r
+         *zout++ = (char) z;\r
+      } else {\r
+         uint8 *p;\r
+         int len,dist;\r
+         if (z == 256) return 1;\r
+         z -= 257;\r
+         len = length_base[z];\r
+         if (length_extra[z]) len += zreceive(length_extra[z]);\r
+         z = zhuffman_decode(&z_distance);\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG");\r
+         dist = dist_base[z];\r
+         if (dist_extra[z]) dist += zreceive(dist_extra[z]);\r
+         if (zout - zout_start < dist) return e("bad dist","Corrupt PNG");\r
+         if (zout + len > zout_end) if (!expand(len)) return 0;\r
+         p = (uint8 *) (zout - dist);\r
+         while (len--)\r
+            *zout++ = *p++;\r
+      }\r
+   }\r
+}\r
+\r
+static int compute_huffman_codes(void)\r
+{\r
+   static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\r
+   static zhuffman z_codelength; // static just to save stack space\r
+   uint8 lencodes[286+32+137];//padding for maximum single op\r
+   uint8 codelength_sizes[19];\r
+   int i,n;\r
+\r
+   int hlit  = zreceive(5) + 257;\r
+   int hdist = zreceive(5) + 1;\r
+   int hclen = zreceive(4) + 4;\r
+\r
+   memset(codelength_sizes, 0, sizeof(codelength_sizes));\r
+   for (i=0; i < hclen; ++i) {\r
+      int s = zreceive(3);\r
+      codelength_sizes[length_dezigzag[i]] = (uint8) s;\r
+   }\r
+   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;\r
+\r
+   n = 0;\r
+   while (n < hlit + hdist) {\r
+      int c = zhuffman_decode(&z_codelength);\r
+      assert(c >= 0 && c < 19);\r
+      if (c < 16)\r
+         lencodes[n++] = (uint8) c;\r
+      else if (c == 16) {\r
+         c = zreceive(2)+3;\r
+         memset(lencodes+n, lencodes[n-1], c);\r
+         n += c;\r
+      } else if (c == 17) {\r
+         c = zreceive(3)+3;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      } else {\r
+         assert(c == 18);\r
+         c = zreceive(7)+11;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      }\r
+   }\r
+   if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");\r
+   if (!zbuild_huffman(&z_length, lencodes, hlit)) return 0;\r
+   if (!zbuild_huffman(&z_distance, lencodes+hlit, hdist)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int parse_uncompressed_block(void)\r
+{\r
+   uint8 header[4];\r
+   int len,nlen,k;\r
+   if (num_bits & 7)\r
+      zreceive(num_bits & 7); // discard\r
+   // drain the bit-packed data into header\r
+   k = 0;\r
+   while (num_bits > 0) {\r
+      header[k++] = (uint8) (code_buffer & 255); // wtf this warns?\r
+      code_buffer >>= 8;\r
+      num_bits -= 8;\r
+   }\r
+   assert(num_bits == 0);\r
+   // now fill header the normal way\r
+   while (k < 4)\r
+      header[k++] = (uint8) zget8();\r
+   len  = header[1] * 256 + header[0];\r
+   nlen = header[3] * 256 + header[2];\r
+   if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");\r
+   if (zbuffer + len > zbuffer_end) return e("read past buffer","Corrupt PNG");\r
+   if (zout + len > zout_end)\r
+      if (!expand(len)) return 0;\r
+   memcpy(zout, zbuffer, len);\r
+   zbuffer += len;\r
+   zout += len;\r
+   return 1;\r
+}\r
+\r
+static int parse_zlib_header(void)\r
+{\r
+   int cmf   = zget8();\r
+   int cm    = cmf & 15;\r
+   /* int cinfo = cmf >> 4; */\r
+   int flg   = zget8();\r
+   if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec\r
+   if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png\r
+   if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png\r
+   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output\r
+   return 1;\r
+}\r
+\r
+static uint8 default_length[288], default_distance[32];\r
+static void init_defaults(void)\r
+{\r
+   int i;   // use <= to match clearly with spec\r
+   for (i=0; i <= 143; ++i)     default_length[i]   = 8;\r
+   for (   ; i <= 255; ++i)     default_length[i]   = 9;\r
+   for (   ; i <= 279; ++i)     default_length[i]   = 7;\r
+   for (   ; i <= 287; ++i)     default_length[i]   = 8;\r
+\r
+   for (i=0; i <=  31; ++i)     default_distance[i] = 5;\r
+}\r
+\r
+static int parse_zlib(int parse_header)\r
+{\r
+   int final, type;\r
+   if (parse_header)\r
+      if (!parse_zlib_header()) return 0;\r
+   num_bits = 0;\r
+   code_buffer = 0;\r
+   do {\r
+      final = zreceive(1);\r
+      type = zreceive(2);\r
+      if (type == 0) {\r
+         if (!parse_uncompressed_block()) return 0;\r
+      } else if (type == 3) {\r
+         return 0;\r
+      } else {\r
+         if (type == 1) {\r
+            // use fixed code lengths\r
+            if (!default_length[0]) init_defaults();\r
+            if (!zbuild_huffman(&z_length  , default_length  , 288)) return 0;\r
+            if (!zbuild_huffman(&z_distance, default_distance,  32)) return 0;\r
+         } else {\r
+            if (!compute_huffman_codes()) return 0;\r
+         }\r
+         if (!parse_huffman_block()) return 0;\r
+      }\r
+   } while (!final);\r
+   return 1;\r
+}\r
+\r
+static int do_zlib(char *obuf, int olen, int exp, int parse_header)\r
+{\r
+   zout_start = obuf;\r
+   zout       = obuf;\r
+   zout_end   = obuf + olen;\r
+   z_expandable = exp;\r
+\r
+   return parse_zlib(parse_header);\r
+}\r
+\r
+char *stbi_zlib_decode_malloc_guesssize(int initial_size, int *outlen)\r
+{\r
+   char *p = (char *) malloc(initial_size);\r
+   if (p == NULL) return NULL;\r
+   if (do_zlib(p, initial_size, 1, 1)) {\r
+      *outlen = (int) (zout - zout_start);\r
+      return zout_start;\r
+   } else {\r
+      free(zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+char *stbi_zlib_decode_malloc(char *buffer, int len, int *outlen)\r
+{\r
+   zbuffer = (uint8 *) buffer;\r
+   zbuffer_end = (uint8 *) buffer+len;\r
+   return stbi_zlib_decode_malloc_guesssize(16384, outlen);\r
+}\r
+\r
+int stbi_zlib_decode_buffer(char *obuffer, int olen, char *ibuffer, int ilen)\r
+{\r
+   zbuffer = (uint8 *) ibuffer;\r
+   zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(obuffer, olen, 0, 1))\r
+      return (int) (zout - zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+char *stbi_zlib_decode_noheader_malloc(char *buffer, int len, int *outlen)\r
+{\r
+   char *p = (char *) malloc(16384);\r
+   if (p == NULL) return NULL;\r
+   zbuffer = (uint8 *) buffer;\r
+   zbuffer_end = (uint8 *) buffer+len;\r
+   if (do_zlib(p, 16384, 1, 0)) {\r
+      *outlen = (int) (zout - zout_start);\r
+      return zout_start;\r
+   } else {\r
+      free(zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, char *ibuffer, int ilen)\r
+{\r
+   zbuffer = (uint8 *) ibuffer;\r
+   zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(obuffer, olen, 0, 0))\r
+      return (int) (zout - zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+// public domain "baseline" PNG decoder   v0.10  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - only 8-bit samples\r
+//      - no CRC checking\r
+//      - allocates lots of intermediate memory\r
+//        - avoids problem of streaming data between subsystems\r
+//        - avoids explicit window management\r
+//    performance\r
+//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding\r
+\r
+\r
+typedef struct\r
+{\r
+   unsigned long length;\r
+   unsigned long type;\r
+} chunk;\r
+\r
+#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))\r
+\r
+static chunk get_chunk_header(void)\r
+{\r
+   chunk c;\r
+   c.length = get32();\r
+   c.type   = get32();\r
+   return c;\r
+}\r
+\r
+static int check_png_header(void)\r
+{\r
+   static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };\r
+   int i;\r
+   for (i=0; i < 8; ++i)\r
+      if (get8() != png_sig[i]) return e("bad png sig","Not a PNG");\r
+   return 1;\r
+}\r
+\r
+static uint8 *idata, *expanded, *out;\r
+\r
+enum {\r
+   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,\r
+   F_avg_first, F_paeth_first,\r
+};\r
+\r
+static uint8 first_row_filter[5] =\r
+{\r
+   F_none, F_sub, F_none, F_avg_first, F_paeth_first\r
+};\r
+\r
+static int paeth(int a, int b, int c)\r
+{\r
+   int p = a + b - c;\r
+   int pa = abs(p-a);\r
+   int pb = abs(p-b);\r
+   int pc = abs(p-c);\r
+   if (pa <= pb && pa <= pc) return a;\r
+   if (pb <= pc) return b;\r
+   return c;\r
+}\r
+\r
+// create the png data from post-deflated data\r
+static int create_png_image(uint8 *raw, uint32 raw_len, int out_n)\r
+{\r
+   uint32 i,j,stride = img_x*out_n;\r
+   int k;\r
+   assert(out_n == img_n || out_n == img_n+1);\r
+   out = (uint8 *) malloc(img_x * img_y * out_n);\r
+   if (!out) return e("outofmem", "Out of memory");\r
+   if (raw_len != (img_n * img_x + 1) * img_y) return e("not enough pixels","Corrupt PNG");\r
+   for (j=0; j < img_y; ++j) {\r
+      uint8 *cur = out + stride*j;\r
+      uint8 *prior = cur - stride;\r
+      int filter = *raw++;\r
+      if (filter > 4) return e("invalid filter","Corrupt PNG");\r
+      // if first row, use special filter that doesn't sample previous row\r
+      if (j == 0) filter = first_row_filter[filter];\r
+      // handle first pixel explicitly\r
+      for (k=0; k < img_n; ++k) {\r
+         switch(filter) {\r
+            case F_none       : cur[k] = raw[k]; break;\r
+            case F_sub        : cur[k] = raw[k]; break;\r
+            case F_up         : cur[k] = raw[k] + prior[k]; break;\r
+            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;\r
+            case F_paeth      : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;\r
+            case F_avg_first  : cur[k] = raw[k]; break;\r
+            case F_paeth_first: cur[k] = raw[k]; break;\r
+         }\r
+      }\r
+      if (img_n != out_n) cur[img_n] = 255;\r
+      raw += img_n;\r
+      cur += out_n;\r
+      prior += out_n;\r
+      // this is a little gross, so that we don't switch per-pixel or per-component\r
+      if (img_n == out_n) {\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=1; i < img_x; ++i, raw+=img_n,cur+=img_n,prior+=img_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      } else {\r
+         assert(img_n+1 == out_n);\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=1; i < img_x; ++i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int compute_transparency(uint8 tc[3], int out_n)\r
+{\r
+   uint32 i, pixel_count = img_x * img_y;\r
+   uint8 *p = out;\r
+\r
+   // compute color-based transparency, assuming we've\r
+   // already got 255 as the alpha value in the output\r
+   assert(out_n == 2 || out_n == 4);\r
+\r
+   p = out;\r
+   if (out_n == 2) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         p[1] = (p[0] == tc[0] ? 0 : 255);\r
+         p += 2;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\r
+            p[3] = 0;\r
+         p += 4;\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int expand_palette(uint8 *palette, int len, int pal_img_n)\r
+{\r
+   uint32 i, pixel_count = img_x * img_y;\r
+   uint8 *p, *temp_out, *orig = out;\r
+\r
+   p = (uint8 *) malloc(pixel_count * pal_img_n);\r
+   if (p == NULL) return e("outofmem", "Out of memory");\r
+\r
+   // between here and free(out) below, exitting would leak\r
+   temp_out = p;\r
+\r
+   if (pal_img_n == 3) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p += 3;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p[3] = palette[n+3];\r
+         p += 4;\r
+      }\r
+   }\r
+   free(out);\r
+   out = temp_out;\r
+   return 1;\r
+}\r
+\r
+static int parse_png_file(int scan, int req_comp)\r
+{\r
+   uint8 palette[1024], pal_img_n=0;\r
+   uint8 has_trans=0, tc[3];\r
+   uint32 ioff=0, idata_limit=0, i, pal_len=0;\r
+   int first=1,k;\r
+\r
+   if (!check_png_header()) return 0;\r
+\r
+   if (scan == SCAN_type) return 1;\r
+\r
+   for(;;first=0) {\r
+      chunk c = get_chunk_header();\r
+      if (first && c.type != PNG_TYPE('I','H','D','R'))\r
+         return e("first not IHDR","Corrupt PNG");\r
+      switch (c.type) {\r
+         case PNG_TYPE('I','H','D','R'): {\r
+            int depth,color,interlace,comp,filter;\r
+            if (!first) return e("multiple IHDR","Corrupt PNG");\r
+            if (c.length != 13) return e("bad IHDR len","Corrupt PNG");\r
+            img_x = get32(); if (img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            img_y = get32(); if (img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            depth = get8();  if (depth != 8)        return e("8bit only","PNG not supported: 8-bit only");\r
+            color = get8();  if (color > 6)         return e("bad ctype","Corrupt PNG");\r
+            if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");\r
+            comp  = get8();  if (comp) return e("bad comp method","Corrupt PNG");\r
+            filter= get8();  if (filter) return e("bad filter method","Corrupt PNG");\r
+            interlace = get8(); if (interlace) return e("interlaced","PNG not supported: interlaced mode");\r
+            if (!img_x || !img_y) return e("0-pixel image","Corrupt PNG");\r
+            if (!pal_img_n) {\r
+               img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);\r
+               if ((1 << 30) / img_x / img_n < img_y) return e("too large", "Image too large to decode");\r
+               if (scan == SCAN_header) return 1;\r
+            } else {\r
+               // if paletted, then pal_n is our final components, and\r
+               // img_n is # components to decompress/filter.\r
+               img_n = 1;\r
+               if ((1 << 30) / img_x / 4 < img_y) return e("too large","Corrupt PNG");\r
+               // if SCAN_header, have to scan to see if we have a tRNS\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('P','L','T','E'):  {\r
+            if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");\r
+            pal_len = c.length / 3;\r
+            if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");\r
+            for (i=0; i < pal_len; ++i) {\r
+               palette[i*4+0] = get8u();\r
+               palette[i*4+1] = get8u();\r
+               palette[i*4+2] = get8u();\r
+               palette[i*4+3] = 255;\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('t','R','N','S'): {\r
+            if (idata) return e("tRNS after IDAT","Corrupt PNG");\r
+            if (pal_img_n) {\r
+               if (scan == SCAN_header) { img_n = 4; return 1; }\r
+               if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");\r
+               if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");\r
+               pal_img_n = 4;\r
+               for (i=0; i < c.length; ++i)\r
+                  palette[i*4+3] = get8u();\r
+            } else {\r
+               if (!(img_n & 1)) return e("tRNS with alpha","Corrupt PNG");\r
+               if (c.length != (uint32) img_n*2) return e("bad tRNS len","Corrupt PNG");\r
+               has_trans = 1;\r
+               for (k=0; k < img_n; ++k)\r
+                  tc[k] = (uint8) get16(); // non 8-bit images will be larger\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','D','A','T'): {\r
+            if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");\r
+            if (scan == SCAN_header) { img_n = pal_img_n; return 1; }\r
+            if (ioff + c.length > idata_limit) {\r
+               uint8 *p;\r
+               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;\r
+               while (ioff + c.length > idata_limit)\r
+                  idata_limit *= 2;\r
+               p = (uint8 *) realloc(idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");\r
+               idata = p;\r
+            }\r
+            #ifndef STBI_NO_STDIO\r
+            if (img_file)\r
+            {\r
+               if (fread(idata+ioff,1,c.length,img_file) != c.length) return e("outofdata","Corrupt PNG");\r
+            }\r
+            else\r
+            #endif\r
+            {\r
+               memcpy(idata+ioff, img_buffer, c.length);\r
+               img_buffer += c.length;\r
+            }\r
+            ioff += c.length;\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','E','N','D'): {\r
+            uint32 raw_len;\r
+            if (scan != SCAN_load) return 1;\r
+            if (idata == NULL) return e("no IDAT","Corrupt PNG");\r
+            expanded = (uint8 *) stbi_zlib_decode_malloc((char *) idata, ioff, (int *) &raw_len);\r
+            if (expanded == NULL) return 0; // zlib should set error\r
+            free(idata); idata = NULL;\r
+            if ((req_comp == img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)\r
+               img_out_n = img_n+1;\r
+            else\r
+               img_out_n = img_n;\r
+            if (!create_png_image(expanded, raw_len, img_out_n)) return 0;\r
+            if (has_trans)\r
+               if (!compute_transparency(tc, img_out_n)) return 0;\r
+            if (pal_img_n) {\r
+               // pal_img_n == 3 or 4\r
+               img_n = pal_img_n; // record the actual colors we had\r
+               img_out_n = pal_img_n;\r
+               if (req_comp >= 3) img_out_n = req_comp;\r
+               if (!expand_palette(palette, pal_len, img_out_n))\r
+                  return 0;\r
+            }\r
+            free(expanded); expanded = NULL;\r
+            return 1;\r
+         }\r
+\r
+         default:\r
+            // if critical, fail\r
+            if ((c.type & (1 << 29)) == 0) {\r
+               #ifndef STBI_NO_FAILURE_STRINGS\r
+               static char invalid_chunk[] = "XXXX chunk not known";\r
+               invalid_chunk[0] = (uint8) (c.type >> 24);\r
+               invalid_chunk[1] = (uint8) (c.type >> 16);\r
+               invalid_chunk[2] = (uint8) (c.type >>  8);\r
+               invalid_chunk[3] = (uint8) (c.type >>  0);\r
+               #endif\r
+               return e(invalid_chunk, "PNG not supported: unknown chunk type");\r
+            }\r
+            skip(c.length);\r
+            break;\r
+      }\r
+      // end of chunk, read and skip CRC\r
+      get8(); get8(); get8(); get8();\r
+   }\r
+}\r
+\r
+static unsigned char *do_png(int *x, int *y, int *n, int req_comp)\r
+{\r
+   unsigned char *result=NULL;\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+   if (parse_png_file(SCAN_load, req_comp)) {\r
+      result = out;\r
+      out = NULL;\r
+      if (req_comp && req_comp != img_out_n) {\r
+         result = convert_format(result, img_out_n, req_comp);\r
+         if (result == NULL) return result;\r
+      }\r
+      *x = img_x;\r
+      *y = img_y;\r
+      if (n) *n = img_n;\r
+   }\r
+   free(out);      out      = NULL;\r
+   free(expanded); expanded = NULL;\r
+   free(idata);    idata    = NULL;\r
+\r
+   return result;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return do_png(x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_png_load(char *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_png_load_from_memory(unsigned char *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer,len);\r
+   return do_png(x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_png_test_file(FILE *f)\r
+{\r
+   int n,r;\r
+   n = ftell(f);\r
+   start_file(f);\r
+   r = parse_png_file(SCAN_type,STBI_default);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_png_test_memory(unsigned char *buffer, int len)\r
+{\r
+   start_mem(buffer, len);\r
+   return parse_png_file(SCAN_type,STBI_default);\r
+}\r
+\r
+// TODO: load header from png\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_png_info             (char *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_png_info_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// Microsoft/Windows BMP image\r
+\r
+static int bmp_test(void)\r
+{\r
+   int sz;\r
+   if (get8() != 'B') return 0;\r
+   if (get8() != 'M') return 0;\r
+   get32le(); // discard filesize\r
+   get16le(); // discard reserved\r
+   get16le(); // discard reserved\r
+   get32le(); // discard data offset\r
+   sz = get32le();\r
+   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_bmp_test_file        (FILE *f)\r
+{\r
+   int r,n = ftell(f);\r
+   start_file(f);\r
+   r = bmp_test();\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_bmp_test_memory      (stbi_uc *buffer, int len)\r
+{\r
+   start_mem(buffer, len);\r
+   return bmp_test();\r
+}\r
+\r
+// returns 0..31 for the highest set bit\r
+static int high_bit(unsigned int z)\r
+{\r
+   int n=0;\r
+   if (z == 0) return -1;\r
+   if (z >= 0x10000) n += 16, z >>= 16;\r
+   if (z >= 0x00100) n +=  8, z >>=  8;\r
+   if (z >= 0x00010) n +=  4, z >>=  4;\r
+   if (z >= 0x00004) n +=  2, z >>=  2;\r
+   if (z >= 0x00002) n +=  1, z >>=  1;\r
+   return n;\r
+}\r
+\r
+static int bitcount(unsigned int a)\r
+{\r
+   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\r
+   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\r
+   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\r
+   a = (a + (a >> 8)); // max 16 per 8 bits\r
+   a = (a + (a >> 16)); // max 32 per 8 bits\r
+   return a & 0xff;\r
+}\r
+\r
+static int shiftsigned(int v, int shift, int bits)\r
+{\r
+   int result;\r
+   int z=0;\r
+\r
+   if (shift < 0) v <<= -shift;\r
+   else v >>= shift;\r
+   result = v;\r
+\r
+   z = bits;\r
+   while (z < 8) {\r
+      result += v >> z;\r
+      z += bits;\r
+   }\r
+   return result;\r
+}\r
+\r
+static stbi_uc *bmp_load(int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned int mr=0,mg=0,mb=0,ma=0;\r
+   stbi_uc pal[256][4];\r
+   int psize=0,i,j,compress=0,width;\r
+   int bpp, flip_vertically, pad, target, offset, hsz;\r
+   if (get8() != 'B' || get8() != 'M') return epuc("not BMP", "Corrupt BMP");\r
+   get32le(); // discard filesize\r
+   get16le(); // discard reserved\r
+   get16le(); // discard reserved\r
+   offset = get32le();\r
+   hsz = get32le();\r
+   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");\r
+   failure_reason = "bad BMP";\r
+   if (hsz == 12) {\r
+      img_x = get16le();\r
+      img_y = get16le();\r
+   } else {\r
+      img_x = get32le();\r
+      img_y = get32le();\r
+   }\r
+   if (get16le() != 1) return 0;\r
+   bpp = get16le();\r
+   if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");\r
+   flip_vertically = ((int) img_y) > 0;\r
+   img_y = abs((int) img_y);\r
+   if (hsz == 12) {\r
+      if (bpp < 24)\r
+         psize = (offset - 14 - 24) / 3;\r
+   } else {\r
+      compress = get32le();\r
+      if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");\r
+      get32le(); // discard sizeof\r
+      get32le(); // discard hres\r
+      get32le(); // discard vres\r
+      get32le(); // discard colorsused\r
+      get32le(); // discard max important\r
+      if (hsz == 40 || hsz == 56) {\r
+         if (hsz == 56) {\r
+            get32le();\r
+            get32le();\r
+            get32le();\r
+            get32le();\r
+         }\r
+         if (bpp == 16 || bpp == 32) {\r
+            mr = mg = mb = 0;\r
+            if (compress == 0) {\r
+               if (bpp == 32) {\r
+                  mr = 0xff << 16;\r
+                  mg = 0xff <<  8;\r
+                  mb = 0xff <<  0;\r
+               } else {\r
+                  mr = 31 << 10;\r
+                  mg = 31 <<  5;\r
+                  mb = 31 <<  0;\r
+               }\r
+            } else if (compress == 3) {\r
+               mr = get32le();\r
+               mg = get32le();\r
+               mb = get32le();\r
+               // not documented, but generated by photoshop and handled by mspaint\r
+               if (mr == mg && mg == mb) {\r
+                  // ?!?!?\r
+                  return NULL;\r
+               }\r
+            } else\r
+               return NULL;\r
+         }\r
+      } else {\r
+         assert(hsz == 108);\r
+         mr = get32le();\r
+         mg = get32le();\r
+         mb = get32le();\r
+         ma = get32le();\r
+         get32le(); // discard color space\r
+         for (i=0; i < 12; ++i)\r
+            get32le(); // discard color space parameters\r
+      }\r
+      if (bpp < 16)\r
+         psize = (offset - 14 - hsz) >> 2;\r
+   }\r
+   img_n = ma ? 4 : 3;\r
+   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4\r
+      target = req_comp;\r
+   else\r
+      target = img_n; // if they want monochrome, we'll post-convert\r
+   out = (stbi_uc *) malloc(target * img_x * img_y);\r
+   if (!out) return epuc("outofmem", "Out of memory");\r
+   if (bpp < 16) {\r
+      int z=0;\r
+      if (psize == 0 || psize > 256) return epuc("invalid", "Corrupt BMP");\r
+      for (i=0; i < psize; ++i) {\r
+         pal[i][2] = get8();\r
+         pal[i][1] = get8();\r
+         pal[i][0] = get8();\r
+         if (hsz != 12) get8();\r
+         pal[i][3] = 255;\r
+      }\r
+      skip(offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));\r
+      if (bpp == 4) width = (img_x + 1) >> 1;\r
+      else if (bpp == 8) width = img_x;\r
+      else return epuc("bad bpp", "Corrupt BMP");\r
+      pad = (-width)&3;\r
+      for (j=0; j < (int) img_y; ++j) {\r
+         for (i=0; i < (int) img_x; i += 2) {\r
+            int v=get8(),v2=0;\r
+            if (bpp == 4) {\r
+               v2 = v & 15;\r
+               v >>= 4;\r
+            }\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+            if (i+1 == (int) img_x) break;\r
+            v = (bpp == 8) ? get8() : v2;\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+         }\r
+         skip(pad);\r
+      }\r
+   } else {\r
+      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;\r
+      int z = 0;\r
+      int easy=0;\r
+      skip(offset - 14 - hsz);\r
+      if (bpp == 24) width = 3 * img_x;\r
+      else if (bpp == 16) width = 2*img_x;\r
+      else /* bpp = 32 and pad = 0 */ width=0;\r
+      pad = (-width) & 3;\r
+      if (bpp == 24) {\r
+         easy = 1;\r
+      } else if (bpp == 32) {\r
+         if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000)\r
+            easy = 2;\r
+      }\r
+      if (!easy) {\r
+         if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP");\r
+         // right shift amt to put high bit in position #7\r
+         rshift = high_bit(mr)-7; rcount = bitcount(mr);\r
+         gshift = high_bit(mg)-7; gcount = bitcount(mr);\r
+         bshift = high_bit(mb)-7; bcount = bitcount(mr);\r
+         ashift = high_bit(ma)-7; acount = bitcount(mr);\r
+      }\r
+      for (j=0; j < (int) img_y; ++j) {\r
+         if (easy) {\r
+            for (i=0; i < (int) img_x; ++i) {\r
+               int a;\r
+               out[z+2] = get8();\r
+               out[z+1] = get8();\r
+               out[z+0] = get8();\r
+               z += 3;\r
+               a = (easy == 2 ? get8() : 255);\r
+               if (target == 4) out[z++] = a;\r
+            }\r
+         } else {\r
+            for (i=0; i < (int) img_x; ++i) {\r
+               unsigned long v = (bpp == 16 ? get16le() : get32le());\r
+               int a;\r
+               out[z++] = shiftsigned(v & mr, rshift, rcount);\r
+               out[z++] = shiftsigned(v & mg, gshift, gcount);\r
+               out[z++] = shiftsigned(v & mb, bshift, bcount);\r
+               a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);\r
+               if (target == 4) out[z++] = a; \r
+            }\r
+         }\r
+         skip(pad);\r
+      }\r
+   }\r
+   if (flip_vertically) {\r
+      stbi_uc t;\r
+      for (j=0; j < (int) img_y>>1; ++j) {\r
+         stbi_uc *p1 = out +      j     *img_x*target;\r
+         stbi_uc *p2 = out + (img_y-1-j)*img_x*target;\r
+         for (i=0; i < (int) img_x*target; ++i) {\r
+            t = p1[i], p1[i] = p2[i], p2[i] = t;\r
+         }\r
+      }\r
+   }\r
+\r
+   if (req_comp && req_comp != target) {\r
+      out = convert_format(out, target, req_comp);\r
+      if (out == NULL) return out; // convert_format frees input on failure\r
+   }\r
+\r
+   *x = img_x;\r
+   *y = img_y;\r
+   if (comp) *comp = target;\r
+   return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_bmp_load             (char *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_bmp_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return bmp_load(x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_bmp_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer, len);\r
+   return bmp_load(x,y,comp,req_comp);\r
+}\r
+\r
+// Targa Truevision - TGA\r
+// by Jonathan Dummer\r
+\r
+static int tga_test(void)\r
+{\r
+       int sz;\r
+       get8u();                //      discard Offset\r
+       sz = get8u();   //      color type\r
+       if( sz > 1 ) return 0;  //      only RGB or indexed allowed\r
+       sz = get8u();   //      image type\r
+       if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0;    //      only RGB or grey allowed, +/- RLE\r
+       get16();                //      discard palette start\r
+       get16();                //      discard palette length\r
+       get8();                 //      discard bits per palette color entry\r
+       get16();                //      discard x origin\r
+       get16();                //      discard y origin\r
+       if( get16() < 1 ) return 0;             //      test width\r
+       if( get16() < 1 ) return 0;             //      test height\r
+       sz = get8();    //      bits per pixel\r
+       if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0;     //      only RGB or RGBA or grey allowed\r
+       return 1;               //      seems to have passed everything\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_tga_test_file        (FILE *f)\r
+{\r
+   int r,n = ftell(f);\r
+   start_file(f);\r
+   r = tga_test();\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_tga_test_memory      (stbi_uc *buffer, int len)\r
+{\r
+   start_mem(buffer, len);\r
+   return tga_test();\r
+}\r
+\r
+static stbi_uc *tga_load(int *x, int *y, int *comp, int req_comp)\r
+{\r
+       //      read in the TGA header stuff\r
+       int tga_offset = get8u();\r
+       int tga_indexed = get8u();\r
+       int tga_image_type = get8u();\r
+       int tga_is_RLE = 0;\r
+       int tga_palette_start = get16le();\r
+       int tga_palette_len = get16le();\r
+       int tga_palette_bits = get8u();\r
+       int tga_x_origin = get16le();\r
+       int tga_y_origin = get16le();\r
+       int tga_width = get16le();\r
+       int tga_height = get16le();\r
+       int tga_bits_per_pixel = get8u();\r
+       int tga_inverted = get8u();\r
+       //      image data\r
+       unsigned char *tga_data;\r
+       unsigned char *tga_palette = NULL;\r
+       int i, j;\r
+       unsigned char raw_data[4];\r
+       unsigned char trans_data[4];\r
+       int RLE_count = 0;\r
+       int RLE_repeating = 0;\r
+       int read_next_pixel = 1;\r
+       //      do a tiny bit of precessing\r
+       if( tga_image_type >= 8 )\r
+       {\r
+               tga_image_type -= 8;\r
+               tga_is_RLE = 1;\r
+       }\r
+       /* int tga_alpha_bits = tga_inverted & 15; */\r
+       tga_inverted = 1 - ((tga_inverted >> 5) & 1);\r
+\r
+       //      error check\r
+       if( //(tga_indexed) ||\r
+               (tga_width < 1) || (tga_height < 1) ||\r
+               (tga_image_type < 1) || (tga_image_type > 3) ||\r
+               ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&\r
+               (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))\r
+               )\r
+       {\r
+               return NULL;\r
+       }\r
+\r
+       //      If I'm paletted, then I'll use the number of bits from the palette\r
+       if( tga_indexed )\r
+       {\r
+               tga_bits_per_pixel = tga_palette_bits;\r
+       }\r
+\r
+       //      tga info\r
+       *x = tga_width;\r
+       *y = tga_height;\r
+       if( (req_comp < 1) || (req_comp > 4) )\r
+       {\r
+               //      just use whatever the file was\r
+               req_comp = tga_bits_per_pixel / 8;\r
+               *comp = req_comp;\r
+       } else\r
+       {\r
+               //      force a new number of components\r
+               *comp = tga_bits_per_pixel/8;\r
+       }\r
+       tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );\r
+\r
+       //      skip to the data's starting position (offset usually = 0)\r
+       skip( tga_offset );\r
+       //      do I need to load a palette?\r
+       if( tga_indexed )\r
+       {\r
+               //      any data to skip? (offset usually = 0)\r
+               skip( tga_palette_start );\r
+               //      load the palette\r
+               tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );\r
+               getn( tga_palette, tga_palette_len * tga_palette_bits / 8 );\r
+       }\r
+       //      load the data\r
+       for( i = 0; i < tga_width * tga_height; ++i )\r
+       {\r
+               //      if I'm in RLE mode, do I need to get a RLE chunk?\r
+               if( tga_is_RLE )\r
+               {\r
+                       if( RLE_count == 0 )\r
+                       {\r
+                               //      yep, get the next byte as a RLE command\r
+                               int RLE_cmd = get8u();\r
+                               RLE_count = 1 + (RLE_cmd & 127);\r
+                               RLE_repeating = RLE_cmd >> 7;\r
+                               read_next_pixel = 1;\r
+                       } else if( !RLE_repeating )\r
+                       {\r
+                               read_next_pixel = 1;\r
+                       }\r
+               } else\r
+               {\r
+                       read_next_pixel = 1;\r
+               }\r
+               //      OK, if I need to read a pixel, do it now\r
+               if( read_next_pixel )\r
+               {\r
+                       //      load however much data we did have\r
+                       if( tga_indexed )\r
+                       {\r
+                               //      read in 1 byte, then perform the lookup\r
+                               int pal_idx = get8u();\r
+                               if( pal_idx >= tga_palette_len )\r
+                               {\r
+                                       //      invalid index\r
+                                       pal_idx = 0;\r
+                               }\r
+                               pal_idx *= tga_bits_per_pixel / 8;\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = tga_palette[pal_idx+j];\r
+                               }\r
+                       } else\r
+                       {\r
+                               //      read in the data raw\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = get8u();\r
+                               }\r
+                       }\r
+                       //      convert raw to the intermediate format\r
+                       switch( tga_bits_per_pixel )\r
+                       {\r
+                       case 8:\r
+                               //      Luminous => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 16:\r
+                               //      Luminous,Alpha => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[1];\r
+                               break;\r
+                       case 24:\r
+                               //      BGR => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 32:\r
+                               //      BGRA => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[3];\r
+                               break;\r
+                       }\r
+                       //      clear the reading flag for the next pixel\r
+                       read_next_pixel = 0;\r
+               } // end of reading a pixel\r
+               //      convert to final format\r
+               switch( req_comp )\r
+               {\r
+               case 1:\r
+                       //      RGBA => Luminance\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       break;\r
+               case 2:\r
+                       //      RGBA => Luminance,Alpha\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       tga_data[i*req_comp+1] = trans_data[3];\r
+                       break;\r
+               case 3:\r
+                       //      RGBA => RGB\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       break;\r
+               case 4:\r
+                       //      RGBA => RGBA\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       tga_data[i*req_comp+3] = trans_data[3];\r
+                       break;\r
+               }\r
+               //      in case we're in RLE mode, keep counting down\r
+               --RLE_count;\r
+       }\r
+       //      do I need to invert the image?\r
+       if( tga_inverted )\r
+       {\r
+               for( j = 0; j*2 < tga_height; ++j )\r
+               {\r
+                       int index1 = j * tga_width * req_comp;\r
+                       int index2 = (tga_height - 1 - j) * tga_width * req_comp;\r
+                       for( i = tga_width * req_comp; i > 0; --i )\r
+                       {\r
+                               unsigned char temp = tga_data[index1];\r
+                               tga_data[index1] = tga_data[index2];\r
+                               tga_data[index2] = temp;\r
+                               ++index1;\r
+                               ++index2;\r
+                       }\r
+               }\r
+       }\r
+       //      clear my palette, if I had one\r
+       if( tga_palette != NULL )\r
+       {\r
+               free( tga_palette );\r
+       }\r
+       //      the things I do to get rid of an error message, and yet keep\r
+       //      Microsoft's C compilers happy... [8^(\r
+       tga_palette_start = tga_palette_len = tga_palette_bits =\r
+                       tga_x_origin = tga_y_origin = 0;\r
+       //      OK, done\r
+       return tga_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_tga_load             (char *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_tga_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return tga_load(x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_tga_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer, len);\r
+   return tga_load(x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB\r
+\r
+static int psd_test(void)\r
+{\r
+       if (get32() != 0x38425053) return 0;    // "8BPS"\r
+       else return 1;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_psd_test_file(FILE *f)\r
+{\r
+   int r,n = ftell(f);\r
+   start_file(f);\r
+   r = psd_test();\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_psd_test_memory(stbi_uc *buffer, int len)\r
+{\r
+   start_mem(buffer, len);\r
+   return psd_test();\r
+}\r
+\r
+static stbi_uc *psd_load(int *x, int *y, int *comp, int req_comp)\r
+{\r
+       int     pixelCount;\r
+       int channelCount, compression;\r
+       int channel, i, count, len;\r
+   int w,h;\r
+\r
+       // Check identifier\r
+       if (get32() != 0x38425053)      // "8BPS"\r
+               return epuc("not PSD", "Corrupt PSD image");\r
+\r
+       // Check file type version.\r
+       if (get16() != 1)\r
+               return epuc("wrong version", "Unsupported version of PSD image");\r
+\r
+       // Skip 6 reserved bytes.\r
+       skip( 6 );\r
+\r
+       // Read the number of channels (R, G, B, A, etc).\r
+       channelCount = get16();\r
+       if (channelCount < 0 || channelCount > 16)\r
+               return epuc("wrong channel count", "Unsupported number of channels in PSD image");\r
+\r
+       // Read the rows and columns of the image.\r
+   h = get32();\r
+   w = get32();\r
+       \r
+       // Make sure the depth is 8 bits.\r
+       if (get16() != 8)\r
+               return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");\r
+\r
+       // Make sure the color mode is RGB.\r
+       // Valid options are:\r
+       //   0: Bitmap\r
+       //   1: Grayscale\r
+       //   2: Indexed color\r
+       //   3: RGB color\r
+       //   4: CMYK color\r
+       //   7: Multichannel\r
+       //   8: Duotone\r
+       //   9: Lab color\r
+       if (get16() != 3)\r
+               return epuc("wrong color format", "PSD is not in RGB color format");\r
+\r
+       // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)\r
+       skip(get32() );\r
+\r
+       // Skip the image resources.  (resolution, pen tool paths, etc)\r
+       skip( get32() );\r
+\r
+       // Skip the reserved data.\r
+       skip( get32() );\r
+\r
+       // Find out if the data is compressed.\r
+       // Known values:\r
+       //   0: no compression\r
+       //   1: RLE compressed\r
+       compression = get16();\r
+       if (compression > 1)\r
+               return epuc("unknown compression type", "PSD has an unknown compression format");\r
+\r
+       // Create the destination image.\r
+       out = (stbi_uc *) malloc(4 * w*h);\r
+       if (!out) return epuc("outofmem", "Out of memory");\r
+   pixelCount = w*h;\r
+\r
+       // Initialize the data to zero.\r
+       //memset( out, 0, pixelCount * 4 );\r
+       \r
+       // Finally, the image data.\r
+       if (compression) {\r
+               // RLE as used by .PSD and .TIFF\r
+               // Loop until you get the number of unpacked bytes you are expecting:\r
+               //     Read the next source byte into n.\r
+               //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.\r
+               //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.\r
+               //     Else if n is 128, noop.\r
+               // Endloop\r
+\r
+               // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,\r
+               // which we're going to just skip.\r
+               skip( h * channelCount * 2 );\r
+\r
+               // Read the RLE data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+                       \r
+         p = out+channel;\r
+                       if (channel >= channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;\r
+                       } else {\r
+                               // Read the RLE data.\r
+                               count = 0;\r
+                               while (count < pixelCount) {\r
+                                       len = get8();\r
+                                       if (len == 128) {\r
+                                               // No-op.\r
+                                       } else if (len < 128) {\r
+                                               // Copy next len+1 bytes literally.\r
+                                               len++;\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = get8();\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       } else if (len > 128) {\r
+                                               uint32  val;\r
+                                               // Next -len+1 bytes in the dest are replicated from next source byte.\r
+                                               // (Interpret len as a negative 8-bit int.)\r
+                                               len ^= 0x0FF;\r
+                                               len += 2;\r
+                  val = get8();\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = val;\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+       } else {\r
+               // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)\r
+               // where each channel consists of an 8-bit value for each pixel in the image.\r
+               \r
+               // Read the data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+                       \r
+         p = out + channel;\r
+                       if (channel > channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;\r
+                       } else {\r
+                               // Read the data.\r
+                               count = 0;\r
+                               for (i = 0; i < pixelCount; i++)\r
+                                       *p = get8(), p += 4;\r
+                       }\r
+               }\r
+       }\r
+\r
+       if (req_comp && req_comp != 4) {\r
+      img_x = w;\r
+      img_y = h;\r
+               out = convert_format(out, 4, req_comp);\r
+               if (out == NULL) return out; // convert_format frees input on failure\r
+       }\r
+\r
+       if (comp) *comp = channelCount;\r
+       *y = h;\r
+       *x = w;\r
+       \r
+       return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_psd_load(char *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_psd_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return psd_load(x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_psd_load_from_memory (stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer, len);\r
+   return psd_load(x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Radiance RGBE HDR loader\r
+// originally by Nicolas Schulz\r
+#ifndef STBI_NO_HDR\r
+static int hdr_test(void)\r
+{\r
+   char *signature = "#?RADIANCE\n";\r
+   int i;\r
+   for (i=0; signature[i]; ++i)\r
+      if (get8() != signature[i])\r
+         return 0;\r
+       return 1;\r
+}\r
+\r
+int stbi_hdr_test_memory(stbi_uc *buffer, int len)\r
+{\r
+       start_mem(buffer, len);\r
+       return hdr_test();\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_hdr_test_file(FILE *f)\r
+{\r
+   int r,n = ftell(f);\r
+   start_file(f);\r
+   r = hdr_test();\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+#define HDR_BUFLEN  1024\r
+static char *hdr_gettoken(char *buffer)\r
+{\r
+   int len=0;\r
+       char *s = buffer, c = '\0';\r
+\r
+   c = get8();\r
+\r
+       while (!at_eof() && c != '\n') {\r
+               buffer[len++] = c;\r
+      if (len == HDR_BUFLEN-1) {\r
+         // flush to end of line\r
+         while (!at_eof() && get8() != '\n')\r
+            ;\r
+         break;\r
+      }\r
+      c = get8();\r
+       }\r
+\r
+   buffer[len] = 0;\r
+       return buffer;\r
+}\r
+\r
+static void hdr_convert(float *output, stbi_uc *input, int req_comp)\r
+{\r
+       if( input[3] != 0 ) {\r
+      float f1;\r
+               // Exponent\r
+               f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));\r
+      if (req_comp <= 2)\r
+         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;\r
+      else {\r
+         output[0] = input[0] * f1;\r
+         output[1] = input[1] * f1;\r
+         output[2] = input[2] * f1;\r
+      }\r
+      if (req_comp == 2) output[1] = 1;\r
+      if (req_comp == 4) output[3] = 1;\r
+       } else {\r
+      switch (req_comp) {\r
+         case 4: output[3] = 1; /* fallthrough */\r
+         case 3: output[0] = output[1] = output[2] = 0;\r
+                 break;\r
+         case 2: output[1] = 1; /* fallthrough */\r
+         case 1: output[0] = 0;\r
+                 break;\r
+      }\r
+       }\r
+}\r
+\r
+\r
+static float *hdr_load(int *x, int *y, int *comp, int req_comp)\r
+{\r
+   char buffer[HDR_BUFLEN];\r
+       char *token;\r
+       int valid = 0;\r
+       int width, height;\r
+   stbi_uc *scanline;\r
+       float *hdr_data;\r
+       int len;\r
+       unsigned char count, value;\r
+       int i, j, k, c1,c2, z;\r
+\r
+\r
+       // Check identifier\r
+       if (strcmp(hdr_gettoken(buffer), "#?RADIANCE") != 0)\r
+               return epf("not HDR", "Corrupt HDR image");\r
+       \r
+       // Parse header\r
+       while(1) {\r
+               token = hdr_gettoken(buffer);\r
+      if (token[0] == 0) break;\r
+               if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;\r
+   }\r
+\r
+       if (!valid)    return epf("unsupported format", "Unsupported HDR format");\r
+\r
+   // Parse width and height\r
+   // can't use sscanf() if we're not using stdio!\r
+   token = hdr_gettoken(buffer);\r
+   if (strncmp(token, "-Y ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   height = strtol(token, &token, 10);\r
+   while (*token == ' ') ++token;\r
+   if (strncmp(token, "+X ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   width = strtol(token, NULL, 10);\r
+\r
+       *x = width;\r
+       *y = height;\r
+\r
+   *comp = 3;\r
+       if (req_comp == 0) req_comp = 3;\r
+\r
+       // Read data\r
+       hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));\r
+\r
+       // Load image data\r
+   // image data is stored as some number of sca\r
+       if( width < 8 || width >= 32768) {\r
+               // Read flat data\r
+      for (j=0; j < height; ++j) {\r
+         for (i=0; i < width; ++i) {\r
+            stbi_uc rgbe[4];\r
+           main_decode_loop:\r
+            getn(rgbe, 4);\r
+            hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);\r
+         }\r
+      }\r
+       } else {\r
+               // Read RLE-encoded data\r
+               scanline = NULL;\r
+\r
+               for (j = 0; j < height; ++j) {\r
+         c1 = get8();\r
+         c2 = get8();\r
+         len = get8();\r
+         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\r
+            // not run-length encoded, so we have to actually use THIS data as a decoded\r
+            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\r
+            stbi_uc rgbe[4] = { c1,c2,len, get8() };\r
+            hdr_convert(hdr_data, rgbe, req_comp);\r
+            i = 1;\r
+            j = 0;\r
+            free(scanline);\r
+            goto main_decode_loop; // yes, this is fucking insane; blame the fucking insane format\r
+         }\r
+         len <<= 8;\r
+         len |= get8();\r
+         if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }\r
+         if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);\r
+                               \r
+                       for (k = 0; k < 4; ++k) {\r
+                               i = 0;\r
+                               while (i < width) {\r
+                                       count = get8();\r
+                                       if (count > 128) {\r
+                                               // Run\r
+                                               value = get8();\r
+                  count -= 128;\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = value;\r
+                                       } else {\r
+                                               // Dump\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = get8();\r
+                                       }\r
+                               }\r
+                       }\r
+         for (i=0; i < width; ++i)\r
+            hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);\r
+               }\r
+      free(scanline);\r
+       }\r
+\r
+   return hdr_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_file(f);\r
+   return hdr_load(x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+float *stbi_hdr_load_from_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   start_mem(buffer, len);\r
+   return hdr_load(x,y,comp,req_comp);\r
+}\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+/////////////////////// write image ///////////////////////\r
+\r
+#ifndef STBI_NO_WRITE\r
+\r
+static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); }\r
+\r
+static void writefv(FILE *f, char *fmt, va_list v)\r
+{\r
+   while (*fmt) {\r
+      switch (*fmt++) {\r
+         case ' ': break;\r
+         case '1': { uint8 x = va_arg(v, int); write8(f,x); break; }\r
+         case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; }\r
+         case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; }\r
+         default:\r
+            assert(0);\r
+            va_end(v);\r
+            return;\r
+      }\r
+   }\r
+}\r
+\r
+static void writef(FILE *f, char *fmt, ...)\r
+{\r
+   va_list v;\r
+   va_start(v, fmt);\r
+   writefv(f,fmt,v);\r
+   va_end(v);\r
+}\r
+\r
+static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)\r
+{\r
+   uint8 bg[3] = { 255, 0, 255}, px[3];\r
+   uint32 zero = 0;\r
+   int i,j,k, j_end;\r
+\r
+   if (vdir < 0) \r
+      j_end = -1, j = y-1;\r
+   else\r
+      j_end =  y, j = 0;\r
+\r
+   for (; j != j_end; j += vdir) {\r
+      for (i=0; i < x; ++i) {\r
+         uint8 *d = (uint8 *) data + (j*x+i)*comp;\r
+         if (write_alpha < 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+         switch (comp) {\r
+            case 1:\r
+            case 2: writef(f, "111", d[0],d[0],d[0]);\r
+                    break;\r
+            case 4:\r
+               if (!write_alpha) {\r
+                  for (k=0; k < 3; ++k)\r
+                     px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;\r
+                  writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]);\r
+                  break;\r
+               }\r
+               /* FALLTHROUGH */\r
+            case 3:\r
+               writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]);\r
+               break;\r
+         }\r
+         if (write_alpha > 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+      }\r
+      fwrite(&zero,scanline_pad,1,f);\r
+   }\r
+}\r
+\r
+static int outfile(char *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...)\r
+{\r
+   FILE *f = fopen(filename, "wb");\r
+   if (f) {\r
+      va_list v;\r
+      va_start(v, fmt);\r
+      writefv(f, fmt, v);\r
+      va_end(v);\r
+      write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);\r
+      fclose(f);\r
+   }\r
+   return f != NULL;\r
+}\r
+\r
+int stbi_write_bmp(char *filename, int x, int y, int comp, void *data)\r
+{\r
+   int pad = (-x*3) & 3;\r
+   return outfile(filename,-1,-1,x,y,comp,data,0,pad,\r
+           "11 4 22 4" "4 44 22 444444",\r
+           'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header\r
+            40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header\r
+}\r
+\r
+int stbi_write_tga(char *filename, int x, int y, int comp, void *data)\r
+{\r
+   int has_alpha = !(comp & 1);\r
+   return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,\r
+                  "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);\r
+}\r
+\r
+// any other image formats that do interleaved rgb data?\r
+//    PNG: requires adler32,crc32 -- significant amount of code\r
+//    PSD: no, channels output separately\r
+//    TIFF: no, stripwise-interleaved... i think\r
+\r
+#endif // STBI_NO_WRITE\r
diff --git a/lib/soil/soil/original/stb_image-1.16.c b/lib/soil/soil/original/stb_image-1.16.c
new file mode 100644 (file)
index 0000000..029b58e
--- /dev/null
@@ -0,0 +1,3821 @@
+/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r
+                      when you control the images you're loading\r
+\r
+   QUICK NOTES:\r
+      Primarily of interest to game developers and other people who can\r
+          avoid problematic images and only need the trivial interface\r
+\r
+      JPEG baseline (no JPEG progressive, no oddball channel decimations)\r
+      PNG non-interlaced\r
+      BMP non-1bpp, non-RLE\r
+      TGA (not sure what subset, if a subset)\r
+      PSD (composited view only, no extra channels)\r
+      HDR (radiance rgbE format)\r
+      writes BMP,TGA (define STBI_NO_WRITE to remove code)\r
+      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)\r
+      supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)\r
+        \r
+   TODO:\r
+      stbi_info_*\r
+  \r
+   history:\r
+      1.16   major bugfix - convert_format converted one too many pixels\r
+      1.15   initialize some fields for thread safety\r
+      1.14   fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)\r
+      1.13   threadsafe\r
+      1.12   const qualifiers in the API\r
+      1.11   Support installable IDCT, colorspace conversion routines\r
+      1.10   Fixes for 64-bit (don't use "unsigned long")\r
+             optimized upsampling by Fabian "ryg" Giesen\r
+      1.09   Fix format-conversion for PSD code (bad global variables!)\r
+      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz\r
+      1.07   attempt to fix C++ warning/errors again\r
+      1.06   attempt to fix C++ warning/errors again\r
+      1.05   fix TGA loading to return correct *comp and use good luminance calc\r
+      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free\r
+      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR\r
+      1.02   support for (subset of) HDR files, float interface for preferred access to them\r
+      1.01   fix bug: possible bug in handling right-side up bmps... not sure\r
+             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all\r
+      1.00   interface to zlib that skips zlib header\r
+      0.99   correct handling of alpha in palette\r
+      0.98   TGA loader by lonesock; dynamically add loaders (untested)\r
+      0.97   jpeg errors on too large a file; also catch another malloc failure\r
+      0.96   fix detection of invalid v value - particleman@mollyrocket forum\r
+      0.95   during header scan, seek to markers in case of padding\r
+      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same\r
+      0.93   handle jpegtran output; verbose errors\r
+      0.92   read 4,8,16,24,32-bit BMP files of several formats\r
+      0.91   output 24-bit Windows 3.0 BMP files\r
+      0.90   fix a few more warnings; bump version number to approach 1.0\r
+      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd\r
+      0.60   fix compiling as c++\r
+      0.59   fix warnings: merge Dave Moore's -Wall fixes\r
+      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian\r
+      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less\r
+                      than 16 available\r
+      0.56   fix bug: zlib uncompressed mode len vs. nlen\r
+      0.55   fix bug: restart_interval not initialized to 0\r
+      0.54   allow NULL for 'int *comp'\r
+      0.53   fix bug in png 3->4; speedup png decoding\r
+      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments\r
+      0.51   obey req_comp requests, 1-component jpegs return as 1-component,\r
+             on 'test' only check type, not whether we support this variant\r
+*/\r
+\r
+\r
+#ifndef STBI_INCLUDE_STB_IMAGE_H\r
+#define STBI_INCLUDE_STB_IMAGE_H\r
+\r
+////   begin header file  ////////////////////////////////////////////////////\r
+//\r
+// Limitations:\r
+//    - no progressive/interlaced support (jpeg, png)\r
+//    - 8-bit samples only (jpeg, png)\r
+//    - not threadsafe\r
+//    - channel subsampling of at most 2 in each dimension (jpeg)\r
+//    - no delayed line count (jpeg) -- IJG doesn't support either\r
+//\r
+// Basic usage (see HDR discussion below):\r
+//    int x,y,n;\r
+//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);\r
+//    // ... process data if not NULL ... \r
+//    // ... x = width, y = height, n = # 8-bit components per pixel ...\r
+//    // ... replace '0' with '1'..'4' to force that many components per pixel\r
+//    stbi_image_free(data)\r
+//\r
+// Standard parameters:\r
+//    int *x       -- outputs image width in pixels\r
+//    int *y       -- outputs image height in pixels\r
+//    int *comp    -- outputs # of image components in image file\r
+//    int req_comp -- if non-zero, # of image components requested in result\r
+//\r
+// The return value from an image loader is an 'unsigned char *' which points\r
+// to the pixel data. The pixel data consists of *y scanlines of *x pixels,\r
+// with each pixel consisting of N interleaved 8-bit components; the first\r
+// pixel pointed to is top-left-most in the image. There is no padding between\r
+// image scanlines or between pixels, regardless of format. The number of\r
+// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.\r
+// If req_comp is non-zero, *comp has the number of components that _would_\r
+// have been output otherwise. E.g. if you set req_comp to 4, you will always\r
+// get RGBA output, but you can check *comp to easily see if it's opaque.\r
+//\r
+// An output image with N components has the following components interleaved\r
+// in this order in each pixel:\r
+//\r
+//     N=#comp     components\r
+//       1           grey\r
+//       2           grey, alpha\r
+//       3           red, green, blue\r
+//       4           red, green, blue, alpha\r
+//\r
+// If image loading fails for any reason, the return value will be NULL,\r
+// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()\r
+// can be queried for an extremely brief, end-user unfriendly explanation\r
+// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid\r
+// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly\r
+// more user-friendly ones.\r
+//\r
+// Paletted PNG and BMP images are automatically depalettized.\r
+//\r
+//\r
+// ===========================================================================\r
+//\r
+// HDR image support   (disable by defining STBI_NO_HDR)\r
+//\r
+// stb_image now supports loading HDR images in general, and currently\r
+// the Radiance .HDR file format, although the support is provided\r
+// generically. You can still load any file through the existing interface;\r
+// if you attempt to load an HDR file, it will be automatically remapped to\r
+// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;\r
+// both of these constants can be reconfigured through this interface:\r
+//\r
+//     stbi_hdr_to_ldr_gamma(2.2f);\r
+//     stbi_hdr_to_ldr_scale(1.0f);\r
+//\r
+// (note, do not use _inverse_ constants; stbi_image will invert them\r
+// appropriately).\r
+//\r
+// Additionally, there is a new, parallel interface for loading files as\r
+// (linear) floats to preserve the full dynamic range:\r
+//\r
+//    float *data = stbi_loadf(filename, &x, &y, &n, 0);\r
+// \r
+// If you load LDR images through this interface, those images will\r
+// be promoted to floating point values, run through the inverse of\r
+// constants corresponding to the above:\r
+//\r
+//     stbi_ldr_to_hdr_scale(1.0f);\r
+//     stbi_ldr_to_hdr_gamma(2.2f);\r
+//\r
+// Finally, given a filename (or an open file or memory block--see header\r
+// file for details) containing image data, you can query for the "most\r
+// appropriate" interface to use (that is, whether the image is HDR or\r
+// not), using:\r
+//\r
+//     stbi_is_hdr(char *filename);\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+\r
+#define STBI_VERSION 1\r
+\r
+enum\r
+{\r
+   STBI_default = 0, // only used for req_comp\r
+\r
+   STBI_grey       = 1,\r
+   STBI_grey_alpha = 2,\r
+   STBI_rgb        = 3,\r
+   STBI_rgb_alpha  = 4,\r
+};\r
+\r
+typedef unsigned char stbi_uc;\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+// WRITING API\r
+\r
+#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)\r
+// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)\r
+// (you must include the appropriate extension in the filename).\r
+// returns TRUE on success, FALSE if couldn't open file, error writing file\r
+extern int      stbi_write_bmp       (char const *filename,     int x, int y, int comp, void *data);\r
+extern int      stbi_write_tga       (char const *filename,     int x, int y, int comp, void *data);\r
+#endif\r
+\r
+// PRIMARY API - works on images of any type\r
+\r
+// load image by filename, open file, or memory buffer\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+// for stbi_load_from_file, file pointer is left pointing immediately after image\r
+\r
+#ifndef STBI_NO_HDR\r
+#ifndef STBI_NO_STDIO\r
+extern float *stbi_loadf            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern float *stbi_loadf_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+\r
+extern void   stbi_hdr_to_ldr_gamma(float gamma);\r
+extern void   stbi_hdr_to_ldr_scale(float scale);\r
+\r
+extern void   stbi_ldr_to_hdr_gamma(float gamma);\r
+extern void   stbi_ldr_to_hdr_scale(float scale);\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+// get a VERY brief reason for failure\r
+// NOT THREADSAFE\r
+extern char    *stbi_failure_reason  (void); \r
+\r
+// free the loaded image -- this is just free()\r
+extern void     stbi_image_free      (void *retval_from_stbi_load);\r
+\r
+// get image dimensions & components without fully decoding\r
+extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr          (char const *filename);\r
+extern int      stbi_is_hdr_from_file(FILE *f);\r
+#endif\r
+\r
+// ZLIB client - used by PNG, available for other purposes\r
+\r
+extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);\r
+extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\r
+\r
+extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\r
+\r
+// TYPE-SPECIFIC ACCESS\r
+\r
+// is it a jpeg?\r
+extern int      stbi_jpeg_test_memory     (stbi_uc const *buffer, int len);\r
+extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_jpeg_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_test_file       (FILE *f);\r
+extern stbi_uc *stbi_jpeg_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+\r
+extern int      stbi_jpeg_info            (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+// is it a png?\r
+extern int      stbi_png_test_memory      (stbi_uc const *buffer, int len);\r
+extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_png_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info             (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_png_test_file        (FILE *f);\r
+extern stbi_uc *stbi_png_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+// is it a bmp?\r
+extern int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_bmp_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_bmp_test_file        (FILE *f);\r
+extern stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a tga?\r
+extern int      stbi_tga_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_tga_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_tga_test_file        (FILE *f);\r
+extern stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a psd?\r
+extern int      stbi_psd_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_psd_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_psd_test_file        (FILE *f);\r
+extern stbi_uc *stbi_psd_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it an hdr?\r
+extern int      stbi_hdr_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern float *  stbi_hdr_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern float *  stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_hdr_test_file        (FILE *f);\r
+extern float *  stbi_hdr_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// define new loaders\r
+typedef struct\r
+{\r
+   int       (*test_memory)(stbi_uc const *buffer, int len);\r
+   stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+   #ifndef STBI_NO_STDIO\r
+   int       (*test_file)(FILE *f);\r
+   stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);\r
+   #endif\r
+} stbi_loader;\r
+\r
+// register a loader by filling out the above structure (you must defined ALL functions)\r
+// returns 1 if added or already added, 0 if not added (too many loaders)\r
+// NOT THREADSAFE\r
+extern int stbi_register_loader(stbi_loader *loader);\r
+\r
+// define faster low-level operations (typically SIMD support)\r
+#if STBI_SIMD\r
+typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize);\r
+// compute an integer IDCT on "input"\r
+//     input[x] = data[x] * dequantize[x]\r
+//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'\r
+//                             CLAMP results to 0..255\r
+typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step);\r
+// compute a conversion from YCbCr to RGB\r
+//     'count' pixels\r
+//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B\r
+//     y: Y input channel\r
+//     cb: Cb input channel; scale/biased to be 0..255\r
+//     cr: Cr input channel; scale/biased to be 0..255\r
+\r
+extern void stbi_install_idct(stbi_idct_8x8 func);\r
+extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);\r
+#endif // STBI_SIMD\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+//\r
+//\r
+////   end header file   /////////////////////////////////////////////////////\r
+#endif // STBI_INCLUDE_STB_IMAGE_H\r
+\r
+#ifndef STBI_HEADER_FILE_ONLY\r
+\r
+#ifndef STBI_NO_HDR\r
+#include <math.h>  // ldexp\r
+#include <string.h> // strcmp\r
+#endif\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+#include <stdlib.h>\r
+#include <memory.h>\r
+#include <assert.h>\r
+#include <stdarg.h>\r
+\r
+#ifndef _MSC_VER\r
+  #ifdef __cplusplus\r
+  #define __forceinline inline\r
+  #else\r
+  #define __forceinline\r
+  #endif\r
+#endif\r
+\r
+\r
+// implementation:\r
+typedef unsigned char uint8;\r
+typedef unsigned short uint16;\r
+typedef   signed short  int16;\r
+typedef unsigned int   uint32;\r
+typedef   signed int    int32;\r
+typedef unsigned int   uint;\r
+\r
+// should produce compiler error if size is wrong\r
+typedef unsigned char validate_uint32[sizeof(uint32)==4];\r
+\r
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)\r
+#define STBI_NO_WRITE\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Generic API that works on all image types\r
+//\r
+\r
+// this is not threadsafe\r
+static char *failure_reason;\r
+\r
+char *stbi_failure_reason(void)\r
+{\r
+   return failure_reason;\r
+}\r
+\r
+static int e(char *str)\r
+{\r
+   failure_reason = str;\r
+   return 0;\r
+}\r
+\r
+#ifdef STBI_NO_FAILURE_STRINGS\r
+   #define e(x,y)  0\r
+#elif defined(STBI_FAILURE_USERMSG)\r
+   #define e(x,y)  e(y)\r
+#else\r
+   #define e(x,y)  e(x)\r
+#endif\r
+\r
+#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))\r
+#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))\r
+\r
+void stbi_image_free(void *retval_from_stbi_load)\r
+{\r
+   free(retval_from_stbi_load);\r
+}\r
+\r
+#define MAX_LOADERS  32\r
+stbi_loader *loaders[MAX_LOADERS];\r
+static int max_loaders = 0;\r
+\r
+int stbi_register_loader(stbi_loader *loader)\r
+{\r
+   int i;\r
+   for (i=0; i < MAX_LOADERS; ++i) {\r
+      // already present?\r
+      if (loaders[i] == loader)\r
+         return 1;\r
+      // end of the list?\r
+      if (loaders[i] == NULL) {\r
+         loaders[i] = loader;\r
+         max_loaders = i+1;\r
+         return 1;\r
+      }\r
+   }\r
+   // no room for it\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);\r
+#endif\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   unsigned char *result;\r
+   if (!f) return epuc("can't fopen", "Unable to open file");\r
+   result = stbi_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_file(f))\r
+      return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_png_test_file(f))\r
+      return stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_file(f))\r
+      return stbi_bmp_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_psd_test_file(f))\r
+      return stbi_psd_load_from_file(f,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f)) {\r
+      float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_file(f))\r
+         return loaders[i]->load_from_file(f,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_file(f))\r
+      return stbi_tga_load_from_file(f,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_memory(buffer,len))\r
+      return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_png_test_memory(buffer,len))\r
+      return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_memory(buffer,len))\r
+      return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_psd_test_memory(buffer,len))\r
+      return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len)) {\r
+      float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_memory(buffer,len))\r
+         return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_memory(buffer,len))\r
+      return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   float *result;\r
+   if (!f) return epf("can't fopen", "Unable to open file");\r
+   result = stbi_loadf_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f))\r
+      return stbi_hdr_load_from_file(f,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_file(f, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len))\r
+      return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is\r
+// defined, for API simplicity; if STBI_NO_HDR is defined, it always\r
+// reports false!\r
+\r
+int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_memory(buffer, len);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_is_hdr          (char const *filename)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   int result=0;\r
+   if (f) {\r
+      result = stbi_is_hdr_from_file(f);\r
+      fclose(f);\r
+   }\r
+   return result;\r
+}\r
+\r
+extern int      stbi_is_hdr_from_file(FILE *f)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_file(f);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#endif\r
+\r
+// @TODO: get image dimensions & components without fully decoding\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_HDR\r
+static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;\r
+static float l2h_gamma=2.2f, l2h_scale=1.0f;\r
+\r
+void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }\r
+void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }\r
+\r
+void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }\r
+void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }\r
+#endif\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Common code used by all image loaders\r
+//\r
+\r
+enum\r
+{\r
+   SCAN_load=0,\r
+   SCAN_type,\r
+   SCAN_header,\r
+};\r
+\r
+typedef struct\r
+{\r
+   uint32 img_x, img_y;\r
+   int img_n, img_out_n;\r
+\r
+   #ifndef STBI_NO_STDIO\r
+   FILE  *img_file;\r
+   #endif\r
+   uint8 *img_buffer, *img_buffer_end;\r
+} stbi;\r
+\r
+#ifndef STBI_NO_STDIO\r
+static void start_file(stbi *s, FILE *f)\r
+{\r
+   s->img_file = f;\r
+}\r
+#endif\r
+\r
+static void start_mem(stbi *s, uint8 const *buffer, int len)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   s->img_file = NULL;\r
+#endif\r
+   s->img_buffer = (uint8 *) buffer;\r
+   s->img_buffer_end = (uint8 *) buffer+len;\r
+}\r
+\r
+__forceinline static int get8(stbi *s)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file) {\r
+      int c = fgetc(s->img_file);\r
+      return c == EOF ? 0 : c;\r
+   }\r
+#endif\r
+   if (s->img_buffer < s->img_buffer_end)\r
+      return *s->img_buffer++;\r
+   return 0;\r
+}\r
+\r
+__forceinline static int at_eof(stbi *s)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file)\r
+      return feof(s->img_file);\r
+#endif\r
+   return s->img_buffer >= s->img_buffer_end;   \r
+}\r
+\r
+__forceinline static uint8 get8u(stbi *s)\r
+{\r
+   return (uint8) get8(s);\r
+}\r
+\r
+static void skip(stbi *s, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file)\r
+      fseek(s->img_file, n, SEEK_CUR);\r
+   else\r
+#endif\r
+      s->img_buffer += n;\r
+}\r
+\r
+static int get16(stbi *s)\r
+{\r
+   int z = get8(s);\r
+   return (z << 8) + get8(s);\r
+}\r
+\r
+static uint32 get32(stbi *s)\r
+{\r
+   uint32 z = get16(s);\r
+   return (z << 16) + get16(s);\r
+}\r
+\r
+static int get16le(stbi *s)\r
+{\r
+   int z = get8(s);\r
+   return z + (get8(s) << 8);\r
+}\r
+\r
+static uint32 get32le(stbi *s)\r
+{\r
+   uint32 z = get16le(s);\r
+   return z + (get16le(s) << 16);\r
+}\r
+\r
+static void getn(stbi *s, stbi_uc *buffer, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file) {\r
+      fread(buffer, 1, n, s->img_file);\r
+      return;\r
+   }\r
+#endif\r
+   memcpy(buffer, s->img_buffer, n);\r
+   s->img_buffer += n;\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  generic converter from built-in img_n to req_comp\r
+//    individual types do this automatically as much as possible (e.g. jpeg\r
+//    does all cases internally since it needs to colorspace convert anyway,\r
+//    and it never has alpha, so very few cases ). png can automatically\r
+//    interleave an alpha=255 channel, but falls back to this for other cases\r
+//\r
+//  assume data buffer is malloced, so malloc a new one and free that one\r
+//  only failure mode is malloc failing\r
+\r
+static uint8 compute_y(int r, int g, int b)\r
+{\r
+   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);\r
+}\r
+\r
+static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)\r
+{\r
+   int i,j;\r
+   unsigned char *good;\r
+\r
+   if (req_comp == img_n) return data;\r
+   assert(req_comp >= 1 && req_comp <= 4);\r
+\r
+   good = (unsigned char *) malloc(req_comp * x * y);\r
+   if (good == NULL) {\r
+      free(data);\r
+      return epuc("outofmem", "Out of memory");\r
+   }\r
+\r
+   for (j=0; j < (int) y; ++j) {\r
+      unsigned char *src  = data + j * x * img_n   ;\r
+      unsigned char *dest = good + j * x * req_comp;\r
+\r
+      #define COMBO(a,b)  ((a)*8+(b))\r
+      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\r
+      // convert source image with img_n components to one with req_comp components;\r
+      // avoid switch per pixel, so use switch per scanline and massive macros\r
+      switch(COMBO(img_n, req_comp)) {\r
+         CASE(1,2) dest[0]=src[0], dest[1]=255; break;\r
+         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;\r
+         CASE(2,1) dest[0]=src[0]; break;\r
+         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;\r
+         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;\r
+         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;\r
+         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;\r
+         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;\r
+         default: assert(0);\r
+      }\r
+      #undef CASE\r
+   }\r
+\r
+   free(data);\r
+   return good;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   float *output = (float *) malloc(x * y * comp * sizeof(float));\r
+   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;\r
+      }\r
+      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+\r
+#define float2int(x)   ((int) (x))\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);\r
+   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+      if (k < comp) {\r
+         float z = data[i*comp+k] * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)\r
+//\r
+//    simple implementation\r
+//      - channel subsampling of at most 2 in each dimension\r
+//      - doesn't support delayed output of y-dimension\r
+//      - simple interface (only one output format: 8-bit interleaved RGB)\r
+//      - doesn't try to recover corrupt jpegs\r
+//      - doesn't allow partial loading, loading multiple at once\r
+//      - still fast on x86 (copying globals into locals doesn't help x86)\r
+//      - allocates lots of intermediate memory (full size of all components)\r
+//        - non-interleaved case requires this anyway\r
+//        - allows good upsampling (see next)\r
+//    high-quality\r
+//      - upsampled channels are bilinearly interpolated, even across blocks\r
+//      - quality integer IDCT derived from IJG's 'slow'\r
+//    performance\r
+//      - fast huffman; reasonable integer IDCT\r
+//      - uses a lot of intermediate memory, could cache poorly\r
+//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4\r
+//          stb_jpeg:   1.34 seconds (MSVC6, default release build)\r
+//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)\r
+//          IJL11.dll:  1.08 seconds (compiled by intel)\r
+//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)\r
+//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)\r
+\r
+// huffman decoding acceleration\r
+#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache\r
+\r
+typedef struct\r
+{\r
+   uint8  fast[1 << FAST_BITS];\r
+   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win\r
+   uint16 code[256];\r
+   uint8  values[256];\r
+   uint8  size[257];\r
+   unsigned int maxcode[18];\r
+   int    delta[17];   // old 'firstsymbol' - old 'firstcode'\r
+} huffman;\r
+\r
+typedef struct\r
+{\r
+   #if STBI_SIMD\r
+   unsigned short dequant2[4][64];\r
+   #endif\r
+   stbi s;\r
+   huffman huff_dc[4];\r
+   huffman huff_ac[4];\r
+   uint8 dequant[4][64];\r
+\r
+// sizes for components, interleaved MCUs\r
+   int img_h_max, img_v_max;\r
+   int img_mcu_x, img_mcu_y;\r
+   int img_mcu_w, img_mcu_h;\r
+\r
+// definition of jpeg image component\r
+   struct\r
+   {\r
+      int id;\r
+      int h,v;\r
+      int tq;\r
+      int hd,ha;\r
+      int dc_pred;\r
+\r
+      int x,y,w2,h2;\r
+      uint8 *data;\r
+      void *raw_data;\r
+      uint8 *linebuf;\r
+   } img_comp[4];\r
+\r
+   uint32         code_buffer; // jpeg entropy-coded buffer\r
+   int            code_bits;   // number of valid bits\r
+   unsigned char  marker;      // marker seen while filling entropy buffer\r
+   int            nomore;      // flag if we saw a marker so must stop\r
+\r
+   int scan_n, order[4];\r
+   int restart_interval, todo;\r
+} jpeg;\r
+\r
+static int build_huffman(huffman *h, int *count)\r
+{\r
+   int i,j,k=0,code;\r
+   // build size list for each symbol (from JPEG spec)\r
+   for (i=0; i < 16; ++i)\r
+      for (j=0; j < count[i]; ++j)\r
+         h->size[k++] = (uint8) (i+1);\r
+   h->size[k] = 0;\r
+\r
+   // compute actual symbols (from jpeg spec)\r
+   code = 0;\r
+   k = 0;\r
+   for(j=1; j <= 16; ++j) {\r
+      // compute delta to add to code to compute symbol id\r
+      h->delta[j] = k - code;\r
+      if (h->size[k] == j) {\r
+         while (h->size[k] == j)\r
+            h->code[k++] = (uint16) (code++);\r
+         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");\r
+      }\r
+      // compute largest code + 1 for this size, preshifted as needed later\r
+      h->maxcode[j] = code << (16-j);\r
+      code <<= 1;\r
+   }\r
+   h->maxcode[j] = 0xffffffff;\r
+\r
+   // build non-spec acceleration table; 255 is flag for not-accelerated\r
+   memset(h->fast, 255, 1 << FAST_BITS);\r
+   for (i=0; i < k; ++i) {\r
+      int s = h->size[i];\r
+      if (s <= FAST_BITS) {\r
+         int c = h->code[i] << (FAST_BITS-s);\r
+         int m = 1 << (FAST_BITS-s);\r
+         for (j=0; j < m; ++j) {\r
+            h->fast[c+j] = (uint8) i;\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static void grow_buffer_unsafe(jpeg *j)\r
+{\r
+   do {\r
+      int b = j->nomore ? 0 : get8(&j->s);\r
+      if (b == 0xff) {\r
+         int c = get8(&j->s);\r
+         if (c != 0) {\r
+            j->marker = (unsigned char) c;\r
+            j->nomore = 1;\r
+            return;\r
+         }\r
+      }\r
+      j->code_buffer = (j->code_buffer << 8) | b;\r
+      j->code_bits += 8;\r
+   } while (j->code_bits <= 24);\r
+}\r
+\r
+// (1 << n) - 1\r
+static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};\r
+\r
+// decode a jpeg huffman value from the bitstream\r
+__forceinline static int decode(jpeg *j, huffman *h)\r
+{\r
+   unsigned int temp;\r
+   int c,k;\r
+\r
+   if (j->code_bits < 16) grow_buffer_unsafe(j);\r
+\r
+   // look at the top FAST_BITS and determine what symbol ID it is,\r
+   // if the code is <= FAST_BITS\r
+   c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);\r
+   k = h->fast[c];\r
+   if (k < 255) {\r
+      if (h->size[k] > j->code_bits)\r
+         return -1;\r
+      j->code_bits -= h->size[k];\r
+      return h->values[k];\r
+   }\r
+\r
+   // naive test is to shift the code_buffer down so k bits are\r
+   // valid, then test against maxcode. To speed this up, we've\r
+   // preshifted maxcode left so that it has (16-k) 0s at the\r
+   // end; in other words, regardless of the number of bits, it\r
+   // wants to be compared against something shifted to have 16;\r
+   // that way we don't need to shift inside the loop.\r
+   if (j->code_bits < 16)\r
+      temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;\r
+   else\r
+      temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;\r
+   for (k=FAST_BITS+1 ; ; ++k)\r
+      if (temp < h->maxcode[k])\r
+         break;\r
+   if (k == 17) {\r
+      // error! code not found\r
+      j->code_bits -= 16;\r
+      return -1;\r
+   }\r
+\r
+   if (k > j->code_bits)\r
+      return -1;\r
+\r
+   // convert the huffman code to the symbol id\r
+   c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];\r
+   assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);\r
+\r
+   // convert the id to a symbol\r
+   j->code_bits -= k;\r
+   return h->values[c];\r
+}\r
+\r
+// combined JPEG 'receive' and JPEG 'extend', since baseline\r
+// always extends everything it receives.\r
+__forceinline static int extend_receive(jpeg *j, int n)\r
+{\r
+   unsigned int m = 1 << (n-1);\r
+   unsigned int k;\r
+   if (j->code_bits < n) grow_buffer_unsafe(j);\r
+   k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];\r
+   j->code_bits -= n;\r
+   // the following test is probably a random branch that won't\r
+   // predict well. I tried to table accelerate it but failed.\r
+   // maybe it's compiling as a conditional move?\r
+   if (k < m)\r
+      return (-1 << n) + k + 1;\r
+   else\r
+      return k;\r
+}\r
+\r
+// given a value that's at position X in the zigzag stream,\r
+// where does it appear in the 8x8 matrix coded as row-major?\r
+static uint8 dezigzag[64+15] =\r
+{\r
+    0,  1,  8, 16,  9,  2,  3, 10,\r
+   17, 24, 32, 25, 18, 11,  4,  5,\r
+   12, 19, 26, 33, 40, 48, 41, 34,\r
+   27, 20, 13,  6,  7, 14, 21, 28,\r
+   35, 42, 49, 56, 57, 50, 43, 36,\r
+   29, 22, 15, 23, 30, 37, 44, 51,\r
+   58, 59, 52, 45, 38, 31, 39, 46,\r
+   53, 60, 61, 54, 47, 55, 62, 63,\r
+   // let corrupt input sample past end\r
+   63, 63, 63, 63, 63, 63, 63, 63,\r
+   63, 63, 63, 63, 63, 63, 63\r
+};\r
+\r
+// decode one 64-entry block--\r
+static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)\r
+{\r
+   int diff,dc,k;\r
+   int t = decode(j, hdc);\r
+   if (t < 0) return e("bad huffman code","Corrupt JPEG");\r
+\r
+   // 0 all the ac values now so we can do it 32-bits at a time\r
+   memset(data,0,64*sizeof(data[0]));\r
+\r
+   diff = t ? extend_receive(j, t) : 0;\r
+   dc = j->img_comp[b].dc_pred + diff;\r
+   j->img_comp[b].dc_pred = dc;\r
+   data[0] = (short) dc;\r
+\r
+   // decode AC components, see JPEG spec\r
+   k = 1;\r
+   do {\r
+      int r,s;\r
+      int rs = decode(j, hac);\r
+      if (rs < 0) return e("bad huffman code","Corrupt JPEG");\r
+      s = rs & 15;\r
+      r = rs >> 4;\r
+      if (s == 0) {\r
+         if (rs != 0xf0) break; // end block\r
+         k += 16;\r
+      } else {\r
+         k += r;\r
+         // decode into unzigzag'd location\r
+         data[dezigzag[k++]] = (short) extend_receive(j,s);\r
+      }\r
+   } while (k < 64);\r
+   return 1;\r
+}\r
+\r
+// take a -128..127 value and clamp it and convert to 0..255\r
+__forceinline static uint8 clamp(int x)\r
+{\r
+   x += 128;\r
+   // trick to use a single test to catch both cases\r
+   if ((unsigned int) x > 255) {\r
+      if (x < 0) return 0;\r
+      if (x > 255) return 255;\r
+   }\r
+   return (uint8) x;\r
+}\r
+\r
+#define f2f(x)  (int) (((x) * 4096 + 0.5))\r
+#define fsh(x)  ((x) << 12)\r
+\r
+// derived from jidctint -- DCT_ISLOW\r
+#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \\r
+   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \\r
+   p2 = s2;                                    \\r
+   p3 = s6;                                    \\r
+   p1 = (p2+p3) * f2f(0.5411961f);             \\r
+   t2 = p1 + p3*f2f(-1.847759065f);            \\r
+   t3 = p1 + p2*f2f( 0.765366865f);            \\r
+   p2 = s0;                                    \\r
+   p3 = s4;                                    \\r
+   t0 = fsh(p2+p3);                            \\r
+   t1 = fsh(p2-p3);                            \\r
+   x0 = t0+t3;                                 \\r
+   x3 = t0-t3;                                 \\r
+   x1 = t1+t2;                                 \\r
+   x2 = t1-t2;                                 \\r
+   t0 = s7;                                    \\r
+   t1 = s5;                                    \\r
+   t2 = s3;                                    \\r
+   t3 = s1;                                    \\r
+   p3 = t0+t2;                                 \\r
+   p4 = t1+t3;                                 \\r
+   p1 = t0+t3;                                 \\r
+   p2 = t1+t2;                                 \\r
+   p5 = (p3+p4)*f2f( 1.175875602f);            \\r
+   t0 = t0*f2f( 0.298631336f);                 \\r
+   t1 = t1*f2f( 2.053119869f);                 \\r
+   t2 = t2*f2f( 3.072711026f);                 \\r
+   t3 = t3*f2f( 1.501321110f);                 \\r
+   p1 = p5 + p1*f2f(-0.899976223f);            \\r
+   p2 = p5 + p2*f2f(-2.562915447f);            \\r
+   p3 = p3*f2f(-1.961570560f);                 \\r
+   p4 = p4*f2f(-0.390180644f);                 \\r
+   t3 += p1+p4;                                \\r
+   t2 += p2+p3;                                \\r
+   t1 += p2+p4;                                \\r
+   t0 += p1+p3;\r
+\r
+#if !STBI_SIMD\r
+// .344 seconds on 3*anemones.jpg\r
+static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)\r
+{\r
+   int i,val[64],*v=val;\r
+   uint8 *o,*dq = dequantize;\r
+   short *d = data;\r
+\r
+   // columns\r
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {\r
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\r
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\r
+           && d[40]==0 && d[48]==0 && d[56]==0) {\r
+         //    no shortcut                 0     seconds\r
+         //    (1|2|3|4|5|6|7)==0          0     seconds\r
+         //    all separate               -0.047 seconds\r
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\r
+         int dcterm = d[0] * dq[0] << 2;\r
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\r
+      } else {\r
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\r
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\r
+         // constants scaled things up by 1<<12; let's bring them back\r
+         // down, but keep 2 extra bits of precision\r
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\r
+         v[ 0] = (x0+t3) >> 10;\r
+         v[56] = (x0-t3) >> 10;\r
+         v[ 8] = (x1+t2) >> 10;\r
+         v[48] = (x1-t2) >> 10;\r
+         v[16] = (x2+t1) >> 10;\r
+         v[40] = (x2-t1) >> 10;\r
+         v[24] = (x3+t0) >> 10;\r
+         v[32] = (x3-t0) >> 10;\r
+      }\r
+   }\r
+\r
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\r
+      // no fast case since the first 1D IDCT spread components out\r
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\r
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first\r
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together\r
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.\r
+      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;\r
+      o[0] = clamp((x0+t3) >> 17);\r
+      o[7] = clamp((x0-t3) >> 17);\r
+      o[1] = clamp((x1+t2) >> 17);\r
+      o[6] = clamp((x1-t2) >> 17);\r
+      o[2] = clamp((x2+t1) >> 17);\r
+      o[5] = clamp((x2-t1) >> 17);\r
+      o[3] = clamp((x3+t0) >> 17);\r
+      o[4] = clamp((x3-t0) >> 17);\r
+   }\r
+}\r
+#else\r
+static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)\r
+{\r
+   int i,val[64],*v=val;\r
+   uint8 *o;\r
+   unsigned short *dq = dequantize;\r
+   short *d = data;\r
+\r
+   // columns\r
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {\r
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\r
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\r
+           && d[40]==0 && d[48]==0 && d[56]==0) {\r
+         //    no shortcut                 0     seconds\r
+         //    (1|2|3|4|5|6|7)==0          0     seconds\r
+         //    all separate               -0.047 seconds\r
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\r
+         int dcterm = d[0] * dq[0] << 2;\r
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\r
+      } else {\r
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\r
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\r
+         // constants scaled things up by 1<<12; let's bring them back\r
+         // down, but keep 2 extra bits of precision\r
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\r
+         v[ 0] = (x0+t3) >> 10;\r
+         v[56] = (x0-t3) >> 10;\r
+         v[ 8] = (x1+t2) >> 10;\r
+         v[48] = (x1-t2) >> 10;\r
+         v[16] = (x2+t1) >> 10;\r
+         v[40] = (x2-t1) >> 10;\r
+         v[24] = (x3+t0) >> 10;\r
+         v[32] = (x3-t0) >> 10;\r
+      }\r
+   }\r
+\r
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\r
+      // no fast case since the first 1D IDCT spread components out\r
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\r
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first\r
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together\r
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.\r
+      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;\r
+      o[0] = clamp((x0+t3) >> 17);\r
+      o[7] = clamp((x0-t3) >> 17);\r
+      o[1] = clamp((x1+t2) >> 17);\r
+      o[6] = clamp((x1-t2) >> 17);\r
+      o[2] = clamp((x2+t1) >> 17);\r
+      o[5] = clamp((x2-t1) >> 17);\r
+      o[3] = clamp((x3+t0) >> 17);\r
+      o[4] = clamp((x3-t0) >> 17);\r
+   }\r
+}\r
+static stbi_idct_8x8 stbi_idct_installed = idct_block;\r
+\r
+extern void stbi_install_idct(stbi_idct_8x8 func)\r
+{\r
+   stbi_idct_installed = func;\r
+}\r
+#endif\r
+\r
+#define MARKER_none  0xff\r
+// if there's a pending marker from the entropy stream, return that\r
+// otherwise, fetch from the stream and get a marker. if there's no\r
+// marker, return 0xff, which is never a valid marker value\r
+static uint8 get_marker(jpeg *j)\r
+{\r
+   uint8 x;\r
+   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }\r
+   x = get8u(&j->s);\r
+   if (x != 0xff) return MARKER_none;\r
+   while (x == 0xff)\r
+      x = get8u(&j->s);\r
+   return x;\r
+}\r
+\r
+// in each scan, we'll have scan_n components, and the order\r
+// of the components is specified by order[]\r
+#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)\r
+\r
+// after a restart interval, reset the entropy decoder and\r
+// the dc prediction\r
+static void reset(jpeg *j)\r
+{\r
+   j->code_bits = 0;\r
+   j->code_buffer = 0;\r
+   j->nomore = 0;\r
+   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;\r
+   j->marker = MARKER_none;\r
+   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;\r
+   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,\r
+   // since we don't even allow 1<<30 pixels\r
+}\r
+\r
+static int parse_entropy_coded_data(jpeg *z)\r
+{\r
+   reset(z);\r
+   if (z->scan_n == 1) {\r
+      int i,j;\r
+      #if STBI_SIMD\r
+      __declspec(align(16))\r
+      #endif\r
+      short data[64];\r
+      int n = z->order[0];\r
+      // non-interleaved data, we just need to process one block at a time,\r
+      // in trivial scanline order\r
+      // number of blocks to do just depends on how many actual "pixels" this\r
+      // component has, independent of interleaved MCU blocking and such\r
+      int w = (z->img_comp[n].x+7) >> 3;\r
+      int h = (z->img_comp[n].y+7) >> 3;\r
+      for (j=0; j < h; ++j) {\r
+         for (i=0; i < w; ++i) {\r
+            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\r
+            #if STBI_SIMD\r
+            stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\r
+            #else\r
+            idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\r
+            #endif\r
+            // every data block is an MCU, so countdown the restart interval\r
+            if (--z->todo <= 0) {\r
+               if (z->code_bits < 24) grow_buffer_unsafe(z);\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(z->marker)) return 1;\r
+               reset(z);\r
+            }\r
+         }\r
+      }\r
+   } else { // interleaved!\r
+      int i,j,k,x,y;\r
+      short data[64];\r
+      for (j=0; j < z->img_mcu_y; ++j) {\r
+         for (i=0; i < z->img_mcu_x; ++i) {\r
+            // scan an interleaved mcu... process scan_n components in order\r
+            for (k=0; k < z->scan_n; ++k) {\r
+               int n = z->order[k];\r
+               // scan out an mcu's worth of this component; that's just determined\r
+               // by the basic H and V specified for the component\r
+               for (y=0; y < z->img_comp[n].v; ++y) {\r
+                  for (x=0; x < z->img_comp[n].h; ++x) {\r
+                     int x2 = (i*z->img_comp[n].h + x)*8;\r
+                     int y2 = (j*z->img_comp[n].v + y)*8;\r
+                     if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\r
+                     #if STBI_SIMD\r
+                     stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\r
+                     #else\r
+                     idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\r
+                     #endif\r
+                  }\r
+               }\r
+            }\r
+            // after all interleaved components, that's an interleaved MCU,\r
+            // so now count down the restart interval\r
+            if (--z->todo <= 0) {\r
+               if (z->code_bits < 24) grow_buffer_unsafe(z);\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(z->marker)) return 1;\r
+               reset(z);\r
+            }\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int process_marker(jpeg *z, int m)\r
+{\r
+   int L;\r
+   switch (m) {\r
+      case MARKER_none: // no marker found\r
+         return e("expected marker","Corrupt JPEG");\r
+\r
+      case 0xC2: // SOF - progressive\r
+         return e("progressive jpeg","JPEG format not supported (progressive)");\r
+\r
+      case 0xDD: // DRI - specify restart interval\r
+         if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG");\r
+         z->restart_interval = get16(&z->s);\r
+         return 1;\r
+\r
+      case 0xDB: // DQT - define quantization table\r
+         L = get16(&z->s)-2;\r
+         while (L > 0) {\r
+            int q = get8(&z->s);\r
+            int p = q >> 4;\r
+            int t = q & 15,i;\r
+            if (p != 0) return e("bad DQT type","Corrupt JPEG");\r
+            if (t > 3) return e("bad DQT table","Corrupt JPEG");\r
+            for (i=0; i < 64; ++i)\r
+               z->dequant[t][dezigzag[i]] = get8u(&z->s);\r
+            #if STBI_SIMD\r
+            for (i=0; i < 64; ++i)\r
+               z->dequant2[t][i] = dequant[t][i];\r
+            #endif\r
+            L -= 65;\r
+         }\r
+         return L==0;\r
+\r
+      case 0xC4: // DHT - define huffman table\r
+         L = get16(&z->s)-2;\r
+         while (L > 0) {\r
+            uint8 *v;\r
+            int sizes[16],i,m=0;\r
+            int q = get8(&z->s);\r
+            int tc = q >> 4;\r
+            int th = q & 15;\r
+            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");\r
+            for (i=0; i < 16; ++i) {\r
+               sizes[i] = get8(&z->s);\r
+               m += sizes[i];\r
+            }\r
+            L -= 17;\r
+            if (tc == 0) {\r
+               if (!build_huffman(z->huff_dc+th, sizes)) return 0;\r
+               v = z->huff_dc[th].values;\r
+            } else {\r
+               if (!build_huffman(z->huff_ac+th, sizes)) return 0;\r
+               v = z->huff_ac[th].values;\r
+            }\r
+            for (i=0; i < m; ++i)\r
+               v[i] = get8u(&z->s);\r
+            L -= m;\r
+         }\r
+         return L==0;\r
+   }\r
+   // check for comment block or APP blocks\r
+   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {\r
+      skip(&z->s, get16(&z->s)-2);\r
+      return 1;\r
+   }\r
+   return 0;\r
+}\r
+\r
+// after we see SOS\r
+static int process_scan_header(jpeg *z)\r
+{\r
+   int i;\r
+   int Ls = get16(&z->s);\r
+   z->scan_n = get8(&z->s);\r
+   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s.img_n) return e("bad SOS component count","Corrupt JPEG");\r
+   if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");\r
+   for (i=0; i < z->scan_n; ++i) {\r
+      int id = get8(&z->s), which;\r
+      int q = get8(&z->s);\r
+      for (which = 0; which < z->s.img_n; ++which)\r
+         if (z->img_comp[which].id == id)\r
+            break;\r
+      if (which == z->s.img_n) return 0;\r
+      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");\r
+      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");\r
+      z->order[i] = which;\r
+   }\r
+   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");\r
+   get8(&z->s); // should be 63, but might be 0\r
+   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");\r
+\r
+   return 1;\r
+}\r
+\r
+static int process_frame_header(jpeg *z, int scan)\r
+{\r
+   stbi *s = &z->s;\r
+   int Lf,p,i,q, h_max=1,v_max=1,c;\r
+   Lf = get16(s);         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG\r
+   p  = get8(s);          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline\r
+   s->img_y = get16(s);   if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG\r
+   s->img_x = get16(s);   if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires\r
+   c = get8(s);\r
+   if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires\r
+   s->img_n = c;\r
+   for (i=0; i < c; ++i) {\r
+      z->img_comp[i].data = NULL;\r
+      z->img_comp[i].linebuf = NULL;\r
+   }\r
+\r
+   if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      z->img_comp[i].id = get8(s);\r
+      if (z->img_comp[i].id != i+1)   // JFIF requires\r
+         if (z->img_comp[i].id != i)  // some version of jpegtran outputs non-JFIF-compliant files!\r
+            return e("bad component ID","Corrupt JPEG");\r
+      q = get8(s);\r
+      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");\r
+      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");\r
+      z->img_comp[i].tq = get8(s);  if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");\r
+   }\r
+\r
+   if (scan != SCAN_load) return 1;\r
+\r
+   if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;\r
+      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;\r
+   }\r
+\r
+   // compute interleaved mcu info\r
+   z->img_h_max = h_max;\r
+   z->img_v_max = v_max;\r
+   z->img_mcu_w = h_max * 8;\r
+   z->img_mcu_h = v_max * 8;\r
+   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;\r
+   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      // number of effective pixels (e.g. for non-interleaved MCU)\r
+      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;\r
+      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;\r
+      // to simplify generation, we'll allocate enough memory to decode\r
+      // the bogus oversized data from using interleaved MCUs and their\r
+      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't\r
+      // discard the extra data until colorspace conversion\r
+      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;\r
+      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;\r
+      z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);\r
+      if (z->img_comp[i].raw_data == NULL) {\r
+         for(--i; i >= 0; --i) {\r
+            free(z->img_comp[i].raw_data);\r
+            z->img_comp[i].data = NULL;\r
+         }\r
+         return e("outofmem", "Out of memory");\r
+      }\r
+      // align blocks for installable-idct using mmx/sse\r
+      z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);\r
+      z->img_comp[i].linebuf = NULL;\r
+   }\r
+\r
+   return 1;\r
+}\r
+\r
+// use comparisons since in some cases we handle more than one case (e.g. SOF)\r
+#define DNL(x)         ((x) == 0xdc)\r
+#define SOI(x)         ((x) == 0xd8)\r
+#define EOI(x)         ((x) == 0xd9)\r
+#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)\r
+#define SOS(x)         ((x) == 0xda)\r
+\r
+static int decode_jpeg_header(jpeg *z, int scan)\r
+{\r
+   int m;\r
+   z->marker = MARKER_none; // initialize cached marker to empty\r
+   m = get_marker(z);\r
+   if (!SOI(m)) return e("no SOI","Corrupt JPEG");\r
+   if (scan == SCAN_type) return 1;\r
+   m = get_marker(z);\r
+   while (!SOF(m)) {\r
+      if (!process_marker(z,m)) return 0;\r
+      m = get_marker(z);\r
+      while (m == MARKER_none) {\r
+         // some files have extra padding after their blocks, so ok, we'll scan\r
+         if (at_eof(&z->s)) return e("no SOF", "Corrupt JPEG");\r
+         m = get_marker(z);\r
+      }\r
+   }\r
+   if (!process_frame_header(z, scan)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int decode_jpeg_image(jpeg *j)\r
+{\r
+   int m;\r
+   j->restart_interval = 0;\r
+   if (!decode_jpeg_header(j, SCAN_load)) return 0;\r
+   m = get_marker(j);\r
+   while (!EOI(m)) {\r
+      if (SOS(m)) {\r
+         if (!process_scan_header(j)) return 0;\r
+         if (!parse_entropy_coded_data(j)) return 0;\r
+      } else {\r
+         if (!process_marker(j, m)) return 0;\r
+      }\r
+      m = get_marker(j);\r
+   }\r
+   return 1;\r
+}\r
+\r
+// static jfif-centered resampling (across block boundaries)\r
+\r
+typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,\r
+                                    int w, int hs);\r
+\r
+#define div4(x) ((uint8) ((x) >> 2))\r
+\r
+static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   return in_near;\r
+}\r
+\r
+static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate two samples vertically for every one in input\r
+   int i;\r
+   for (i=0; i < w; ++i)\r
+      out[i] = div4(3*in_near[i] + in_far[i] + 2);\r
+   return out;\r
+}\r
+\r
+static uint8*  resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate two samples horizontally for every one in input\r
+   int i;\r
+   uint8 *input = in_near;\r
+   if (w == 1) {\r
+      // if only one sample, can't do any interpolation\r
+      out[0] = out[1] = input[0];\r
+      return out;\r
+   }\r
+\r
+   out[0] = input[0];\r
+   out[1] = div4(input[0]*3 + input[1] + 2);\r
+   for (i=1; i < w-1; ++i) {\r
+      int n = 3*input[i]+2;\r
+      out[i*2+0] = div4(n+input[i-1]);\r
+      out[i*2+1] = div4(n+input[i+1]);\r
+   }\r
+   out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);\r
+   out[i*2+1] = input[w-1];\r
+   return out;\r
+}\r
+\r
+#define div16(x) ((uint8) ((x) >> 4))\r
+\r
+static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate 2x2 samples for every one in input\r
+   int i,t0,t1;\r
+   if (w == 1) {\r
+      out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);\r
+      return out;\r
+   }\r
+\r
+   t1 = 3*in_near[0] + in_far[0];\r
+   out[0] = div4(t1+2);\r
+   for (i=1; i < w; ++i) {\r
+      t0 = t1;\r
+      t1 = 3*in_near[i]+in_far[i];\r
+      out[i*2-1] = div16(3*t0 + t1 + 8);\r
+      out[i*2  ] = div16(3*t1 + t0 + 8);\r
+   }\r
+   out[w*2-1] = div4(t1+2);\r
+   return out;\r
+}\r
+\r
+static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // resample with nearest-neighbor\r
+   int i,j;\r
+   for (i=0; i < w; ++i)\r
+      for (j=0; j < hs; ++j)\r
+         out[i*hs+j] = in_near[i];\r
+   return out;\r
+}\r
+\r
+#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))\r
+\r
+// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)\r
+// VC6 without processor=Pro is generating multiple LEAs per multiply!\r
+static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pcr, int count, int step)\r
+{\r
+   int i;\r
+   for (i=0; i < count; ++i) {\r
+      int y_fixed = (y[i] << 16) + 32768; // rounding\r
+      int r,g,b;\r
+      int cr = pcr[i] - 128;\r
+      int cb = pcb[i] - 128;\r
+      r = y_fixed + cr*float2fixed(1.40200f);\r
+      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);\r
+      b = y_fixed                            + cb*float2fixed(1.77200f);\r
+      r >>= 16;\r
+      g >>= 16;\r
+      b >>= 16;\r
+      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\r
+      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\r
+      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\r
+      out[0] = (uint8)r;\r
+      out[1] = (uint8)g;\r
+      out[2] = (uint8)b;\r
+      out[3] = 255;\r
+      out += step;\r
+   }\r
+}\r
+\r
+#if STBI_SIMD\r
+static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;\r
+\r
+void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)\r
+{\r
+   stbi_YCbCr_installed = func;\r
+}\r
+#endif\r
+\r
+\r
+// clean up the temporary component buffers\r
+static void cleanup_jpeg(jpeg *j)\r
+{\r
+   int i;\r
+   for (i=0; i < j->s.img_n; ++i) {\r
+      if (j->img_comp[i].data) {\r
+         free(j->img_comp[i].raw_data);\r
+         j->img_comp[i].data = NULL;\r
+      }\r
+      if (j->img_comp[i].linebuf) {\r
+         free(j->img_comp[i].linebuf);\r
+         j->img_comp[i].linebuf = NULL;\r
+      }\r
+   }\r
+}\r
+\r
+typedef struct\r
+{\r
+   resample_row_func resample;\r
+   uint8 *line0,*line1;\r
+   int hs,vs;   // expansion factor in each axis\r
+   int w_lores; // horizontal pixels pre-expansion \r
+   int ystep;   // how far through vertical expansion we are\r
+   int ypos;    // which pre-expansion row we're on\r
+} stbi_resample;\r
+\r
+static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)\r
+{\r
+   int n, decode_n;\r
+   // validate req_comp\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+   z->s.img_n = 0;\r
+\r
+   // load a jpeg image from whichever source\r
+   if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }\r
+\r
+   // determine actual number of components to generate\r
+   n = req_comp ? req_comp : z->s.img_n;\r
+\r
+   if (z->s.img_n == 3 && n < 3)\r
+      decode_n = 1;\r
+   else\r
+      decode_n = z->s.img_n;\r
+\r
+   // resample and color-convert\r
+   {\r
+      int k;\r
+      uint i,j;\r
+      uint8 *output;\r
+      uint8 *coutput[4];\r
+\r
+      stbi_resample res_comp[4];\r
+\r
+      for (k=0; k < decode_n; ++k) {\r
+         stbi_resample *r = &res_comp[k];\r
+\r
+         // allocate line buffer big enough for upsampling off the edges\r
+         // with upsample factor of 4\r
+         z->img_comp[k].linebuf = (uint8 *) malloc(z->s.img_x + 3);\r
+         if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }\r
+\r
+         r->hs      = z->img_h_max / z->img_comp[k].h;\r
+         r->vs      = z->img_v_max / z->img_comp[k].v;\r
+         r->ystep   = r->vs >> 1;\r
+         r->w_lores = (z->s.img_x + r->hs-1) / r->hs;\r
+         r->ypos    = 0;\r
+         r->line0   = r->line1 = z->img_comp[k].data;\r
+\r
+         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;\r
+         else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;\r
+         else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;\r
+         else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;\r
+         else                               r->resample = resample_row_generic;\r
+      }\r
+\r
+      // can't error after this so, this is safe\r
+      output = (uint8 *) malloc(n * z->s.img_x * z->s.img_y + 1);\r
+      if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }\r
+\r
+      // now go ahead and resample\r
+      for (j=0; j < z->s.img_y; ++j) {\r
+         uint8 *out = output + n * z->s.img_x * j;\r
+         for (k=0; k < decode_n; ++k) {\r
+            stbi_resample *r = &res_comp[k];\r
+            int y_bot = r->ystep >= (r->vs >> 1);\r
+            coutput[k] = r->resample(z->img_comp[k].linebuf,\r
+                                     y_bot ? r->line1 : r->line0,\r
+                                     y_bot ? r->line0 : r->line1,\r
+                                     r->w_lores, r->hs);\r
+            if (++r->ystep >= r->vs) {\r
+               r->ystep = 0;\r
+               r->line0 = r->line1;\r
+               if (++r->ypos < z->img_comp[k].y)\r
+                  r->line1 += z->img_comp[k].w2;\r
+            }\r
+         }\r
+         if (n >= 3) {\r
+            uint8 *y = coutput[0];\r
+            if (z->s.img_n == 3) {\r
+               #if STBI_SIMD\r
+               stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);\r
+               #else\r
+               YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s.img_x, n);\r
+               #endif\r
+            } else\r
+               for (i=0; i < z->s.img_x; ++i) {\r
+                  out[0] = out[1] = out[2] = y[i];\r
+                  out[3] = 255; // not used if n==3\r
+                  out += n;\r
+               }\r
+         } else {\r
+            uint8 *y = coutput[0];\r
+            if (n == 1)\r
+               for (i=0; i < z->s.img_x; ++i) out[i] = y[i];\r
+            else\r
+               for (i=0; i < z->s.img_x; ++i) *out++ = y[i], *out++ = 255;\r
+         }\r
+      }\r
+      cleanup_jpeg(z);\r
+      *out_x = z->s.img_x;\r
+      *out_y = z->s.img_y;\r
+      if (comp) *comp  = z->s.img_n; // report original components, not output\r
+      return output;\r
+   }\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   jpeg j;\r
+   start_file(&j.s, f);\r
+   return load_jpeg_image(&j, x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_jpeg_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   jpeg j;\r
+   start_mem(&j.s, buffer,len);\r
+   return load_jpeg_image(&j, x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_jpeg_test_file(FILE *f)\r
+{\r
+   int n,r;\r
+   jpeg j;\r
+   n = ftell(f);\r
+   start_file(&j.s, f);\r
+   r = decode_jpeg_header(&j, SCAN_type);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_jpeg_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   jpeg j;\r
+   start_mem(&j.s, buffer,len);\r
+   return decode_jpeg_header(&j, SCAN_type);\r
+}\r
+\r
+// @TODO:\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_jpeg_info            (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// public domain zlib decode    v0.2  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - all input must be provided in an upfront buffer\r
+//      - all output is written to a single output buffer (can malloc/realloc)\r
+//    performance\r
+//      - fast huffman\r
+\r
+// fast-way is faster to check than jpeg huffman, but slow way is slower\r
+#define ZFAST_BITS  9 // accelerate all cases in default tables\r
+#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)\r
+\r
+// zlib-style huffman encoding\r
+// (jpegs packs from left, zlib from right, so can't share code)\r
+typedef struct\r
+{\r
+   uint16 fast[1 << ZFAST_BITS];\r
+   uint16 firstcode[16];\r
+   int maxcode[17];\r
+   uint16 firstsymbol[16];\r
+   uint8  size[288];\r
+   uint16 value[288]; \r
+} zhuffman;\r
+\r
+__forceinline static int bitreverse16(int n)\r
+{\r
+  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);\r
+  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);\r
+  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);\r
+  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);\r
+  return n;\r
+}\r
+\r
+__forceinline static int bit_reverse(int v, int bits)\r
+{\r
+   assert(bits <= 16);\r
+   // to bit reverse n bits, reverse 16 and shift\r
+   // e.g. 11 bits, bit reverse and shift away 5\r
+   return bitreverse16(v) >> (16-bits);\r
+}\r
+\r
+static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)\r
+{\r
+   int i,k=0;\r
+   int code, next_code[16], sizes[17];\r
+\r
+   // DEFLATE spec for generating codes\r
+   memset(sizes, 0, sizeof(sizes));\r
+   memset(z->fast, 255, sizeof(z->fast));\r
+   for (i=0; i < num; ++i) \r
+      ++sizes[sizelist[i]];\r
+   sizes[0] = 0;\r
+   for (i=1; i < 16; ++i)\r
+      assert(sizes[i] <= (1 << i));\r
+   code = 0;\r
+   for (i=1; i < 16; ++i) {\r
+      next_code[i] = code;\r
+      z->firstcode[i] = (uint16) code;\r
+      z->firstsymbol[i] = (uint16) k;\r
+      code = (code + sizes[i]);\r
+      if (sizes[i])\r
+         if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");\r
+      z->maxcode[i] = code << (16-i); // preshift for inner loop\r
+      code <<= 1;\r
+      k += sizes[i];\r
+   }\r
+   z->maxcode[16] = 0x10000; // sentinel\r
+   for (i=0; i < num; ++i) {\r
+      int s = sizelist[i];\r
+      if (s) {\r
+         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];\r
+         z->size[c] = (uint8)s;\r
+         z->value[c] = (uint16)i;\r
+         if (s <= ZFAST_BITS) {\r
+            int k = bit_reverse(next_code[s],s);\r
+            while (k < (1 << ZFAST_BITS)) {\r
+               z->fast[k] = (uint16) c;\r
+               k += (1 << s);\r
+            }\r
+         }\r
+         ++next_code[s];\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+// zlib-from-memory implementation for PNG reading\r
+//    because PNG allows splitting the zlib stream arbitrarily,\r
+//    and it's annoying structurally to have PNG call ZLIB call PNG,\r
+//    we require PNG read all the IDATs and combine them into a single\r
+//    memory buffer\r
+\r
+typedef struct\r
+{\r
+   uint8 *zbuffer, *zbuffer_end;\r
+   int num_bits;\r
+   uint32 code_buffer;\r
+\r
+   char *zout;\r
+   char *zout_start;\r
+   char *zout_end;\r
+   int   z_expandable;\r
+\r
+   zhuffman z_length, z_distance;\r
+} zbuf;\r
+\r
+__forceinline static int zget8(zbuf *z)\r
+{\r
+   if (z->zbuffer >= z->zbuffer_end) return 0;\r
+   return *z->zbuffer++;\r
+}\r
+\r
+static void fill_bits(zbuf *z)\r
+{\r
+   do {\r
+      assert(z->code_buffer < (1U << z->num_bits));\r
+      z->code_buffer |= zget8(z) << z->num_bits;\r
+      z->num_bits += 8;\r
+   } while (z->num_bits <= 24);\r
+}\r
+\r
+__forceinline static unsigned int zreceive(zbuf *z, int n)\r
+{\r
+   unsigned int k;\r
+   if (z->num_bits < n) fill_bits(z);\r
+   k = z->code_buffer & ((1 << n) - 1);\r
+   z->code_buffer >>= n;\r
+   z->num_bits -= n;\r
+   return k;   \r
+}\r
+\r
+__forceinline static int zhuffman_decode(zbuf *a, zhuffman *z)\r
+{\r
+   int b,s,k;\r
+   if (a->num_bits < 16) fill_bits(a);\r
+   b = z->fast[a->code_buffer & ZFAST_MASK];\r
+   if (b < 0xffff) {\r
+      s = z->size[b];\r
+      a->code_buffer >>= s;\r
+      a->num_bits -= s;\r
+      return z->value[b];\r
+   }\r
+\r
+   // not resolved by fast table, so compute it the slow way\r
+   // use jpeg approach, which requires MSbits at top\r
+   k = bit_reverse(a->code_buffer, 16);\r
+   for (s=ZFAST_BITS+1; ; ++s)\r
+      if (k < z->maxcode[s])\r
+         break;\r
+   if (s == 16) return -1; // invalid code!\r
+   // code size is s, so:\r
+   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];\r
+   assert(z->size[b] == s);\r
+   a->code_buffer >>= s;\r
+   a->num_bits -= s;\r
+   return z->value[b];\r
+}\r
+\r
+static int expand(zbuf *z, int n)  // need to make room for n bytes\r
+{\r
+   char *q;\r
+   int cur, limit;\r
+   if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");\r
+   cur   = (int) (z->zout     - z->zout_start);\r
+   limit = (int) (z->zout_end - z->zout_start);\r
+   while (cur + n > limit)\r
+      limit *= 2;\r
+   q = (char *) realloc(z->zout_start, limit);\r
+   if (q == NULL) return e("outofmem", "Out of memory");\r
+   z->zout_start = q;\r
+   z->zout       = q + cur;\r
+   z->zout_end   = q + limit;\r
+   return 1;\r
+}\r
+\r
+static int length_base[31] = {\r
+   3,4,5,6,7,8,9,10,11,13,\r
+   15,17,19,23,27,31,35,43,51,59,\r
+   67,83,99,115,131,163,195,227,258,0,0 };\r
+\r
+static int length_extra[31]= \r
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\r
+\r
+static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,\r
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\r
+\r
+static int dist_extra[32] =\r
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\r
+\r
+static int parse_huffman_block(zbuf *a)\r
+{\r
+   for(;;) {\r
+      int z = zhuffman_decode(a, &a->z_length);\r
+      if (z < 256) {\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes\r
+         if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;\r
+         *a->zout++ = (char) z;\r
+      } else {\r
+         uint8 *p;\r
+         int len,dist;\r
+         if (z == 256) return 1;\r
+         z -= 257;\r
+         len = length_base[z];\r
+         if (length_extra[z]) len += zreceive(a, length_extra[z]);\r
+         z = zhuffman_decode(a, &a->z_distance);\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG");\r
+         dist = dist_base[z];\r
+         if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);\r
+         if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");\r
+         if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;\r
+         p = (uint8 *) (a->zout - dist);\r
+         while (len--)\r
+            *a->zout++ = *p++;\r
+      }\r
+   }\r
+}\r
+\r
+static int compute_huffman_codes(zbuf *a)\r
+{\r
+   static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\r
+   static zhuffman z_codelength; // static just to save stack space\r
+   uint8 lencodes[286+32+137];//padding for maximum single op\r
+   uint8 codelength_sizes[19];\r
+   int i,n;\r
+\r
+   int hlit  = zreceive(a,5) + 257;\r
+   int hdist = zreceive(a,5) + 1;\r
+   int hclen = zreceive(a,4) + 4;\r
+\r
+   memset(codelength_sizes, 0, sizeof(codelength_sizes));\r
+   for (i=0; i < hclen; ++i) {\r
+      int s = zreceive(a,3);\r
+      codelength_sizes[length_dezigzag[i]] = (uint8) s;\r
+   }\r
+   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;\r
+\r
+   n = 0;\r
+   while (n < hlit + hdist) {\r
+      int c = zhuffman_decode(a, &z_codelength);\r
+      assert(c >= 0 && c < 19);\r
+      if (c < 16)\r
+         lencodes[n++] = (uint8) c;\r
+      else if (c == 16) {\r
+         c = zreceive(a,2)+3;\r
+         memset(lencodes+n, lencodes[n-1], c);\r
+         n += c;\r
+      } else if (c == 17) {\r
+         c = zreceive(a,3)+3;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      } else {\r
+         assert(c == 18);\r
+         c = zreceive(a,7)+11;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      }\r
+   }\r
+   if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");\r
+   if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;\r
+   if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int parse_uncompressed_block(zbuf *a)\r
+{\r
+   uint8 header[4];\r
+   int len,nlen,k;\r
+   if (a->num_bits & 7)\r
+      zreceive(a, a->num_bits & 7); // discard\r
+   // drain the bit-packed data into header\r
+   k = 0;\r
+   while (a->num_bits > 0) {\r
+      header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?\r
+      a->code_buffer >>= 8;\r
+      a->num_bits -= 8;\r
+   }\r
+   assert(a->num_bits == 0);\r
+   // now fill header the normal way\r
+   while (k < 4)\r
+      header[k++] = (uint8) zget8(a);\r
+   len  = header[1] * 256 + header[0];\r
+   nlen = header[3] * 256 + header[2];\r
+   if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");\r
+   if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");\r
+   if (a->zout + len > a->zout_end)\r
+      if (!expand(a, len)) return 0;\r
+   memcpy(a->zout, a->zbuffer, len);\r
+   a->zbuffer += len;\r
+   a->zout += len;\r
+   return 1;\r
+}\r
+\r
+static int parse_zlib_header(zbuf *a)\r
+{\r
+   int cmf   = zget8(a);\r
+   int cm    = cmf & 15;\r
+   /* int cinfo = cmf >> 4; */\r
+   int flg   = zget8(a);\r
+   if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec\r
+   if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png\r
+   if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png\r
+   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output\r
+   return 1;\r
+}\r
+\r
+// @TODO: should statically initialize these for optimal thread safety\r
+static uint8 default_length[288], default_distance[32];\r
+static void init_defaults(void)\r
+{\r
+   int i;   // use <= to match clearly with spec\r
+   for (i=0; i <= 143; ++i)     default_length[i]   = 8;\r
+   for (   ; i <= 255; ++i)     default_length[i]   = 9;\r
+   for (   ; i <= 279; ++i)     default_length[i]   = 7;\r
+   for (   ; i <= 287; ++i)     default_length[i]   = 8;\r
+\r
+   for (i=0; i <=  31; ++i)     default_distance[i] = 5;\r
+}\r
+\r
+static int parse_zlib(zbuf *a, int parse_header)\r
+{\r
+   int final, type;\r
+   if (parse_header)\r
+      if (!parse_zlib_header(a)) return 0;\r
+   a->num_bits = 0;\r
+   a->code_buffer = 0;\r
+   do {\r
+      final = zreceive(a,1);\r
+      type = zreceive(a,2);\r
+      if (type == 0) {\r
+         if (!parse_uncompressed_block(a)) return 0;\r
+      } else if (type == 3) {\r
+         return 0;\r
+      } else {\r
+         if (type == 1) {\r
+            // use fixed code lengths\r
+            if (!default_distance[31]) init_defaults();\r
+            if (!zbuild_huffman(&a->z_length  , default_length  , 288)) return 0;\r
+            if (!zbuild_huffman(&a->z_distance, default_distance,  32)) return 0;\r
+         } else {\r
+            if (!compute_huffman_codes(a)) return 0;\r
+         }\r
+         if (!parse_huffman_block(a)) return 0;\r
+      }\r
+   } while (!final);\r
+   return 1;\r
+}\r
+\r
+static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)\r
+{\r
+   a->zout_start = obuf;\r
+   a->zout       = obuf;\r
+   a->zout_end   = obuf + olen;\r
+   a->z_expandable = exp;\r
+\r
+   return parse_zlib(a, parse_header);\r
+}\r
+\r
+char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)\r
+{\r
+   zbuf a;\r
+   char *p = (char *) malloc(initial_size);\r
+   if (p == NULL) return NULL;\r
+   a.zbuffer = (uint8 *) buffer;\r
+   a.zbuffer_end = (uint8 *) buffer + len;\r
+   if (do_zlib(&a, p, initial_size, 1, 1)) {\r
+      if (outlen) *outlen = (int) (a.zout - a.zout_start);\r
+      return a.zout_start;\r
+   } else {\r
+      free(a.zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)\r
+{\r
+   return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);\r
+}\r
+\r
+int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)\r
+{\r
+   zbuf a;\r
+   a.zbuffer = (uint8 *) ibuffer;\r
+   a.zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(&a, obuffer, olen, 0, 1))\r
+      return (int) (a.zout - a.zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)\r
+{\r
+   zbuf a;\r
+   char *p = (char *) malloc(16384);\r
+   if (p == NULL) return NULL;\r
+   a.zbuffer = (uint8 *) buffer;\r
+   a.zbuffer_end = (uint8 *) buffer+len;\r
+   if (do_zlib(&a, p, 16384, 1, 0)) {\r
+      if (outlen) *outlen = (int) (a.zout - a.zout_start);\r
+      return a.zout_start;\r
+   } else {\r
+      free(a.zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)\r
+{\r
+   zbuf a;\r
+   a.zbuffer = (uint8 *) ibuffer;\r
+   a.zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(&a, obuffer, olen, 0, 0))\r
+      return (int) (a.zout - a.zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+// public domain "baseline" PNG decoder   v0.10  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - only 8-bit samples\r
+//      - no CRC checking\r
+//      - allocates lots of intermediate memory\r
+//        - avoids problem of streaming data between subsystems\r
+//        - avoids explicit window management\r
+//    performance\r
+//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding\r
+\r
+\r
+typedef struct\r
+{\r
+   uint32 length;\r
+   uint32 type;\r
+} chunk;\r
+\r
+#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))\r
+\r
+static chunk get_chunk_header(stbi *s)\r
+{\r
+   chunk c;\r
+   c.length = get32(s);\r
+   c.type   = get32(s);\r
+   return c;\r
+}\r
+\r
+static int check_png_header(stbi *s)\r
+{\r
+   static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };\r
+   int i;\r
+   for (i=0; i < 8; ++i)\r
+      if (get8(s) != png_sig[i]) return e("bad png sig","Not a PNG");\r
+   return 1;\r
+}\r
+\r
+typedef struct\r
+{\r
+   stbi s;\r
+   uint8 *idata, *expanded, *out;\r
+} png;\r
+\r
+\r
+enum {\r
+   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,\r
+   F_avg_first, F_paeth_first,\r
+};\r
+\r
+static uint8 first_row_filter[5] =\r
+{\r
+   F_none, F_sub, F_none, F_avg_first, F_paeth_first\r
+};\r
+\r
+static int paeth(int a, int b, int c)\r
+{\r
+   int p = a + b - c;\r
+   int pa = abs(p-a);\r
+   int pb = abs(p-b);\r
+   int pc = abs(p-c);\r
+   if (pa <= pb && pa <= pc) return a;\r
+   if (pb <= pc) return b;\r
+   return c;\r
+}\r
+\r
+// create the png data from post-deflated data\r
+static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n)\r
+{\r
+   stbi *s = &a->s;\r
+   uint32 i,j,stride = s->img_x*out_n;\r
+   int k;\r
+   int img_n = s->img_n; // copy it into a local for later\r
+   assert(out_n == s->img_n || out_n == s->img_n+1);\r
+   a->out = (uint8 *) malloc(s->img_x * s->img_y * out_n);\r
+   if (!a->out) return e("outofmem", "Out of memory");\r
+   if (raw_len != (img_n * s->img_x + 1) * s->img_y) return e("not enough pixels","Corrupt PNG");\r
+   for (j=0; j < s->img_y; ++j) {\r
+      uint8 *cur = a->out + stride*j;\r
+      uint8 *prior = cur - stride;\r
+      int filter = *raw++;\r
+      if (filter > 4) return e("invalid filter","Corrupt PNG");\r
+      // if first row, use special filter that doesn't sample previous row\r
+      if (j == 0) filter = first_row_filter[filter];\r
+      // handle first pixel explicitly\r
+      for (k=0; k < img_n; ++k) {\r
+         switch(filter) {\r
+            case F_none       : cur[k] = raw[k]; break;\r
+            case F_sub        : cur[k] = raw[k]; break;\r
+            case F_up         : cur[k] = raw[k] + prior[k]; break;\r
+            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;\r
+            case F_paeth      : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;\r
+            case F_avg_first  : cur[k] = raw[k]; break;\r
+            case F_paeth_first: cur[k] = raw[k]; break;\r
+         }\r
+      }\r
+      if (img_n != out_n) cur[img_n] = 255;\r
+      raw += img_n;\r
+      cur += out_n;\r
+      prior += out_n;\r
+      // this is a little gross, so that we don't switch per-pixel or per-component\r
+      if (img_n == out_n) {\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=s->img_x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      } else {\r
+         assert(img_n+1 == out_n);\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=s->img_x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int compute_transparency(png *z, uint8 tc[3], int out_n)\r
+{\r
+   stbi *s = &z->s;\r
+   uint32 i, pixel_count = s->img_x * s->img_y;\r
+   uint8 *p = z->out;\r
+\r
+   // compute color-based transparency, assuming we've\r
+   // already got 255 as the alpha value in the output\r
+   assert(out_n == 2 || out_n == 4);\r
+\r
+   if (out_n == 2) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         p[1] = (p[0] == tc[0] ? 0 : 255);\r
+         p += 2;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\r
+            p[3] = 0;\r
+         p += 4;\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)\r
+{\r
+   uint32 i, pixel_count = a->s.img_x * a->s.img_y;\r
+   uint8 *p, *temp_out, *orig = a->out;\r
+\r
+   p = (uint8 *) malloc(pixel_count * pal_img_n);\r
+   if (p == NULL) return e("outofmem", "Out of memory");\r
+\r
+   // between here and free(out) below, exitting would leak\r
+   temp_out = p;\r
+\r
+   if (pal_img_n == 3) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p += 3;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p[3] = palette[n+3];\r
+         p += 4;\r
+      }\r
+   }\r
+   free(a->out);\r
+   a->out = temp_out;\r
+   return 1;\r
+}\r
+\r
+static int parse_png_file(png *z, int scan, int req_comp)\r
+{\r
+   uint8 palette[1024], pal_img_n=0;\r
+   uint8 has_trans=0, tc[3];\r
+   uint32 ioff=0, idata_limit=0, i, pal_len=0;\r
+   int first=1,k;\r
+   stbi *s = &z->s;\r
+\r
+   if (!check_png_header(s)) return 0;\r
+\r
+   if (scan == SCAN_type) return 1;\r
+\r
+   for(;;first=0) {\r
+      chunk c = get_chunk_header(s);\r
+      if (first && c.type != PNG_TYPE('I','H','D','R'))\r
+         return e("first not IHDR","Corrupt PNG");\r
+      switch (c.type) {\r
+         case PNG_TYPE('I','H','D','R'): {\r
+            int depth,color,interlace,comp,filter;\r
+            if (!first) return e("multiple IHDR","Corrupt PNG");\r
+            if (c.length != 13) return e("bad IHDR len","Corrupt PNG");\r
+            s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            depth = get8(s);  if (depth != 8)        return e("8bit only","PNG not supported: 8-bit only");\r
+            color = get8(s);  if (color > 6)         return e("bad ctype","Corrupt PNG");\r
+            if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");\r
+            comp  = get8(s);  if (comp) return e("bad comp method","Corrupt PNG");\r
+            filter= get8(s);  if (filter) return e("bad filter method","Corrupt PNG");\r
+            interlace = get8(s); if (interlace) return e("interlaced","PNG not supported: interlaced mode");\r
+            if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");\r
+            if (!pal_img_n) {\r
+               s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);\r
+               if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");\r
+               if (scan == SCAN_header) return 1;\r
+            } else {\r
+               // if paletted, then pal_n is our final components, and\r
+               // img_n is # components to decompress/filter.\r
+               s->img_n = 1;\r
+               if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");\r
+               // if SCAN_header, have to scan to see if we have a tRNS\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('P','L','T','E'):  {\r
+            if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");\r
+            pal_len = c.length / 3;\r
+            if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");\r
+            for (i=0; i < pal_len; ++i) {\r
+               palette[i*4+0] = get8u(s);\r
+               palette[i*4+1] = get8u(s);\r
+               palette[i*4+2] = get8u(s);\r
+               palette[i*4+3] = 255;\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('t','R','N','S'): {\r
+            if (z->idata) return e("tRNS after IDAT","Corrupt PNG");\r
+            if (pal_img_n) {\r
+               if (scan == SCAN_header) { s->img_n = 4; return 1; }\r
+               if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");\r
+               if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");\r
+               pal_img_n = 4;\r
+               for (i=0; i < c.length; ++i)\r
+                  palette[i*4+3] = get8u(s);\r
+            } else {\r
+               if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");\r
+               if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");\r
+               has_trans = 1;\r
+               for (k=0; k < s->img_n; ++k)\r
+                  tc[k] = (uint8) get16(s); // non 8-bit images will be larger\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','D','A','T'): {\r
+            if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");\r
+            if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }\r
+            if (ioff + c.length > idata_limit) {\r
+               uint8 *p;\r
+               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;\r
+               while (ioff + c.length > idata_limit)\r
+                  idata_limit *= 2;\r
+               p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");\r
+               z->idata = p;\r
+            }\r
+            #ifndef STBI_NO_STDIO\r
+            if (s->img_file)\r
+            {\r
+               if (fread(z->idata+ioff,1,c.length,s->img_file) != c.length) return e("outofdata","Corrupt PNG");\r
+            }\r
+            else\r
+            #endif\r
+            {\r
+               memcpy(z->idata+ioff, s->img_buffer, c.length);\r
+               s->img_buffer += c.length;\r
+            }\r
+            ioff += c.length;\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','E','N','D'): {\r
+            uint32 raw_len;\r
+            if (scan != SCAN_load) return 1;\r
+            if (z->idata == NULL) return e("no IDAT","Corrupt PNG");\r
+            z->expanded = (uint8 *) stbi_zlib_decode_malloc((char *) z->idata, ioff, (int *) &raw_len);\r
+            if (z->expanded == NULL) return 0; // zlib should set error\r
+            free(z->idata); z->idata = NULL;\r
+            if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)\r
+               s->img_out_n = s->img_n+1;\r
+            else\r
+               s->img_out_n = s->img_n;\r
+            if (!create_png_image(z, z->expanded, raw_len, s->img_out_n)) return 0;\r
+            if (has_trans)\r
+               if (!compute_transparency(z, tc, s->img_out_n)) return 0;\r
+            if (pal_img_n) {\r
+               // pal_img_n == 3 or 4\r
+               s->img_n = pal_img_n; // record the actual colors we had\r
+               s->img_out_n = pal_img_n;\r
+               if (req_comp >= 3) s->img_out_n = req_comp;\r
+               if (!expand_palette(z, palette, pal_len, s->img_out_n))\r
+                  return 0;\r
+            }\r
+            free(z->expanded); z->expanded = NULL;\r
+            return 1;\r
+         }\r
+\r
+         default:\r
+            // if critical, fail\r
+            if ((c.type & (1 << 29)) == 0) {\r
+               #ifndef STBI_NO_FAILURE_STRINGS\r
+               // not threadsafe\r
+               static char invalid_chunk[] = "XXXX chunk not known";\r
+               invalid_chunk[0] = (uint8) (c.type >> 24);\r
+               invalid_chunk[1] = (uint8) (c.type >> 16);\r
+               invalid_chunk[2] = (uint8) (c.type >>  8);\r
+               invalid_chunk[3] = (uint8) (c.type >>  0);\r
+               #endif\r
+               return e(invalid_chunk, "PNG not supported: unknown chunk type");\r
+            }\r
+            skip(s, c.length);\r
+            break;\r
+      }\r
+      // end of chunk, read and skip CRC\r
+      get32(s);\r
+   }\r
+}\r
+\r
+static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)\r
+{\r
+   unsigned char *result=NULL;\r
+   p->expanded = NULL;\r
+   p->idata = NULL;\r
+   p->out = NULL;\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+   if (parse_png_file(p, SCAN_load, req_comp)) {\r
+      result = p->out;\r
+      p->out = NULL;\r
+      if (req_comp && req_comp != p->s.img_out_n) {\r
+         result = convert_format(result, p->s.img_out_n, req_comp, p->s.img_x, p->s.img_y);\r
+         p->s.img_out_n = req_comp;\r
+         if (result == NULL) return result;\r
+      }\r
+      *x = p->s.img_x;\r
+      *y = p->s.img_y;\r
+      if (n) *n = p->s.img_n;\r
+   }\r
+   free(p->out);      p->out      = NULL;\r
+   free(p->expanded); p->expanded = NULL;\r
+   free(p->idata);    p->idata    = NULL;\r
+\r
+   return result;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   png p;\r
+   start_file(&p.s, f);\r
+   return do_png(&p, x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_png_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_png_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   png p;\r
+   start_mem(&p.s, buffer,len);\r
+   return do_png(&p, x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_png_test_file(FILE *f)\r
+{\r
+   png p;\r
+   int n,r;\r
+   n = ftell(f);\r
+   start_file(&p.s, f);\r
+   r = parse_png_file(&p, SCAN_type,STBI_default);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_png_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   png p;\r
+   start_mem(&p.s, buffer, len);\r
+   return parse_png_file(&p, SCAN_type,STBI_default);\r
+}\r
+\r
+// TODO: load header from png\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_png_info             (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// Microsoft/Windows BMP image\r
+\r
+static int bmp_test(stbi *s)\r
+{\r
+   int sz;\r
+   if (get8(s) != 'B') return 0;\r
+   if (get8(s) != 'M') return 0;\r
+   get32le(s); // discard filesize\r
+   get16le(s); // discard reserved\r
+   get16le(s); // discard reserved\r
+   get32le(s); // discard data offset\r
+   sz = get32le(s);\r
+   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_bmp_test_file        (FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s,f);\r
+   r = bmp_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return bmp_test(&s);\r
+}\r
+\r
+// returns 0..31 for the highest set bit\r
+static int high_bit(unsigned int z)\r
+{\r
+   int n=0;\r
+   if (z == 0) return -1;\r
+   if (z >= 0x10000) n += 16, z >>= 16;\r
+   if (z >= 0x00100) n +=  8, z >>=  8;\r
+   if (z >= 0x00010) n +=  4, z >>=  4;\r
+   if (z >= 0x00004) n +=  2, z >>=  2;\r
+   if (z >= 0x00002) n +=  1, z >>=  1;\r
+   return n;\r
+}\r
+\r
+static int bitcount(unsigned int a)\r
+{\r
+   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\r
+   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\r
+   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\r
+   a = (a + (a >> 8)); // max 16 per 8 bits\r
+   a = (a + (a >> 16)); // max 32 per 8 bits\r
+   return a & 0xff;\r
+}\r
+\r
+static int shiftsigned(int v, int shift, int bits)\r
+{\r
+   int result;\r
+   int z=0;\r
+\r
+   if (shift < 0) v <<= -shift;\r
+   else v >>= shift;\r
+   result = v;\r
+\r
+   z = bits;\r
+   while (z < 8) {\r
+      result += v >> z;\r
+      z += bits;\r
+   }\r
+   return result;\r
+}\r
+\r
+static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   uint8 *out;\r
+   unsigned int mr=0,mg=0,mb=0,ma=0;\r
+   stbi_uc pal[256][4];\r
+   int psize=0,i,j,compress=0,width;\r
+   int bpp, flip_vertically, pad, target, offset, hsz;\r
+   if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");\r
+   get32le(s); // discard filesize\r
+   get16le(s); // discard reserved\r
+   get16le(s); // discard reserved\r
+   offset = get32le(s);\r
+   hsz = get32le(s);\r
+   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");\r
+   failure_reason = "bad BMP";\r
+   if (hsz == 12) {\r
+      s->img_x = get16le(s);\r
+      s->img_y = get16le(s);\r
+   } else {\r
+      s->img_x = get32le(s);\r
+      s->img_y = get32le(s);\r
+   }\r
+   if (get16le(s) != 1) return 0;\r
+   bpp = get16le(s);\r
+   if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");\r
+   flip_vertically = ((int) s->img_y) > 0;\r
+   s->img_y = abs((int) s->img_y);\r
+   if (hsz == 12) {\r
+      if (bpp < 24)\r
+         psize = (offset - 14 - 24) / 3;\r
+   } else {\r
+      compress = get32le(s);\r
+      if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");\r
+      get32le(s); // discard sizeof\r
+      get32le(s); // discard hres\r
+      get32le(s); // discard vres\r
+      get32le(s); // discard colorsused\r
+      get32le(s); // discard max important\r
+      if (hsz == 40 || hsz == 56) {\r
+         if (hsz == 56) {\r
+            get32le(s);\r
+            get32le(s);\r
+            get32le(s);\r
+            get32le(s);\r
+         }\r
+         if (bpp == 16 || bpp == 32) {\r
+            mr = mg = mb = 0;\r
+            if (compress == 0) {\r
+               if (bpp == 32) {\r
+                  mr = 0xff << 16;\r
+                  mg = 0xff <<  8;\r
+                  mb = 0xff <<  0;\r
+               } else {\r
+                  mr = 31 << 10;\r
+                  mg = 31 <<  5;\r
+                  mb = 31 <<  0;\r
+               }\r
+            } else if (compress == 3) {\r
+               mr = get32le(s);\r
+               mg = get32le(s);\r
+               mb = get32le(s);\r
+               // not documented, but generated by photoshop and handled by mspaint\r
+               if (mr == mg && mg == mb) {\r
+                  // ?!?!?\r
+                  return NULL;\r
+               }\r
+            } else\r
+               return NULL;\r
+         }\r
+      } else {\r
+         assert(hsz == 108);\r
+         mr = get32le(s);\r
+         mg = get32le(s);\r
+         mb = get32le(s);\r
+         ma = get32le(s);\r
+         get32le(s); // discard color space\r
+         for (i=0; i < 12; ++i)\r
+            get32le(s); // discard color space parameters\r
+      }\r
+      if (bpp < 16)\r
+         psize = (offset - 14 - hsz) >> 2;\r
+   }\r
+   s->img_n = ma ? 4 : 3;\r
+   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4\r
+      target = req_comp;\r
+   else\r
+      target = s->img_n; // if they want monochrome, we'll post-convert\r
+   out = (stbi_uc *) malloc(target * s->img_x * s->img_y);\r
+   if (!out) return epuc("outofmem", "Out of memory");\r
+   if (bpp < 16) {\r
+      int z=0;\r
+      if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }\r
+      for (i=0; i < psize; ++i) {\r
+         pal[i][2] = get8(s);\r
+         pal[i][1] = get8(s);\r
+         pal[i][0] = get8(s);\r
+         if (hsz != 12) get8(s);\r
+         pal[i][3] = 255;\r
+      }\r
+      skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));\r
+      if (bpp == 4) width = (s->img_x + 1) >> 1;\r
+      else if (bpp == 8) width = s->img_x;\r
+      else { free(out); return epuc("bad bpp", "Corrupt BMP"); }\r
+      pad = (-width)&3;\r
+      for (j=0; j < (int) s->img_y; ++j) {\r
+         for (i=0; i < (int) s->img_x; i += 2) {\r
+            int v=get8(s),v2=0;\r
+            if (bpp == 4) {\r
+               v2 = v & 15;\r
+               v >>= 4;\r
+            }\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+            if (i+1 == (int) s->img_x) break;\r
+            v = (bpp == 8) ? get8(s) : v2;\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+         }\r
+         skip(s, pad);\r
+      }\r
+   } else {\r
+      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;\r
+      int z = 0;\r
+      int easy=0;\r
+      skip(s, offset - 14 - hsz);\r
+      if (bpp == 24) width = 3 * s->img_x;\r
+      else if (bpp == 16) width = 2*s->img_x;\r
+      else /* bpp = 32 and pad = 0 */ width=0;\r
+      pad = (-width) & 3;\r
+      if (bpp == 24) {\r
+         easy = 1;\r
+      } else if (bpp == 32) {\r
+         if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000)\r
+            easy = 2;\r
+      }\r
+      if (!easy) {\r
+         if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP");\r
+         // right shift amt to put high bit in position #7\r
+         rshift = high_bit(mr)-7; rcount = bitcount(mr);\r
+         gshift = high_bit(mg)-7; gcount = bitcount(mr);\r
+         bshift = high_bit(mb)-7; bcount = bitcount(mr);\r
+         ashift = high_bit(ma)-7; acount = bitcount(mr);\r
+      }\r
+      for (j=0; j < (int) s->img_y; ++j) {\r
+         if (easy) {\r
+            for (i=0; i < (int) s->img_x; ++i) {\r
+               int a;\r
+               out[z+2] = get8(s);\r
+               out[z+1] = get8(s);\r
+               out[z+0] = get8(s);\r
+               z += 3;\r
+               a = (easy == 2 ? get8(s) : 255);\r
+               if (target == 4) out[z++] = a;\r
+            }\r
+         } else {\r
+            for (i=0; i < (int) s->img_x; ++i) {\r
+               uint32 v = (bpp == 16 ? get16le(s) : get32le(s));\r
+               int a;\r
+               out[z++] = shiftsigned(v & mr, rshift, rcount);\r
+               out[z++] = shiftsigned(v & mg, gshift, gcount);\r
+               out[z++] = shiftsigned(v & mb, bshift, bcount);\r
+               a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);\r
+               if (target == 4) out[z++] = a; \r
+            }\r
+         }\r
+         skip(s, pad);\r
+      }\r
+   }\r
+   if (flip_vertically) {\r
+      stbi_uc t;\r
+      for (j=0; j < (int) s->img_y>>1; ++j) {\r
+         stbi_uc *p1 = out +      j     *s->img_x*target;\r
+         stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;\r
+         for (i=0; i < (int) s->img_x*target; ++i) {\r
+            t = p1[i], p1[i] = p2[i], p2[i] = t;\r
+         }\r
+      }\r
+   }\r
+\r
+   if (req_comp && req_comp != target) {\r
+      out = convert_format(out, target, req_comp, s->img_x, s->img_y);\r
+      if (out == NULL) return out; // convert_format frees input on failure\r
+   }\r
+\r
+   *x = s->img_x;\r
+   *y = s->img_y;\r
+   if (comp) *comp = target;\r
+   return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_bmp_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_bmp_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return bmp_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return bmp_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+// Targa Truevision - TGA\r
+// by Jonathan Dummer\r
+\r
+static int tga_test(stbi *s)\r
+{\r
+       int sz;\r
+       get8u(s);               //      discard Offset\r
+       sz = get8u(s);  //      color type\r
+       if( sz > 1 ) return 0;  //      only RGB or indexed allowed\r
+       sz = get8u(s);  //      image type\r
+       if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0;    //      only RGB or grey allowed, +/- RLE\r
+       get16(s);               //      discard palette start\r
+       get16(s);               //      discard palette length\r
+       get8(s);                        //      discard bits per palette color entry\r
+       get16(s);               //      discard x origin\r
+       get16(s);               //      discard y origin\r
+       if( get16(s) < 1 ) return 0;            //      test width\r
+       if( get16(s) < 1 ) return 0;            //      test height\r
+       sz = get8(s);   //      bits per pixel\r
+       if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0;     //      only RGB or RGBA or grey allowed\r
+       return 1;               //      seems to have passed everything\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_tga_test_file        (FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = tga_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_tga_test_memory      (stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return tga_test(&s);\r
+}\r
+\r
+static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       //      read in the TGA header stuff\r
+       int tga_offset = get8u(s);\r
+       int tga_indexed = get8u(s);\r
+       int tga_image_type = get8u(s);\r
+       int tga_is_RLE = 0;\r
+       int tga_palette_start = get16le(s);\r
+       int tga_palette_len = get16le(s);\r
+       int tga_palette_bits = get8u(s);\r
+       int tga_x_origin = get16le(s);\r
+       int tga_y_origin = get16le(s);\r
+       int tga_width = get16le(s);\r
+       int tga_height = get16le(s);\r
+       int tga_bits_per_pixel = get8u(s);\r
+       int tga_inverted = get8u(s);\r
+       //      image data\r
+       unsigned char *tga_data;\r
+       unsigned char *tga_palette = NULL;\r
+       int i, j;\r
+       unsigned char raw_data[4];\r
+       unsigned char trans_data[4];\r
+       int RLE_count = 0;\r
+       int RLE_repeating = 0;\r
+       int read_next_pixel = 1;\r
+       //      do a tiny bit of precessing\r
+       if( tga_image_type >= 8 )\r
+       {\r
+               tga_image_type -= 8;\r
+               tga_is_RLE = 1;\r
+       }\r
+       /* int tga_alpha_bits = tga_inverted & 15; */\r
+       tga_inverted = 1 - ((tga_inverted >> 5) & 1);\r
+\r
+       //      error check\r
+       if( //(tga_indexed) ||\r
+               (tga_width < 1) || (tga_height < 1) ||\r
+               (tga_image_type < 1) || (tga_image_type > 3) ||\r
+               ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&\r
+               (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))\r
+               )\r
+       {\r
+               return NULL;\r
+       }\r
+\r
+       //      If I'm paletted, then I'll use the number of bits from the palette\r
+       if( tga_indexed )\r
+       {\r
+               tga_bits_per_pixel = tga_palette_bits;\r
+       }\r
+\r
+       //      tga info\r
+       *x = tga_width;\r
+       *y = tga_height;\r
+       if( (req_comp < 1) || (req_comp > 4) )\r
+       {\r
+               //      just use whatever the file was\r
+               req_comp = tga_bits_per_pixel / 8;\r
+               *comp = req_comp;\r
+       } else\r
+       {\r
+               //      force a new number of components\r
+               *comp = tga_bits_per_pixel/8;\r
+       }\r
+       tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );\r
+\r
+       //      skip to the data's starting position (offset usually = 0)\r
+       skip(s, tga_offset );\r
+       //      do I need to load a palette?\r
+       if( tga_indexed )\r
+       {\r
+               //      any data to skip? (offset usually = 0)\r
+               skip(s, tga_palette_start );\r
+               //      load the palette\r
+               tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );\r
+               getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 );\r
+       }\r
+       //      load the data\r
+       for( i = 0; i < tga_width * tga_height; ++i )\r
+       {\r
+               //      if I'm in RLE mode, do I need to get a RLE chunk?\r
+               if( tga_is_RLE )\r
+               {\r
+                       if( RLE_count == 0 )\r
+                       {\r
+                               //      yep, get the next byte as a RLE command\r
+                               int RLE_cmd = get8u(s);\r
+                               RLE_count = 1 + (RLE_cmd & 127);\r
+                               RLE_repeating = RLE_cmd >> 7;\r
+                               read_next_pixel = 1;\r
+                       } else if( !RLE_repeating )\r
+                       {\r
+                               read_next_pixel = 1;\r
+                       }\r
+               } else\r
+               {\r
+                       read_next_pixel = 1;\r
+               }\r
+               //      OK, if I need to read a pixel, do it now\r
+               if( read_next_pixel )\r
+               {\r
+                       //      load however much data we did have\r
+                       if( tga_indexed )\r
+                       {\r
+                               //      read in 1 byte, then perform the lookup\r
+                               int pal_idx = get8u(s);\r
+                               if( pal_idx >= tga_palette_len )\r
+                               {\r
+                                       //      invalid index\r
+                                       pal_idx = 0;\r
+                               }\r
+                               pal_idx *= tga_bits_per_pixel / 8;\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = tga_palette[pal_idx+j];\r
+                               }\r
+                       } else\r
+                       {\r
+                               //      read in the data raw\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = get8u(s);\r
+                               }\r
+                       }\r
+                       //      convert raw to the intermediate format\r
+                       switch( tga_bits_per_pixel )\r
+                       {\r
+                       case 8:\r
+                               //      Luminous => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 16:\r
+                               //      Luminous,Alpha => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[1];\r
+                               break;\r
+                       case 24:\r
+                               //      BGR => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 32:\r
+                               //      BGRA => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[3];\r
+                               break;\r
+                       }\r
+                       //      clear the reading flag for the next pixel\r
+                       read_next_pixel = 0;\r
+               } // end of reading a pixel\r
+               //      convert to final format\r
+               switch( req_comp )\r
+               {\r
+               case 1:\r
+                       //      RGBA => Luminance\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       break;\r
+               case 2:\r
+                       //      RGBA => Luminance,Alpha\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       tga_data[i*req_comp+1] = trans_data[3];\r
+                       break;\r
+               case 3:\r
+                       //      RGBA => RGB\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       break;\r
+               case 4:\r
+                       //      RGBA => RGBA\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       tga_data[i*req_comp+3] = trans_data[3];\r
+                       break;\r
+               }\r
+               //      in case we're in RLE mode, keep counting down\r
+               --RLE_count;\r
+       }\r
+       //      do I need to invert the image?\r
+       if( tga_inverted )\r
+       {\r
+               for( j = 0; j*2 < tga_height; ++j )\r
+               {\r
+                       int index1 = j * tga_width * req_comp;\r
+                       int index2 = (tga_height - 1 - j) * tga_width * req_comp;\r
+                       for( i = tga_width * req_comp; i > 0; --i )\r
+                       {\r
+                               unsigned char temp = tga_data[index1];\r
+                               tga_data[index1] = tga_data[index2];\r
+                               tga_data[index2] = temp;\r
+                               ++index1;\r
+                               ++index2;\r
+                       }\r
+               }\r
+       }\r
+       //      clear my palette, if I had one\r
+       if( tga_palette != NULL )\r
+       {\r
+               free( tga_palette );\r
+       }\r
+       //      the things I do to get rid of an error message, and yet keep\r
+       //      Microsoft's C compilers happy... [8^(\r
+       tga_palette_start = tga_palette_len = tga_palette_bits =\r
+                       tga_x_origin = tga_y_origin = 0;\r
+       //      OK, done\r
+       return tga_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_tga_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_tga_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return tga_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return tga_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB\r
+\r
+static int psd_test(stbi *s)\r
+{\r
+       if (get32(s) != 0x38425053) return 0;   // "8BPS"\r
+       else return 1;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_psd_test_file(FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = psd_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_psd_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return psd_test(&s);\r
+}\r
+\r
+static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       int     pixelCount;\r
+       int channelCount, compression;\r
+       int channel, i, count, len;\r
+   int w,h;\r
+   uint8 *out;\r
+\r
+       // Check identifier\r
+       if (get32(s) != 0x38425053)     // "8BPS"\r
+               return epuc("not PSD", "Corrupt PSD image");\r
+\r
+       // Check file type version.\r
+       if (get16(s) != 1)\r
+               return epuc("wrong version", "Unsupported version of PSD image");\r
+\r
+       // Skip 6 reserved bytes.\r
+       skip(s, 6 );\r
+\r
+       // Read the number of channels (R, G, B, A, etc).\r
+       channelCount = get16(s);\r
+       if (channelCount < 0 || channelCount > 16)\r
+               return epuc("wrong channel count", "Unsupported number of channels in PSD image");\r
+\r
+       // Read the rows and columns of the image.\r
+   h = get32(s);\r
+   w = get32(s);\r
+       \r
+       // Make sure the depth is 8 bits.\r
+       if (get16(s) != 8)\r
+               return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");\r
+\r
+       // Make sure the color mode is RGB.\r
+       // Valid options are:\r
+       //   0: Bitmap\r
+       //   1: Grayscale\r
+       //   2: Indexed color\r
+       //   3: RGB color\r
+       //   4: CMYK color\r
+       //   7: Multichannel\r
+       //   8: Duotone\r
+       //   9: Lab color\r
+       if (get16(s) != 3)\r
+               return epuc("wrong color format", "PSD is not in RGB color format");\r
+\r
+       // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)\r
+       skip(s,get32(s) );\r
+\r
+       // Skip the image resources.  (resolution, pen tool paths, etc)\r
+       skip(s, get32(s) );\r
+\r
+       // Skip the reserved data.\r
+       skip(s, get32(s) );\r
+\r
+       // Find out if the data is compressed.\r
+       // Known values:\r
+       //   0: no compression\r
+       //   1: RLE compressed\r
+       compression = get16(s);\r
+       if (compression > 1)\r
+               return epuc("bad compression", "PSD has an unknown compression format");\r
+\r
+       // Create the destination image.\r
+       out = (stbi_uc *) malloc(4 * w*h);\r
+       if (!out) return epuc("outofmem", "Out of memory");\r
+   pixelCount = w*h;\r
+\r
+       // Initialize the data to zero.\r
+       //memset( out, 0, pixelCount * 4 );\r
+       \r
+       // Finally, the image data.\r
+       if (compression) {\r
+               // RLE as used by .PSD and .TIFF\r
+               // Loop until you get the number of unpacked bytes you are expecting:\r
+               //     Read the next source byte into n.\r
+               //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.\r
+               //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.\r
+               //     Else if n is 128, noop.\r
+               // Endloop\r
+\r
+               // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,\r
+               // which we're going to just skip.\r
+               skip(s, h * channelCount * 2 );\r
+\r
+               // Read the RLE data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+                       \r
+         p = out+channel;\r
+                       if (channel >= channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;\r
+                       } else {\r
+                               // Read the RLE data.\r
+                               count = 0;\r
+                               while (count < pixelCount) {\r
+                                       len = get8(s);\r
+                                       if (len == 128) {\r
+                                               // No-op.\r
+                                       } else if (len < 128) {\r
+                                               // Copy next len+1 bytes literally.\r
+                                               len++;\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = get8(s);\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       } else if (len > 128) {\r
+                                               uint32  val;\r
+                                               // Next -len+1 bytes in the dest are replicated from next source byte.\r
+                                               // (Interpret len as a negative 8-bit int.)\r
+                                               len ^= 0x0FF;\r
+                                               len += 2;\r
+                  val = get8(s);\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = val;\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+               \r
+       } else {\r
+               // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)\r
+               // where each channel consists of an 8-bit value for each pixel in the image.\r
+               \r
+               // Read the data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+                       \r
+         p = out + channel;\r
+                       if (channel > channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;\r
+                       } else {\r
+                               // Read the data.\r
+                               count = 0;\r
+                               for (i = 0; i < pixelCount; i++)\r
+                                       *p = get8(s), p += 4;\r
+                       }\r
+               }\r
+       }\r
+\r
+       if (req_comp && req_comp != 4) {\r
+               out = convert_format(out, 4, req_comp, w, h);\r
+               if (out == NULL) return out; // convert_format frees input on failure\r
+       }\r
+\r
+       if (comp) *comp = channelCount;\r
+       *y = h;\r
+       *x = w;\r
+       \r
+       return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_psd_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return psd_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return psd_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Radiance RGBE HDR loader\r
+// originally by Nicolas Schulz\r
+#ifndef STBI_NO_HDR\r
+static int hdr_test(stbi *s)\r
+{\r
+   char *signature = "#?RADIANCE\n";\r
+   int i;\r
+   for (i=0; signature[i]; ++i)\r
+      if (get8(s) != signature[i])\r
+         return 0;\r
+       return 1;\r
+}\r
+\r
+int stbi_hdr_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+       start_mem(&s, buffer, len);\r
+       return hdr_test(&s);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_hdr_test_file(FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = hdr_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+#define HDR_BUFLEN  1024\r
+static char *hdr_gettoken(stbi *z, char *buffer)\r
+{\r
+   int len=0;\r
+       char *s = buffer, c = '\0';\r
+\r
+   c = get8(z);\r
+\r
+       while (!at_eof(z) && c != '\n') {\r
+               buffer[len++] = c;\r
+      if (len == HDR_BUFLEN-1) {\r
+         // flush to end of line\r
+         while (!at_eof(z) && get8(z) != '\n')\r
+            ;\r
+         break;\r
+      }\r
+      c = get8(z);\r
+       }\r
+\r
+   buffer[len] = 0;\r
+       return buffer;\r
+}\r
+\r
+static void hdr_convert(float *output, stbi_uc *input, int req_comp)\r
+{\r
+       if( input[3] != 0 ) {\r
+      float f1;\r
+               // Exponent\r
+               f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));\r
+      if (req_comp <= 2)\r
+         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;\r
+      else {\r
+         output[0] = input[0] * f1;\r
+         output[1] = input[1] * f1;\r
+         output[2] = input[2] * f1;\r
+      }\r
+      if (req_comp == 2) output[1] = 1;\r
+      if (req_comp == 4) output[3] = 1;\r
+       } else {\r
+      switch (req_comp) {\r
+         case 4: output[3] = 1; /* fallthrough */\r
+         case 3: output[0] = output[1] = output[2] = 0;\r
+                 break;\r
+         case 2: output[1] = 1; /* fallthrough */\r
+         case 1: output[0] = 0;\r
+                 break;\r
+      }\r
+       }\r
+}\r
+\r
+\r
+static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   char buffer[HDR_BUFLEN];\r
+       char *token;\r
+       int valid = 0;\r
+       int width, height;\r
+   stbi_uc *scanline;\r
+       float *hdr_data;\r
+       int len;\r
+       unsigned char count, value;\r
+       int i, j, k, c1,c2, z;\r
+\r
+\r
+       // Check identifier\r
+       if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)\r
+               return epf("not HDR", "Corrupt HDR image");\r
+       \r
+       // Parse header\r
+       while(1) {\r
+               token = hdr_gettoken(s,buffer);\r
+      if (token[0] == 0) break;\r
+               if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;\r
+   }\r
+\r
+       if (!valid)    return epf("unsupported format", "Unsupported HDR format");\r
+\r
+   // Parse width and height\r
+   // can't use sscanf() if we're not using stdio!\r
+   token = hdr_gettoken(s,buffer);\r
+   if (strncmp(token, "-Y ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   height = strtol(token, &token, 10);\r
+   while (*token == ' ') ++token;\r
+   if (strncmp(token, "+X ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   width = strtol(token, NULL, 10);\r
+\r
+       *x = width;\r
+       *y = height;\r
+\r
+   *comp = 3;\r
+       if (req_comp == 0) req_comp = 3;\r
+\r
+       // Read data\r
+       hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));\r
+\r
+       // Load image data\r
+   // image data is stored as some number of sca\r
+       if( width < 8 || width >= 32768) {\r
+               // Read flat data\r
+      for (j=0; j < height; ++j) {\r
+         for (i=0; i < width; ++i) {\r
+            stbi_uc rgbe[4];\r
+           main_decode_loop:\r
+            getn(s, rgbe, 4);\r
+            hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);\r
+         }\r
+      }\r
+       } else {\r
+               // Read RLE-encoded data\r
+               scanline = NULL;\r
+\r
+               for (j = 0; j < height; ++j) {\r
+         c1 = get8(s);\r
+         c2 = get8(s);\r
+         len = get8(s);\r
+         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\r
+            // not run-length encoded, so we have to actually use THIS data as a decoded\r
+            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\r
+            stbi_uc rgbe[4] = { c1,c2,len, get8(s) };\r
+            hdr_convert(hdr_data, rgbe, req_comp);\r
+            i = 1;\r
+            j = 0;\r
+            free(scanline);\r
+            goto main_decode_loop; // yes, this is fucking insane; blame the fucking insane format\r
+         }\r
+         len <<= 8;\r
+         len |= get8(s);\r
+         if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }\r
+         if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);\r
+                               \r
+                       for (k = 0; k < 4; ++k) {\r
+                               i = 0;\r
+                               while (i < width) {\r
+                                       count = get8(s);\r
+                                       if (count > 128) {\r
+                                               // Run\r
+                                               value = get8(s);\r
+                  count -= 128;\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = value;\r
+                                       } else {\r
+                                               // Dump\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = get8(s);\r
+                                       }\r
+                               }\r
+                       }\r
+         for (i=0; i < width; ++i)\r
+            hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);\r
+               }\r
+      free(scanline);\r
+       }\r
+\r
+   return hdr_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s,f);\r
+   return hdr_load(&s,x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+float *stbi_hdr_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s,buffer, len);\r
+   return hdr_load(&s,x,y,comp,req_comp);\r
+}\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+/////////////////////// write image ///////////////////////\r
+\r
+#ifndef STBI_NO_WRITE\r
+\r
+static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); }\r
+\r
+static void writefv(FILE *f, char *fmt, va_list v)\r
+{\r
+   while (*fmt) {\r
+      switch (*fmt++) {\r
+         case ' ': break;\r
+         case '1': { uint8 x = va_arg(v, int); write8(f,x); break; }\r
+         case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; }\r
+         case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; }\r
+         default:\r
+            assert(0);\r
+            va_end(v);\r
+            return;\r
+      }\r
+   }\r
+}\r
+\r
+static void writef(FILE *f, char *fmt, ...)\r
+{\r
+   va_list v;\r
+   va_start(v, fmt);\r
+   writefv(f,fmt,v);\r
+   va_end(v);\r
+}\r
+\r
+static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)\r
+{\r
+   uint8 bg[3] = { 255, 0, 255}, px[3];\r
+   uint32 zero = 0;\r
+   int i,j,k, j_end;\r
+\r
+   if (vdir < 0) \r
+      j_end = -1, j = y-1;\r
+   else\r
+      j_end =  y, j = 0;\r
+\r
+   for (; j != j_end; j += vdir) {\r
+      for (i=0; i < x; ++i) {\r
+         uint8 *d = (uint8 *) data + (j*x+i)*comp;\r
+         if (write_alpha < 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+         switch (comp) {\r
+            case 1:\r
+            case 2: writef(f, "111", d[0],d[0],d[0]);\r
+                    break;\r
+            case 4:\r
+               if (!write_alpha) {\r
+                  for (k=0; k < 3; ++k)\r
+                     px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;\r
+                  writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]);\r
+                  break;\r
+               }\r
+               /* FALLTHROUGH */\r
+            case 3:\r
+               writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]);\r
+               break;\r
+         }\r
+         if (write_alpha > 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+      }\r
+      fwrite(&zero,scanline_pad,1,f);\r
+   }\r
+}\r
+\r
+static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...)\r
+{\r
+   FILE *f = fopen(filename, "wb");\r
+   if (f) {\r
+      va_list v;\r
+      va_start(v, fmt);\r
+      writefv(f, fmt, v);\r
+      va_end(v);\r
+      write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);\r
+      fclose(f);\r
+   }\r
+   return f != NULL;\r
+}\r
+\r
+int stbi_write_bmp(char const *filename, int x, int y, int comp, void *data)\r
+{\r
+   int pad = (-x*3) & 3;\r
+   return outfile(filename,-1,-1,x,y,comp,data,0,pad,\r
+           "11 4 22 4" "4 44 22 444444",\r
+           'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header\r
+            40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header\r
+}\r
+\r
+int stbi_write_tga(char const *filename, int x, int y, int comp, void *data)\r
+{\r
+   int has_alpha = !(comp & 1);\r
+   return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,\r
+                  "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);\r
+}\r
+\r
+// any other image formats that do interleaved rgb data?\r
+//    PNG: requires adler32,crc32 -- significant amount of code\r
+//    PSD: no, channels output separately\r
+//    TIFF: no, stripwise-interleaved... i think\r
+\r
+#endif // STBI_NO_WRITE\r
+\r
+#endif // STBI_HEADER_FILE_ONLY\r
+\r
diff --git a/lib/soil/soil/stb_image_aug.c b/lib/soil/soil/stb_image_aug.c
new file mode 100644 (file)
index 0000000..2fa7233
--- /dev/null
@@ -0,0 +1,3682 @@
+/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r
+                      when you control the images you're loading\r
+\r
+   QUICK NOTES:\r
+      Primarily of interest to game developers and other people who can\r
+          avoid problematic images and only need the trivial interface\r
+\r
+      JPEG baseline (no JPEG progressive, no oddball channel decimations)\r
+      PNG non-interlaced\r
+      BMP non-1bpp, non-RLE\r
+      TGA (not sure what subset, if a subset)\r
+      PSD (composited view only, no extra channels)\r
+      HDR (radiance rgbE format)\r
+      writes BMP,TGA (define STBI_NO_WRITE to remove code)\r
+      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)\r
+      supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)\r
+\r
+   TODO:\r
+      stbi_info_*\r
+\r
+   history:\r
+      1.16   major bugfix - convert_format converted one too many pixels\r
+      1.15   initialize some fields for thread safety\r
+      1.14   fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)\r
+      1.13   threadsafe\r
+      1.12   const qualifiers in the API\r
+      1.11   Support installable IDCT, colorspace conversion routines\r
+      1.10   Fixes for 64-bit (don't use "unsigned long")\r
+             optimized upsampling by Fabian "ryg" Giesen\r
+      1.09   Fix format-conversion for PSD code (bad global variables!)\r
+      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz\r
+      1.07   attempt to fix C++ warning/errors again\r
+      1.06   attempt to fix C++ warning/errors again\r
+      1.05   fix TGA loading to return correct *comp and use good luminance calc\r
+      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free\r
+      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR\r
+      1.02   support for (subset of) HDR files, float interface for preferred access to them\r
+      1.01   fix bug: possible bug in handling right-side up bmps... not sure\r
+             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all\r
+      1.00   interface to zlib that skips zlib header\r
+      0.99   correct handling of alpha in palette\r
+      0.98   TGA loader by lonesock; dynamically add loaders (untested)\r
+      0.97   jpeg errors on too large a file; also catch another malloc failure\r
+      0.96   fix detection of invalid v value - particleman@mollyrocket forum\r
+      0.95   during header scan, seek to markers in case of padding\r
+      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same\r
+      0.93   handle jpegtran output; verbose errors\r
+      0.92   read 4,8,16,24,32-bit BMP files of several formats\r
+      0.91   output 24-bit Windows 3.0 BMP files\r
+      0.90   fix a few more warnings; bump version number to approach 1.0\r
+      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd\r
+      0.60   fix compiling as c++\r
+      0.59   fix warnings: merge Dave Moore's -Wall fixes\r
+      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian\r
+      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less\r
+                      than 16 available\r
+      0.56   fix bug: zlib uncompressed mode len vs. nlen\r
+      0.55   fix bug: restart_interval not initialized to 0\r
+      0.54   allow NULL for 'int *comp'\r
+      0.53   fix bug in png 3->4; speedup png decoding\r
+      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments\r
+      0.51   obey req_comp requests, 1-component jpegs return as 1-component,\r
+             on 'test' only check type, not whether we support this variant\r
+*/\r
+\r
+#include "stb_image_aug.h"\r
+\r
+#ifndef STBI_NO_HDR\r
+#include <math.h>  // ldexp\r
+#include <string.h> // strcmp\r
+#endif\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+#include <stdlib.h>\r
+#include <memory.h>\r
+#include <assert.h>\r
+#include <stdarg.h>\r
+\r
+#ifndef _MSC_VER\r
+  #ifdef __cplusplus\r
+  #define __forceinline inline\r
+  #else\r
+  #define __forceinline\r
+  #endif\r
+#endif\r
+\r
+\r
+// implementation:\r
+typedef unsigned char uint8;\r
+typedef unsigned short uint16;\r
+typedef   signed short  int16;\r
+typedef unsigned int   uint32;\r
+typedef   signed int    int32;\r
+typedef unsigned int   uint;\r
+\r
+// should produce compiler error if size is wrong\r
+typedef unsigned char validate_uint32[sizeof(uint32)==4];\r
+\r
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)\r
+#define STBI_NO_WRITE\r
+#endif\r
+\r
+#ifndef STBI_NO_DDS\r
+#include "stbi_DDS_aug.h"\r
+#endif\r
+\r
+//     I (JLD) want full messages for SOIL\r
+#define STBI_FAILURE_USERMSG 1\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Generic API that works on all image types\r
+//\r
+\r
+// this is not threadsafe\r
+static char *failure_reason;\r
+\r
+char *stbi_failure_reason(void)\r
+{\r
+   return failure_reason;\r
+}\r
+\r
+static int e(char *str)\r
+{\r
+   failure_reason = str;\r
+   return 0;\r
+}\r
+\r
+#ifdef STBI_NO_FAILURE_STRINGS\r
+   #define e(x,y)  0\r
+#elif defined(STBI_FAILURE_USERMSG)\r
+   #define e(x,y)  e(y)\r
+#else\r
+   #define e(x,y)  e(x)\r
+#endif\r
+\r
+#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))\r
+#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))\r
+\r
+void stbi_image_free(void *retval_from_stbi_load)\r
+{\r
+   free(retval_from_stbi_load);\r
+}\r
+\r
+#define MAX_LOADERS  32\r
+stbi_loader *loaders[MAX_LOADERS];\r
+static int max_loaders = 0;\r
+\r
+int stbi_register_loader(stbi_loader *loader)\r
+{\r
+   int i;\r
+   for (i=0; i < MAX_LOADERS; ++i) {\r
+      // already present?\r
+      if (loaders[i] == loader)\r
+         return 1;\r
+      // end of the list?\r
+      if (loaders[i] == NULL) {\r
+         loaders[i] = loader;\r
+         max_loaders = i+1;\r
+         return 1;\r
+      }\r
+   }\r
+   // no room for it\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);\r
+#endif\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   unsigned char *result;\r
+   if (!f) return epuc("can't fopen", "Unable to open file");\r
+   result = stbi_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_file(f))\r
+      return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_png_test_file(f))\r
+      return stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_file(f))\r
+      return stbi_bmp_load_from_file(f,x,y,comp,req_comp);\r
+   if (stbi_psd_test_file(f))\r
+      return stbi_psd_load_from_file(f,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_DDS\r
+   if (stbi_dds_test_file(f))\r
+      return stbi_dds_load_from_file(f,x,y,comp,req_comp);\r
+   #endif\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f)) {\r
+      float *hdr = stbi_hdr_load_from_file(f, x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_file(f))\r
+         return loaders[i]->load_from_file(f,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_file(f))\r
+      return stbi_tga_load_from_file(f,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   int i;\r
+   if (stbi_jpeg_test_memory(buffer,len))\r
+      return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_png_test_memory(buffer,len))\r
+      return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_bmp_test_memory(buffer,len))\r
+      return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   if (stbi_psd_test_memory(buffer,len))\r
+      return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   #ifndef STBI_NO_DDS\r
+   if (stbi_dds_test_memory(buffer,len))\r
+      return stbi_dds_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   #endif\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len)) {\r
+      float *hdr = stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);\r
+   }\r
+   #endif\r
+   for (i=0; i < max_loaders; ++i)\r
+      if (loaders[i]->test_memory(buffer,len))\r
+         return loaders[i]->load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   // test tga last because it's a crappy test!\r
+   if (stbi_tga_test_memory(buffer,len))\r
+      return stbi_tga_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+   return epuc("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   float *result;\r
+   if (!f) return epf("can't fopen", "Unable to open file");\r
+   result = stbi_loadf_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+\r
+float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_file(f))\r
+      return stbi_hdr_load_from_file(f,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_file(f, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   #ifndef STBI_NO_HDR\r
+   if (stbi_hdr_test_memory(buffer, len))\r
+      return stbi_hdr_load_from_memory(buffer, len,x,y,comp,req_comp);\r
+   #endif\r
+   data = stbi_load_from_memory(buffer, len, x, y, comp, req_comp);\r
+   if (data)\r
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);\r
+   return epf("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif\r
+\r
+// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is\r
+// defined, for API simplicity; if STBI_NO_HDR is defined, it always\r
+// reports false!\r
+\r
+int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_memory(buffer, len);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_is_hdr          (char const *filename)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   int result=0;\r
+   if (f) {\r
+      result = stbi_is_hdr_from_file(f);\r
+      fclose(f);\r
+   }\r
+   return result;\r
+}\r
+\r
+extern int      stbi_is_hdr_from_file(FILE *f)\r
+{\r
+   #ifndef STBI_NO_HDR\r
+   return stbi_hdr_test_file(f);\r
+   #else\r
+   return 0;\r
+   #endif\r
+}\r
+\r
+#endif\r
+\r
+// @TODO: get image dimensions & components without fully decoding\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_HDR\r
+static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;\r
+static float l2h_gamma=2.2f, l2h_scale=1.0f;\r
+\r
+void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }\r
+void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }\r
+\r
+void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }\r
+void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }\r
+#endif\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Common code used by all image loaders\r
+//\r
+\r
+enum\r
+{\r
+   SCAN_load=0,\r
+   SCAN_type,\r
+   SCAN_header,\r
+};\r
+\r
+typedef struct\r
+{\r
+   uint32 img_x, img_y;\r
+   int img_n, img_out_n;\r
+\r
+   #ifndef STBI_NO_STDIO\r
+   FILE  *img_file;\r
+   #endif\r
+   uint8 *img_buffer, *img_buffer_end;\r
+} stbi;\r
+\r
+#ifndef STBI_NO_STDIO\r
+static void start_file(stbi *s, FILE *f)\r
+{\r
+   s->img_file = f;\r
+}\r
+#endif\r
+\r
+static void start_mem(stbi *s, uint8 const *buffer, int len)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   s->img_file = NULL;\r
+#endif\r
+   s->img_buffer = (uint8 *) buffer;\r
+   s->img_buffer_end = (uint8 *) buffer+len;\r
+}\r
+\r
+__forceinline static int get8(stbi *s)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file) {\r
+      int c = fgetc(s->img_file);\r
+      return c == EOF ? 0 : c;\r
+   }\r
+#endif\r
+   if (s->img_buffer < s->img_buffer_end)\r
+      return *s->img_buffer++;\r
+   return 0;\r
+}\r
+\r
+__forceinline static int at_eof(stbi *s)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file)\r
+      return feof(s->img_file);\r
+#endif\r
+   return s->img_buffer >= s->img_buffer_end;\r
+}\r
+\r
+__forceinline static uint8 get8u(stbi *s)\r
+{\r
+   return (uint8) get8(s);\r
+}\r
+\r
+static void skip(stbi *s, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file)\r
+      fseek(s->img_file, n, SEEK_CUR);\r
+   else\r
+#endif\r
+      s->img_buffer += n;\r
+}\r
+\r
+static int get16(stbi *s)\r
+{\r
+   int z = get8(s);\r
+   return (z << 8) + get8(s);\r
+}\r
+\r
+static uint32 get32(stbi *s)\r
+{\r
+   uint32 z = get16(s);\r
+   return (z << 16) + get16(s);\r
+}\r
+\r
+static int get16le(stbi *s)\r
+{\r
+   int z = get8(s);\r
+   return z + (get8(s) << 8);\r
+}\r
+\r
+static uint32 get32le(stbi *s)\r
+{\r
+   uint32 z = get16le(s);\r
+   return z + (get16le(s) << 16);\r
+}\r
+\r
+static void getn(stbi *s, stbi_uc *buffer, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+   if (s->img_file) {\r
+      fread(buffer, 1, n, s->img_file);\r
+      return;\r
+   }\r
+#endif\r
+   memcpy(buffer, s->img_buffer, n);\r
+   s->img_buffer += n;\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  generic converter from built-in img_n to req_comp\r
+//    individual types do this automatically as much as possible (e.g. jpeg\r
+//    does all cases internally since it needs to colorspace convert anyway,\r
+//    and it never has alpha, so very few cases ). png can automatically\r
+//    interleave an alpha=255 channel, but falls back to this for other cases\r
+//\r
+//  assume data buffer is malloced, so malloc a new one and free that one\r
+//  only failure mode is malloc failing\r
+\r
+static uint8 compute_y(int r, int g, int b)\r
+{\r
+   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);\r
+}\r
+\r
+static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)\r
+{\r
+   int i,j;\r
+   unsigned char *good;\r
+\r
+   if (req_comp == img_n) return data;\r
+   assert(req_comp >= 1 && req_comp <= 4);\r
+\r
+   good = (unsigned char *) malloc(req_comp * x * y);\r
+   if (good == NULL) {\r
+      free(data);\r
+      return epuc("outofmem", "Out of memory");\r
+   }\r
+\r
+   for (j=0; j < (int) y; ++j) {\r
+      unsigned char *src  = data + j * x * img_n   ;\r
+      unsigned char *dest = good + j * x * req_comp;\r
+\r
+      #define COMBO(a,b)  ((a)*8+(b))\r
+      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\r
+      // convert source image with img_n components to one with req_comp components;\r
+      // avoid switch per pixel, so use switch per scanline and massive macros\r
+      switch(COMBO(img_n, req_comp)) {\r
+         CASE(1,2) dest[0]=src[0], dest[1]=255; break;\r
+         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;\r
+         CASE(2,1) dest[0]=src[0]; break;\r
+         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;\r
+         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;\r
+         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;\r
+         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;\r
+         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;\r
+         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;\r
+         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;\r
+         default: assert(0);\r
+      }\r
+      #undef CASE\r
+   }\r
+\r
+   free(data);\r
+   return good;\r
+}\r
+\r
+#ifndef STBI_NO_HDR\r
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   float *output = (float *) malloc(x * y * comp * sizeof(float));\r
+   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;\r
+      }\r
+      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+\r
+#define float2int(x)   ((int) (x))\r
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)\r
+{\r
+   int i,k,n;\r
+   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);\r
+   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }\r
+   // compute number of non-alpha components\r
+   if (comp & 1) n = comp; else n = comp-1;\r
+   for (i=0; i < x*y; ++i) {\r
+      for (k=0; k < n; ++k) {\r
+         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+      if (k < comp) {\r
+         float z = data[i*comp+k] * 255 + 0.5f;\r
+         if (z < 0) z = 0;\r
+         if (z > 255) z = 255;\r
+         output[i*comp + k] = float2int(z);\r
+      }\r
+   }\r
+   free(data);\r
+   return output;\r
+}\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)\r
+//\r
+//    simple implementation\r
+//      - channel subsampling of at most 2 in each dimension\r
+//      - doesn't support delayed output of y-dimension\r
+//      - simple interface (only one output format: 8-bit interleaved RGB)\r
+//      - doesn't try to recover corrupt jpegs\r
+//      - doesn't allow partial loading, loading multiple at once\r
+//      - still fast on x86 (copying globals into locals doesn't help x86)\r
+//      - allocates lots of intermediate memory (full size of all components)\r
+//        - non-interleaved case requires this anyway\r
+//        - allows good upsampling (see next)\r
+//    high-quality\r
+//      - upsampled channels are bilinearly interpolated, even across blocks\r
+//      - quality integer IDCT derived from IJG's 'slow'\r
+//    performance\r
+//      - fast huffman; reasonable integer IDCT\r
+//      - uses a lot of intermediate memory, could cache poorly\r
+//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4\r
+//          stb_jpeg:   1.34 seconds (MSVC6, default release build)\r
+//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)\r
+//          IJL11.dll:  1.08 seconds (compiled by intel)\r
+//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)\r
+//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)\r
+\r
+// huffman decoding acceleration\r
+#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache\r
+\r
+typedef struct\r
+{\r
+   uint8  fast[1 << FAST_BITS];\r
+   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win\r
+   uint16 code[256];\r
+   uint8  values[256];\r
+   uint8  size[257];\r
+   unsigned int maxcode[18];\r
+   int    delta[17];   // old 'firstsymbol' - old 'firstcode'\r
+} huffman;\r
+\r
+typedef struct\r
+{\r
+   #if STBI_SIMD\r
+   unsigned short dequant2[4][64];\r
+   #endif\r
+   stbi s;\r
+   huffman huff_dc[4];\r
+   huffman huff_ac[4];\r
+   uint8 dequant[4][64];\r
+\r
+// sizes for components, interleaved MCUs\r
+   int img_h_max, img_v_max;\r
+   int img_mcu_x, img_mcu_y;\r
+   int img_mcu_w, img_mcu_h;\r
+\r
+// definition of jpeg image component\r
+   struct\r
+   {\r
+      int id;\r
+      int h,v;\r
+      int tq;\r
+      int hd,ha;\r
+      int dc_pred;\r
+\r
+      int x,y,w2,h2;\r
+      uint8 *data;\r
+      void *raw_data;\r
+      uint8 *linebuf;\r
+   } img_comp[4];\r
+\r
+   uint32         code_buffer; // jpeg entropy-coded buffer\r
+   int            code_bits;   // number of valid bits\r
+   unsigned char  marker;      // marker seen while filling entropy buffer\r
+   int            nomore;      // flag if we saw a marker so must stop\r
+\r
+   int scan_n, order[4];\r
+   int restart_interval, todo;\r
+} jpeg;\r
+\r
+static int build_huffman(huffman *h, int *count)\r
+{\r
+   int i,j,k=0,code;\r
+   // build size list for each symbol (from JPEG spec)\r
+   for (i=0; i < 16; ++i)\r
+      for (j=0; j < count[i]; ++j)\r
+         h->size[k++] = (uint8) (i+1);\r
+   h->size[k] = 0;\r
+\r
+   // compute actual symbols (from jpeg spec)\r
+   code = 0;\r
+   k = 0;\r
+   for(j=1; j <= 16; ++j) {\r
+      // compute delta to add to code to compute symbol id\r
+      h->delta[j] = k - code;\r
+      if (h->size[k] == j) {\r
+         while (h->size[k] == j)\r
+            h->code[k++] = (uint16) (code++);\r
+         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");\r
+      }\r
+      // compute largest code + 1 for this size, preshifted as needed later\r
+      h->maxcode[j] = code << (16-j);\r
+      code <<= 1;\r
+   }\r
+   h->maxcode[j] = 0xffffffff;\r
+\r
+   // build non-spec acceleration table; 255 is flag for not-accelerated\r
+   memset(h->fast, 255, 1 << FAST_BITS);\r
+   for (i=0; i < k; ++i) {\r
+      int s = h->size[i];\r
+      if (s <= FAST_BITS) {\r
+         int c = h->code[i] << (FAST_BITS-s);\r
+         int m = 1 << (FAST_BITS-s);\r
+         for (j=0; j < m; ++j) {\r
+            h->fast[c+j] = (uint8) i;\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static void grow_buffer_unsafe(jpeg *j)\r
+{\r
+   do {\r
+      int b = j->nomore ? 0 : get8(&j->s);\r
+      if (b == 0xff) {\r
+         int c = get8(&j->s);\r
+         if (c != 0) {\r
+            j->marker = (unsigned char) c;\r
+            j->nomore = 1;\r
+            return;\r
+         }\r
+      }\r
+      j->code_buffer = (j->code_buffer << 8) | b;\r
+      j->code_bits += 8;\r
+   } while (j->code_bits <= 24);\r
+}\r
+\r
+// (1 << n) - 1\r
+static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};\r
+\r
+// decode a jpeg huffman value from the bitstream\r
+__forceinline static int decode(jpeg *j, huffman *h)\r
+{\r
+   unsigned int temp;\r
+   int c,k;\r
+\r
+   if (j->code_bits < 16) grow_buffer_unsafe(j);\r
+\r
+   // look at the top FAST_BITS and determine what symbol ID it is,\r
+   // if the code is <= FAST_BITS\r
+   c = (j->code_buffer >> (j->code_bits - FAST_BITS)) & ((1 << FAST_BITS)-1);\r
+   k = h->fast[c];\r
+   if (k < 255) {\r
+      if (h->size[k] > j->code_bits)\r
+         return -1;\r
+      j->code_bits -= h->size[k];\r
+      return h->values[k];\r
+   }\r
+\r
+   // naive test is to shift the code_buffer down so k bits are\r
+   // valid, then test against maxcode. To speed this up, we've\r
+   // preshifted maxcode left so that it has (16-k) 0s at the\r
+   // end; in other words, regardless of the number of bits, it\r
+   // wants to be compared against something shifted to have 16;\r
+   // that way we don't need to shift inside the loop.\r
+   if (j->code_bits < 16)\r
+      temp = (j->code_buffer << (16 - j->code_bits)) & 0xffff;\r
+   else\r
+      temp = (j->code_buffer >> (j->code_bits - 16)) & 0xffff;\r
+   for (k=FAST_BITS+1 ; ; ++k)\r
+      if (temp < h->maxcode[k])\r
+         break;\r
+   if (k == 17) {\r
+      // error! code not found\r
+      j->code_bits -= 16;\r
+      return -1;\r
+   }\r
+\r
+   if (k > j->code_bits)\r
+      return -1;\r
+\r
+   // convert the huffman code to the symbol id\r
+   c = ((j->code_buffer >> (j->code_bits - k)) & bmask[k]) + h->delta[k];\r
+   assert((((j->code_buffer) >> (j->code_bits - h->size[c])) & bmask[h->size[c]]) == h->code[c]);\r
+\r
+   // convert the id to a symbol\r
+   j->code_bits -= k;\r
+   return h->values[c];\r
+}\r
+\r
+// combined JPEG 'receive' and JPEG 'extend', since baseline\r
+// always extends everything it receives.\r
+__forceinline static int extend_receive(jpeg *j, int n)\r
+{\r
+   unsigned int m = 1 << (n-1);\r
+   unsigned int k;\r
+   if (j->code_bits < n) grow_buffer_unsafe(j);\r
+   k = (j->code_buffer >> (j->code_bits - n)) & bmask[n];\r
+   j->code_bits -= n;\r
+   // the following test is probably a random branch that won't\r
+   // predict well. I tried to table accelerate it but failed.\r
+   // maybe it's compiling as a conditional move?\r
+   if (k < m)\r
+      return (-1 << n) + k + 1;\r
+   else\r
+      return k;\r
+}\r
+\r
+// given a value that's at position X in the zigzag stream,\r
+// where does it appear in the 8x8 matrix coded as row-major?\r
+static uint8 dezigzag[64+15] =\r
+{\r
+    0,  1,  8, 16,  9,  2,  3, 10,\r
+   17, 24, 32, 25, 18, 11,  4,  5,\r
+   12, 19, 26, 33, 40, 48, 41, 34,\r
+   27, 20, 13,  6,  7, 14, 21, 28,\r
+   35, 42, 49, 56, 57, 50, 43, 36,\r
+   29, 22, 15, 23, 30, 37, 44, 51,\r
+   58, 59, 52, 45, 38, 31, 39, 46,\r
+   53, 60, 61, 54, 47, 55, 62, 63,\r
+   // let corrupt input sample past end\r
+   63, 63, 63, 63, 63, 63, 63, 63,\r
+   63, 63, 63, 63, 63, 63, 63\r
+};\r
+\r
+// decode one 64-entry block--\r
+static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)\r
+{\r
+   int diff,dc,k;\r
+   int t = decode(j, hdc);\r
+   if (t < 0) return e("bad huffman code","Corrupt JPEG");\r
+\r
+   // 0 all the ac values now so we can do it 32-bits at a time\r
+   memset(data,0,64*sizeof(data[0]));\r
+\r
+   diff = t ? extend_receive(j, t) : 0;\r
+   dc = j->img_comp[b].dc_pred + diff;\r
+   j->img_comp[b].dc_pred = dc;\r
+   data[0] = (short) dc;\r
+\r
+   // decode AC components, see JPEG spec\r
+   k = 1;\r
+   do {\r
+      int r,s;\r
+      int rs = decode(j, hac);\r
+      if (rs < 0) return e("bad huffman code","Corrupt JPEG");\r
+      s = rs & 15;\r
+      r = rs >> 4;\r
+      if (s == 0) {\r
+         if (rs != 0xf0) break; // end block\r
+         k += 16;\r
+      } else {\r
+         k += r;\r
+         // decode into unzigzag'd location\r
+         data[dezigzag[k++]] = (short) extend_receive(j,s);\r
+      }\r
+   } while (k < 64);\r
+   return 1;\r
+}\r
+\r
+// take a -128..127 value and clamp it and convert to 0..255\r
+__forceinline static uint8 clamp(int x)\r
+{\r
+   x += 128;\r
+   // trick to use a single test to catch both cases\r
+   if ((unsigned int) x > 255) {\r
+      if (x < 0) return 0;\r
+      if (x > 255) return 255;\r
+   }\r
+   return (uint8) x;\r
+}\r
+\r
+#define f2f(x)  (int) (((x) * 4096 + 0.5))\r
+#define fsh(x)  ((x) << 12)\r
+\r
+// derived from jidctint -- DCT_ISLOW\r
+#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \\r
+   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \\r
+   p2 = s2;                                    \\r
+   p3 = s6;                                    \\r
+   p1 = (p2+p3) * f2f(0.5411961f);             \\r
+   t2 = p1 + p3*f2f(-1.847759065f);            \\r
+   t3 = p1 + p2*f2f( 0.765366865f);            \\r
+   p2 = s0;                                    \\r
+   p3 = s4;                                    \\r
+   t0 = fsh(p2+p3);                            \\r
+   t1 = fsh(p2-p3);                            \\r
+   x0 = t0+t3;                                 \\r
+   x3 = t0-t3;                                 \\r
+   x1 = t1+t2;                                 \\r
+   x2 = t1-t2;                                 \\r
+   t0 = s7;                                    \\r
+   t1 = s5;                                    \\r
+   t2 = s3;                                    \\r
+   t3 = s1;                                    \\r
+   p3 = t0+t2;                                 \\r
+   p4 = t1+t3;                                 \\r
+   p1 = t0+t3;                                 \\r
+   p2 = t1+t2;                                 \\r
+   p5 = (p3+p4)*f2f( 1.175875602f);            \\r
+   t0 = t0*f2f( 0.298631336f);                 \\r
+   t1 = t1*f2f( 2.053119869f);                 \\r
+   t2 = t2*f2f( 3.072711026f);                 \\r
+   t3 = t3*f2f( 1.501321110f);                 \\r
+   p1 = p5 + p1*f2f(-0.899976223f);            \\r
+   p2 = p5 + p2*f2f(-2.562915447f);            \\r
+   p3 = p3*f2f(-1.961570560f);                 \\r
+   p4 = p4*f2f(-0.390180644f);                 \\r
+   t3 += p1+p4;                                \\r
+   t2 += p2+p3;                                \\r
+   t1 += p2+p4;                                \\r
+   t0 += p1+p3;\r
+\r
+#if !STBI_SIMD\r
+// .344 seconds on 3*anemones.jpg\r
+static void idct_block(uint8 *out, int out_stride, short data[64], uint8 *dequantize)\r
+{\r
+   int i,val[64],*v=val;\r
+   uint8 *o,*dq = dequantize;\r
+   short *d = data;\r
+\r
+   // columns\r
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {\r
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\r
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\r
+           && d[40]==0 && d[48]==0 && d[56]==0) {\r
+         //    no shortcut                 0     seconds\r
+         //    (1|2|3|4|5|6|7)==0          0     seconds\r
+         //    all separate               -0.047 seconds\r
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\r
+         int dcterm = d[0] * dq[0] << 2;\r
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\r
+      } else {\r
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\r
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\r
+         // constants scaled things up by 1<<12; let's bring them back\r
+         // down, but keep 2 extra bits of precision\r
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\r
+         v[ 0] = (x0+t3) >> 10;\r
+         v[56] = (x0-t3) >> 10;\r
+         v[ 8] = (x1+t2) >> 10;\r
+         v[48] = (x1-t2) >> 10;\r
+         v[16] = (x2+t1) >> 10;\r
+         v[40] = (x2-t1) >> 10;\r
+         v[24] = (x3+t0) >> 10;\r
+         v[32] = (x3-t0) >> 10;\r
+      }\r
+   }\r
+\r
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\r
+      // no fast case since the first 1D IDCT spread components out\r
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\r
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first\r
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together\r
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.\r
+      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;\r
+      o[0] = clamp((x0+t3) >> 17);\r
+      o[7] = clamp((x0-t3) >> 17);\r
+      o[1] = clamp((x1+t2) >> 17);\r
+      o[6] = clamp((x1-t2) >> 17);\r
+      o[2] = clamp((x2+t1) >> 17);\r
+      o[5] = clamp((x2-t1) >> 17);\r
+      o[3] = clamp((x3+t0) >> 17);\r
+      o[4] = clamp((x3-t0) >> 17);\r
+   }\r
+}\r
+#else\r
+static void idct_block(uint8 *out, int out_stride, short data[64], unsigned short *dequantize)\r
+{\r
+   int i,val[64],*v=val;\r
+   uint8 *o;\r
+   unsigned short *dq = dequantize;\r
+   short *d = data;\r
+\r
+   // columns\r
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {\r
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing\r
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0\r
+           && d[40]==0 && d[48]==0 && d[56]==0) {\r
+         //    no shortcut                 0     seconds\r
+         //    (1|2|3|4|5|6|7)==0          0     seconds\r
+         //    all separate               -0.047 seconds\r
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds\r
+         int dcterm = d[0] * dq[0] << 2;\r
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;\r
+      } else {\r
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],\r
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])\r
+         // constants scaled things up by 1<<12; let's bring them back\r
+         // down, but keep 2 extra bits of precision\r
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;\r
+         v[ 0] = (x0+t3) >> 10;\r
+         v[56] = (x0-t3) >> 10;\r
+         v[ 8] = (x1+t2) >> 10;\r
+         v[48] = (x1-t2) >> 10;\r
+         v[16] = (x2+t1) >> 10;\r
+         v[40] = (x2-t1) >> 10;\r
+         v[24] = (x3+t0) >> 10;\r
+         v[32] = (x3-t0) >> 10;\r
+      }\r
+   }\r
+\r
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {\r
+      // no fast case since the first 1D IDCT spread components out\r
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])\r
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first\r
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together\r
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.\r
+      x0 += 65536; x1 += 65536; x2 += 65536; x3 += 65536;\r
+      o[0] = clamp((x0+t3) >> 17);\r
+      o[7] = clamp((x0-t3) >> 17);\r
+      o[1] = clamp((x1+t2) >> 17);\r
+      o[6] = clamp((x1-t2) >> 17);\r
+      o[2] = clamp((x2+t1) >> 17);\r
+      o[5] = clamp((x2-t1) >> 17);\r
+      o[3] = clamp((x3+t0) >> 17);\r
+      o[4] = clamp((x3-t0) >> 17);\r
+   }\r
+}\r
+static stbi_idct_8x8 stbi_idct_installed = idct_block;\r
+\r
+extern void stbi_install_idct(stbi_idct_8x8 func)\r
+{\r
+   stbi_idct_installed = func;\r
+}\r
+#endif\r
+\r
+#define MARKER_none  0xff\r
+// if there's a pending marker from the entropy stream, return that\r
+// otherwise, fetch from the stream and get a marker. if there's no\r
+// marker, return 0xff, which is never a valid marker value\r
+static uint8 get_marker(jpeg *j)\r
+{\r
+   uint8 x;\r
+   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }\r
+   x = get8u(&j->s);\r
+   if (x != 0xff) return MARKER_none;\r
+   while (x == 0xff)\r
+      x = get8u(&j->s);\r
+   return x;\r
+}\r
+\r
+// in each scan, we'll have scan_n components, and the order\r
+// of the components is specified by order[]\r
+#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)\r
+\r
+// after a restart interval, reset the entropy decoder and\r
+// the dc prediction\r
+static void reset(jpeg *j)\r
+{\r
+   j->code_bits = 0;\r
+   j->code_buffer = 0;\r
+   j->nomore = 0;\r
+   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;\r
+   j->marker = MARKER_none;\r
+   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;\r
+   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,\r
+   // since we don't even allow 1<<30 pixels\r
+}\r
+\r
+static int parse_entropy_coded_data(jpeg *z)\r
+{\r
+   reset(z);\r
+   if (z->scan_n == 1) {\r
+      int i,j;\r
+      #if STBI_SIMD\r
+      __declspec(align(16))\r
+      #endif\r
+      short data[64];\r
+      int n = z->order[0];\r
+      // non-interleaved data, we just need to process one block at a time,\r
+      // in trivial scanline order\r
+      // number of blocks to do just depends on how many actual "pixels" this\r
+      // component has, independent of interleaved MCU blocking and such\r
+      int w = (z->img_comp[n].x+7) >> 3;\r
+      int h = (z->img_comp[n].y+7) >> 3;\r
+      for (j=0; j < h; ++j) {\r
+         for (i=0; i < w; ++i) {\r
+            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\r
+            #if STBI_SIMD\r
+            stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\r
+            #else\r
+            idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\r
+            #endif\r
+            // every data block is an MCU, so countdown the restart interval\r
+            if (--z->todo <= 0) {\r
+               if (z->code_bits < 24) grow_buffer_unsafe(z);\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(z->marker)) return 1;\r
+               reset(z);\r
+            }\r
+         }\r
+      }\r
+   } else { // interleaved!\r
+      int i,j,k,x,y;\r
+      short data[64];\r
+      for (j=0; j < z->img_mcu_y; ++j) {\r
+         for (i=0; i < z->img_mcu_x; ++i) {\r
+            // scan an interleaved mcu... process scan_n components in order\r
+            for (k=0; k < z->scan_n; ++k) {\r
+               int n = z->order[k];\r
+               // scan out an mcu's worth of this component; that's just determined\r
+               // by the basic H and V specified for the component\r
+               for (y=0; y < z->img_comp[n].v; ++y) {\r
+                  for (x=0; x < z->img_comp[n].h; ++x) {\r
+                     int x2 = (i*z->img_comp[n].h + x)*8;\r
+                     int y2 = (j*z->img_comp[n].v + y)*8;\r
+                     if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;\r
+                     #if STBI_SIMD\r
+                     stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);\r
+                     #else\r
+                     idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);\r
+                     #endif\r
+                  }\r
+               }\r
+            }\r
+            // after all interleaved components, that's an interleaved MCU,\r
+            // so now count down the restart interval\r
+            if (--z->todo <= 0) {\r
+               if (z->code_bits < 24) grow_buffer_unsafe(z);\r
+               // if it's NOT a restart, then just bail, so we get corrupt data\r
+               // rather than no data\r
+               if (!RESTART(z->marker)) return 1;\r
+               reset(z);\r
+            }\r
+         }\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int process_marker(jpeg *z, int m)\r
+{\r
+   int L;\r
+   switch (m) {\r
+      case MARKER_none: // no marker found\r
+         return e("expected marker","Corrupt JPEG");\r
+\r
+      case 0xC2: // SOF - progressive\r
+         return e("progressive jpeg","JPEG format not supported (progressive)");\r
+\r
+      case 0xDD: // DRI - specify restart interval\r
+         if (get16(&z->s) != 4) return e("bad DRI len","Corrupt JPEG");\r
+         z->restart_interval = get16(&z->s);\r
+         return 1;\r
+\r
+      case 0xDB: // DQT - define quantization table\r
+         L = get16(&z->s)-2;\r
+         while (L > 0) {\r
+            int q = get8(&z->s);\r
+            int p = q >> 4;\r
+            int t = q & 15,i;\r
+            if (p != 0) return e("bad DQT type","Corrupt JPEG");\r
+            if (t > 3) return e("bad DQT table","Corrupt JPEG");\r
+            for (i=0; i < 64; ++i)\r
+               z->dequant[t][dezigzag[i]] = get8u(&z->s);\r
+            #if STBI_SIMD\r
+            for (i=0; i < 64; ++i)\r
+               z->dequant2[t][i] = dequant[t][i];\r
+            #endif\r
+            L -= 65;\r
+         }\r
+         return L==0;\r
+\r
+      case 0xC4: // DHT - define huffman table\r
+         L = get16(&z->s)-2;\r
+         while (L > 0) {\r
+            uint8 *v;\r
+            int sizes[16],i,m=0;\r
+            int q = get8(&z->s);\r
+            int tc = q >> 4;\r
+            int th = q & 15;\r
+            if (tc > 1 || th > 3) return e("bad DHT header","Corrupt JPEG");\r
+            for (i=0; i < 16; ++i) {\r
+               sizes[i] = get8(&z->s);\r
+               m += sizes[i];\r
+            }\r
+            L -= 17;\r
+            if (tc == 0) {\r
+               if (!build_huffman(z->huff_dc+th, sizes)) return 0;\r
+               v = z->huff_dc[th].values;\r
+            } else {\r
+               if (!build_huffman(z->huff_ac+th, sizes)) return 0;\r
+               v = z->huff_ac[th].values;\r
+            }\r
+            for (i=0; i < m; ++i)\r
+               v[i] = get8u(&z->s);\r
+            L -= m;\r
+         }\r
+         return L==0;\r
+   }\r
+   // check for comment block or APP blocks\r
+   if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {\r
+      skip(&z->s, get16(&z->s)-2);\r
+      return 1;\r
+   }\r
+   return 0;\r
+}\r
+\r
+// after we see SOS\r
+static int process_scan_header(jpeg *z)\r
+{\r
+   int i;\r
+   int Ls = get16(&z->s);\r
+   z->scan_n = get8(&z->s);\r
+   if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s.img_n) return e("bad SOS component count","Corrupt JPEG");\r
+   if (Ls != 6+2*z->scan_n) return e("bad SOS len","Corrupt JPEG");\r
+   for (i=0; i < z->scan_n; ++i) {\r
+      int id = get8(&z->s), which;\r
+      int q = get8(&z->s);\r
+      for (which = 0; which < z->s.img_n; ++which)\r
+         if (z->img_comp[which].id == id)\r
+            break;\r
+      if (which == z->s.img_n) return 0;\r
+      z->img_comp[which].hd = q >> 4;   if (z->img_comp[which].hd > 3) return e("bad DC huff","Corrupt JPEG");\r
+      z->img_comp[which].ha = q & 15;   if (z->img_comp[which].ha > 3) return e("bad AC huff","Corrupt JPEG");\r
+      z->order[i] = which;\r
+   }\r
+   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");\r
+   get8(&z->s); // should be 63, but might be 0\r
+   if (get8(&z->s) != 0) return e("bad SOS","Corrupt JPEG");\r
+\r
+   return 1;\r
+}\r
+\r
+static int process_frame_header(jpeg *z, int scan)\r
+{\r
+   stbi *s = &z->s;\r
+   int Lf,p,i,q, h_max=1,v_max=1,c;\r
+   Lf = get16(s);         if (Lf < 11) return e("bad SOF len","Corrupt JPEG"); // JPEG\r
+   p  = get8(s);          if (p != 8) return e("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline\r
+   s->img_y = get16(s);   if (s->img_y == 0) return e("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG\r
+   s->img_x = get16(s);   if (s->img_x == 0) return e("0 width","Corrupt JPEG"); // JPEG requires\r
+   c = get8(s);\r
+   if (c != 3 && c != 1) return e("bad component count","Corrupt JPEG");    // JFIF requires\r
+   s->img_n = c;\r
+   for (i=0; i < c; ++i) {\r
+      z->img_comp[i].data = NULL;\r
+      z->img_comp[i].linebuf = NULL;\r
+   }\r
+\r
+   if (Lf != 8+3*s->img_n) return e("bad SOF len","Corrupt JPEG");\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      z->img_comp[i].id = get8(s);\r
+      if (z->img_comp[i].id != i+1)   // JFIF requires\r
+         if (z->img_comp[i].id != i)  // some version of jpegtran outputs non-JFIF-compliant files!\r
+            return e("bad component ID","Corrupt JPEG");\r
+      q = get8(s);\r
+      z->img_comp[i].h = (q >> 4);  if (!z->img_comp[i].h || z->img_comp[i].h > 4) return e("bad H","Corrupt JPEG");\r
+      z->img_comp[i].v = q & 15;    if (!z->img_comp[i].v || z->img_comp[i].v > 4) return e("bad V","Corrupt JPEG");\r
+      z->img_comp[i].tq = get8(s);  if (z->img_comp[i].tq > 3) return e("bad TQ","Corrupt JPEG");\r
+   }\r
+\r
+   if (scan != SCAN_load) return 1;\r
+\r
+   if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;\r
+      if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;\r
+   }\r
+\r
+   // compute interleaved mcu info\r
+   z->img_h_max = h_max;\r
+   z->img_v_max = v_max;\r
+   z->img_mcu_w = h_max * 8;\r
+   z->img_mcu_h = v_max * 8;\r
+   z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;\r
+   z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;\r
+\r
+   for (i=0; i < s->img_n; ++i) {\r
+      // number of effective pixels (e.g. for non-interleaved MCU)\r
+      z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;\r
+      z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;\r
+      // to simplify generation, we'll allocate enough memory to decode\r
+      // the bogus oversized data from using interleaved MCUs and their\r
+      // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't\r
+      // discard the extra data until colorspace conversion\r
+      z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;\r
+      z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;\r
+      z->img_comp[i].raw_data = malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);\r
+      if (z->img_comp[i].raw_data == NULL) {\r
+         for(--i; i >= 0; --i) {\r
+            free(z->img_comp[i].raw_data);\r
+            z->img_comp[i].data = NULL;\r
+         }\r
+         return e("outofmem", "Out of memory");\r
+      }\r
+      // align blocks for installable-idct using mmx/sse\r
+      z->img_comp[i].data = (uint8*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);\r
+      z->img_comp[i].linebuf = NULL;\r
+   }\r
+\r
+   return 1;\r
+}\r
+\r
+// use comparisons since in some cases we handle more than one case (e.g. SOF)\r
+#define DNL(x)         ((x) == 0xdc)\r
+#define SOI(x)         ((x) == 0xd8)\r
+#define EOI(x)         ((x) == 0xd9)\r
+#define SOF(x)         ((x) == 0xc0 || (x) == 0xc1)\r
+#define SOS(x)         ((x) == 0xda)\r
+\r
+static int decode_jpeg_header(jpeg *z, int scan)\r
+{\r
+   int m;\r
+   z->marker = MARKER_none; // initialize cached marker to empty\r
+   m = get_marker(z);\r
+   if (!SOI(m)) return e("no SOI","Corrupt JPEG");\r
+   if (scan == SCAN_type) return 1;\r
+   m = get_marker(z);\r
+   while (!SOF(m)) {\r
+      if (!process_marker(z,m)) return 0;\r
+      m = get_marker(z);\r
+      while (m == MARKER_none) {\r
+         // some files have extra padding after their blocks, so ok, we'll scan\r
+         if (at_eof(&z->s)) return e("no SOF", "Corrupt JPEG");\r
+         m = get_marker(z);\r
+      }\r
+   }\r
+   if (!process_frame_header(z, scan)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int decode_jpeg_image(jpeg *j)\r
+{\r
+   int m;\r
+   j->restart_interval = 0;\r
+   if (!decode_jpeg_header(j, SCAN_load)) return 0;\r
+   m = get_marker(j);\r
+   while (!EOI(m)) {\r
+      if (SOS(m)) {\r
+         if (!process_scan_header(j)) return 0;\r
+         if (!parse_entropy_coded_data(j)) return 0;\r
+      } else {\r
+         if (!process_marker(j, m)) return 0;\r
+      }\r
+      m = get_marker(j);\r
+   }\r
+   return 1;\r
+}\r
+\r
+// static jfif-centered resampling (across block boundaries)\r
+\r
+typedef uint8 *(*resample_row_func)(uint8 *out, uint8 *in0, uint8 *in1,\r
+                                    int w, int hs);\r
+\r
+#define div4(x) ((uint8) ((x) >> 2))\r
+\r
+static uint8 *resample_row_1(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   return in_near;\r
+}\r
+\r
+static uint8* resample_row_v_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate two samples vertically for every one in input\r
+   int i;\r
+   for (i=0; i < w; ++i)\r
+      out[i] = div4(3*in_near[i] + in_far[i] + 2);\r
+   return out;\r
+}\r
+\r
+static uint8*  resample_row_h_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate two samples horizontally for every one in input\r
+   int i;\r
+   uint8 *input = in_near;\r
+   if (w == 1) {\r
+      // if only one sample, can't do any interpolation\r
+      out[0] = out[1] = input[0];\r
+      return out;\r
+   }\r
+\r
+   out[0] = input[0];\r
+   out[1] = div4(input[0]*3 + input[1] + 2);\r
+   for (i=1; i < w-1; ++i) {\r
+      int n = 3*input[i]+2;\r
+      out[i*2+0] = div4(n+input[i-1]);\r
+      out[i*2+1] = div4(n+input[i+1]);\r
+   }\r
+   out[i*2+0] = div4(input[w-2]*3 + input[w-1] + 2);\r
+   out[i*2+1] = input[w-1];\r
+   return out;\r
+}\r
+\r
+#define div16(x) ((uint8) ((x) >> 4))\r
+\r
+static uint8 *resample_row_hv_2(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // need to generate 2x2 samples for every one in input\r
+   int i,t0,t1;\r
+   if (w == 1) {\r
+      out[0] = out[1] = div4(3*in_near[0] + in_far[0] + 2);\r
+      return out;\r
+   }\r
+\r
+   t1 = 3*in_near[0] + in_far[0];\r
+   out[0] = div4(t1+2);\r
+   for (i=1; i < w; ++i) {\r
+      t0 = t1;\r
+      t1 = 3*in_near[i]+in_far[i];\r
+      out[i*2-1] = div16(3*t0 + t1 + 8);\r
+      out[i*2  ] = div16(3*t1 + t0 + 8);\r
+   }\r
+   out[w*2-1] = div4(t1+2);\r
+   return out;\r
+}\r
+\r
+static uint8 *resample_row_generic(uint8 *out, uint8 *in_near, uint8 *in_far, int w, int hs)\r
+{\r
+   // resample with nearest-neighbor\r
+   int i,j;\r
+   for (i=0; i < w; ++i)\r
+      for (j=0; j < hs; ++j)\r
+         out[i*hs+j] = in_near[i];\r
+   return out;\r
+}\r
+\r
+#define float2fixed(x)  ((int) ((x) * 65536 + 0.5))\r
+\r
+// 0.38 seconds on 3*anemones.jpg   (0.25 with processor = Pro)\r
+// VC6 without processor=Pro is generating multiple LEAs per multiply!\r
+static void YCbCr_to_RGB_row(uint8 *out, uint8 *y, uint8 *pcb, uint8 *pcr, int count, int step)\r
+{\r
+   int i;\r
+   for (i=0; i < count; ++i) {\r
+      int y_fixed = (y[i] << 16) + 32768; // rounding\r
+      int r,g,b;\r
+      int cr = pcr[i] - 128;\r
+      int cb = pcb[i] - 128;\r
+      r = y_fixed + cr*float2fixed(1.40200f);\r
+      g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);\r
+      b = y_fixed                            + cb*float2fixed(1.77200f);\r
+      r >>= 16;\r
+      g >>= 16;\r
+      b >>= 16;\r
+      if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }\r
+      if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }\r
+      if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }\r
+      out[0] = (uint8)r;\r
+      out[1] = (uint8)g;\r
+      out[2] = (uint8)b;\r
+      out[3] = 255;\r
+      out += step;\r
+   }\r
+}\r
+\r
+#if STBI_SIMD\r
+static stbi_YCbCr_to_RGB_run stbi_YCbCr_installed = YCbCr_to_RGB_row;\r
+\r
+void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)\r
+{\r
+   stbi_YCbCr_installed = func;\r
+}\r
+#endif\r
+\r
+\r
+// clean up the temporary component buffers\r
+static void cleanup_jpeg(jpeg *j)\r
+{\r
+   int i;\r
+   for (i=0; i < j->s.img_n; ++i) {\r
+      if (j->img_comp[i].data) {\r
+         free(j->img_comp[i].raw_data);\r
+         j->img_comp[i].data = NULL;\r
+      }\r
+      if (j->img_comp[i].linebuf) {\r
+         free(j->img_comp[i].linebuf);\r
+         j->img_comp[i].linebuf = NULL;\r
+      }\r
+   }\r
+}\r
+\r
+typedef struct\r
+{\r
+   resample_row_func resample;\r
+   uint8 *line0,*line1;\r
+   int hs,vs;   // expansion factor in each axis\r
+   int w_lores; // horizontal pixels pre-expansion\r
+   int ystep;   // how far through vertical expansion we are\r
+   int ypos;    // which pre-expansion row we're on\r
+} stbi_resample;\r
+\r
+static uint8 *load_jpeg_image(jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)\r
+{\r
+   int n, decode_n;\r
+   // validate req_comp\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+   z->s.img_n = 0;\r
+\r
+   // load a jpeg image from whichever source\r
+   if (!decode_jpeg_image(z)) { cleanup_jpeg(z); return NULL; }\r
+\r
+   // determine actual number of components to generate\r
+   n = req_comp ? req_comp : z->s.img_n;\r
+\r
+   if (z->s.img_n == 3 && n < 3)\r
+      decode_n = 1;\r
+   else\r
+      decode_n = z->s.img_n;\r
+\r
+   // resample and color-convert\r
+   {\r
+      int k;\r
+      uint i,j;\r
+      uint8 *output;\r
+      uint8 *coutput[4];\r
+\r
+      stbi_resample res_comp[4];\r
+\r
+      for (k=0; k < decode_n; ++k) {\r
+         stbi_resample *r = &res_comp[k];\r
+\r
+         // allocate line buffer big enough for upsampling off the edges\r
+         // with upsample factor of 4\r
+         z->img_comp[k].linebuf = (uint8 *) malloc(z->s.img_x + 3);\r
+         if (!z->img_comp[k].linebuf) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }\r
+\r
+         r->hs      = z->img_h_max / z->img_comp[k].h;\r
+         r->vs      = z->img_v_max / z->img_comp[k].v;\r
+         r->ystep   = r->vs >> 1;\r
+         r->w_lores = (z->s.img_x + r->hs-1) / r->hs;\r
+         r->ypos    = 0;\r
+         r->line0   = r->line1 = z->img_comp[k].data;\r
+\r
+         if      (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;\r
+         else if (r->hs == 1 && r->vs == 2) r->resample = resample_row_v_2;\r
+         else if (r->hs == 2 && r->vs == 1) r->resample = resample_row_h_2;\r
+         else if (r->hs == 2 && r->vs == 2) r->resample = resample_row_hv_2;\r
+         else                               r->resample = resample_row_generic;\r
+      }\r
+\r
+      // can't error after this so, this is safe\r
+      output = (uint8 *) malloc(n * z->s.img_x * z->s.img_y + 1);\r
+      if (!output) { cleanup_jpeg(z); return epuc("outofmem", "Out of memory"); }\r
+\r
+      // now go ahead and resample\r
+      for (j=0; j < z->s.img_y; ++j) {\r
+         uint8 *out = output + n * z->s.img_x * j;\r
+         for (k=0; k < decode_n; ++k) {\r
+            stbi_resample *r = &res_comp[k];\r
+            int y_bot = r->ystep >= (r->vs >> 1);\r
+            coutput[k] = r->resample(z->img_comp[k].linebuf,\r
+                                     y_bot ? r->line1 : r->line0,\r
+                                     y_bot ? r->line0 : r->line1,\r
+                                     r->w_lores, r->hs);\r
+            if (++r->ystep >= r->vs) {\r
+               r->ystep = 0;\r
+               r->line0 = r->line1;\r
+               if (++r->ypos < z->img_comp[k].y)\r
+                  r->line1 += z->img_comp[k].w2;\r
+            }\r
+         }\r
+         if (n >= 3) {\r
+            uint8 *y = coutput[0];\r
+            if (z->s.img_n == 3) {\r
+               #if STBI_SIMD\r
+               stbi_YCbCr_installed(out, y, coutput[1], coutput[2], z->s.img_x, n);\r
+               #else\r
+               YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s.img_x, n);\r
+               #endif\r
+            } else\r
+               for (i=0; i < z->s.img_x; ++i) {\r
+                  out[0] = out[1] = out[2] = y[i];\r
+                  out[3] = 255; // not used if n==3\r
+                  out += n;\r
+               }\r
+         } else {\r
+            uint8 *y = coutput[0];\r
+            if (n == 1)\r
+               for (i=0; i < z->s.img_x; ++i) out[i] = y[i];\r
+            else\r
+               for (i=0; i < z->s.img_x; ++i) *out++ = y[i], *out++ = 255;\r
+         }\r
+      }\r
+      cleanup_jpeg(z);\r
+      *out_x = z->s.img_x;\r
+      *out_y = z->s.img_y;\r
+      if (comp) *comp  = z->s.img_n; // report original components, not output\r
+      return output;\r
+   }\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_jpeg_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   jpeg j;\r
+   start_file(&j.s, f);\r
+   return load_jpeg_image(&j, x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_jpeg_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   jpeg j;\r
+   start_mem(&j.s, buffer,len);\r
+   return load_jpeg_image(&j, x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_jpeg_test_file(FILE *f)\r
+{\r
+   int n,r;\r
+   jpeg j;\r
+   n = ftell(f);\r
+   start_file(&j.s, f);\r
+   r = decode_jpeg_header(&j, SCAN_type);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_jpeg_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   jpeg j;\r
+   start_mem(&j.s, buffer,len);\r
+   return decode_jpeg_header(&j, SCAN_type);\r
+}\r
+\r
+// @TODO:\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_jpeg_info            (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// public domain zlib decode    v0.2  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - all input must be provided in an upfront buffer\r
+//      - all output is written to a single output buffer (can malloc/realloc)\r
+//    performance\r
+//      - fast huffman\r
+\r
+// fast-way is faster to check than jpeg huffman, but slow way is slower\r
+#define ZFAST_BITS  9 // accelerate all cases in default tables\r
+#define ZFAST_MASK  ((1 << ZFAST_BITS) - 1)\r
+\r
+// zlib-style huffman encoding\r
+// (jpegs packs from left, zlib from right, so can't share code)\r
+typedef struct\r
+{\r
+   uint16 fast[1 << ZFAST_BITS];\r
+   uint16 firstcode[16];\r
+   int maxcode[17];\r
+   uint16 firstsymbol[16];\r
+   uint8  size[288];\r
+   uint16 value[288];\r
+} zhuffman;\r
+\r
+__forceinline static int bitreverse16(int n)\r
+{\r
+  n = ((n & 0xAAAA) >>  1) | ((n & 0x5555) << 1);\r
+  n = ((n & 0xCCCC) >>  2) | ((n & 0x3333) << 2);\r
+  n = ((n & 0xF0F0) >>  4) | ((n & 0x0F0F) << 4);\r
+  n = ((n & 0xFF00) >>  8) | ((n & 0x00FF) << 8);\r
+  return n;\r
+}\r
+\r
+__forceinline static int bit_reverse(int v, int bits)\r
+{\r
+   assert(bits <= 16);\r
+   // to bit reverse n bits, reverse 16 and shift\r
+   // e.g. 11 bits, bit reverse and shift away 5\r
+   return bitreverse16(v) >> (16-bits);\r
+}\r
+\r
+static int zbuild_huffman(zhuffman *z, uint8 *sizelist, int num)\r
+{\r
+   int i,k=0;\r
+   int code, next_code[16], sizes[17];\r
+\r
+   // DEFLATE spec for generating codes\r
+   memset(sizes, 0, sizeof(sizes));\r
+   memset(z->fast, 255, sizeof(z->fast));\r
+   for (i=0; i < num; ++i)\r
+      ++sizes[sizelist[i]];\r
+   sizes[0] = 0;\r
+   for (i=1; i < 16; ++i)\r
+      assert(sizes[i] <= (1 << i));\r
+   code = 0;\r
+   for (i=1; i < 16; ++i) {\r
+      next_code[i] = code;\r
+      z->firstcode[i] = (uint16) code;\r
+      z->firstsymbol[i] = (uint16) k;\r
+      code = (code + sizes[i]);\r
+      if (sizes[i])\r
+         if (code-1 >= (1 << i)) return e("bad codelengths","Corrupt JPEG");\r
+      z->maxcode[i] = code << (16-i); // preshift for inner loop\r
+      code <<= 1;\r
+      k += sizes[i];\r
+   }\r
+   z->maxcode[16] = 0x10000; // sentinel\r
+   for (i=0; i < num; ++i) {\r
+      int s = sizelist[i];\r
+      if (s) {\r
+         int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];\r
+         z->size[c] = (uint8)s;\r
+         z->value[c] = (uint16)i;\r
+         if (s <= ZFAST_BITS) {\r
+            int k = bit_reverse(next_code[s],s);\r
+            while (k < (1 << ZFAST_BITS)) {\r
+               z->fast[k] = (uint16) c;\r
+               k += (1 << s);\r
+            }\r
+         }\r
+         ++next_code[s];\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+// zlib-from-memory implementation for PNG reading\r
+//    because PNG allows splitting the zlib stream arbitrarily,\r
+//    and it's annoying structurally to have PNG call ZLIB call PNG,\r
+//    we require PNG read all the IDATs and combine them into a single\r
+//    memory buffer\r
+\r
+typedef struct\r
+{\r
+   uint8 *zbuffer, *zbuffer_end;\r
+   int num_bits;\r
+   uint32 code_buffer;\r
+\r
+   char *zout;\r
+   char *zout_start;\r
+   char *zout_end;\r
+   int   z_expandable;\r
+\r
+   zhuffman z_length, z_distance;\r
+} zbuf;\r
+\r
+__forceinline static int zget8(zbuf *z)\r
+{\r
+   if (z->zbuffer >= z->zbuffer_end) return 0;\r
+   return *z->zbuffer++;\r
+}\r
+\r
+static void fill_bits(zbuf *z)\r
+{\r
+   do {\r
+      assert(z->code_buffer < (1U << z->num_bits));\r
+      z->code_buffer |= zget8(z) << z->num_bits;\r
+      z->num_bits += 8;\r
+   } while (z->num_bits <= 24);\r
+}\r
+\r
+__forceinline static unsigned int zreceive(zbuf *z, int n)\r
+{\r
+   unsigned int k;\r
+   if (z->num_bits < n) fill_bits(z);\r
+   k = z->code_buffer & ((1 << n) - 1);\r
+   z->code_buffer >>= n;\r
+   z->num_bits -= n;\r
+   return k;\r
+}\r
+\r
+__forceinline static int zhuffman_decode(zbuf *a, zhuffman *z)\r
+{\r
+   int b,s,k;\r
+   if (a->num_bits < 16) fill_bits(a);\r
+   b = z->fast[a->code_buffer & ZFAST_MASK];\r
+   if (b < 0xffff) {\r
+      s = z->size[b];\r
+      a->code_buffer >>= s;\r
+      a->num_bits -= s;\r
+      return z->value[b];\r
+   }\r
+\r
+   // not resolved by fast table, so compute it the slow way\r
+   // use jpeg approach, which requires MSbits at top\r
+   k = bit_reverse(a->code_buffer, 16);\r
+   for (s=ZFAST_BITS+1; ; ++s)\r
+      if (k < z->maxcode[s])\r
+         break;\r
+   if (s == 16) return -1; // invalid code!\r
+   // code size is s, so:\r
+   b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];\r
+   assert(z->size[b] == s);\r
+   a->code_buffer >>= s;\r
+   a->num_bits -= s;\r
+   return z->value[b];\r
+}\r
+\r
+static int expand(zbuf *z, int n)  // need to make room for n bytes\r
+{\r
+   char *q;\r
+   int cur, limit;\r
+   if (!z->z_expandable) return e("output buffer limit","Corrupt PNG");\r
+   cur   = (int) (z->zout     - z->zout_start);\r
+   limit = (int) (z->zout_end - z->zout_start);\r
+   while (cur + n > limit)\r
+      limit *= 2;\r
+   q = (char *) realloc(z->zout_start, limit);\r
+   if (q == NULL) return e("outofmem", "Out of memory");\r
+   z->zout_start = q;\r
+   z->zout       = q + cur;\r
+   z->zout_end   = q + limit;\r
+   return 1;\r
+}\r
+\r
+static int length_base[31] = {\r
+   3,4,5,6,7,8,9,10,11,13,\r
+   15,17,19,23,27,31,35,43,51,59,\r
+   67,83,99,115,131,163,195,227,258,0,0 };\r
+\r
+static int length_extra[31]=\r
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };\r
+\r
+static int dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,\r
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};\r
+\r
+static int dist_extra[32] =\r
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\r
+\r
+static int parse_huffman_block(zbuf *a)\r
+{\r
+   for(;;) {\r
+      int z = zhuffman_decode(a, &a->z_length);\r
+      if (z < 256) {\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG"); // error in huffman codes\r
+         if (a->zout >= a->zout_end) if (!expand(a, 1)) return 0;\r
+         *a->zout++ = (char) z;\r
+      } else {\r
+         uint8 *p;\r
+         int len,dist;\r
+         if (z == 256) return 1;\r
+         z -= 257;\r
+         len = length_base[z];\r
+         if (length_extra[z]) len += zreceive(a, length_extra[z]);\r
+         z = zhuffman_decode(a, &a->z_distance);\r
+         if (z < 0) return e("bad huffman code","Corrupt PNG");\r
+         dist = dist_base[z];\r
+         if (dist_extra[z]) dist += zreceive(a, dist_extra[z]);\r
+         if (a->zout - a->zout_start < dist) return e("bad dist","Corrupt PNG");\r
+         if (a->zout + len > a->zout_end) if (!expand(a, len)) return 0;\r
+         p = (uint8 *) (a->zout - dist);\r
+         while (len--)\r
+            *a->zout++ = *p++;\r
+      }\r
+   }\r
+}\r
+\r
+static int compute_huffman_codes(zbuf *a)\r
+{\r
+   static uint8 length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };\r
+   static zhuffman z_codelength; // static just to save stack space\r
+   uint8 lencodes[286+32+137];//padding for maximum single op\r
+   uint8 codelength_sizes[19];\r
+   int i,n;\r
+\r
+   int hlit  = zreceive(a,5) + 257;\r
+   int hdist = zreceive(a,5) + 1;\r
+   int hclen = zreceive(a,4) + 4;\r
+\r
+   memset(codelength_sizes, 0, sizeof(codelength_sizes));\r
+   for (i=0; i < hclen; ++i) {\r
+      int s = zreceive(a,3);\r
+      codelength_sizes[length_dezigzag[i]] = (uint8) s;\r
+   }\r
+   if (!zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;\r
+\r
+   n = 0;\r
+   while (n < hlit + hdist) {\r
+      int c = zhuffman_decode(a, &z_codelength);\r
+      assert(c >= 0 && c < 19);\r
+      if (c < 16)\r
+         lencodes[n++] = (uint8) c;\r
+      else if (c == 16) {\r
+         c = zreceive(a,2)+3;\r
+         memset(lencodes+n, lencodes[n-1], c);\r
+         n += c;\r
+      } else if (c == 17) {\r
+         c = zreceive(a,3)+3;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      } else {\r
+         assert(c == 18);\r
+         c = zreceive(a,7)+11;\r
+         memset(lencodes+n, 0, c);\r
+         n += c;\r
+      }\r
+   }\r
+   if (n != hlit+hdist) return e("bad codelengths","Corrupt PNG");\r
+   if (!zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;\r
+   if (!zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;\r
+   return 1;\r
+}\r
+\r
+static int parse_uncompressed_block(zbuf *a)\r
+{\r
+   uint8 header[4];\r
+   int len,nlen,k;\r
+   if (a->num_bits & 7)\r
+      zreceive(a, a->num_bits & 7); // discard\r
+   // drain the bit-packed data into header\r
+   k = 0;\r
+   while (a->num_bits > 0) {\r
+      header[k++] = (uint8) (a->code_buffer & 255); // wtf this warns?\r
+      a->code_buffer >>= 8;\r
+      a->num_bits -= 8;\r
+   }\r
+   assert(a->num_bits == 0);\r
+   // now fill header the normal way\r
+   while (k < 4)\r
+      header[k++] = (uint8) zget8(a);\r
+   len  = header[1] * 256 + header[0];\r
+   nlen = header[3] * 256 + header[2];\r
+   if (nlen != (len ^ 0xffff)) return e("zlib corrupt","Corrupt PNG");\r
+   if (a->zbuffer + len > a->zbuffer_end) return e("read past buffer","Corrupt PNG");\r
+   if (a->zout + len > a->zout_end)\r
+      if (!expand(a, len)) return 0;\r
+   memcpy(a->zout, a->zbuffer, len);\r
+   a->zbuffer += len;\r
+   a->zout += len;\r
+   return 1;\r
+}\r
+\r
+static int parse_zlib_header(zbuf *a)\r
+{\r
+   int cmf   = zget8(a);\r
+   int cm    = cmf & 15;\r
+   /* int cinfo = cmf >> 4; */\r
+   int flg   = zget8(a);\r
+   if ((cmf*256+flg) % 31 != 0) return e("bad zlib header","Corrupt PNG"); // zlib spec\r
+   if (flg & 32) return e("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png\r
+   if (cm != 8) return e("bad compression","Corrupt PNG"); // DEFLATE required for png\r
+   // window = 1 << (8 + cinfo)... but who cares, we fully buffer output\r
+   return 1;\r
+}\r
+\r
+// @TODO: should statically initialize these for optimal thread safety\r
+static uint8 default_length[288], default_distance[32];\r
+static void init_defaults(void)\r
+{\r
+   int i;   // use <= to match clearly with spec\r
+   for (i=0; i <= 143; ++i)     default_length[i]   = 8;\r
+   for (   ; i <= 255; ++i)     default_length[i]   = 9;\r
+   for (   ; i <= 279; ++i)     default_length[i]   = 7;\r
+   for (   ; i <= 287; ++i)     default_length[i]   = 8;\r
+\r
+   for (i=0; i <=  31; ++i)     default_distance[i] = 5;\r
+}\r
+\r
+static int parse_zlib(zbuf *a, int parse_header)\r
+{\r
+   int final, type;\r
+   if (parse_header)\r
+      if (!parse_zlib_header(a)) return 0;\r
+   a->num_bits = 0;\r
+   a->code_buffer = 0;\r
+   do {\r
+      final = zreceive(a,1);\r
+      type = zreceive(a,2);\r
+      if (type == 0) {\r
+         if (!parse_uncompressed_block(a)) return 0;\r
+      } else if (type == 3) {\r
+         return 0;\r
+      } else {\r
+         if (type == 1) {\r
+            // use fixed code lengths\r
+            if (!default_distance[31]) init_defaults();\r
+            if (!zbuild_huffman(&a->z_length  , default_length  , 288)) return 0;\r
+            if (!zbuild_huffman(&a->z_distance, default_distance,  32)) return 0;\r
+         } else {\r
+            if (!compute_huffman_codes(a)) return 0;\r
+         }\r
+         if (!parse_huffman_block(a)) return 0;\r
+      }\r
+   } while (!final);\r
+   return 1;\r
+}\r
+\r
+static int do_zlib(zbuf *a, char *obuf, int olen, int exp, int parse_header)\r
+{\r
+   a->zout_start = obuf;\r
+   a->zout       = obuf;\r
+   a->zout_end   = obuf + olen;\r
+   a->z_expandable = exp;\r
+\r
+   return parse_zlib(a, parse_header);\r
+}\r
+\r
+char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)\r
+{\r
+   zbuf a;\r
+   char *p = (char *) malloc(initial_size);\r
+   if (p == NULL) return NULL;\r
+   a.zbuffer = (uint8 *) buffer;\r
+   a.zbuffer_end = (uint8 *) buffer + len;\r
+   if (do_zlib(&a, p, initial_size, 1, 1)) {\r
+      if (outlen) *outlen = (int) (a.zout - a.zout_start);\r
+      return a.zout_start;\r
+   } else {\r
+      free(a.zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)\r
+{\r
+   return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);\r
+}\r
+\r
+int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)\r
+{\r
+   zbuf a;\r
+   a.zbuffer = (uint8 *) ibuffer;\r
+   a.zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(&a, obuffer, olen, 0, 1))\r
+      return (int) (a.zout - a.zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)\r
+{\r
+   zbuf a;\r
+   char *p = (char *) malloc(16384);\r
+   if (p == NULL) return NULL;\r
+   a.zbuffer = (uint8 *) buffer;\r
+   a.zbuffer_end = (uint8 *) buffer+len;\r
+   if (do_zlib(&a, p, 16384, 1, 0)) {\r
+      if (outlen) *outlen = (int) (a.zout - a.zout_start);\r
+      return a.zout_start;\r
+   } else {\r
+      free(a.zout_start);\r
+      return NULL;\r
+   }\r
+}\r
+\r
+int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)\r
+{\r
+   zbuf a;\r
+   a.zbuffer = (uint8 *) ibuffer;\r
+   a.zbuffer_end = (uint8 *) ibuffer + ilen;\r
+   if (do_zlib(&a, obuffer, olen, 0, 0))\r
+      return (int) (a.zout - a.zout_start);\r
+   else\r
+      return -1;\r
+}\r
+\r
+// public domain "baseline" PNG decoder   v0.10  Sean Barrett 2006-11-18\r
+//    simple implementation\r
+//      - only 8-bit samples\r
+//      - no CRC checking\r
+//      - allocates lots of intermediate memory\r
+//        - avoids problem of streaming data between subsystems\r
+//        - avoids explicit window management\r
+//    performance\r
+//      - uses stb_zlib, a PD zlib implementation with fast huffman decoding\r
+\r
+\r
+typedef struct\r
+{\r
+   uint32 length;\r
+   uint32 type;\r
+} chunk;\r
+\r
+#define PNG_TYPE(a,b,c,d)  (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))\r
+\r
+static chunk get_chunk_header(stbi *s)\r
+{\r
+   chunk c;\r
+   c.length = get32(s);\r
+   c.type   = get32(s);\r
+   return c;\r
+}\r
+\r
+static int check_png_header(stbi *s)\r
+{\r
+   static uint8 png_sig[8] = { 137,80,78,71,13,10,26,10 };\r
+   int i;\r
+   for (i=0; i < 8; ++i)\r
+      if (get8(s) != png_sig[i]) return e("bad png sig","Not a PNG");\r
+   return 1;\r
+}\r
+\r
+typedef struct\r
+{\r
+   stbi s;\r
+   uint8 *idata, *expanded, *out;\r
+} png;\r
+\r
+\r
+enum {\r
+   F_none=0, F_sub=1, F_up=2, F_avg=3, F_paeth=4,\r
+   F_avg_first, F_paeth_first,\r
+};\r
+\r
+static uint8 first_row_filter[5] =\r
+{\r
+   F_none, F_sub, F_none, F_avg_first, F_paeth_first\r
+};\r
+\r
+static int paeth(int a, int b, int c)\r
+{\r
+   int p = a + b - c;\r
+   int pa = abs(p-a);\r
+   int pb = abs(p-b);\r
+   int pc = abs(p-c);\r
+   if (pa <= pb && pa <= pc) return a;\r
+   if (pb <= pc) return b;\r
+   return c;\r
+}\r
+\r
+// create the png data from post-deflated data\r
+static int create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n)\r
+{\r
+   stbi *s = &a->s;\r
+   uint32 i,j,stride = s->img_x*out_n;\r
+   int k;\r
+   int img_n = s->img_n; // copy it into a local for later\r
+   assert(out_n == s->img_n || out_n == s->img_n+1);\r
+   a->out = (uint8 *) malloc(s->img_x * s->img_y * out_n);\r
+   if (!a->out) return e("outofmem", "Out of memory");\r
+   if (raw_len != (img_n * s->img_x + 1) * s->img_y) return e("not enough pixels","Corrupt PNG");\r
+   for (j=0; j < s->img_y; ++j) {\r
+      uint8 *cur = a->out + stride*j;\r
+      uint8 *prior = cur - stride;\r
+      int filter = *raw++;\r
+      if (filter > 4) return e("invalid filter","Corrupt PNG");\r
+      // if first row, use special filter that doesn't sample previous row\r
+      if (j == 0) filter = first_row_filter[filter];\r
+      // handle first pixel explicitly\r
+      for (k=0; k < img_n; ++k) {\r
+         switch(filter) {\r
+            case F_none       : cur[k] = raw[k]; break;\r
+            case F_sub        : cur[k] = raw[k]; break;\r
+            case F_up         : cur[k] = raw[k] + prior[k]; break;\r
+            case F_avg        : cur[k] = raw[k] + (prior[k]>>1); break;\r
+            case F_paeth      : cur[k] = (uint8) (raw[k] + paeth(0,prior[k],0)); break;\r
+            case F_avg_first  : cur[k] = raw[k]; break;\r
+            case F_paeth_first: cur[k] = raw[k]; break;\r
+         }\r
+      }\r
+      if (img_n != out_n) cur[img_n] = 255;\r
+      raw += img_n;\r
+      cur += out_n;\r
+      prior += out_n;\r
+      // this is a little gross, so that we don't switch per-pixel or per-component\r
+      if (img_n == out_n) {\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=s->img_x-1; i >= 1; --i, raw+=img_n,cur+=img_n,prior+=img_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-img_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-img_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-img_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-img_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      } else {\r
+         assert(img_n+1 == out_n);\r
+         #define CASE(f) \\r
+             case f:     \\r
+                for (i=s->img_x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \\r
+                   for (k=0; k < img_n; ++k)\r
+         switch(filter) {\r
+            CASE(F_none)  cur[k] = raw[k]; break;\r
+            CASE(F_sub)   cur[k] = raw[k] + cur[k-out_n]; break;\r
+            CASE(F_up)    cur[k] = raw[k] + prior[k]; break;\r
+            CASE(F_avg)   cur[k] = raw[k] + ((prior[k] + cur[k-out_n])>>1); break;\r
+            CASE(F_paeth)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;\r
+            CASE(F_avg_first)    cur[k] = raw[k] + (cur[k-out_n] >> 1); break;\r
+            CASE(F_paeth_first)  cur[k] = (uint8) (raw[k] + paeth(cur[k-out_n],0,0)); break;\r
+         }\r
+         #undef CASE\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int compute_transparency(png *z, uint8 tc[3], int out_n)\r
+{\r
+   stbi *s = &z->s;\r
+   uint32 i, pixel_count = s->img_x * s->img_y;\r
+   uint8 *p = z->out;\r
+\r
+   // compute color-based transparency, assuming we've\r
+   // already got 255 as the alpha value in the output\r
+   assert(out_n == 2 || out_n == 4);\r
+\r
+   if (out_n == 2) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         p[1] = (p[0] == tc[0] ? 0 : 255);\r
+         p += 2;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])\r
+            p[3] = 0;\r
+         p += 4;\r
+      }\r
+   }\r
+   return 1;\r
+}\r
+\r
+static int expand_palette(png *a, uint8 *palette, int len, int pal_img_n)\r
+{\r
+   uint32 i, pixel_count = a->s.img_x * a->s.img_y;\r
+   uint8 *p, *temp_out, *orig = a->out;\r
+\r
+   p = (uint8 *) malloc(pixel_count * pal_img_n);\r
+   if (p == NULL) return e("outofmem", "Out of memory");\r
+\r
+   // between here and free(out) below, exitting would leak\r
+   temp_out = p;\r
+\r
+   if (pal_img_n == 3) {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p += 3;\r
+      }\r
+   } else {\r
+      for (i=0; i < pixel_count; ++i) {\r
+         int n = orig[i]*4;\r
+         p[0] = palette[n  ];\r
+         p[1] = palette[n+1];\r
+         p[2] = palette[n+2];\r
+         p[3] = palette[n+3];\r
+         p += 4;\r
+      }\r
+   }\r
+   free(a->out);\r
+   a->out = temp_out;\r
+   return 1;\r
+}\r
+\r
+static int parse_png_file(png *z, int scan, int req_comp)\r
+{\r
+   uint8 palette[1024], pal_img_n=0;\r
+   uint8 has_trans=0, tc[3];\r
+   uint32 ioff=0, idata_limit=0, i, pal_len=0;\r
+   int first=1,k;\r
+   stbi *s = &z->s;\r
+\r
+   if (!check_png_header(s)) return 0;\r
+\r
+   if (scan == SCAN_type) return 1;\r
+\r
+   for(;;first=0) {\r
+      chunk c = get_chunk_header(s);\r
+      if (first && c.type != PNG_TYPE('I','H','D','R'))\r
+         return e("first not IHDR","Corrupt PNG");\r
+      switch (c.type) {\r
+         case PNG_TYPE('I','H','D','R'): {\r
+            int depth,color,interlace,comp,filter;\r
+            if (!first) return e("multiple IHDR","Corrupt PNG");\r
+            if (c.length != 13) return e("bad IHDR len","Corrupt PNG");\r
+            s->img_x = get32(s); if (s->img_x > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            s->img_y = get32(s); if (s->img_y > (1 << 24)) return e("too large","Very large image (corrupt?)");\r
+            depth = get8(s);  if (depth != 8)        return e("8bit only","PNG not supported: 8-bit only");\r
+            color = get8(s);  if (color > 6)         return e("bad ctype","Corrupt PNG");\r
+            if (color == 3) pal_img_n = 3; else if (color & 1) return e("bad ctype","Corrupt PNG");\r
+            comp  = get8(s);  if (comp) return e("bad comp method","Corrupt PNG");\r
+            filter= get8(s);  if (filter) return e("bad filter method","Corrupt PNG");\r
+            interlace = get8(s); if (interlace) return e("interlaced","PNG not supported: interlaced mode");\r
+            if (!s->img_x || !s->img_y) return e("0-pixel image","Corrupt PNG");\r
+            if (!pal_img_n) {\r
+               s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);\r
+               if ((1 << 30) / s->img_x / s->img_n < s->img_y) return e("too large", "Image too large to decode");\r
+               if (scan == SCAN_header) return 1;\r
+            } else {\r
+               // if paletted, then pal_n is our final components, and\r
+               // img_n is # components to decompress/filter.\r
+               s->img_n = 1;\r
+               if ((1 << 30) / s->img_x / 4 < s->img_y) return e("too large","Corrupt PNG");\r
+               // if SCAN_header, have to scan to see if we have a tRNS\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('P','L','T','E'):  {\r
+            if (c.length > 256*3) return e("invalid PLTE","Corrupt PNG");\r
+            pal_len = c.length / 3;\r
+            if (pal_len * 3 != c.length) return e("invalid PLTE","Corrupt PNG");\r
+            for (i=0; i < pal_len; ++i) {\r
+               palette[i*4+0] = get8u(s);\r
+               palette[i*4+1] = get8u(s);\r
+               palette[i*4+2] = get8u(s);\r
+               palette[i*4+3] = 255;\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('t','R','N','S'): {\r
+            if (z->idata) return e("tRNS after IDAT","Corrupt PNG");\r
+            if (pal_img_n) {\r
+               if (scan == SCAN_header) { s->img_n = 4; return 1; }\r
+               if (pal_len == 0) return e("tRNS before PLTE","Corrupt PNG");\r
+               if (c.length > pal_len) return e("bad tRNS len","Corrupt PNG");\r
+               pal_img_n = 4;\r
+               for (i=0; i < c.length; ++i)\r
+                  palette[i*4+3] = get8u(s);\r
+            } else {\r
+               if (!(s->img_n & 1)) return e("tRNS with alpha","Corrupt PNG");\r
+               if (c.length != (uint32) s->img_n*2) return e("bad tRNS len","Corrupt PNG");\r
+               has_trans = 1;\r
+               for (k=0; k < s->img_n; ++k)\r
+                  tc[k] = (uint8) get16(s); // non 8-bit images will be larger\r
+            }\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','D','A','T'): {\r
+            if (pal_img_n && !pal_len) return e("no PLTE","Corrupt PNG");\r
+            if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }\r
+            if (ioff + c.length > idata_limit) {\r
+               uint8 *p;\r
+               if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;\r
+               while (ioff + c.length > idata_limit)\r
+                  idata_limit *= 2;\r
+               p = (uint8 *) realloc(z->idata, idata_limit); if (p == NULL) return e("outofmem", "Out of memory");\r
+               z->idata = p;\r
+            }\r
+            #ifndef STBI_NO_STDIO\r
+            if (s->img_file)\r
+            {\r
+               if (fread(z->idata+ioff,1,c.length,s->img_file) != c.length) return e("outofdata","Corrupt PNG");\r
+            }\r
+            else\r
+            #endif\r
+            {\r
+               memcpy(z->idata+ioff, s->img_buffer, c.length);\r
+               s->img_buffer += c.length;\r
+            }\r
+            ioff += c.length;\r
+            break;\r
+         }\r
+\r
+         case PNG_TYPE('I','E','N','D'): {\r
+            uint32 raw_len;\r
+            if (scan != SCAN_load) return 1;\r
+            if (z->idata == NULL) return e("no IDAT","Corrupt PNG");\r
+            z->expanded = (uint8 *) stbi_zlib_decode_malloc((char *) z->idata, ioff, (int *) &raw_len);\r
+            if (z->expanded == NULL) return 0; // zlib should set error\r
+            free(z->idata); z->idata = NULL;\r
+            if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)\r
+               s->img_out_n = s->img_n+1;\r
+            else\r
+               s->img_out_n = s->img_n;\r
+            if (!create_png_image(z, z->expanded, raw_len, s->img_out_n)) return 0;\r
+            if (has_trans)\r
+               if (!compute_transparency(z, tc, s->img_out_n)) return 0;\r
+            if (pal_img_n) {\r
+               // pal_img_n == 3 or 4\r
+               s->img_n = pal_img_n; // record the actual colors we had\r
+               s->img_out_n = pal_img_n;\r
+               if (req_comp >= 3) s->img_out_n = req_comp;\r
+               if (!expand_palette(z, palette, pal_len, s->img_out_n))\r
+                  return 0;\r
+            }\r
+            free(z->expanded); z->expanded = NULL;\r
+            return 1;\r
+         }\r
+\r
+         default:\r
+            // if critical, fail\r
+            if ((c.type & (1 << 29)) == 0) {\r
+               #ifndef STBI_NO_FAILURE_STRINGS\r
+               // not threadsafe\r
+               static char invalid_chunk[] = "XXXX chunk not known";\r
+               invalid_chunk[0] = (uint8) (c.type >> 24);\r
+               invalid_chunk[1] = (uint8) (c.type >> 16);\r
+               invalid_chunk[2] = (uint8) (c.type >>  8);\r
+               invalid_chunk[3] = (uint8) (c.type >>  0);\r
+               #endif\r
+               return e(invalid_chunk, "PNG not supported: unknown chunk type");\r
+            }\r
+            skip(s, c.length);\r
+            break;\r
+      }\r
+      // end of chunk, read and skip CRC\r
+      get32(s);\r
+   }\r
+}\r
+\r
+static unsigned char *do_png(png *p, int *x, int *y, int *n, int req_comp)\r
+{\r
+   unsigned char *result=NULL;\r
+   p->expanded = NULL;\r
+   p->idata = NULL;\r
+   p->out = NULL;\r
+   if (req_comp < 0 || req_comp > 4) return epuc("bad req_comp", "Internal error");\r
+   if (parse_png_file(p, SCAN_load, req_comp)) {\r
+      result = p->out;\r
+      p->out = NULL;\r
+      if (req_comp && req_comp != p->s.img_out_n) {\r
+         result = convert_format(result, p->s.img_out_n, req_comp, p->s.img_x, p->s.img_y);\r
+         p->s.img_out_n = req_comp;\r
+         if (result == NULL) return result;\r
+      }\r
+      *x = p->s.img_x;\r
+      *y = p->s.img_y;\r
+      if (n) *n = p->s.img_n;\r
+   }\r
+   free(p->out);      p->out      = NULL;\r
+   free(p->expanded); p->expanded = NULL;\r
+   free(p->idata);    p->idata    = NULL;\r
+\r
+   return result;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+unsigned char *stbi_png_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   png p;\r
+   start_file(&p.s, f);\r
+   return do_png(&p, x,y,comp,req_comp);\r
+}\r
+\r
+unsigned char *stbi_png_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   unsigned char *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+unsigned char *stbi_png_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   png p;\r
+   start_mem(&p.s, buffer,len);\r
+   return do_png(&p, x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_png_test_file(FILE *f)\r
+{\r
+   png p;\r
+   int n,r;\r
+   n = ftell(f);\r
+   start_file(&p.s, f);\r
+   r = parse_png_file(&p, SCAN_type,STBI_default);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_png_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   png p;\r
+   start_mem(&p.s, buffer, len);\r
+   return parse_png_file(&p, SCAN_type,STBI_default);\r
+}\r
+\r
+// TODO: load header from png\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_png_info             (char const *filename,           int *x, int *y, int *comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+// Microsoft/Windows BMP image\r
+\r
+static int bmp_test(stbi *s)\r
+{\r
+   int sz;\r
+   if (get8(s) != 'B') return 0;\r
+   if (get8(s) != 'M') return 0;\r
+   get32le(s); // discard filesize\r
+   get16le(s); // discard reserved\r
+   get16le(s); // discard reserved\r
+   get32le(s); // discard data offset\r
+   sz = get32le(s);\r
+   if (sz == 12 || sz == 40 || sz == 56 || sz == 108) return 1;\r
+   return 0;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_bmp_test_file        (FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s,f);\r
+   r = bmp_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return bmp_test(&s);\r
+}\r
+\r
+// returns 0..31 for the highest set bit\r
+static int high_bit(unsigned int z)\r
+{\r
+   int n=0;\r
+   if (z == 0) return -1;\r
+   if (z >= 0x10000) n += 16, z >>= 16;\r
+   if (z >= 0x00100) n +=  8, z >>=  8;\r
+   if (z >= 0x00010) n +=  4, z >>=  4;\r
+   if (z >= 0x00004) n +=  2, z >>=  2;\r
+   if (z >= 0x00002) n +=  1, z >>=  1;\r
+   return n;\r
+}\r
+\r
+static int bitcount(unsigned int a)\r
+{\r
+   a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2\r
+   a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4\r
+   a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits\r
+   a = (a + (a >> 8)); // max 16 per 8 bits\r
+   a = (a + (a >> 16)); // max 32 per 8 bits\r
+   return a & 0xff;\r
+}\r
+\r
+static int shiftsigned(int v, int shift, int bits)\r
+{\r
+   int result;\r
+   int z=0;\r
+\r
+   if (shift < 0) v <<= -shift;\r
+   else v >>= shift;\r
+   result = v;\r
+\r
+   z = bits;\r
+   while (z < 8) {\r
+      result += v >> z;\r
+      z += bits;\r
+   }\r
+   return result;\r
+}\r
+\r
+static stbi_uc *bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   uint8 *out;\r
+   unsigned int mr=0,mg=0,mb=0,ma=0;\r
+   stbi_uc pal[256][4];\r
+   int psize=0,i,j,compress=0,width;\r
+   int bpp, flip_vertically, pad, target, offset, hsz;\r
+   if (get8(s) != 'B' || get8(s) != 'M') return epuc("not BMP", "Corrupt BMP");\r
+   get32le(s); // discard filesize\r
+   get16le(s); // discard reserved\r
+   get16le(s); // discard reserved\r
+   offset = get32le(s);\r
+   hsz = get32le(s);\r
+   if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108) return epuc("unknown BMP", "BMP type not supported: unknown");\r
+   failure_reason = "bad BMP";\r
+   if (hsz == 12) {\r
+      s->img_x = get16le(s);\r
+      s->img_y = get16le(s);\r
+   } else {\r
+      s->img_x = get32le(s);\r
+      s->img_y = get32le(s);\r
+   }\r
+   if (get16le(s) != 1) return 0;\r
+   bpp = get16le(s);\r
+   if (bpp == 1) return epuc("monochrome", "BMP type not supported: 1-bit");\r
+   flip_vertically = ((int) s->img_y) > 0;\r
+   s->img_y = abs((int) s->img_y);\r
+   if (hsz == 12) {\r
+      if (bpp < 24)\r
+         psize = (offset - 14 - 24) / 3;\r
+   } else {\r
+      compress = get32le(s);\r
+      if (compress == 1 || compress == 2) return epuc("BMP RLE", "BMP type not supported: RLE");\r
+      get32le(s); // discard sizeof\r
+      get32le(s); // discard hres\r
+      get32le(s); // discard vres\r
+      get32le(s); // discard colorsused\r
+      get32le(s); // discard max important\r
+      if (hsz == 40 || hsz == 56) {\r
+         if (hsz == 56) {\r
+            get32le(s);\r
+            get32le(s);\r
+            get32le(s);\r
+            get32le(s);\r
+         }\r
+         if (bpp == 16 || bpp == 32) {\r
+            mr = mg = mb = 0;\r
+            if (compress == 0) {\r
+               if (bpp == 32) {\r
+                  mr = 0xff << 16;\r
+                  mg = 0xff <<  8;\r
+                  mb = 0xff <<  0;\r
+               } else {\r
+                  mr = 31 << 10;\r
+                  mg = 31 <<  5;\r
+                  mb = 31 <<  0;\r
+               }\r
+            } else if (compress == 3) {\r
+               mr = get32le(s);\r
+               mg = get32le(s);\r
+               mb = get32le(s);\r
+               // not documented, but generated by photoshop and handled by mspaint\r
+               if (mr == mg && mg == mb) {\r
+                  // ?!?!?\r
+                  return NULL;\r
+               }\r
+            } else\r
+               return NULL;\r
+         }\r
+      } else {\r
+         assert(hsz == 108);\r
+         mr = get32le(s);\r
+         mg = get32le(s);\r
+         mb = get32le(s);\r
+         ma = get32le(s);\r
+         get32le(s); // discard color space\r
+         for (i=0; i < 12; ++i)\r
+            get32le(s); // discard color space parameters\r
+      }\r
+      if (bpp < 16)\r
+         psize = (offset - 14 - hsz) >> 2;\r
+   }\r
+   s->img_n = ma ? 4 : 3;\r
+   if (req_comp && req_comp >= 3) // we can directly decode 3 or 4\r
+      target = req_comp;\r
+   else\r
+      target = s->img_n; // if they want monochrome, we'll post-convert\r
+   out = (stbi_uc *) malloc(target * s->img_x * s->img_y);\r
+   if (!out) return epuc("outofmem", "Out of memory");\r
+   if (bpp < 16) {\r
+      int z=0;\r
+      if (psize == 0 || psize > 256) { free(out); return epuc("invalid", "Corrupt BMP"); }\r
+      for (i=0; i < psize; ++i) {\r
+         pal[i][2] = get8(s);\r
+         pal[i][1] = get8(s);\r
+         pal[i][0] = get8(s);\r
+         if (hsz != 12) get8(s);\r
+         pal[i][3] = 255;\r
+      }\r
+      skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));\r
+      if (bpp == 4) width = (s->img_x + 1) >> 1;\r
+      else if (bpp == 8) width = s->img_x;\r
+      else { free(out); return epuc("bad bpp", "Corrupt BMP"); }\r
+      pad = (-width)&3;\r
+      for (j=0; j < (int) s->img_y; ++j) {\r
+         for (i=0; i < (int) s->img_x; i += 2) {\r
+            int v=get8(s),v2=0;\r
+            if (bpp == 4) {\r
+               v2 = v & 15;\r
+               v >>= 4;\r
+            }\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+            if (i+1 == (int) s->img_x) break;\r
+            v = (bpp == 8) ? get8(s) : v2;\r
+            out[z++] = pal[v][0];\r
+            out[z++] = pal[v][1];\r
+            out[z++] = pal[v][2];\r
+            if (target == 4) out[z++] = 255;\r
+         }\r
+         skip(s, pad);\r
+      }\r
+   } else {\r
+      int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;\r
+      int z = 0;\r
+      int easy=0;\r
+      skip(s, offset - 14 - hsz);\r
+      if (bpp == 24) width = 3 * s->img_x;\r
+      else if (bpp == 16) width = 2*s->img_x;\r
+      else /* bpp = 32 and pad = 0 */ width=0;\r
+      pad = (-width) & 3;\r
+      if (bpp == 24) {\r
+         easy = 1;\r
+      } else if (bpp == 32) {\r
+         if (mb == 0xff && mg == 0xff00 && mr == 0xff000000 && ma == 0xff000000)\r
+            easy = 2;\r
+      }\r
+      if (!easy) {\r
+         if (!mr || !mg || !mb) return epuc("bad masks", "Corrupt BMP");\r
+         // right shift amt to put high bit in position #7\r
+         rshift = high_bit(mr)-7; rcount = bitcount(mr);\r
+         gshift = high_bit(mg)-7; gcount = bitcount(mr);\r
+         bshift = high_bit(mb)-7; bcount = bitcount(mr);\r
+         ashift = high_bit(ma)-7; acount = bitcount(mr);\r
+      }\r
+      for (j=0; j < (int) s->img_y; ++j) {\r
+         if (easy) {\r
+            for (i=0; i < (int) s->img_x; ++i) {\r
+               int a;\r
+               out[z+2] = get8(s);\r
+               out[z+1] = get8(s);\r
+               out[z+0] = get8(s);\r
+               z += 3;\r
+               a = (easy == 2 ? get8(s) : 255);\r
+               if (target == 4) out[z++] = a;\r
+            }\r
+         } else {\r
+            for (i=0; i < (int) s->img_x; ++i) {\r
+               uint32 v = (bpp == 16 ? get16le(s) : get32le(s));\r
+               int a;\r
+               out[z++] = shiftsigned(v & mr, rshift, rcount);\r
+               out[z++] = shiftsigned(v & mg, gshift, gcount);\r
+               out[z++] = shiftsigned(v & mb, bshift, bcount);\r
+               a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);\r
+               if (target == 4) out[z++] = a;\r
+            }\r
+         }\r
+         skip(s, pad);\r
+      }\r
+   }\r
+   if (flip_vertically) {\r
+      stbi_uc t;\r
+      for (j=0; j < (int) s->img_y>>1; ++j) {\r
+         stbi_uc *p1 = out +      j     *s->img_x*target;\r
+         stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;\r
+         for (i=0; i < (int) s->img_x*target; ++i) {\r
+            t = p1[i], p1[i] = p2[i], p2[i] = t;\r
+         }\r
+      }\r
+   }\r
+\r
+   if (req_comp && req_comp != target) {\r
+      out = convert_format(out, target, req_comp, s->img_x, s->img_y);\r
+      if (out == NULL) return out; // convert_format frees input on failure\r
+   }\r
+\r
+   *x = s->img_x;\r
+   *y = s->img_y;\r
+   if (comp) *comp = target;\r
+   return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_bmp_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_bmp_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return bmp_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return bmp_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+// Targa Truevision - TGA\r
+// by Jonathan Dummer\r
+\r
+static int tga_test(stbi *s)\r
+{\r
+       int sz;\r
+       get8u(s);               //      discard Offset\r
+       sz = get8u(s);  //      color type\r
+       if( sz > 1 ) return 0;  //      only RGB or indexed allowed\r
+       sz = get8u(s);  //      image type\r
+       if( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0;    //      only RGB or grey allowed, +/- RLE\r
+       get16(s);               //      discard palette start\r
+       get16(s);               //      discard palette length\r
+       get8(s);                        //      discard bits per palette color entry\r
+       get16(s);               //      discard x origin\r
+       get16(s);               //      discard y origin\r
+       if( get16(s) < 1 ) return 0;            //      test width\r
+       if( get16(s) < 1 ) return 0;            //      test height\r
+       sz = get8(s);   //      bits per pixel\r
+       if( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) ) return 0;     //      only RGB or RGBA or grey allowed\r
+       return 1;               //      seems to have passed everything\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_tga_test_file        (FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = tga_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_tga_test_memory      (stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return tga_test(&s);\r
+}\r
+\r
+static stbi_uc *tga_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       //      read in the TGA header stuff\r
+       int tga_offset = get8u(s);\r
+       int tga_indexed = get8u(s);\r
+       int tga_image_type = get8u(s);\r
+       int tga_is_RLE = 0;\r
+       int tga_palette_start = get16le(s);\r
+       int tga_palette_len = get16le(s);\r
+       int tga_palette_bits = get8u(s);\r
+       int tga_x_origin = get16le(s);\r
+       int tga_y_origin = get16le(s);\r
+       int tga_width = get16le(s);\r
+       int tga_height = get16le(s);\r
+       int tga_bits_per_pixel = get8u(s);\r
+       int tga_inverted = get8u(s);\r
+       //      image data\r
+       unsigned char *tga_data;\r
+       unsigned char *tga_palette = NULL;\r
+       int i, j;\r
+       unsigned char raw_data[4];\r
+       unsigned char trans_data[] = { 0,0,0,0 };\r
+       int RLE_count = 0;\r
+       int RLE_repeating = 0;\r
+       int read_next_pixel = 1;\r
+       //      do a tiny bit of precessing\r
+       if( tga_image_type >= 8 )\r
+       {\r
+               tga_image_type -= 8;\r
+               tga_is_RLE = 1;\r
+       }\r
+       /* int tga_alpha_bits = tga_inverted & 15; */\r
+       tga_inverted = 1 - ((tga_inverted >> 5) & 1);\r
+\r
+       //      error check\r
+       if( //(tga_indexed) ||\r
+               (tga_width < 1) || (tga_height < 1) ||\r
+               (tga_image_type < 1) || (tga_image_type > 3) ||\r
+               ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&\r
+               (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))\r
+               )\r
+       {\r
+               return NULL;\r
+       }\r
+\r
+       //      If I'm paletted, then I'll use the number of bits from the palette\r
+       if( tga_indexed )\r
+       {\r
+               tga_bits_per_pixel = tga_palette_bits;\r
+       }\r
+\r
+       //      tga info\r
+       *x = tga_width;\r
+       *y = tga_height;\r
+       if( (req_comp < 1) || (req_comp > 4) )\r
+       {\r
+               //      just use whatever the file was\r
+               req_comp = tga_bits_per_pixel / 8;\r
+               *comp = req_comp;\r
+       } else\r
+       {\r
+               //      force a new number of components\r
+               *comp = tga_bits_per_pixel/8;\r
+       }\r
+       tga_data = (unsigned char*)malloc( tga_width * tga_height * req_comp );\r
+\r
+       //      skip to the data's starting position (offset usually = 0)\r
+       skip(s, tga_offset );\r
+       //      do I need to load a palette?\r
+       if( tga_indexed )\r
+       {\r
+               //      any data to skip? (offset usually = 0)\r
+               skip(s, tga_palette_start );\r
+               //      load the palette\r
+               tga_palette = (unsigned char*)malloc( tga_palette_len * tga_palette_bits / 8 );\r
+               getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 );\r
+       }\r
+       //      load the data\r
+       for( i = 0; i < tga_width * tga_height; ++i )\r
+       {\r
+               //      if I'm in RLE mode, do I need to get a RLE chunk?\r
+               if( tga_is_RLE )\r
+               {\r
+                       if( RLE_count == 0 )\r
+                       {\r
+                               //      yep, get the next byte as a RLE command\r
+                               int RLE_cmd = get8u(s);\r
+                               RLE_count = 1 + (RLE_cmd & 127);\r
+                               RLE_repeating = RLE_cmd >> 7;\r
+                               read_next_pixel = 1;\r
+                       } else if( !RLE_repeating )\r
+                       {\r
+                               read_next_pixel = 1;\r
+                       }\r
+               } else\r
+               {\r
+                       read_next_pixel = 1;\r
+               }\r
+               //      OK, if I need to read a pixel, do it now\r
+               if( read_next_pixel )\r
+               {\r
+                       //      load however much data we did have\r
+                       if( tga_indexed )\r
+                       {\r
+                               //      read in 1 byte, then perform the lookup\r
+                               int pal_idx = get8u(s);\r
+                               if( pal_idx >= tga_palette_len )\r
+                               {\r
+                                       //      invalid index\r
+                                       pal_idx = 0;\r
+                               }\r
+                               pal_idx *= tga_bits_per_pixel / 8;\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = tga_palette[pal_idx+j];\r
+                               }\r
+                       } else\r
+                       {\r
+                               //      read in the data raw\r
+                               for( j = 0; j*8 < tga_bits_per_pixel; ++j )\r
+                               {\r
+                                       raw_data[j] = get8u(s);\r
+                               }\r
+                       }\r
+                       //      convert raw to the intermediate format\r
+                       switch( tga_bits_per_pixel )\r
+                       {\r
+                       case 8:\r
+                               //      Luminous => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 16:\r
+                               //      Luminous,Alpha => RGBA\r
+                               trans_data[0] = raw_data[0];\r
+                               trans_data[1] = raw_data[0];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[1];\r
+                               break;\r
+                       case 24:\r
+                               //      BGR => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = 255;\r
+                               break;\r
+                       case 32:\r
+                               //      BGRA => RGBA\r
+                               trans_data[0] = raw_data[2];\r
+                               trans_data[1] = raw_data[1];\r
+                               trans_data[2] = raw_data[0];\r
+                               trans_data[3] = raw_data[3];\r
+                               break;\r
+                       }\r
+                       //      clear the reading flag for the next pixel\r
+                       read_next_pixel = 0;\r
+               } // end of reading a pixel\r
+               //      convert to final format\r
+               switch( req_comp )\r
+               {\r
+               case 1:\r
+                       //      RGBA => Luminance\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       break;\r
+               case 2:\r
+                       //      RGBA => Luminance,Alpha\r
+                       tga_data[i*req_comp+0] = compute_y(trans_data[0],trans_data[1],trans_data[2]);\r
+                       tga_data[i*req_comp+1] = trans_data[3];\r
+                       break;\r
+               case 3:\r
+                       //      RGBA => RGB\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       break;\r
+               case 4:\r
+                       //      RGBA => RGBA\r
+                       tga_data[i*req_comp+0] = trans_data[0];\r
+                       tga_data[i*req_comp+1] = trans_data[1];\r
+                       tga_data[i*req_comp+2] = trans_data[2];\r
+                       tga_data[i*req_comp+3] = trans_data[3];\r
+                       break;\r
+               }\r
+               //      in case we're in RLE mode, keep counting down\r
+               --RLE_count;\r
+       }\r
+       //      do I need to invert the image?\r
+       if( tga_inverted )\r
+       {\r
+               for( j = 0; j*2 < tga_height; ++j )\r
+               {\r
+                       int index1 = j * tga_width * req_comp;\r
+                       int index2 = (tga_height - 1 - j) * tga_width * req_comp;\r
+                       for( i = tga_width * req_comp; i > 0; --i )\r
+                       {\r
+                               unsigned char temp = tga_data[index1];\r
+                               tga_data[index1] = tga_data[index2];\r
+                               tga_data[index2] = temp;\r
+                               ++index1;\r
+                               ++index2;\r
+                       }\r
+               }\r
+       }\r
+       //      clear my palette, if I had one\r
+       if( tga_palette != NULL )\r
+       {\r
+               free( tga_palette );\r
+       }\r
+       //      the things I do to get rid of an error message, and yet keep\r
+       //      Microsoft's C compilers happy... [8^(\r
+       tga_palette_start = tga_palette_len = tga_palette_bits =\r
+                       tga_x_origin = tga_y_origin = 0;\r
+       //      OK, done\r
+       return tga_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_tga_load             (char const *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_tga_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return tga_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return tga_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicholas Schulz, tweaked by STB\r
+\r
+static int psd_test(stbi *s)\r
+{\r
+       if (get32(s) != 0x38425053) return 0;   // "8BPS"\r
+       else return 1;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_psd_test_file(FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = psd_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int stbi_psd_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return psd_test(&s);\r
+}\r
+\r
+static stbi_uc *psd_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       int     pixelCount;\r
+       int channelCount, compression;\r
+       int channel, i, count, len;\r
+   int w,h;\r
+   uint8 *out;\r
+\r
+       // Check identifier\r
+       if (get32(s) != 0x38425053)     // "8BPS"\r
+               return epuc("not PSD", "Corrupt PSD image");\r
+\r
+       // Check file type version.\r
+       if (get16(s) != 1)\r
+               return epuc("wrong version", "Unsupported version of PSD image");\r
+\r
+       // Skip 6 reserved bytes.\r
+       skip(s, 6 );\r
+\r
+       // Read the number of channels (R, G, B, A, etc).\r
+       channelCount = get16(s);\r
+       if (channelCount < 0 || channelCount > 16)\r
+               return epuc("wrong channel count", "Unsupported number of channels in PSD image");\r
+\r
+       // Read the rows and columns of the image.\r
+   h = get32(s);\r
+   w = get32(s);\r
+\r
+       // Make sure the depth is 8 bits.\r
+       if (get16(s) != 8)\r
+               return epuc("unsupported bit depth", "PSD bit depth is not 8 bit");\r
+\r
+       // Make sure the color mode is RGB.\r
+       // Valid options are:\r
+       //   0: Bitmap\r
+       //   1: Grayscale\r
+       //   2: Indexed color\r
+       //   3: RGB color\r
+       //   4: CMYK color\r
+       //   7: Multichannel\r
+       //   8: Duotone\r
+       //   9: Lab color\r
+       if (get16(s) != 3)\r
+               return epuc("wrong color format", "PSD is not in RGB color format");\r
+\r
+       // Skip the Mode Data.  (It's the palette for indexed color; other info for other modes.)\r
+       skip(s,get32(s) );\r
+\r
+       // Skip the image resources.  (resolution, pen tool paths, etc)\r
+       skip(s, get32(s) );\r
+\r
+       // Skip the reserved data.\r
+       skip(s, get32(s) );\r
+\r
+       // Find out if the data is compressed.\r
+       // Known values:\r
+       //   0: no compression\r
+       //   1: RLE compressed\r
+       compression = get16(s);\r
+       if (compression > 1)\r
+               return epuc("bad compression", "PSD has an unknown compression format");\r
+\r
+       // Create the destination image.\r
+       out = (stbi_uc *) malloc(4 * w*h);\r
+       if (!out) return epuc("outofmem", "Out of memory");\r
+   pixelCount = w*h;\r
+\r
+       // Initialize the data to zero.\r
+       //memset( out, 0, pixelCount * 4 );\r
+\r
+       // Finally, the image data.\r
+       if (compression) {\r
+               // RLE as used by .PSD and .TIFF\r
+               // Loop until you get the number of unpacked bytes you are expecting:\r
+               //     Read the next source byte into n.\r
+               //     If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.\r
+               //     Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.\r
+               //     Else if n is 128, noop.\r
+               // Endloop\r
+\r
+               // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,\r
+               // which we're going to just skip.\r
+               skip(s, h * channelCount * 2 );\r
+\r
+               // Read the RLE data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+\r
+         p = out+channel;\r
+                       if (channel >= channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;\r
+                       } else {\r
+                               // Read the RLE data.\r
+                               count = 0;\r
+                               while (count < pixelCount) {\r
+                                       len = get8(s);\r
+                                       if (len == 128) {\r
+                                               // No-op.\r
+                                       } else if (len < 128) {\r
+                                               // Copy next len+1 bytes literally.\r
+                                               len++;\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = get8(s);\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       } else if (len > 128) {\r
+                                               uint32  val;\r
+                                               // Next -len+1 bytes in the dest are replicated from next source byte.\r
+                                               // (Interpret len as a negative 8-bit int.)\r
+                                               len ^= 0x0FF;\r
+                                               len += 2;\r
+                  val = get8(s);\r
+                                               count += len;\r
+                                               while (len) {\r
+                                                       *p = val;\r
+                     p += 4;\r
+                                                       len--;\r
+                                               }\r
+                                       }\r
+                               }\r
+                       }\r
+               }\r
+\r
+       } else {\r
+               // We're at the raw image data.  It's each channel in order (Red, Green, Blue, Alpha, ...)\r
+               // where each channel consists of an 8-bit value for each pixel in the image.\r
+\r
+               // Read the data by channel.\r
+               for (channel = 0; channel < 4; channel++) {\r
+                       uint8 *p;\r
+\r
+         p = out + channel;\r
+                       if (channel > channelCount) {\r
+                               // Fill this channel with default data.\r
+                               for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;\r
+                       } else {\r
+                               // Read the data.\r
+                               count = 0;\r
+                               for (i = 0; i < pixelCount; i++)\r
+                                       *p = get8(s), p += 4;\r
+                       }\r
+               }\r
+       }\r
+\r
+       if (req_comp && req_comp != 4) {\r
+               out = convert_format(out, 4, req_comp, w, h);\r
+               if (out == NULL) return out; // convert_format frees input on failure\r
+       }\r
+\r
+       if (comp) *comp = channelCount;\r
+       *y = h;\r
+       *x = w;\r
+\r
+       return out;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_psd_load(char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_psd_load_from_file(f, x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+\r
+stbi_uc *stbi_psd_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s, f);\r
+   return psd_load(&s, x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s, buffer, len);\r
+   return psd_load(&s, x,y,comp,req_comp);\r
+}\r
+\r
+\r
+// *************************************************************************************************\r
+// Radiance RGBE HDR loader\r
+// originally by Nicolas Schulz\r
+#ifndef STBI_NO_HDR\r
+static int hdr_test(stbi *s)\r
+{\r
+   char *signature = "#?RADIANCE\n";\r
+   int i;\r
+   for (i=0; signature[i]; ++i)\r
+      if (get8(s) != signature[i])\r
+         return 0;\r
+       return 1;\r
+}\r
+\r
+int stbi_hdr_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+       start_mem(&s, buffer, len);\r
+       return hdr_test(&s);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_hdr_test_file(FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s, f);\r
+   r = hdr_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+#define HDR_BUFLEN  1024\r
+static char *hdr_gettoken(stbi *z, char *buffer)\r
+{\r
+   int len=0;\r
+       //char *s = buffer,\r
+       char c = '\0';\r
+\r
+   c = get8(z);\r
+\r
+       while (!at_eof(z) && c != '\n') {\r
+               buffer[len++] = c;\r
+      if (len == HDR_BUFLEN-1) {\r
+         // flush to end of line\r
+         while (!at_eof(z) && get8(z) != '\n')\r
+            ;\r
+         break;\r
+      }\r
+      c = get8(z);\r
+       }\r
+\r
+   buffer[len] = 0;\r
+       return buffer;\r
+}\r
+\r
+static void hdr_convert(float *output, stbi_uc *input, int req_comp)\r
+{\r
+       if( input[3] != 0 ) {\r
+      float f1;\r
+               // Exponent\r
+               f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));\r
+      if (req_comp <= 2)\r
+         output[0] = (input[0] + input[1] + input[2]) * f1 / 3;\r
+      else {\r
+         output[0] = input[0] * f1;\r
+         output[1] = input[1] * f1;\r
+         output[2] = input[2] * f1;\r
+      }\r
+      if (req_comp == 2) output[1] = 1;\r
+      if (req_comp == 4) output[3] = 1;\r
+       } else {\r
+      switch (req_comp) {\r
+         case 4: output[3] = 1; /* fallthrough */\r
+         case 3: output[0] = output[1] = output[2] = 0;\r
+                 break;\r
+         case 2: output[1] = 1; /* fallthrough */\r
+         case 1: output[0] = 0;\r
+                 break;\r
+      }\r
+       }\r
+}\r
+\r
+\r
+static float *hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   char buffer[HDR_BUFLEN];\r
+       char *token;\r
+       int valid = 0;\r
+       int width, height;\r
+   stbi_uc *scanline;\r
+       float *hdr_data;\r
+       int len;\r
+       unsigned char count, value;\r
+       int i, j, k, c1,c2, z;\r
+\r
+\r
+       // Check identifier\r
+       if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)\r
+               return epf("not HDR", "Corrupt HDR image");\r
+\r
+       // Parse header\r
+       while(1) {\r
+               token = hdr_gettoken(s,buffer);\r
+      if (token[0] == 0) break;\r
+               if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;\r
+   }\r
+\r
+       if (!valid)    return epf("unsupported format", "Unsupported HDR format");\r
+\r
+   // Parse width and height\r
+   // can't use sscanf() if we're not using stdio!\r
+   token = hdr_gettoken(s,buffer);\r
+   if (strncmp(token, "-Y ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   height = strtol(token, &token, 10);\r
+   while (*token == ' ') ++token;\r
+   if (strncmp(token, "+X ", 3))  return epf("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   width = strtol(token, NULL, 10);\r
+\r
+       *x = width;\r
+       *y = height;\r
+\r
+   *comp = 3;\r
+       if (req_comp == 0) req_comp = 3;\r
+\r
+       // Read data\r
+       hdr_data = (float *) malloc(height * width * req_comp * sizeof(float));\r
+\r
+       // Load image data\r
+   // image data is stored as some number of sca\r
+       if( width < 8 || width >= 32768) {\r
+               // Read flat data\r
+      for (j=0; j < height; ++j) {\r
+         for (i=0; i < width; ++i) {\r
+            stbi_uc rgbe[4];\r
+           main_decode_loop:\r
+            getn(s, rgbe, 4);\r
+            hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);\r
+         }\r
+      }\r
+       } else {\r
+               // Read RLE-encoded data\r
+               scanline = NULL;\r
+\r
+               for (j = 0; j < height; ++j) {\r
+         c1 = get8(s);\r
+         c2 = get8(s);\r
+         len = get8(s);\r
+         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\r
+            // not run-length encoded, so we have to actually use THIS data as a decoded\r
+            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\r
+            stbi_uc rgbe[4] = { c1,c2,len, get8(s) };\r
+            hdr_convert(hdr_data, rgbe, req_comp);\r
+            i = 1;\r
+            j = 0;\r
+            free(scanline);\r
+            goto main_decode_loop; // yes, this is fucking insane; blame the fucking insane format\r
+         }\r
+         len <<= 8;\r
+         len |= get8(s);\r
+         if (len != width) { free(hdr_data); free(scanline); return epf("invalid decoded scanline length", "corrupt HDR"); }\r
+         if (scanline == NULL) scanline = (stbi_uc *) malloc(width * 4);\r
+\r
+                       for (k = 0; k < 4; ++k) {\r
+                               i = 0;\r
+                               while (i < width) {\r
+                                       count = get8(s);\r
+                                       if (count > 128) {\r
+                                               // Run\r
+                                               value = get8(s);\r
+                  count -= 128;\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = value;\r
+                                       } else {\r
+                                               // Dump\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = get8(s);\r
+                                       }\r
+                               }\r
+                       }\r
+         for (i=0; i < width; ++i)\r
+            hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);\r
+               }\r
+      free(scanline);\r
+       }\r
+\r
+   return hdr_data;\r
+}\r
+\r
+static stbi_uc *hdr_load_rgbe(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   char buffer[HDR_BUFLEN];\r
+       char *token;\r
+       int valid = 0;\r
+       int width, height;\r
+   stbi_uc *scanline;\r
+       stbi_uc *rgbe_data;\r
+       int len;\r
+       unsigned char count, value;\r
+       int i, j, k, c1,c2, z;\r
+\r
+\r
+       // Check identifier\r
+       if (strcmp(hdr_gettoken(s,buffer), "#?RADIANCE") != 0)\r
+               return epuc("not HDR", "Corrupt HDR image");\r
+\r
+       // Parse header\r
+       while(1) {\r
+               token = hdr_gettoken(s,buffer);\r
+      if (token[0] == 0) break;\r
+               if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;\r
+   }\r
+\r
+       if (!valid)    return epuc("unsupported format", "Unsupported HDR format");\r
+\r
+   // Parse width and height\r
+   // can't use sscanf() if we're not using stdio!\r
+   token = hdr_gettoken(s,buffer);\r
+   if (strncmp(token, "-Y ", 3))  return epuc("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   height = strtol(token, &token, 10);\r
+   while (*token == ' ') ++token;\r
+   if (strncmp(token, "+X ", 3))  return epuc("unsupported data layout", "Unsupported HDR format");\r
+   token += 3;\r
+   width = strtol(token, NULL, 10);\r
+\r
+       *x = width;\r
+       *y = height;\r
+\r
+       // RGBE _MUST_ come out as 4 components\r
+   *comp = 4;\r
+       req_comp = 4;\r
+\r
+       // Read data\r
+       rgbe_data = (stbi_uc *) malloc(height * width * req_comp * sizeof(stbi_uc));\r
+       //      point to the beginning\r
+       scanline = rgbe_data;\r
+\r
+       // Load image data\r
+   // image data is stored as some number of scan lines\r
+       if( width < 8 || width >= 32768) {\r
+               // Read flat data\r
+      for (j=0; j < height; ++j) {\r
+         for (i=0; i < width; ++i) {\r
+           main_decode_loop:\r
+            //getn(rgbe, 4);\r
+            getn(s,scanline, 4);\r
+                       scanline += 4;\r
+         }\r
+      }\r
+       } else {\r
+               // Read RLE-encoded data\r
+               for (j = 0; j < height; ++j) {\r
+         c1 = get8(s);\r
+         c2 = get8(s);\r
+         len = get8(s);\r
+         if (c1 != 2 || c2 != 2 || (len & 0x80)) {\r
+            // not run-length encoded, so we have to actually use THIS data as a decoded\r
+            // pixel (note this can't be a valid pixel--one of RGB must be >= 128)\r
+            scanline[0] = c1;\r
+            scanline[1] = c2;\r
+            scanline[2] = len;\r
+            scanline[3] = get8(s);\r
+            scanline += 4;\r
+            i = 1;\r
+            j = 0;\r
+            goto main_decode_loop; // yes, this is insane; blame the insane format\r
+         }\r
+         len <<= 8;\r
+         len |= get8(s);\r
+         if (len != width) { free(rgbe_data); return epuc("invalid decoded scanline length", "corrupt HDR"); }\r
+                       for (k = 0; k < 4; ++k) {\r
+                               i = 0;\r
+                               while (i < width) {\r
+                                       count = get8(s);\r
+                                       if (count > 128) {\r
+                                               // Run\r
+                                               value = get8(s);\r
+                  count -= 128;\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = value;\r
+                                       } else {\r
+                                               // Dump\r
+                                               for (z = 0; z < count; ++z)\r
+                                                       scanline[i++ * 4 + k] = get8(s);\r
+                                       }\r
+                               }\r
+                       }\r
+                       //      move the scanline on\r
+                       scanline += 4 * width;\r
+               }\r
+       }\r
+\r
+   return rgbe_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+float *stbi_hdr_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s,f);\r
+   return hdr_load(&s,x,y,comp,req_comp);\r
+}\r
+\r
+stbi_uc *stbi_hdr_load_rgbe_file(FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_file(&s,f);\r
+   return hdr_load_rgbe(&s,x,y,comp,req_comp);\r
+}\r
+\r
+stbi_uc *stbi_hdr_load_rgbe        (char const *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   FILE *f = fopen(filename, "rb");\r
+   unsigned char *result;\r
+   if (!f) return epuc("can't fopen", "Unable to open file");\r
+   result = stbi_hdr_load_rgbe_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return result;\r
+}\r
+#endif\r
+\r
+float *stbi_hdr_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s,buffer, len);\r
+   return hdr_load(&s,x,y,comp,req_comp);\r
+}\r
+\r
+stbi_uc *stbi_hdr_load_rgbe_memory(stbi_uc *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi s;\r
+   start_mem(&s,buffer, len);\r
+   return hdr_load_rgbe(&s,x,y,comp,req_comp);\r
+}\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+/////////////////////// write image ///////////////////////\r
+\r
+#ifndef STBI_NO_WRITE\r
+\r
+static void write8(FILE *f, int x) { uint8 z = (uint8) x; fwrite(&z,1,1,f); }\r
+\r
+static void writefv(FILE *f, char *fmt, va_list v)\r
+{\r
+   while (*fmt) {\r
+      switch (*fmt++) {\r
+         case ' ': break;\r
+         case '1': { uint8 x = va_arg(v, int); write8(f,x); break; }\r
+         case '2': { int16 x = va_arg(v, int); write8(f,x); write8(f,x>>8); break; }\r
+         case '4': { int32 x = va_arg(v, int); write8(f,x); write8(f,x>>8); write8(f,x>>16); write8(f,x>>24); break; }\r
+         default:\r
+            assert(0);\r
+            va_end(v);\r
+            return;\r
+      }\r
+   }\r
+}\r
+\r
+static void writef(FILE *f, char *fmt, ...)\r
+{\r
+   va_list v;\r
+   va_start(v, fmt);\r
+   writefv(f,fmt,v);\r
+   va_end(v);\r
+}\r
+\r
+static void write_pixels(FILE *f, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad)\r
+{\r
+   uint8 bg[3] = { 255, 0, 255}, px[3];\r
+   uint32 zero = 0;\r
+   int i,j,k, j_end;\r
+\r
+   if (vdir < 0)\r
+      j_end = -1, j = y-1;\r
+   else\r
+      j_end =  y, j = 0;\r
+\r
+   for (; j != j_end; j += vdir) {\r
+      for (i=0; i < x; ++i) {\r
+         uint8 *d = (uint8 *) data + (j*x+i)*comp;\r
+         if (write_alpha < 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+         switch (comp) {\r
+            case 1:\r
+            case 2: writef(f, "111", d[0],d[0],d[0]);\r
+                    break;\r
+            case 4:\r
+               if (!write_alpha) {\r
+                  for (k=0; k < 3; ++k)\r
+                     px[k] = bg[k] + ((d[k] - bg[k]) * d[3])/255;\r
+                  writef(f, "111", px[1-rgb_dir],px[1],px[1+rgb_dir]);\r
+                  break;\r
+               }\r
+               /* FALLTHROUGH */\r
+            case 3:\r
+               writef(f, "111", d[1-rgb_dir],d[1],d[1+rgb_dir]);\r
+               break;\r
+         }\r
+         if (write_alpha > 0)\r
+            fwrite(&d[comp-1], 1, 1, f);\r
+      }\r
+      fwrite(&zero,scanline_pad,1,f);\r
+   }\r
+}\r
+\r
+static int outfile(char const *filename, int rgb_dir, int vdir, int x, int y, int comp, void *data, int alpha, int pad, char *fmt, ...)\r
+{\r
+   FILE *f = fopen(filename, "wb");\r
+   if (f) {\r
+      va_list v;\r
+      va_start(v, fmt);\r
+      writefv(f, fmt, v);\r
+      va_end(v);\r
+      write_pixels(f,rgb_dir,vdir,x,y,comp,data,alpha,pad);\r
+      fclose(f);\r
+   }\r
+   return f != NULL;\r
+}\r
+\r
+int stbi_write_bmp(char const *filename, int x, int y, int comp, void *data)\r
+{\r
+   int pad = (-x*3) & 3;\r
+   return outfile(filename,-1,-1,x,y,comp,data,0,pad,\r
+           "11 4 22 4" "4 44 22 444444",\r
+           'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40,  // file header\r
+            40, x,y, 1,24, 0,0,0,0,0,0);             // bitmap header\r
+}\r
+\r
+int stbi_write_tga(char const *filename, int x, int y, int comp, void *data)\r
+{\r
+   int has_alpha = !(comp & 1);\r
+   return outfile(filename, -1,-1, x, y, comp, data, has_alpha, 0,\r
+                  "111 221 2222 11", 0,0,2, 0,0,0, 0,0,x,y, 24+8*has_alpha, 8*has_alpha);\r
+}\r
+\r
+// any other image formats that do interleaved rgb data?\r
+//    PNG: requires adler32,crc32 -- significant amount of code\r
+//    PSD: no, channels output separately\r
+//    TIFF: no, stripwise-interleaved... i think\r
+\r
+#endif // STBI_NO_WRITE\r
+\r
+//     add in my DDS loading support\r
+#ifndef STBI_NO_DDS\r
+#include "stbi_DDS_aug_c.h"\r
+#endif\r
diff --git a/lib/soil/soil/stb_image_aug.h b/lib/soil/soil/stb_image_aug.h
new file mode 100644 (file)
index 0000000..52ea75c
--- /dev/null
@@ -0,0 +1,354 @@
+/* stbi-1.16 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r
+                      when you control the images you're loading\r
+\r
+   QUICK NOTES:\r
+      Primarily of interest to game developers and other people who can\r
+          avoid problematic images and only need the trivial interface\r
+\r
+      JPEG baseline (no JPEG progressive, no oddball channel decimations)\r
+      PNG non-interlaced\r
+      BMP non-1bpp, non-RLE\r
+      TGA (not sure what subset, if a subset)\r
+      PSD (composited view only, no extra channels)\r
+      HDR (radiance rgbE format)\r
+      writes BMP,TGA (define STBI_NO_WRITE to remove code)\r
+      decoded from memory or through stdio FILE (define STBI_NO_STDIO to remove code)\r
+      supports installable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)\r
+        \r
+   TODO:\r
+      stbi_info_*\r
+  \r
+   history:\r
+      1.16   major bugfix - convert_format converted one too many pixels\r
+      1.15   initialize some fields for thread safety\r
+      1.14   fix threadsafe conversion bug; header-file-only version (#define STBI_HEADER_FILE_ONLY before including)\r
+      1.13   threadsafe\r
+      1.12   const qualifiers in the API\r
+      1.11   Support installable IDCT, colorspace conversion routines\r
+      1.10   Fixes for 64-bit (don't use "unsigned long")\r
+             optimized upsampling by Fabian "ryg" Giesen\r
+      1.09   Fix format-conversion for PSD code (bad global variables!)\r
+      1.08   Thatcher Ulrich's PSD code integrated by Nicolas Schulz\r
+      1.07   attempt to fix C++ warning/errors again\r
+      1.06   attempt to fix C++ warning/errors again\r
+      1.05   fix TGA loading to return correct *comp and use good luminance calc\r
+      1.04   default float alpha is 1, not 255; use 'void *' for stbi_image_free\r
+      1.03   bugfixes to STBI_NO_STDIO, STBI_NO_HDR\r
+      1.02   support for (subset of) HDR files, float interface for preferred access to them\r
+      1.01   fix bug: possible bug in handling right-side up bmps... not sure\r
+             fix bug: the stbi_bmp_load() and stbi_tga_load() functions didn't work at all\r
+      1.00   interface to zlib that skips zlib header\r
+      0.99   correct handling of alpha in palette\r
+      0.98   TGA loader by lonesock; dynamically add loaders (untested)\r
+      0.97   jpeg errors on too large a file; also catch another malloc failure\r
+      0.96   fix detection of invalid v value - particleman@mollyrocket forum\r
+      0.95   during header scan, seek to markers in case of padding\r
+      0.94   STBI_NO_STDIO to disable stdio usage; rename all #defines the same\r
+      0.93   handle jpegtran output; verbose errors\r
+      0.92   read 4,8,16,24,32-bit BMP files of several formats\r
+      0.91   output 24-bit Windows 3.0 BMP files\r
+      0.90   fix a few more warnings; bump version number to approach 1.0\r
+      0.61   bugfixes due to Marc LeBlanc, Christopher Lloyd\r
+      0.60   fix compiling as c++\r
+      0.59   fix warnings: merge Dave Moore's -Wall fixes\r
+      0.58   fix bug: zlib uncompressed mode len/nlen was wrong endian\r
+      0.57   fix bug: jpg last huffman symbol before marker was >9 bits but less\r
+                      than 16 available\r
+      0.56   fix bug: zlib uncompressed mode len vs. nlen\r
+      0.55   fix bug: restart_interval not initialized to 0\r
+      0.54   allow NULL for 'int *comp'\r
+      0.53   fix bug in png 3->4; speedup png decoding\r
+      0.52   png handles req_comp=3,4 directly; minor cleanup; jpeg comments\r
+      0.51   obey req_comp requests, 1-component jpegs return as 1-component,\r
+             on 'test' only check type, not whether we support this variant\r
+*/\r
+\r
+#ifndef HEADER_STB_IMAGE_AUGMENTED\r
+#define HEADER_STB_IMAGE_AUGMENTED\r
+\r
+////   begin header file  ////////////////////////////////////////////////////\r
+//\r
+// Limitations:\r
+//    - no progressive/interlaced support (jpeg, png)\r
+//    - 8-bit samples only (jpeg, png)\r
+//    - not threadsafe\r
+//    - channel subsampling of at most 2 in each dimension (jpeg)\r
+//    - no delayed line count (jpeg) -- IJG doesn't support either\r
+//\r
+// Basic usage (see HDR discussion below):\r
+//    int x,y,n;\r
+//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);\r
+//    // ... process data if not NULL ... \r
+//    // ... x = width, y = height, n = # 8-bit components per pixel ...\r
+//    // ... replace '0' with '1'..'4' to force that many components per pixel\r
+//    stbi_image_free(data)\r
+//\r
+// Standard parameters:\r
+//    int *x       -- outputs image width in pixels\r
+//    int *y       -- outputs image height in pixels\r
+//    int *comp    -- outputs # of image components in image file\r
+//    int req_comp -- if non-zero, # of image components requested in result\r
+//\r
+// The return value from an image loader is an 'unsigned char *' which points\r
+// to the pixel data. The pixel data consists of *y scanlines of *x pixels,\r
+// with each pixel consisting of N interleaved 8-bit components; the first\r
+// pixel pointed to is top-left-most in the image. There is no padding between\r
+// image scanlines or between pixels, regardless of format. The number of\r
+// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.\r
+// If req_comp is non-zero, *comp has the number of components that _would_\r
+// have been output otherwise. E.g. if you set req_comp to 4, you will always\r
+// get RGBA output, but you can check *comp to easily see if it's opaque.\r
+//\r
+// An output image with N components has the following components interleaved\r
+// in this order in each pixel:\r
+//\r
+//     N=#comp     components\r
+//       1           grey\r
+//       2           grey, alpha\r
+//       3           red, green, blue\r
+//       4           red, green, blue, alpha\r
+//\r
+// If image loading fails for any reason, the return value will be NULL,\r
+// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()\r
+// can be queried for an extremely brief, end-user unfriendly explanation\r
+// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid\r
+// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly\r
+// more user-friendly ones.\r
+//\r
+// Paletted PNG and BMP images are automatically depalettized.\r
+//\r
+//\r
+// ===========================================================================\r
+//\r
+// HDR image support   (disable by defining STBI_NO_HDR)\r
+//\r
+// stb_image now supports loading HDR images in general, and currently\r
+// the Radiance .HDR file format, although the support is provided\r
+// generically. You can still load any file through the existing interface;\r
+// if you attempt to load an HDR file, it will be automatically remapped to\r
+// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;\r
+// both of these constants can be reconfigured through this interface:\r
+//\r
+//     stbi_hdr_to_ldr_gamma(2.2f);\r
+//     stbi_hdr_to_ldr_scale(1.0f);\r
+//\r
+// (note, do not use _inverse_ constants; stbi_image will invert them\r
+// appropriately).\r
+//\r
+// Additionally, there is a new, parallel interface for loading files as\r
+// (linear) floats to preserve the full dynamic range:\r
+//\r
+//    float *data = stbi_loadf(filename, &x, &y, &n, 0);\r
+// \r
+// If you load LDR images through this interface, those images will\r
+// be promoted to floating point values, run through the inverse of\r
+// constants corresponding to the above:\r
+//\r
+//     stbi_ldr_to_hdr_scale(1.0f);\r
+//     stbi_ldr_to_hdr_gamma(2.2f);\r
+//\r
+// Finally, given a filename (or an open file or memory block--see header\r
+// file for details) containing image data, you can query for the "most\r
+// appropriate" interface to use (that is, whether the image is HDR or\r
+// not), using:\r
+//\r
+//     stbi_is_hdr(char *filename);\r
+\r
+#ifndef STBI_NO_STDIO\r
+#include <stdio.h>\r
+#endif\r
+\r
+#define STBI_VERSION 1\r
+\r
+enum\r
+{\r
+   STBI_default = 0, // only used for req_comp\r
+\r
+   STBI_grey       = 1,\r
+   STBI_grey_alpha = 2,\r
+   STBI_rgb        = 3,\r
+   STBI_rgb_alpha  = 4,\r
+};\r
+\r
+typedef unsigned char stbi_uc;\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+// WRITING API\r
+\r
+#if !defined(STBI_NO_WRITE) && !defined(STBI_NO_STDIO)\r
+// write a BMP/TGA file given tightly packed 'comp' channels (no padding, nor bmp-stride-padding)\r
+// (you must include the appropriate extension in the filename).\r
+// returns TRUE on success, FALSE if couldn't open file, error writing file\r
+extern int      stbi_write_bmp       (char const *filename,     int x, int y, int comp, void *data);\r
+extern int      stbi_write_tga       (char const *filename,     int x, int y, int comp, void *data);\r
+#endif\r
+\r
+// PRIMARY API - works on images of any type\r
+\r
+// load image by filename, open file, or memory buffer\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+// for stbi_load_from_file, file pointer is left pointing immediately after image\r
+\r
+#ifndef STBI_NO_HDR\r
+#ifndef STBI_NO_STDIO\r
+extern float *stbi_loadf            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern float *stbi_loadf_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+\r
+extern void   stbi_hdr_to_ldr_gamma(float gamma);\r
+extern void   stbi_hdr_to_ldr_scale(float scale);\r
+\r
+extern void   stbi_ldr_to_hdr_gamma(float gamma);\r
+extern void   stbi_ldr_to_hdr_scale(float scale);\r
+\r
+#endif // STBI_NO_HDR\r
+\r
+// get a VERY brief reason for failure\r
+// NOT THREADSAFE\r
+extern char    *stbi_failure_reason  (void); \r
+\r
+// free the loaded image -- this is just free()\r
+extern void     stbi_image_free      (void *retval_from_stbi_load);\r
+\r
+// get image dimensions & components without fully decoding\r
+extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_is_hdr          (char const *filename);\r
+extern int      stbi_is_hdr_from_file(FILE *f);\r
+#endif\r
+\r
+// ZLIB client - used by PNG, available for other purposes\r
+\r
+extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);\r
+extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\r
+\r
+extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);\r
+extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);\r
+\r
+// TYPE-SPECIFIC ACCESS\r
+\r
+// is it a jpeg?\r
+extern int      stbi_jpeg_test_memory     (stbi_uc const *buffer, int len);\r
+extern stbi_uc *stbi_jpeg_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_jpeg_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_jpeg_test_file       (FILE *f);\r
+extern stbi_uc *stbi_jpeg_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+\r
+extern int      stbi_jpeg_info            (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_jpeg_info_from_file  (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+// is it a png?\r
+extern int      stbi_png_test_memory      (stbi_uc const *buffer, int len);\r
+extern stbi_uc *stbi_png_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern stbi_uc *stbi_png_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info             (char const *filename,     int *x, int *y, int *comp);\r
+extern int      stbi_png_test_file        (FILE *f);\r
+extern stbi_uc *stbi_png_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern int      stbi_png_info_from_file   (FILE *f,                  int *x, int *y, int *comp);\r
+#endif\r
+\r
+// is it a bmp?\r
+extern int      stbi_bmp_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_bmp_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_bmp_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_bmp_test_file        (FILE *f);\r
+extern stbi_uc *stbi_bmp_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a tga?\r
+extern int      stbi_tga_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_tga_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_tga_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_tga_test_file        (FILE *f);\r
+extern stbi_uc *stbi_tga_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a psd?\r
+extern int      stbi_psd_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_psd_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_psd_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_psd_test_file        (FILE *f);\r
+extern stbi_uc *stbi_psd_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it an hdr?\r
+extern int      stbi_hdr_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern float *  stbi_hdr_load             (char const *filename,     int *x, int *y, int *comp, int req_comp);\r
+extern float *  stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_hdr_load_rgbe        (char const *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern float *  stbi_hdr_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_hdr_test_file        (FILE *f);\r
+extern float *  stbi_hdr_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_hdr_load_rgbe_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// define new loaders\r
+typedef struct\r
+{\r
+   int       (*test_memory)(stbi_uc const *buffer, int len);\r
+   stbi_uc * (*load_from_memory)(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+   #ifndef STBI_NO_STDIO\r
+   int       (*test_file)(FILE *f);\r
+   stbi_uc * (*load_from_file)(FILE *f, int *x, int *y, int *comp, int req_comp);\r
+   #endif\r
+} stbi_loader;\r
+\r
+// register a loader by filling out the above structure (you must defined ALL functions)\r
+// returns 1 if added or already added, 0 if not added (too many loaders)\r
+// NOT THREADSAFE\r
+extern int stbi_register_loader(stbi_loader *loader);\r
+\r
+// define faster low-level operations (typically SIMD support)\r
+#if STBI_SIMD\r
+typedef void (*stbi_idct_8x8)(uint8 *out, int out_stride, short data[64], unsigned short *dequantize);\r
+// compute an integer IDCT on "input"\r
+//     input[x] = data[x] * dequantize[x]\r
+//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'\r
+//                             CLAMP results to 0..255\r
+typedef void (*stbi_YCbCr_to_RGB_run)(uint8 *output, uint8 const *y, uint8 const *cb, uint8 const *cr, int count, int step);\r
+// compute a conversion from YCbCr to RGB\r
+//     'count' pixels\r
+//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B\r
+//     y: Y input channel\r
+//     cb: Cb input channel; scale/biased to be 0..255\r
+//     cr: Cr input channel; scale/biased to be 0..255\r
+\r
+extern void stbi_install_idct(stbi_idct_8x8 func);\r
+extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);\r
+#endif // STBI_SIMD\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+//\r
+//\r
+////   end header file   /////////////////////////////////////////////////////\r
+#endif // STBI_INCLUDE_STB_IMAGE_H\r
diff --git a/lib/soil/soil/stbi_DDS_aug.h b/lib/soil/soil/stbi_DDS_aug.h
new file mode 100644 (file)
index 0000000..7317d63
--- /dev/null
@@ -0,0 +1,21 @@
+/*\r
+       adding DDS loading support to stbi\r
+*/\r
+\r
+#ifndef HEADER_STB_IMAGE_DDS_AUGMENTATION
+#define HEADER_STB_IMAGE_DDS_AUGMENTATION\r
+\r
+//     is it a DDS file?\r
+extern int      stbi_dds_test_memory      (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_dds_load             (char *filename,           int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_dds_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+#ifndef STBI_NO_STDIO\r
+extern int      stbi_dds_test_file        (FILE *f);\r
+extern stbi_uc *stbi_dds_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+//\r
+//\r
+////   end header file   /////////////////////////////////////////////////////\r
+#endif // HEADER_STB_IMAGE_DDS_AUGMENTATION\r
diff --git a/lib/soil/soil/stbi_DDS_aug_c.h b/lib/soil/soil/stbi_DDS_aug_c.h
new file mode 100644 (file)
index 0000000..683d1cf
--- /dev/null
@@ -0,0 +1,511 @@
+\r
+///    DDS file support, does decoding, _not_ direct uploading\r
+///    (use SOIL for that ;-)\r
+\r
+///    A bunch of DirectDraw Surface structures and flags\r
+typedef struct {\r
+    unsigned int    dwMagic;\r
+    unsigned int    dwSize;\r
+    unsigned int    dwFlags;\r
+    unsigned int    dwHeight;\r
+    unsigned int    dwWidth;\r
+    unsigned int    dwPitchOrLinearSize;\r
+    unsigned int    dwDepth;\r
+    unsigned int    dwMipMapCount;\r
+    unsigned int    dwReserved1[ 11 ];\r
+\r
+    //  DDPIXELFORMAT\r
+    struct {\r
+      unsigned int    dwSize;\r
+      unsigned int    dwFlags;\r
+      unsigned int    dwFourCC;\r
+      unsigned int    dwRGBBitCount;\r
+      unsigned int    dwRBitMask;\r
+      unsigned int    dwGBitMask;\r
+      unsigned int    dwBBitMask;\r
+      unsigned int    dwAlphaBitMask;\r
+    }               sPixelFormat;\r
+\r
+    //  DDCAPS2\r
+    struct {\r
+      unsigned int    dwCaps1;\r
+      unsigned int    dwCaps2;\r
+      unsigned int    dwDDSX;\r
+      unsigned int    dwReserved;\r
+    }               sCaps;\r
+    unsigned int    dwReserved2;\r
+} DDS_header ;\r
+\r
+//     the following constants were copied directly off the MSDN website\r
+\r
+//     The dwFlags member of the original DDSURFACEDESC2 structure\r
+//     can be set to one or more of the following values.\r
+#define DDSD_CAPS      0x00000001\r
+#define DDSD_HEIGHT    0x00000002\r
+#define DDSD_WIDTH     0x00000004\r
+#define DDSD_PITCH     0x00000008\r
+#define DDSD_PIXELFORMAT       0x00001000\r
+#define DDSD_MIPMAPCOUNT       0x00020000\r
+#define DDSD_LINEARSIZE        0x00080000\r
+#define DDSD_DEPTH     0x00800000\r
+\r
+//     DirectDraw Pixel Format\r
+#define DDPF_ALPHAPIXELS       0x00000001\r
+#define DDPF_FOURCC    0x00000004\r
+#define DDPF_RGB       0x00000040\r
+\r
+//     The dwCaps1 member of the DDSCAPS2 structure can be\r
+//     set to one or more of the following values.\r
+#define DDSCAPS_COMPLEX        0x00000008\r
+#define DDSCAPS_TEXTURE        0x00001000\r
+#define DDSCAPS_MIPMAP 0x00400000\r
+\r
+//     The dwCaps2 member of the DDSCAPS2 structure can be\r
+//     set to one or more of the following values.\r
+#define DDSCAPS2_CUBEMAP       0x00000200\r
+#define DDSCAPS2_CUBEMAP_POSITIVEX     0x00000400\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEX     0x00000800\r
+#define DDSCAPS2_CUBEMAP_POSITIVEY     0x00001000\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEY     0x00002000\r
+#define DDSCAPS2_CUBEMAP_POSITIVEZ     0x00004000\r
+#define DDSCAPS2_CUBEMAP_NEGATIVEZ     0x00008000\r
+#define DDSCAPS2_VOLUME        0x00200000\r
+\r
+static int dds_test(stbi *s)\r
+{\r
+       //      check the magic number\r
+       if (get8(s) != 'D') return 0;\r
+       if (get8(s) != 'D') return 0;\r
+       if (get8(s) != 'S') return 0;\r
+       if (get8(s) != ' ') return 0;\r
+       //      check header size\r
+       if (get32le(s) != 124) return 0;\r
+       return 1;\r
+}\r
+#ifndef STBI_NO_STDIO\r
+int      stbi_dds_test_file        (FILE *f)\r
+{\r
+   stbi s;\r
+   int r,n = ftell(f);\r
+   start_file(&s,f);\r
+   r = dds_test(&s);\r
+   fseek(f,n,SEEK_SET);\r
+   return r;\r
+}\r
+#endif\r
+\r
+int      stbi_dds_test_memory      (stbi_uc const *buffer, int len)\r
+{\r
+   stbi s;\r
+   start_mem(&s,buffer, len);\r
+   return dds_test(&s);\r
+}\r
+\r
+//     helper functions\r
+int stbi_convert_bit_range( int c, int from_bits, int to_bits )\r
+{\r
+       int b = (1 << (from_bits - 1)) + c * ((1 << to_bits) - 1);\r
+       return (b + (b >> from_bits)) >> from_bits;\r
+}\r
+void stbi_rgb_888_from_565( unsigned int c, int *r, int *g, int *b )\r
+{\r
+       *r = stbi_convert_bit_range( (c >> 11) & 31, 5, 8 );\r
+       *g = stbi_convert_bit_range( (c >> 05) & 63, 6, 8 );\r
+       *b = stbi_convert_bit_range( (c >> 00) & 31, 5, 8 );\r
+}\r
+void stbi_decode_DXT1_block(\r
+                       unsigned char uncompressed[16*4],\r
+                       unsigned char compressed[8] )\r
+{\r
+       int next_bit = 4*8;\r
+       int i, r, g, b;\r
+       int c0, c1;\r
+       unsigned char decode_colors[4*4];\r
+       //      find the 2 primary colors\r
+       c0 = compressed[0] + (compressed[1] << 8);\r
+       c1 = compressed[2] + (compressed[3] << 8);\r
+       stbi_rgb_888_from_565( c0, &r, &g, &b );\r
+       decode_colors[0] = r;\r
+       decode_colors[1] = g;\r
+       decode_colors[2] = b;\r
+       decode_colors[3] = 255;\r
+       stbi_rgb_888_from_565( c1, &r, &g, &b );\r
+       decode_colors[4] = r;\r
+       decode_colors[5] = g;\r
+       decode_colors[6] = b;\r
+       decode_colors[7] = 255;\r
+       if( c0 > c1 )\r
+       {\r
+               //      no alpha, 2 interpolated colors\r
+               decode_colors[8] = (2*decode_colors[0] + decode_colors[4]) / 3;\r
+               decode_colors[9] = (2*decode_colors[1] + decode_colors[5]) / 3;\r
+               decode_colors[10] = (2*decode_colors[2] + decode_colors[6]) / 3;\r
+               decode_colors[11] = 255;\r
+               decode_colors[12] = (decode_colors[0] + 2*decode_colors[4]) / 3;\r
+               decode_colors[13] = (decode_colors[1] + 2*decode_colors[5]) / 3;\r
+               decode_colors[14] = (decode_colors[2] + 2*decode_colors[6]) / 3;\r
+               decode_colors[15] = 255;\r
+       } else\r
+       {\r
+               //      1 interpolated color, alpha\r
+               decode_colors[8] = (decode_colors[0] + decode_colors[4]) / 2;\r
+               decode_colors[9] = (decode_colors[1] + decode_colors[5]) / 2;\r
+               decode_colors[10] = (decode_colors[2] + decode_colors[6]) / 2;\r
+               decode_colors[11] = 255;\r
+               decode_colors[12] = 0;\r
+               decode_colors[13] = 0;\r
+               decode_colors[14] = 0;\r
+               decode_colors[15] = 0;\r
+       }\r
+       //      decode the block\r
+       for( i = 0; i < 16*4; i += 4 )\r
+       {\r
+               int idx = ((compressed[next_bit>>3] >> (next_bit & 7)) & 3) * 4;\r
+               next_bit += 2;\r
+               uncompressed[i+0] = decode_colors[idx+0];\r
+               uncompressed[i+1] = decode_colors[idx+1];\r
+               uncompressed[i+2] = decode_colors[idx+2];\r
+               uncompressed[i+3] = decode_colors[idx+3];\r
+       }\r
+       //      done\r
+}\r
+void stbi_decode_DXT23_alpha_block(\r
+                       unsigned char uncompressed[16*4],\r
+                       unsigned char compressed[8] )\r
+{\r
+       int i, next_bit = 0;\r
+       //      each alpha value gets 4 bits\r
+       for( i = 3; i < 16*4; i += 4 )\r
+       {\r
+               uncompressed[i] = stbi_convert_bit_range(\r
+                               (compressed[next_bit>>3] >> (next_bit&7)) & 15,\r
+                               4, 8 );\r
+               next_bit += 4;\r
+       }\r
+}\r
+void stbi_decode_DXT45_alpha_block(\r
+                       unsigned char uncompressed[16*4],\r
+                       unsigned char compressed[8] )\r
+{\r
+       int i, next_bit = 8*2;\r
+       unsigned char decode_alpha[8];\r
+       //      each alpha value gets 3 bits, and the 1st 2 bytes are the range\r
+       decode_alpha[0] = compressed[0];\r
+       decode_alpha[1] = compressed[1];\r
+       if( decode_alpha[0] > decode_alpha[1] )\r
+       {\r
+               //      6 step intermediate\r
+               decode_alpha[2] = (6*decode_alpha[0] + 1*decode_alpha[1]) / 7;\r
+               decode_alpha[3] = (5*decode_alpha[0] + 2*decode_alpha[1]) / 7;\r
+               decode_alpha[4] = (4*decode_alpha[0] + 3*decode_alpha[1]) / 7;\r
+               decode_alpha[5] = (3*decode_alpha[0] + 4*decode_alpha[1]) / 7;\r
+               decode_alpha[6] = (2*decode_alpha[0] + 5*decode_alpha[1]) / 7;\r
+               decode_alpha[7] = (1*decode_alpha[0] + 6*decode_alpha[1]) / 7;\r
+       } else\r
+       {\r
+               //      4 step intermediate, pluss full and none\r
+               decode_alpha[2] = (4*decode_alpha[0] + 1*decode_alpha[1]) / 5;\r
+               decode_alpha[3] = (3*decode_alpha[0] + 2*decode_alpha[1]) / 5;\r
+               decode_alpha[4] = (2*decode_alpha[0] + 3*decode_alpha[1]) / 5;\r
+               decode_alpha[5] = (1*decode_alpha[0] + 4*decode_alpha[1]) / 5;\r
+               decode_alpha[6] = 0;\r
+               decode_alpha[7] = 255;\r
+       }\r
+       for( i = 3; i < 16*4; i += 4 )\r
+       {\r
+               int idx = 0, bit;\r
+               bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;\r
+               idx += bit << 0;\r
+               ++next_bit;\r
+               bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;\r
+               idx += bit << 1;\r
+               ++next_bit;\r
+               bit = (compressed[next_bit>>3] >> (next_bit&7)) & 1;\r
+               idx += bit << 2;\r
+               ++next_bit;\r
+               uncompressed[i] = decode_alpha[idx & 7];\r
+       }\r
+       //      done\r
+}\r
+void stbi_decode_DXT_color_block(\r
+                       unsigned char uncompressed[16*4],\r
+                       unsigned char compressed[8] )\r
+{\r
+       int next_bit = 4*8;\r
+       int i, r, g, b;\r
+       int c0, c1;\r
+       unsigned char decode_colors[4*3];\r
+       //      find the 2 primary colors\r
+       c0 = compressed[0] + (compressed[1] << 8);\r
+       c1 = compressed[2] + (compressed[3] << 8);\r
+       stbi_rgb_888_from_565( c0, &r, &g, &b );\r
+       decode_colors[0] = r;\r
+       decode_colors[1] = g;\r
+       decode_colors[2] = b;\r
+       stbi_rgb_888_from_565( c1, &r, &g, &b );\r
+       decode_colors[3] = r;\r
+       decode_colors[4] = g;\r
+       decode_colors[5] = b;\r
+       //      Like DXT1, but no choicees:\r
+       //      no alpha, 2 interpolated colors\r
+       decode_colors[6] = (2*decode_colors[0] + decode_colors[3]) / 3;\r
+       decode_colors[7] = (2*decode_colors[1] + decode_colors[4]) / 3;\r
+       decode_colors[8] = (2*decode_colors[2] + decode_colors[5]) / 3;\r
+       decode_colors[9] = (decode_colors[0] + 2*decode_colors[3]) / 3;\r
+       decode_colors[10] = (decode_colors[1] + 2*decode_colors[4]) / 3;\r
+       decode_colors[11] = (decode_colors[2] + 2*decode_colors[5]) / 3;\r
+       //      decode the block\r
+       for( i = 0; i < 16*4; i += 4 )\r
+       {\r
+               int idx = ((compressed[next_bit>>3] >> (next_bit & 7)) & 3) * 3;\r
+               next_bit += 2;\r
+               uncompressed[i+0] = decode_colors[idx+0];\r
+               uncompressed[i+1] = decode_colors[idx+1];\r
+               uncompressed[i+2] = decode_colors[idx+2];\r
+       }\r
+       //      done\r
+}\r
+static stbi_uc *dds_load(stbi *s, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       //      all variables go up front\r
+       stbi_uc *dds_data = NULL;\r
+       stbi_uc block[16*4];\r
+       stbi_uc compressed[8];\r
+       int flags, DXT_family;\r
+       int has_alpha, has_mipmap;\r
+       int is_compressed, cubemap_faces;\r
+       int block_pitch, num_blocks;\r
+       DDS_header header;\r
+       int i, sz, cf;\r
+       //      load the header\r
+       if( sizeof( DDS_header ) != 128 )\r
+       {\r
+               return NULL;\r
+       }\r
+       getn( s, (stbi_uc*)(&header), 128 );\r
+       //      and do some checking\r
+       if( header.dwMagic != (('D' << 0) | ('D' << 8) | ('S' << 16) | (' ' << 24)) ) return NULL;\r
+       if( header.dwSize != 124 ) return NULL;\r
+       flags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT;\r
+       if( (header.dwFlags & flags) != flags ) return NULL;\r
+       /*      According to the MSDN spec, the dwFlags should contain\r
+               DDSD_LINEARSIZE if it's compressed, or DDSD_PITCH if\r
+               uncompressed.  Some DDS writers do not conform to the\r
+               spec, so I need to make my reader more tolerant */\r
+       if( header.sPixelFormat.dwSize != 32 ) return NULL;\r
+       flags = DDPF_FOURCC | DDPF_RGB;\r
+       if( (header.sPixelFormat.dwFlags & flags) == 0 ) return NULL;\r
+       if( (header.sCaps.dwCaps1 & DDSCAPS_TEXTURE) == 0 ) return NULL;\r
+       //      get the image data\r
+       s->img_x = header.dwWidth;\r
+       s->img_y = header.dwHeight;\r
+       s->img_n = 4;\r
+       is_compressed = (header.sPixelFormat.dwFlags & DDPF_FOURCC) / DDPF_FOURCC;\r
+       has_alpha = (header.sPixelFormat.dwFlags & DDPF_ALPHAPIXELS) / DDPF_ALPHAPIXELS;\r
+       has_mipmap = (header.sCaps.dwCaps1 & DDSCAPS_MIPMAP) && (header.dwMipMapCount > 1);\r
+       cubemap_faces = (header.sCaps.dwCaps2 & DDSCAPS2_CUBEMAP) / DDSCAPS2_CUBEMAP;\r
+       /*      I need cubemaps to have square faces    */\r
+       cubemap_faces &= (s->img_x == s->img_y);\r
+       cubemap_faces *= 5;\r
+       cubemap_faces += 1;\r
+       block_pitch = (s->img_x+3) >> 2;\r
+       num_blocks = block_pitch * ((s->img_y+3) >> 2);\r
+       /*      let the user know what's going on       */\r
+       *x = s->img_x;\r
+       *y = s->img_y;\r
+       *comp = s->img_n;\r
+       /*      is this uncompressed?   */\r
+       if( is_compressed )\r
+       {\r
+               /*      compressed      */\r
+               //      note: header.sPixelFormat.dwFourCC is something like (('D'<<0)|('X'<<8)|('T'<<16)|('1'<<24))\r
+               DXT_family = 1 + (header.sPixelFormat.dwFourCC >> 24) - '1';\r
+               if( (DXT_family < 1) || (DXT_family > 5) ) return NULL;\r
+               /*      check the expected size...oops, nevermind...\r
+                       those non-compliant writers leave\r
+                       dwPitchOrLinearSize == 0        */\r
+               //      passed all the tests, get the RAM for decoding\r
+               sz = (s->img_x)*(s->img_y)*4*cubemap_faces;\r
+               dds_data = (unsigned char*)malloc( sz );\r
+               /*      do this once for each face      */\r
+               for( cf = 0; cf < cubemap_faces; ++ cf )\r
+               {\r
+                       //      now read and decode all the blocks\r
+                       for( i = 0; i < num_blocks; ++i )\r
+                       {\r
+                               //      where are we?\r
+                               int bx, by, bw=4, bh=4;\r
+                               int ref_x = 4 * (i % block_pitch);\r
+                               int ref_y = 4 * (i / block_pitch);\r
+                               //      get the next block's worth of compressed data, and decompress it\r
+                               if( DXT_family == 1 )\r
+                               {\r
+                                       //      DXT1\r
+                                       getn( s, compressed, 8 );\r
+                                       stbi_decode_DXT1_block( block, compressed );\r
+                               } else if( DXT_family < 4 )\r
+                               {\r
+                                       //      DXT2/3\r
+                                       getn( s, compressed, 8 );\r
+                                       stbi_decode_DXT23_alpha_block ( block, compressed );\r
+                                       getn( s, compressed, 8 );\r
+                                       stbi_decode_DXT_color_block ( block, compressed );\r
+                               } else\r
+                               {\r
+                                       //      DXT4/5\r
+                                       getn( s, compressed, 8 );\r
+                                       stbi_decode_DXT45_alpha_block ( block, compressed );\r
+                                       getn( s, compressed, 8 );\r
+                                       stbi_decode_DXT_color_block ( block, compressed );\r
+                               }\r
+                               //      is this a partial block?\r
+                               if( ref_x + 4 > s->img_x )\r
+                               {\r
+                                       bw = s->img_x - ref_x;\r
+                               }\r
+                               if( ref_y + 4 > s->img_y )\r
+                               {\r
+                                       bh = s->img_y - ref_y;\r
+                               }\r
+                               //      now drop our decompressed data into the buffer\r
+                               for( by = 0; by < bh; ++by )\r
+                               {\r
+                                       int idx = 4*((ref_y+by+cf*s->img_x)*s->img_x + ref_x);\r
+                                       for( bx = 0; bx < bw*4; ++bx )\r
+                                       {\r
+\r
+                                               dds_data[idx+bx] = block[by*16+bx];\r
+                                       }\r
+                               }\r
+                       }\r
+                       /*      done reading and decoding the main image...\r
+                               skip MIPmaps if present */\r
+                       if( has_mipmap )\r
+                       {\r
+                               int block_size = 16;\r
+                               if( DXT_family == 1 )\r
+                               {\r
+                                       block_size = 8;\r
+                               }\r
+                               for( i = 1; i < header.dwMipMapCount; ++i )\r
+                               {\r
+                                       int mx = s->img_x >> (i + 2);\r
+                                       int my = s->img_y >> (i + 2);\r
+                                       if( mx < 1 )\r
+                                       {\r
+                                               mx = 1;\r
+                                       }\r
+                                       if( my < 1 )\r
+                                       {\r
+                                               my = 1;\r
+                                       }\r
+                                       skip( s, mx*my*block_size );\r
+                               }\r
+                       }\r
+               }/* per cubemap face */\r
+       } else\r
+       {\r
+               /*      uncompressed    */\r
+               DXT_family = 0;\r
+               s->img_n = 3;\r
+               if( has_alpha )\r
+               {\r
+                       s->img_n = 4;\r
+               }\r
+               *comp = s->img_n;\r
+               sz = s->img_x*s->img_y*s->img_n*cubemap_faces;\r
+               dds_data = (unsigned char*)malloc( sz );\r
+               /*      do this once for each face      */\r
+               for( cf = 0; cf < cubemap_faces; ++ cf )\r
+               {\r
+                       /*      read the main image for this face       */\r
+                       getn( s, &dds_data[cf*s->img_x*s->img_y*s->img_n], s->img_x*s->img_y*s->img_n );\r
+                       /*      done reading and decoding the main image...\r
+                               skip MIPmaps if present */\r
+                       if( has_mipmap )\r
+                       {\r
+                               for( i = 1; i < header.dwMipMapCount; ++i )\r
+                               {\r
+                                       int mx = s->img_x >> i;\r
+                                       int my = s->img_y >> i;\r
+                                       if( mx < 1 )\r
+                                       {\r
+                                               mx = 1;\r
+                                       }\r
+                                       if( my < 1 )\r
+                                       {\r
+                                               my = 1;\r
+                                       }\r
+                                       skip( s, mx*my*s->img_n );\r
+                               }\r
+                       }\r
+               }\r
+               /*      data was BGR, I need it RGB     */\r
+               for( i = 0; i < sz; i += s->img_n )\r
+               {\r
+                       unsigned char temp = dds_data[i];\r
+                       dds_data[i] = dds_data[i+2];\r
+                       dds_data[i+2] = temp;\r
+               }\r
+       }\r
+       /*      finished decompressing into RGBA,\r
+               adjust the y size if we have a cubemap\r
+               note: sz is already up to date  */\r
+       s->img_y *= cubemap_faces;\r
+       *y = s->img_y;\r
+       //      did the user want something else, or\r
+       //      see if all the alpha values are 255 (i.e. no transparency)\r
+       has_alpha = 0;\r
+       if( s->img_n == 4)\r
+       {\r
+               for( i = 3; (i < sz) && (has_alpha == 0); i += 4 )\r
+               {\r
+                       has_alpha |= (dds_data[i] < 255);\r
+               }\r
+       }\r
+       if( (req_comp <= 4) && (req_comp >= 1) )\r
+       {\r
+               //      user has some requirements, meet them\r
+               if( req_comp != s->img_n )\r
+               {\r
+                       dds_data = convert_format( dds_data, s->img_n, req_comp, s->img_x, s->img_y );\r
+                       *comp = s->img_n;\r
+               }\r
+       } else\r
+       {\r
+               //      user had no requirements, only drop to RGB is no alpha\r
+               if( (has_alpha == 0) && (s->img_n == 4) )\r
+               {\r
+                       dds_data = convert_format( dds_data, 4, 3, s->img_x, s->img_y );\r
+                       *comp = 3;\r
+               }\r
+       }\r
+       //      OK, done\r
+       return dds_data;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_dds_load_from_file   (FILE *f,                  int *x, int *y, int *comp, int req_comp)\r
+{\r
+       stbi s;\r
+   start_file(&s,f);\r
+   return dds_load(&s,x,y,comp,req_comp);\r
+}\r
+\r
+stbi_uc *stbi_dds_load             (char *filename,           int *x, int *y, int *comp, int req_comp)\r
+{\r
+   stbi_uc *data;\r
+   FILE *f = fopen(filename, "rb");\r
+   if (!f) return NULL;\r
+   data = stbi_dds_load_from_file(f,x,y,comp,req_comp);\r
+   fclose(f);\r
+   return data;\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_dds_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+       stbi s;\r
+   start_mem(&s,buffer, len);\r
+   return dds_load(&s,x,y,comp,req_comp);\r
+}\r
diff --git a/lib/soil/soil/test_SOIL.cpp b/lib/soil/soil/test_SOIL.cpp
new file mode 100644 (file)
index 0000000..9c4c091
--- /dev/null
@@ -0,0 +1,379 @@
+#include <string>\r
+#include <iostream>\r
+\r
+#include <windows.h>\r
+#include <shellapi.h>\r
+#include <gl/gl.h>\r
+#include <gl/glext.h>\r
+\r
+#include "SOIL.h"\r
+\r
+LRESULT CALLBACK WindowProc(HWND, UINT, WPARAM, LPARAM);\r
+void EnableOpenGL(HWND hwnd, HDC*, HGLRC*);\r
+void DisableOpenGL(HWND, HDC, HGLRC);\r
+\r
+int WINAPI WinMain(HINSTANCE hInstance,\r
+                   HINSTANCE hPrevInstance,\r
+                   LPSTR lpCmdLine,\r
+                   int nCmdShow)\r
+{\r
+    WNDCLASSEX wcex;\r
+    HWND hwnd;\r
+    HDC hDC;\r
+    HGLRC hRC;\r
+    MSG msg;\r
+    BOOL bQuit = FALSE;\r
+    float theta = 0.0f;\r
+\r
+    // register window class\r
+    wcex.cbSize = sizeof(WNDCLASSEX);\r
+    wcex.style = CS_OWNDC;\r
+    wcex.lpfnWndProc = WindowProc;\r
+    wcex.cbClsExtra = 0;\r
+    wcex.cbWndExtra = 0;\r
+    wcex.hInstance = hInstance;\r
+    wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);\r
+    wcex.hCursor = LoadCursor(NULL, IDC_ARROW);\r
+    wcex.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);\r
+    wcex.lpszMenuName = NULL;\r
+    wcex.lpszClassName = "GLSample";\r
+    wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\r
+\r
+\r
+    if (!RegisterClassEx(&wcex))\r
+        return 0;\r
+\r
+    // create main window\r
+    hwnd = CreateWindowEx(0,\r
+                          "GLSample",\r
+                          "SOIL Sample",\r
+                          WS_OVERLAPPEDWINDOW,\r
+                          CW_USEDEFAULT,\r
+                          CW_USEDEFAULT,\r
+                          512,\r
+                          512,\r
+                          NULL,\r
+                          NULL,\r
+                          hInstance,\r
+                          NULL);\r
+\r
+    ShowWindow(hwnd, nCmdShow);\r
+\r
+    // check my error handling\r
+    /*\r
+    SOIL_load_OGL_texture( "img_test.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, 0 );\r
+    std::cout << "'" << SOIL_last_result() << "'" << std::endl;\r
+    */\r
+\r
+\r
+    // enable OpenGL for the window\r
+    EnableOpenGL(hwnd, &hDC, &hRC);\r
+\r
+    glEnable( GL_BLEND );\r
+    //glDisable( GL_BLEND );\r
+    // straight alpha\r
+    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\r
+    // premultiplied alpha (remember to do the same in glColor!!)\r
+    //glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );\r
+\r
+    // do I want alpha thresholding?\r
+    glEnable( GL_ALPHA_TEST );\r
+    glAlphaFunc( GL_GREATER, 0.5f );\r
+\r
+    // log what the use is asking us to load\r
+    std::string load_me = lpCmdLine;\r
+    if( load_me.length() > 2 )\r
+    {\r
+               //load_me = load_me.substr( 1, load_me.length() - 2 );\r
+               load_me = load_me.substr( 0, load_me.length() - 0 );\r
+    } else\r
+    {\r
+       //load_me = "img_test_uncompressed.dds";\r
+       //load_me = "img_test_indexed.tga";\r
+       //load_me = "img_test.dds";\r
+       load_me = "img_test.png";\r
+       //load_me = "odd_size.jpg";\r
+       //load_me = "img_cheryl.jpg";\r
+       //load_me = "oak_odd.png";\r
+       //load_me = "field_128_cube.dds";\r
+       //load_me = "field_128_cube_nomip.dds";\r
+       //load_me = "field_128_cube_uc.dds";\r
+       //load_me = "field_128_cube_uc_nomip.dds";\r
+       //load_me = "Goblin.dds";\r
+       //load_me = "parquet.dds";\r
+       //load_me = "stpeters_probe.hdr";\r
+       //load_me = "VeraMoBI_sdf.png";\r
+\r
+       //      for testing the texture rectangle code\r
+       //load_me = "test_rect.png";\r
+    }\r
+       std::cout << "'" << load_me << "'" << std::endl;\r
+\r
+       //      1st try to load it as a single-image-cubemap\r
+       //      (note, need DDS ordered faces: "EWUDNS")\r
+       GLuint tex_ID;\r
+    int time_me;\r
+\r
+    std::cout << "Attempting to load as a cubemap" << std::endl;\r
+    time_me = clock();\r
+       tex_ID = SOIL_load_OGL_single_cubemap(\r
+                       load_me.c_str(),\r
+                       SOIL_DDS_CUBEMAP_FACE_ORDER,\r
+                       SOIL_LOAD_AUTO,\r
+                       SOIL_CREATE_NEW_ID,\r
+                       SOIL_FLAG_POWER_OF_TWO\r
+                       | SOIL_FLAG_MIPMAPS\r
+                       //| SOIL_FLAG_COMPRESS_TO_DXT\r
+                       //| SOIL_FLAG_TEXTURE_REPEATS\r
+                       //| SOIL_FLAG_INVERT_Y\r
+                       | SOIL_FLAG_DDS_LOAD_DIRECT\r
+                       );\r
+       time_me = clock() - time_me;\r
+       std::cout << "the load time was " << 0.001f * time_me << " seconds (warning: low resolution timer)" << std::endl;\r
+    if( tex_ID > 0 )\r
+    {\r
+       glEnable( GL_TEXTURE_CUBE_MAP );\r
+               glEnable( GL_TEXTURE_GEN_S );\r
+               glEnable( GL_TEXTURE_GEN_T );\r
+               glEnable( GL_TEXTURE_GEN_R );\r
+               glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );\r
+               glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );\r
+               glTexGeni( GL_R, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP );\r
+               glBindTexture( GL_TEXTURE_CUBE_MAP, tex_ID );\r
+               //      report\r
+               std::cout << "the loaded single cube map ID was " << tex_ID << std::endl;\r
+               //std::cout << "the load time was " << 0.001f * time_me << " seconds (warning: low resolution timer)" << std::endl;\r
+    } else\r
+    {\r
+       std::cout << "Attempting to load as a HDR texture" << std::endl;\r
+               time_me = clock();\r
+               tex_ID = SOIL_load_OGL_HDR_texture(\r
+                               load_me.c_str(),\r
+                               //SOIL_HDR_RGBE,\r
+                               //SOIL_HDR_RGBdivA,\r
+                               SOIL_HDR_RGBdivA2,\r
+                               0,\r
+                               SOIL_CREATE_NEW_ID,\r
+                               SOIL_FLAG_POWER_OF_TWO\r
+                               | SOIL_FLAG_MIPMAPS\r
+                               //| SOIL_FLAG_COMPRESS_TO_DXT\r
+                               );\r
+               time_me = clock() - time_me;\r
+               std::cout << "the load time was " << 0.001f * time_me << " seconds (warning: low resolution timer)" << std::endl;\r
+\r
+               //      did I fail?\r
+               if( tex_ID < 1 )\r
+               {\r
+                       //      loading of the single-image-cubemap failed, try it as a simple texture\r
+                       std::cout << "Attempting to load as a simple 2D texture" << std::endl;\r
+                       //      load the texture, if specified\r
+                       time_me = clock();\r
+                       tex_ID = SOIL_load_OGL_texture(\r
+                                       load_me.c_str(),\r
+                                       SOIL_LOAD_AUTO,\r
+                                       SOIL_CREATE_NEW_ID,\r
+                                       SOIL_FLAG_POWER_OF_TWO\r
+                                       | SOIL_FLAG_MIPMAPS\r
+                                       //| SOIL_FLAG_MULTIPLY_ALPHA\r
+                                       //| SOIL_FLAG_COMPRESS_TO_DXT\r
+                                       | SOIL_FLAG_DDS_LOAD_DIRECT\r
+                                       //| SOIL_FLAG_NTSC_SAFE_RGB\r
+                                       //| SOIL_FLAG_CoCg_Y\r
+                                       //| SOIL_FLAG_TEXTURE_RECTANGLE\r
+                                       );\r
+                       time_me = clock() - time_me;\r
+                       std::cout << "the load time was " << 0.001f * time_me << " seconds (warning: low resolution timer)" << std::endl;\r
+               }\r
+\r
+               if( tex_ID > 0 )\r
+               {\r
+                       //      enable texturing\r
+                       glEnable( GL_TEXTURE_2D );\r
+                       //glEnable( 0x84F5 );// enables texture rectangle\r
+                       //  bind an OpenGL texture ID\r
+                       glBindTexture( GL_TEXTURE_2D, tex_ID );\r
+                       //      report\r
+                       std::cout << "the loaded texture ID was " << tex_ID << std::endl;\r
+                       //std::cout << "the load time was " << 0.001f * time_me << " seconds (warning: low resolution timer)" << std::endl;\r
+               } else\r
+               {\r
+                       //      loading of the texture failed...why?\r
+                       glDisable( GL_TEXTURE_2D );\r
+                       std::cout << "Texture loading failed: '" << SOIL_last_result() << "'" << std::endl;\r
+               }\r
+    }\r
+\r
+    // program main loop\r
+    const float ref_mag = 0.1f;\r
+    while (!bQuit)\r
+    {\r
+        // check for messages\r
+        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))\r
+        {\r
+            // handle or dispatch messages\r
+            if (msg.message == WM_QUIT)\r
+            {\r
+                bQuit = TRUE;\r
+            }\r
+            else\r
+            {\r
+                TranslateMessage(&msg);\r
+                DispatchMessage(&msg);\r
+            }\r
+        }\r
+        else\r
+        {\r
+            // OpenGL animation code goes here\r
+            theta = clock() * 0.1;\r
+\r
+            float tex_u_max = 1.0f;//0.2f;\r
+            float tex_v_max = 1.0f;//0.2f;\r
+\r
+            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\r
+            glClear(GL_COLOR_BUFFER_BIT);\r
+\r
+            glPushMatrix();\r
+            glScalef( 0.8f, 0.8f, 0.8f );\r
+            //glRotatef(-0.314159f*theta, 0.0f, 0.0f, 1.0f);\r
+                       glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );\r
+                       glNormal3f( 0.0f, 0.0f, 1.0f );\r
+            glBegin(GL_QUADS);\r
+                               glNormal3f( -ref_mag, -ref_mag, 1.0f );\r
+                glTexCoord2f( 0.0f, tex_v_max );\r
+                glVertex3f( -1.0f, -1.0f, -0.1f );\r
+\r
+                glNormal3f( ref_mag, -ref_mag, 1.0f );\r
+                glTexCoord2f( tex_u_max, tex_v_max );\r
+                glVertex3f( 1.0f, -1.0f, -0.1f );\r
+\r
+                glNormal3f( ref_mag, ref_mag, 1.0f );\r
+                glTexCoord2f( tex_u_max, 0.0f );\r
+                glVertex3f( 1.0f, 1.0f, -0.1f );\r
+\r
+                glNormal3f( -ref_mag, ref_mag, 1.0f );\r
+                glTexCoord2f( 0.0f, 0.0f );\r
+                glVertex3f( -1.0f, 1.0f, -0.1f );\r
+            glEnd();\r
+            glPopMatrix();\r
+\r
+                       tex_u_max = 1.0f;\r
+            tex_v_max = 1.0f;\r
+            glPushMatrix();\r
+            glScalef( 0.8f, 0.8f, 0.8f );\r
+            glRotatef(theta, 0.0f, 0.0f, 1.0f);\r
+                       glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );\r
+                       glNormal3f( 0.0f, 0.0f, 1.0f );\r
+            glBegin(GL_QUADS);\r
+                glTexCoord2f( 0.0f, tex_v_max );               glVertex3f( 0.0f, 0.0f, 0.1f );\r
+                glTexCoord2f( tex_u_max, tex_v_max );          glVertex3f( 1.0f, 0.0f, 0.1f );\r
+                glTexCoord2f( tex_u_max, 0.0f );               glVertex3f( 1.0f, 1.0f, 0.1f );\r
+                glTexCoord2f( 0.0f, 0.0f );            glVertex3f( 0.0f, 1.0f, 0.1f );\r
+            glEnd();\r
+            glPopMatrix();\r
+\r
+            {\r
+                               /*      check for errors        */\r
+                               GLenum err_code = glGetError();\r
+                               while( GL_NO_ERROR != err_code )\r
+                               {\r
+                                       printf( "OpenGL Error @ %s: %i", "drawing loop", err_code );\r
+                                       err_code = glGetError();\r
+                               }\r
+                       }\r
+\r
+            SwapBuffers(hDC);\r
+\r
+            Sleep (1);\r
+        }\r
+    }\r
+\r
+    // and show off the screenshot capability\r
+    /*\r
+    load_me += "-screenshot.tga";\r
+    SOIL_save_screenshot( load_me.c_str(), SOIL_SAVE_TYPE_TGA, 0, 0, 512, 512 );\r
+    //*/\r
+    //*\r
+    load_me += "-screenshot.bmp";\r
+    SOIL_save_screenshot( load_me.c_str(), SOIL_SAVE_TYPE_BMP, 0, 0, 512, 512 );\r
+    //*/\r
+    /*\r
+    load_me += "-screenshot.dds";\r
+    SOIL_save_screenshot( load_me.c_str(), SOIL_SAVE_TYPE_DDS, 0, 0, 512, 512 );\r
+    //*/\r
+\r
+    // shutdown OpenGL\r
+    DisableOpenGL(hwnd, hDC, hRC);\r
+\r
+    // destroy the window explicitly\r
+    DestroyWindow(hwnd);\r
+\r
+    return msg.wParam;\r
+}\r
+\r
+LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)\r
+{\r
+    switch (uMsg)\r
+    {\r
+        case WM_CLOSE:\r
+            PostQuitMessage(0);\r
+        break;\r
+\r
+        case WM_DESTROY:\r
+            return 0;\r
+\r
+        case WM_KEYDOWN:\r
+        {\r
+            switch (wParam)\r
+            {\r
+                case VK_ESCAPE:\r
+                    PostQuitMessage(0);\r
+                break;\r
+            }\r
+        }\r
+        break;\r
+\r
+        default:\r
+            return DefWindowProc(hwnd, uMsg, wParam, lParam);\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)\r
+{\r
+    PIXELFORMATDESCRIPTOR pfd;\r
+\r
+    int iFormat;\r
+\r
+    /* get the device context (DC) */\r
+    *hDC = GetDC(hwnd);\r
+\r
+    /* set the pixel format for the DC */\r
+    ZeroMemory(&pfd, sizeof(pfd));\r
+\r
+    pfd.nSize = sizeof(pfd);\r
+    pfd.nVersion = 1;\r
+    pfd.dwFlags = PFD_DRAW_TO_WINDOW |\r
+                  PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;\r
+    pfd.iPixelType = PFD_TYPE_RGBA;\r
+    pfd.cColorBits = 24;\r
+    pfd.cDepthBits = 16;\r
+    pfd.iLayerType = PFD_MAIN_PLANE;\r
+\r
+    iFormat = ChoosePixelFormat(*hDC, &pfd);\r
+\r
+    SetPixelFormat(*hDC, iFormat, &pfd);\r
+\r
+    /* create and enable the render context (RC) */\r
+    *hRC = wglCreateContext(*hDC);\r
+\r
+    wglMakeCurrent(*hDC, *hRC);\r
+}\r
+\r
+void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC)\r
+{\r
+    wglMakeCurrent(NULL, NULL);\r
+    wglDeleteContext(hRC);\r
+    ReleaseDC(hwnd, hDC);\r
+}\r
+\r