--- /dev/null
+/* stbi-1.29 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c\r
+ when you control the images you're loading\r
+ no warranty implied; use at your own risk\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)\r
+ PNG 8-bit only\r
+\r
+ TGA (not sure what subset, if a subset)\r
+ BMP non-1bpp, non-RLE\r
+ PSD (composited view only, no extra channels)\r
+\r
+ GIF (*comp always reports as 4-channel)\r
+ HDR (radiance rgbE format)\r
+ PIC (Softimage PIC)\r
+\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
+ Latest revisions:\r
+ 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville \r
+ 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)\r
+ 1.27 (2010-08-01) cast-to-uint8 to fix warnings (Laurent Gomila)\r
+ allow trailing 0s at end of image data (Laurent Gomila)\r
+ 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ\r
+ 1.25 (2010-07-17) refix trans_data warning (Won Chun)\r
+ 1.24 (2010-07-12) perf improvements reading from files\r
+ minor perf improvements for jpeg\r
+ deprecated type-specific functions in hope of feedback\r
+ attempt to fix trans_data warning (Won Chun)\r
+ 1.23 fixed bug in iPhone support\r
+ 1.22 (2010-07-10) removed image *writing* support to stb_image_write.h\r
+ stbi_info support from Jetro Lauha\r
+ GIF support from Jean-Marc Lienher\r
+ iPhone PNG-extensions from James Brown\r
+ warning-fixes from Nicolas Schulz and Janez Zemva\r
+ 1.21 fix use of 'uint8' in header (reported by jon blow)\r
+ 1.20 added support for Softimage PIC, by Tom Seddon\r
+\r
+ See end of file for full revision history.\r
+\r
+ TODO:\r
+ stbi_info support for BMP,PSD,HDR,PIC\r
+ rewrite stbi_info and load_file variations to share file handling code\r
+ (current system allows individual functions to be called directly,\r
+ since each does all the work, but I doubt anyone uses this in practice)\r
+\r
+\r
+ ============================ Contributors =========================\r
+ \r
+ Image formats Optimizations & bugfixes\r
+ Sean Barrett (jpeg, png, bmp) Fabian "ryg" Giesen\r
+ Nicolas Schulz (hdr, psd) \r
+ Jonathan Dummer (tga) Bug fixes & warning fixes \r
+ Jean-Marc Lienher (gif) Marc LeBlanc \r
+ Tom Seddon (pic) Christpher Lloyd \r
+ Thatcher Ulrich (psd) Dave Moore \r
+ Won Chun \r
+ the Horde3D community \r
+ Extensions, features Janez Zemva \r
+ Jetro Lauha (stbi_info) Jonathan Blow \r
+ James "moose2000" Brown (iPhone PNG) Laurent Gomila \r
+ Aruelien Pocheville\r
+\r
+ If your name should be here but isn't, let Sean know.\r
+\r
+*/\r
+\r
+#ifndef STBI_INCLUDE_STB_IMAGE_H\r
+#define STBI_INCLUDE_STB_IMAGE_H\r
+\r
+// To get a header file for this, either cut and paste the header,\r
+// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and\r
+// then include stb_image.c from it.\r
+\r
+//// begin header file ////////////////////////////////////////////////////\r
+//\r
+// Limitations:\r
+// - no jpeg progressive support\r
+// - non-HDR formats support 8-bit samples only (jpeg, png)\r
+// - no delayed line count (jpeg) -- IJG doesn't support either\r
+// - no 1-bit BMP\r
+// - GIF always returns *comp=4\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, BMP, GIF, and PIC images are automatically depalettized.\r
+//\r
+// ===========================================================================\r
+//\r
+// iPhone PNG support:\r
+//\r
+// By default we convert iphone-formatted PNGs back to RGB; nominally they\r
+// would silently load as BGR, except the existing code should have just\r
+// failed on such iPhone PNGs. But you can disable this conversion by\r
+// by calling stbi_convert_iphone_png_to_rgb(0), in which case\r
+// you will always just get the native iphone "format" through.\r
+//\r
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per\r
+// pixel to remove any premultiplied alpha *only* if the image file explicitly\r
+// says there's premultiplied data (currently only happens in iPhone images,\r
+// and only if iPhone convert-to-rgb processing is on).\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
+// PRIMARY API - works on images of any type\r
+\r
+// load image by filename, open file, or memory buffer\r
+extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+\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
+// for stbi_load_from_file, file pointer is left pointing immediately after image\r
+#endif\r
+\r
+#ifndef STBI_NO_HDR\r
+ extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+\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
+\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
+#endif // STBI_NO_HDR\r
+\r
+// get a VERY brief reason for failure\r
+// NOT THREADSAFE\r
+extern const 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
+\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
+\r
+extern int stbi_is_hdr (char const *filename);\r
+extern int stbi_is_hdr_from_file(FILE *f);\r
+#endif\r
+\r
+// for image formats that explicitly notate that they have premultiplied alpha,\r
+// we just return the colors as stored in the file. set this flag to force\r
+// unpremultiplication. results are undefined if the unpremultiply overflow.\r
+extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);\r
+\r
+// indicate whether we should process iphone images back to canonical format,\r
+// or just pass them through "as-is"\r
+extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);\r
+\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
+// 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 define 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
+#ifdef STBI_SIMD\r
+typedef void (*stbi_idct_8x8)(stbi_uc *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)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc 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
+\r
+\r
+\r
+// TYPE-SPECIFIC ACCESS\r
+\r
+#ifdef STBI_TYPE_SPECIFIC_FUNCTIONS\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
+// is it a pic?\r
+extern int stbi_pic_test_memory (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_pic_load (char const *filename, int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_pic_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_pic_test_file (FILE *f);\r
+extern stbi_uc *stbi_pic_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a gif?\r
+extern int stbi_gif_test_memory (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_gif_load (char const *filename, int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_gif_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int stbi_gif_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern int stbi_gif_test_file (FILE *f);\r
+extern stbi_uc *stbi_gif_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);\r
+extern int stbi_gif_info (char const *filename, int *x, int *y, int *comp);\r
+extern int stbi_gif_info_from_file (FILE *f, int *x, int *y, int *comp);\r
+#endif\r
+\r
+#endif//STBI_TYPE_SPECIFIC_FUNCTIONS\r
+\r
+\r
+\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 ? 1 : -1];\r
+\r
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)\r
+#define STBI_NO_WRITE\r
+#endif\r
+\r
+#define STBI_NOTUSED(v) v=v\r
+\r
+#ifdef _MSC_VER\r
+#define STBI_HAS_LRTOL\r
+#endif\r
+\r
+#ifdef STBI_HAS_LRTOL\r
+ #define stbi_lrot(x,y) _lrotl(x,y)\r
+#else\r
+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Generic API that works on all image types\r
+//\r
+\r
+// deprecated functions\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
+// is it a pic?\r
+extern int stbi_pic_test_memory (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_pic_load (char const *filename, int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_pic_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_pic_test_file (FILE *f);\r
+extern stbi_uc *stbi_pic_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);\r
+#endif\r
+\r
+// is it a gif?\r
+extern int stbi_gif_test_memory (stbi_uc const *buffer, int len);\r
+\r
+extern stbi_uc *stbi_gif_load (char const *filename, int *x, int *y, int *comp, int req_comp);\r
+extern stbi_uc *stbi_gif_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);\r
+extern int stbi_gif_info_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp);\r
+\r
+#ifndef STBI_NO_STDIO\r
+extern int stbi_gif_test_file (FILE *f);\r
+extern stbi_uc *stbi_gif_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);\r
+extern int stbi_gif_info (char const *filename, int *x, int *y, int *comp);\r
+extern int stbi_gif_info_from_file (FILE *f, int *x, int *y, int *comp);\r
+#endif\r
+\r
+\r
+// this is not threadsafe\r
+static const char *failure_reason;\r
+\r
+const char *stbi_failure_reason(void)\r
+{\r
+ return failure_reason;\r
+}\r
+\r
+static int e(const 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)) return stbi_jpeg_load_from_file(f,x,y,comp,req_comp);\r
+ if (stbi_png_test_file(f)) return stbi_png_load_from_file(f,x,y,comp,req_comp);\r
+ if (stbi_bmp_test_file(f)) return stbi_bmp_load_from_file(f,x,y,comp,req_comp);\r
+ if (stbi_gif_test_file(f)) return stbi_gif_load_from_file(f,x,y,comp,req_comp);\r
+ if (stbi_psd_test_file(f)) return stbi_psd_load_from_file(f,x,y,comp,req_comp);\r
+ if (stbi_pic_test_file(f)) return stbi_pic_load_from_file(f,x,y,comp,req_comp);\r
+\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
+\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)) return stbi_jpeg_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+ if (stbi_png_test_memory(buffer,len)) return stbi_png_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+ if (stbi_bmp_test_memory(buffer,len)) return stbi_bmp_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+ if (stbi_gif_test_memory(buffer,len)) return stbi_gif_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+ if (stbi_psd_test_memory(buffer,len)) return stbi_psd_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+ if (stbi_pic_test_memory(buffer,len)) return stbi_pic_load_from_memory(buffer,len,x,y,comp,req_comp);\r
+\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
+\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
+ STBI_NOTUSED(buffer);\r
+ STBI_NOTUSED(len);\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
+#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
+ int buflen;\r
+ uint8 buffer_start[128];\r
+ int from_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
+ s->buflen = sizeof(s->buffer_start);\r
+ s->img_buffer_end = s->buffer_start + s->buflen;\r
+ s->img_buffer = s->img_buffer_end;\r
+ s->from_file = 1;\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
+ s->from_file = 0;\r
+#endif\r
+ s->img_buffer = (uint8 *) buffer;\r
+ s->img_buffer_end = (uint8 *) buffer+len;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+static void refill_buffer(stbi *s)\r
+{\r
+ int n = fread(s->buffer_start, 1, s->buflen, s->img_file);\r
+ if (n == 0) {\r
+ s->from_file = 0;\r
+ s->img_buffer = s->img_buffer_end-1;\r
+ *s->img_buffer = 0;\r
+ } else {\r
+ s->img_buffer = s->buffer_start;\r
+ s->img_buffer_end = s->buffer_start + n;\r
+ }\r
+}\r
+#endif\r
+\r
+__forceinline static int get8(stbi *s)\r
+{\r
+ if (s->img_buffer < s->img_buffer_end)\r
+ return *s->img_buffer++;\r
+#ifndef STBI_NO_STDIO\r
+ if (s->from_file) {\r
+ refill_buffer(s);\r
+ return *s->img_buffer++;\r
+ }\r
+#endif\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
+ if (!feof(s->img_file)) return 0;\r
+ // if feof() is true, check if buffer = end\r
+ // special case: we've only got the special 0 character at the end\r
+ if (s->from_file == 0) return 1;\r
+ }\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
+ int blen = s->img_buffer_end - s->img_buffer;\r
+ if (blen < n) {\r
+ s->img_buffer = s->img_buffer_end;\r
+ fseek(s->img_file, n - blen, SEEK_CUR);\r
+ return;\r
+ }\r
+ }\r
+#endif\r
+ s->img_buffer += n;\r
+}\r
+\r
+static int getn(stbi *s, stbi_uc *buffer, int n)\r
+{\r
+#ifndef STBI_NO_STDIO\r
+ if (s->img_file) {\r
+ int blen = s->img_buffer_end - s->img_buffer;\r
+ if (blen < n) {\r
+ int res;\r
+ memcpy(buffer, s->img_buffer, blen);\r
+ res = ((int) fread(buffer + blen, 1, n - blen, s->img_file) == (n-blen));\r
+ s->img_buffer = s->img_buffer_end;\r
+ return res;\r
+ }\r
+ }\r
+#endif\r
+ if (s->img_buffer+n <= s->img_buffer_end) {\r
+ memcpy(buffer, s->img_buffer, n);\r
+ s->img_buffer += n;\r
+ return 1;\r
+ } else\r
+ return 0;\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
+//////////////////////////////////////////////////////////////////////////////\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] = (uint8) 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] = (uint8) 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
+ #ifdef 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 |= b << (24 - j->code_bits);\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 >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);\r
+ k = h->fast[c];\r
+ if (k < 255) {\r
+ int s = h->size[k];\r
+ if (s > j->code_bits)\r
+ return -1;\r
+ j->code_buffer <<= s;\r
+ j->code_bits -= s;\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
+ temp = j->code_buffer >> 16;\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 >> (32 - k)) & bmask[k]) + h->delta[k];\r
+ assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);\r
+\r
+ // convert the id to a symbol\r
+ j->code_bits -= k;\r
+ j->code_buffer <<= 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
+\r
+ #if 1\r
+ k = stbi_lrot(j->code_buffer, n);\r
+ j->code_buffer = k & ~bmask[n];\r
+ k &= bmask[n];\r
+ j->code_bits -= n;\r
+ #else\r
+ k = (j->code_buffer >> (32 - n)) & bmask[n];\r
+ j->code_bits -= n;\r
+ j->code_buffer <<= n;\r
+ #endif\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
+ // 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
+#ifdef STBI_SIMD\r
+typedef unsigned short stbi_dequantize_t;\r
+#else\r
+typedef uint8 stbi_dequantize_t;\r
+#endif\r
+\r
+// .344 seconds on 3*anemones.jpg\r
+static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)\r
+{\r
+ int i,val[64],*v=val;\r
+ stbi_dequantize_t *dq = dequantize;\r
+ uint8 *o;\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
+ // so we want to round that, which means adding 0.5 * 1<<17,\r
+ // aka 65536. Also, we'll end up with -128 to 127 that we want\r
+ // to encode as 0..255 by adding 128, so we'll add that before the shift\r
+ x0 += 65536 + (128<<17);\r
+ x1 += 65536 + (128<<17);\r
+ x2 += 65536 + (128<<17);\r
+ x3 += 65536 + (128<<17);\r
+ // tried computing the shifts into temps, or'ing the temps to see\r
+ // if any were out of range, but that was slower\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
+#ifdef STBI_SIMD\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
+ #ifdef 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
+ #ifdef 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
+ #ifdef 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
+ #ifdef STBI_SIMD\r
+ for (i=0; i < 64; ++i)\r
+ z->dequant2[t][i] = z->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
+ if (j->marker == MARKER_none ) {\r
+ // handle 0s at the end of image data from IP Kamera 9060\r
+ while (!at_eof(&j->s)) {\r
+ int x = get8(&j->s);\r
+ if (x == 255) {\r
+ j->marker = get8u(&j->s);\r
+ break;\r
+ } else if (x != 0) {\r
+ return 0;\r
+ }\r
+ }\r
+ // if we reach eof without hitting a marker, get_marker() below will fail and we'll eventually return 0\r
+ }\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
+ STBI_NOTUSED(out);\r
+ STBI_NOTUSED(in_far);\r
+ STBI_NOTUSED(w);\r
+ STBI_NOTUSED(hs);\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
+ STBI_NOTUSED(hs);\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
+\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
+\r
+ STBI_NOTUSED(in_far);\r
+ STBI_NOTUSED(hs);\r
+\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
+\r
+ STBI_NOTUSED(hs);\r
+\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
+ in_far = in_far;\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, const uint8 *y, const uint8 *pcb, const 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
+#ifdef 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
+ #ifdef 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
+ #ifdef STBI_SMALL_STACK\r
+ unsigned char *result;\r
+ jpeg *j = (jpeg *) malloc(sizeof(*j));\r
+ start_mem(&j->s, buffer, len);\r
+ result = load_jpeg_image(j,x,y,comp,req_comp);\r
+ free(j);\r
+ return result;\r
+ #else\r
+ jpeg j;\r
+ start_mem(&j.s, buffer,len);\r
+ return load_jpeg_image(&j, x,y,comp,req_comp);\r
+ #endif\r
+}\r
+\r
+static int stbi_jpeg_info_raw(jpeg *j, int *x, int *y, int *comp)\r
+{\r
+ if (!decode_jpeg_header(j, SCAN_header))\r
+ return 0;\r
+ if (x) *x = j->s.img_x;\r
+ if (y) *y = j->s.img_y;\r
+ if (comp) *comp = j->s.img_n;\r
+ return 1;\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
+\r
+int stbi_jpeg_info_from_file(FILE *f, int *x, int *y, int *comp)\r
+{\r
+ jpeg j;\r
+ long n = ftell(f);\r
+ int res;\r
+ start_file(&j.s, f);\r
+ res = stbi_jpeg_info_raw(&j, x, y, comp);\r
+ fseek(f, n, SEEK_SET);\r
+ return res;\r
+}\r
+\r
+int stbi_jpeg_info(char const *filename, int *x, int *y, int *comp)\r
+{\r
+ FILE *f = fopen(filename, "rb");\r
+ int result;\r
+ if (!f) return e("can't fopen", "Unable to open file");\r
+ result = stbi_jpeg_info_from_file(f, x, y, comp);\r
+ fclose(f);\r
+ return result;\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
+int stbi_jpeg_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\r
+{\r
+ jpeg j;\r
+ start_mem(&j.s, buffer, len);\r
+ return stbi_jpeg_info_raw(&j, x, y, comp);\r
+}\r
+\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
+ zhuffman z_codelength;\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
+int stbi_png_partial; // a quick hack to only allow decoding some of a PNG... I should implement real streaming support instead\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
+ if (stbi_png_partial && a->zout - a->zout_start > 65536)\r
+ break;\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
+char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)\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, parse_header)) {\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_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_raw(png *a, uint8 *raw, uint32 raw_len, int out_n, uint32 x, uint32 y)\r
+{\r
+ stbi *s = &a->s;\r
+ uint32 i,j,stride = 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
+ if (stbi_png_partial) y = 1;\r
+ a->out = (uint8 *) malloc(x * y * out_n);\r
+ if (!a->out) return e("outofmem", "Out of memory");\r
+ if (!stbi_png_partial) {\r
+ if (s->img_x == x && s->img_y == y) {\r
+ if (raw_len != (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");\r
+ } else { // interlaced:\r
+ if (raw_len < (img_n * x + 1) * y) return e("not enough pixels","Corrupt PNG");\r
+ }\r
+ }\r
+ for (j=0; j < 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=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=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 create_png_image(png *a, uint8 *raw, uint32 raw_len, int out_n, int interlaced)\r
+{\r
+ uint8 *final;\r
+ int p;\r
+ int save;\r
+ if (!interlaced)\r
+ return create_png_image_raw(a, raw, raw_len, out_n, a->s.img_x, a->s.img_y);\r
+ save = stbi_png_partial;\r
+ stbi_png_partial = 0;\r
+\r
+ // de-interlacing\r
+ final = (uint8 *) malloc(a->s.img_x * a->s.img_y * out_n);\r
+ for (p=0; p < 7; ++p) {\r
+ int xorig[] = { 0,4,0,2,0,1,0 };\r
+ int yorig[] = { 0,0,4,0,2,0,1 };\r
+ int xspc[] = { 8,8,4,4,2,2,1 };\r
+ int yspc[] = { 8,8,8,4,4,2,2 };\r
+ int i,j,x,y;\r
+ // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1\r
+ x = (a->s.img_x - xorig[p] + xspc[p]-1) / xspc[p];\r
+ y = (a->s.img_y - yorig[p] + yspc[p]-1) / yspc[p];\r
+ if (x && y) {\r
+ if (!create_png_image_raw(a, raw, raw_len, out_n, x, y)) {\r
+ free(final);\r
+ return 0;\r
+ }\r
+ for (j=0; j < y; ++j)\r
+ for (i=0; i < x; ++i)\r
+ memcpy(final + (j*yspc[p]+yorig[p])*a->s.img_x*out_n + (i*xspc[p]+xorig[p])*out_n,\r
+ a->out + (j*x+i)*out_n, out_n);\r
+ free(a->out);\r
+ raw += (x*out_n+1)*y;\r
+ raw_len -= (x*out_n+1)*y;\r
+ }\r
+ }\r
+ a->out = final;\r
+\r
+ stbi_png_partial = save;\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
+\r
+ STBI_NOTUSED(len);\r
+\r
+ return 1;\r
+}\r
+\r
+static int stbi_unpremultiply_on_load = 0;\r
+static int stbi_de_iphone_flag = 0;\r
+\r
+void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)\r
+{\r
+ stbi_unpremultiply_on_load = flag_true_if_should_unpremultiply;\r
+}\r
+void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)\r
+{\r
+ stbi_de_iphone_flag = flag_true_if_should_convert;\r
+}\r
+\r
+static void stbi_de_iphone(png *z)\r
+{\r
+ stbi *s = &z->s;\r
+ uint32 i, pixel_count = s->img_x * s->img_y;\r
+ uint8 *p = z->out;\r
+\r
+ if (s->img_out_n == 3) { // convert bgr to rgb\r
+ for (i=0; i < pixel_count; ++i) {\r
+ uint8 t = p[0];\r
+ p[0] = p[2];\r
+ p[2] = t;\r
+ p += 3;\r
+ }\r
+ } else {\r
+ assert(s->img_out_n == 4);\r
+ if (stbi_unpremultiply_on_load) {\r
+ // convert bgr to rgb and unpremultiply\r
+ for (i=0; i < pixel_count; ++i) {\r
+ uint8 a = p[3];\r
+ uint8 t = p[0];\r
+ if (a) {\r
+ p[0] = p[2] * 255 / a;\r
+ p[1] = p[1] * 255 / a;\r
+ p[2] = t * 255 / a;\r
+ } else {\r
+ p[0] = p[2];\r
+ p[2] = t;\r
+ } \r
+ p += 4;\r
+ }\r
+ } else {\r
+ // convert bgr to rgb\r
+ for (i=0; i < pixel_count; ++i) {\r
+ uint8 t = p[0];\r
+ p[0] = p[2];\r
+ p[2] = t;\r
+ p += 4;\r
+ }\r
+ }\r
+ }\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,interlace=0, iphone=0;\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 (;;) {\r
+ chunk c = get_chunk_header(s);\r
+ switch (c.type) {\r
+ case PNG_TYPE('C','g','B','I'):\r
+ iphone = stbi_de_iphone_flag;\r
+ skip(s, c.length);\r
+ break;\r
+ case PNG_TYPE('I','H','D','R'): {\r
+ int depth,color,comp,filter;\r
+ if (!first) return e("multiple IHDR","Corrupt PNG");\r
+ first = 0;\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>1) return e("bad interlace method","Corrupt PNG");\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 (first) return e("first not IHDR", "Corrupt PNG");\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 (first) return e("first not IHDR", "Corrupt PNG");\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 (first) return e("first not IHDR", "Corrupt PNG");\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
+ if (!getn(s, z->idata+ioff,c.length)) return e("outofdata","Corrupt PNG");\r
+ ioff += c.length;\r
+ break;\r
+ }\r
+\r
+ case PNG_TYPE('I','E','N','D'): {\r
+ uint32 raw_len;\r
+ if (first) return e("first not IHDR", "Corrupt PNG");\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_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !iphone);\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, interlace)) return 0;\r
+ if (has_trans)\r
+ if (!compute_transparency(z, tc, s->img_out_n)) return 0;\r
+ if (iphone && s->img_out_n > 2)\r
+ stbi_de_iphone(z);\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 (first) return e("first not IHDR", "Corrupt PNG");\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
+static int stbi_png_info_raw(png *p, int *x, int *y, int *comp)\r
+{\r
+ if (!parse_png_file(p, SCAN_header, 0))\r
+ return 0;\r
+ if (x) *x = p->s.img_x;\r
+ if (y) *y = p->s.img_y;\r
+ if (comp) *comp = p->s.img_n;\r
+ return 1;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_png_info (char const *filename, int *x, int *y, int *comp)\r
+{\r
+ int res;\r
+ FILE *f = fopen(filename, "rb");\r
+ if (!f) return 0;\r
+ res = stbi_png_info_from_file(f, x, y, comp);\r
+ fclose(f);\r
+ return res;\r
+}\r
+\r
+int stbi_png_info_from_file(FILE *f, int *x, int *y, int *comp)\r
+{\r
+ png p;\r
+ int res;\r
+ long n = ftell(f);\r
+ start_file(&p.s, f);\r
+ res = stbi_png_info_raw(&p, x, y, comp);\r
+ fseek(f, n, SEEK_SET);\r
+ return res;\r
+}\r
+#endif // !STBI_NO_STDIO\r
+\r
+int stbi_png_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\r
+{\r
+ png p;\r
+ start_mem(&p.s, buffer, len);\r
+ return stbi_png_info_raw(&p, x, y, comp);\r
+}\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, fake_a=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
+ 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 epuc("bad BMP", "bad BMP");\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 = 0xffu << 16;\r
+ mg = 0xffu << 8;\r
+ mb = 0xffu << 0;\r
+ ma = 0xffu << 24;\r
+ fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255\r
+ } else {\r
+ mr = 31u << 10;\r
+ mg = 31u << 5;\r
+ mb = 31u << 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 epuc("bad BMP", "bad BMP");\r
+ }\r
+ } else\r
+ return epuc("bad BMP", "bad BMP");\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] = get8u(s);\r
+ pal[i][1] = get8u(s);\r
+ pal[i][0] = get8u(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] = get8u(s);\r
+ out[z+1] = get8u(s);\r
+ out[z+0] = get8u(s);\r
+ z += 3;\r
+ a = (easy == 2 ? get8(s) : 255);\r
+ if (target == 4) out[z++] = (uint8) 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++] = (uint8) shiftsigned(v & mr, rshift, rcount);\r
+ out[z++] = (uint8) shiftsigned(v & mg, gshift, gcount);\r
+ out[z++] = (uint8) shiftsigned(v & mb, bshift, bcount);\r
+ a = (ma ? shiftsigned(v & ma, ashift, acount) : 255);\r
+ if (target == 4) out[z++] = (uint8) 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_info(stbi *s, int *x, int *y, int *comp)\r
+{\r
+ int tga_w, tga_h, tga_comp;\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
+ // only RGB or grey allowed, +/- RLE\r
+ if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;\r
+ get16le(s); // discard palette start\r
+ get16le(s); // discard palette length\r
+ get8(s); // discard bits per palette color entry\r
+ get16le(s); // discard x origin\r
+ get16le(s); // discard y origin\r
+ tga_w = get16le(s);\r
+ if( tga_w < 1 ) return 0; // test width\r
+ tga_h = get16le(s);\r
+ if( tga_h < 1 ) return 0; // test height\r
+ sz = get8(s); // bits per pixel\r
+ // only RGB or RGBA or grey allowed\r
+ if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) return 0;\r
+ tga_comp = sz;\r
+ if (x) *x = tga_w;\r
+ if (y) *y = tga_h;\r
+ if (comp) *comp = tga_comp / 8;\r
+ return 1; // seems to have passed everything\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_tga_info_from_file(FILE *f, int *x, int *y, int *comp)\r
+{\r
+ stbi s;\r
+ int r;\r
+ long n = ftell(f);\r
+ start_file(&s, f);\r
+ r = tga_info(&s, x, y, comp);\r
+ fseek(f, n, SEEK_SET);\r
+ return r;\r
+}\r
+#endif\r
+\r
+int stbi_tga_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\r
+{\r
+ stbi s;\r
+ start_mem(&s, buffer, len);\r
+ return tga_info(&s, x, y, comp);\r
+}\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
+\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
+ if (!getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 ))\r
+ return NULL;\r
+ }\r
+ // load the data\r
+ trans_data[0] = trans_data[1] = trans_data[2] = trans_data[3] = 0;\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 Nicolas 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 = get8u(s);\r
+ p += 4;\r
+ len--;\r
+ }\r
+ } else if (len > 128) {\r
+ uint8 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 = get8u(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
+ for (i = 0; i < pixelCount; i++)\r
+ *p = get8u(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
+// Softimage PIC loader\r
+// by Tom Seddon\r
+//\r
+// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format\r
+// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/\r
+\r
+static int pic_is4(stbi *s,const char *str)\r
+{\r
+ int i;\r
+ for (i=0; i<4; ++i)\r
+ if (get8(s) != (stbi_uc)str[i])\r
+ return 0;\r
+\r
+ return 1;\r
+}\r
+\r
+static int pic_test(stbi *s)\r
+{\r
+ int i;\r
+\r
+ if (!pic_is4(s,"\x53\x80\xF6\x34"))\r
+ return 0;\r
+\r
+ for(i=0;i<84;++i)\r
+ get8(s);\r
+\r
+ if (!pic_is4(s,"PICT"))\r
+ return 0;\r
+\r
+ return 1;\r
+}\r
+\r
+typedef struct\r
+{\r
+ stbi_uc size,type,channel;\r
+} pic_packet_t;\r
+\r
+static stbi_uc *pic_readval(stbi *s, int channel, stbi_uc *dest)\r
+{\r
+ int mask=0x80, i;\r
+\r
+ for (i=0; i<4; ++i, mask>>=1) {\r
+ if (channel & mask) {\r
+ if (at_eof(s)) return epuc("bad file","PIC file too short");\r
+ dest[i]=get8u(s);\r
+ }\r
+ }\r
+\r
+ return dest;\r
+}\r
+\r
+static void pic_copyval(int channel,stbi_uc *dest,const stbi_uc *src)\r
+{\r
+ int mask=0x80,i;\r
+\r
+ for (i=0;i<4; ++i, mask>>=1)\r
+ if (channel&mask)\r
+ dest[i]=src[i];\r
+}\r
+\r
+static stbi_uc *pic_load2(stbi *s,int width,int height,int *comp, stbi_uc *result)\r
+{\r
+ int act_comp=0,num_packets=0,y,chained;\r
+ pic_packet_t packets[10];\r
+\r
+ // this will (should...) cater for even some bizarre stuff like having data\r
+ // for the same channel in multiple packets.\r
+ do {\r
+ pic_packet_t *packet;\r
+\r
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))\r
+ return epuc("bad format","too many packets");\r
+\r
+ packet = &packets[num_packets++];\r
+\r
+ chained = get8(s);\r
+ packet->size = get8u(s);\r
+ packet->type = get8u(s);\r
+ packet->channel = get8u(s);\r
+\r
+ act_comp |= packet->channel;\r
+\r
+ if (at_eof(s)) return epuc("bad file","file too short (reading packets)");\r
+ if (packet->size != 8) return epuc("bad format","packet isn't 8bpp");\r
+ } while (chained);\r
+\r
+ *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?\r
+\r
+ for(y=0; y<height; ++y) {\r
+ int packet_idx;\r
+\r
+ for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {\r
+ pic_packet_t *packet = &packets[packet_idx];\r
+ stbi_uc *dest = result+y*width*4;\r
+\r
+ switch (packet->type) {\r
+ default:\r
+ return epuc("bad format","packet has bad compression type");\r
+\r
+ case 0: {//uncompressed\r
+ int x;\r
+\r
+ for(x=0;x<width;++x, dest+=4)\r
+ if (!pic_readval(s,packet->channel,dest))\r
+ return 0;\r
+ break;\r
+ }\r
+\r
+ case 1://Pure RLE\r
+ {\r
+ int left=width, i;\r
+\r
+ while (left>0) {\r
+ stbi_uc count,value[4];\r
+\r
+ count=get8u(s);\r
+ if (at_eof(s)) return epuc("bad file","file too short (pure read count)");\r
+\r
+ if (count > left)\r
+ count = (uint8) left;\r
+\r
+ if (!pic_readval(s,packet->channel,value)) return 0;\r
+\r
+ for(i=0; i<count; ++i,dest+=4)\r
+ pic_copyval(packet->channel,dest,value);\r
+ left -= count;\r
+ }\r
+ }\r
+ break;\r
+\r
+ case 2: {//Mixed RLE\r
+ int left=width;\r
+ while (left>0) {\r
+ int count = get8(s), i;\r
+ if (at_eof(s)) return epuc("bad file","file too short (mixed read count)");\r
+\r
+ if (count >= 128) { // Repeated\r
+ stbi_uc value[4];\r
+ int i;\r
+\r
+ if (count==128)\r
+ count = get16(s);\r
+ else\r
+ count -= 127;\r
+ if (count > left)\r
+ return epuc("bad file","scanline overrun");\r
+\r
+ if (!pic_readval(s,packet->channel,value))\r
+ return 0;\r
+\r
+ for(i=0;i<count;++i, dest += 4)\r
+ pic_copyval(packet->channel,dest,value);\r
+ } else { // Raw\r
+ ++count;\r
+ if (count>left) return epuc("bad file","scanline overrun");\r
+\r
+ for(i=0;i<count;++i, dest+=4)\r
+ if (!pic_readval(s,packet->channel,dest))\r
+ return 0;\r
+ }\r
+ left-=count;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ }\r
+ }\r
+\r
+ return result;\r
+}\r
+\r
+static stbi_uc *pic_load(stbi *s,int *px,int *py,int *comp,int req_comp)\r
+{\r
+ stbi_uc *result;\r
+ int i, x,y;\r
+\r
+ for (i=0; i<92; ++i)\r
+ get8(s);\r
+\r
+ x = get16(s);\r
+ y = get16(s);\r
+ if (at_eof(s)) return epuc("bad file","file too short (pic header)");\r
+ if ((1 << 28) / x < y) return epuc("too large", "Image too large to decode");\r
+\r
+ get32(s); //skip `ratio'\r
+ get16(s); //skip `fields'\r
+ get16(s); //skip `pad'\r
+\r
+ // intermediate buffer is RGBA\r
+ result = (stbi_uc *) malloc(x*y*4);\r
+ memset(result, 0xff, x*y*4);\r
+\r
+ if (!pic_load2(s,x,y,comp, result)) {\r
+ free(result);\r
+ result=0;\r
+ }\r
+ *px = x;\r
+ *py = y;\r
+ if (req_comp == 0) req_comp = *comp;\r
+ result=convert_format(result,4,req_comp,x,y);\r
+\r
+ return result;\r
+}\r
+\r
+int stbi_pic_test_memory(stbi_uc const *buffer, int len)\r
+{\r
+ stbi s;\r
+ start_mem(&s,buffer,len);\r
+ return pic_test(&s);\r
+}\r
+\r
+stbi_uc *stbi_pic_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 pic_load(&s,x,y,comp,req_comp);\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_pic_test_file(FILE *f)\r
+{\r
+ int result;\r
+ long l = ftell(f);\r
+ stbi s;\r
+ start_file(&s,f);\r
+ result = pic_test(&s);\r
+ fseek(f,l,SEEK_SET);\r
+ return result;\r
+}\r
+\r
+stbi_uc *stbi_pic_load(char const *filename,int *x, int *y, int *comp, int req_comp)\r
+{\r
+ stbi_uc *result;\r
+ FILE *f=fopen(filename,"rb");\r
+ if (!f) return 0;\r
+ result = stbi_pic_load_from_file(f,x,y,comp,req_comp);\r
+ fclose(f);\r
+ return result;\r
+}\r
+\r
+stbi_uc *stbi_pic_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 pic_load(&s,x,y,comp,req_comp);\r
+}\r
+#endif\r
+\r
+// *************************************************************************************************\r
+// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb\r
+typedef struct stbi_gif_lzw_struct {\r
+ int16 prefix;\r
+ uint8 first;\r
+ uint8 suffix;\r
+} stbi_gif_lzw;\r
+\r
+typedef struct stbi_gif_struct\r
+{\r
+ int w,h;\r
+ stbi_uc *out; // output buffer (always 4 components)\r
+ int flags, bgindex, ratio, transparent, eflags;\r
+ uint8 pal[256][4];\r
+ uint8 lpal[256][4];\r
+ stbi_gif_lzw codes[4096];\r
+ uint8 *color_table;\r
+ int parse, step;\r
+ int lflags;\r
+ int start_x, start_y;\r
+ int max_x, max_y;\r
+ int cur_x, cur_y;\r
+ int line_size;\r
+} stbi_gif;\r
+\r
+static int gif_test(stbi *s)\r
+{\r
+ int sz;\r
+ if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8') return 0;\r
+ sz = get8(s);\r
+ if (sz != '9' && sz != '7') return 0;\r
+ if (get8(s) != 'a') return 0;\r
+ return 1;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_gif_test_file (FILE *f)\r
+{\r
+ stbi s;\r
+ int r,n = ftell(f);\r
+ start_file(&s,f);\r
+ r = gif_test(&s);\r
+ fseek(f,n,SEEK_SET);\r
+ return r;\r
+}\r
+#endif\r
+\r
+int stbi_gif_test_memory (stbi_uc const *buffer, int len)\r
+{\r
+ stbi s;\r
+ start_mem(&s, buffer, len);\r
+ return gif_test(&s);\r
+}\r
+\r
+static void stbi_gif_parse_colortable(stbi *s, uint8 pal[256][4], int num_entries, int transp)\r
+{\r
+ int i;\r
+ for (i=0; i < num_entries; ++i) {\r
+ pal[i][2] = get8u(s);\r
+ pal[i][1] = get8u(s);\r
+ pal[i][0] = get8u(s);\r
+ pal[i][3] = transp ? 0 : 255;\r
+ } \r
+}\r
+\r
+static int stbi_gif_header(stbi *s, stbi_gif *g, int *comp, int is_info)\r
+{\r
+ uint8 version;\r
+ if (get8(s) != 'G' || get8(s) != 'I' || get8(s) != 'F' || get8(s) != '8')\r
+ return e("not GIF", "Corrupt GIF");\r
+\r
+ version = get8u(s);\r
+ if (version != '7' && version != '9') return e("not GIF", "Corrupt GIF");\r
+ if (get8(s) != 'a') return e("not GIF", "Corrupt GIF");\r
+ \r
+ failure_reason = "";\r
+ g->w = get16le(s);\r
+ g->h = get16le(s);\r
+ g->flags = get8(s);\r
+ g->bgindex = get8(s);\r
+ g->ratio = get8(s);\r
+ g->transparent = -1;\r
+\r
+ if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments\r
+\r
+ if (is_info) return 1;\r
+\r
+ if (g->flags & 0x80)\r
+ stbi_gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);\r
+\r
+ return 1;\r
+}\r
+\r
+static int stbi_gif_info_raw(stbi *s, int *x, int *y, int *comp)\r
+{\r
+ stbi_gif g; \r
+ if (!stbi_gif_header(s, &g, comp, 1)) return 0;\r
+ if (x) *x = g.w;\r
+ if (y) *y = g.h;\r
+ return 1;\r
+}\r
+\r
+static void stbi_out_gif_code(stbi_gif *g, uint16 code)\r
+{\r
+ uint8 *p, *c;\r
+\r
+ // recurse to decode the prefixes, since the linked-list is backwards,\r
+ // and working backwards through an interleaved image would be nasty\r
+ if (g->codes[code].prefix >= 0)\r
+ stbi_out_gif_code(g, g->codes[code].prefix);\r
+\r
+ if (g->cur_y >= g->max_y) return;\r
+ \r
+ p = &g->out[g->cur_x + g->cur_y];\r
+ c = &g->color_table[g->codes[code].suffix * 4];\r
+\r
+ if (c[3] >= 128) {\r
+ p[0] = c[2];\r
+ p[1] = c[1];\r
+ p[2] = c[0];\r
+ p[3] = c[3];\r
+ }\r
+ g->cur_x += 4;\r
+\r
+ if (g->cur_x >= g->max_x) {\r
+ g->cur_x = g->start_x;\r
+ g->cur_y += g->step;\r
+\r
+ while (g->cur_y >= g->max_y && g->parse > 0) {\r
+ g->step = (1 << g->parse) * g->line_size;\r
+ g->cur_y = g->start_y + (g->step >> 1);\r
+ --g->parse;\r
+ }\r
+ }\r
+}\r
+\r
+static uint8 *stbi_process_gif_raster(stbi *s, stbi_gif *g)\r
+{\r
+ uint8 lzw_cs;\r
+ int32 len, code;\r
+ uint32 first;\r
+ int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;\r
+ stbi_gif_lzw *p;\r
+\r
+ lzw_cs = get8u(s);\r
+ clear = 1 << lzw_cs;\r
+ first = 1;\r
+ codesize = lzw_cs + 1;\r
+ codemask = (1 << codesize) - 1;\r
+ bits = 0;\r
+ valid_bits = 0;\r
+ for (code = 0; code < clear; code++) {\r
+ g->codes[code].prefix = -1;\r
+ g->codes[code].first = (uint8) code;\r
+ g->codes[code].suffix = (uint8) code;\r
+ }\r
+\r
+ // support no starting clear code\r
+ avail = clear+2;\r
+ oldcode = -1;\r
+\r
+ len = 0;\r
+ for(;;) {\r
+ if (valid_bits < codesize) {\r
+ if (len == 0) {\r
+ len = get8(s); // start new block\r
+ if (len == 0) \r
+ return g->out;\r
+ }\r
+ --len;\r
+ bits |= (int32) get8(s) << valid_bits;\r
+ valid_bits += 8;\r
+ } else {\r
+ int32 code = bits & codemask;\r
+ bits >>= codesize;\r
+ valid_bits -= codesize;\r
+ // @OPTIMIZE: is there some way we can accelerate the non-clear path?\r
+ if (code == clear) { // clear code\r
+ codesize = lzw_cs + 1;\r
+ codemask = (1 << codesize) - 1;\r
+ avail = clear + 2;\r
+ oldcode = -1;\r
+ first = 0;\r
+ } else if (code == clear + 1) { // end of stream code\r
+ skip(s, len);\r
+ while ((len = get8(s)) > 0)\r
+ skip(s,len);\r
+ return g->out;\r
+ } else if (code <= avail) {\r
+ if (first) return epuc("no clear code", "Corrupt GIF");\r
+\r
+ if (oldcode >= 0) {\r
+ p = &g->codes[avail++];\r
+ if (avail > 4096) return epuc("too many codes", "Corrupt GIF");\r
+ p->prefix = (int16) oldcode;\r
+ p->first = g->codes[oldcode].first;\r
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;\r
+ } else if (code == avail)\r
+ return epuc("illegal code in raster", "Corrupt GIF");\r
+\r
+ stbi_out_gif_code(g, (uint16) code);\r
+\r
+ if ((avail & codemask) == 0 && avail <= 0x0FFF) {\r
+ codesize++;\r
+ codemask = (1 << codesize) - 1;\r
+ }\r
+\r
+ oldcode = code;\r
+ } else {\r
+ return epuc("illegal code in raster", "Corrupt GIF");\r
+ }\r
+ } \r
+ }\r
+}\r
+\r
+static void stbi_fill_gif_background(stbi_gif *g)\r
+{\r
+ int i;\r
+ uint8 *c = g->pal[g->bgindex];\r
+ // @OPTIMIZE: write a dword at a time\r
+ for (i = 0; i < g->w * g->h * 4; i += 4) {\r
+ uint8 *p = &g->out[i];\r
+ p[0] = c[2];\r
+ p[1] = c[1];\r
+ p[2] = c[0];\r
+ p[3] = c[3];\r
+ }\r
+}\r
+\r
+// this function is designed to support animated gifs, although stb_image doesn't support it\r
+static uint8 *stbi_gif_load_next(stbi *s, stbi_gif *g, int *comp, int req_comp)\r
+{\r
+ int i;\r
+ uint8 *old_out = 0;\r
+\r
+ if (g->out == 0) {\r
+ if (!stbi_gif_header(s, g, comp,0)) return 0; // failure_reason set by stbi_gif_header\r
+ g->out = (uint8 *) malloc(4 * g->w * g->h);\r
+ if (g->out == 0) return epuc("outofmem", "Out of memory");\r
+ stbi_fill_gif_background(g);\r
+ } else {\r
+ // animated-gif-only path\r
+ if (((g->eflags & 0x1C) >> 2) == 3) {\r
+ old_out = g->out;\r
+ g->out = (uint8 *) malloc(4 * g->w * g->h);\r
+ if (g->out == 0) return epuc("outofmem", "Out of memory");\r
+ memcpy(g->out, old_out, g->w*g->h*4);\r
+ }\r
+ }\r
+ \r
+ for (;;) {\r
+ switch (get8(s)) {\r
+ case 0x2C: /* Image Descriptor */\r
+ {\r
+ int32 x, y, w, h;\r
+ uint8 *o;\r
+\r
+ x = get16le(s);\r
+ y = get16le(s);\r
+ w = get16le(s);\r
+ h = get16le(s);\r
+ if (((x + w) > (g->w)) || ((y + h) > (g->h)))\r
+ return epuc("bad Image Descriptor", "Corrupt GIF");\r
+\r
+ g->line_size = g->w * 4;\r
+ g->start_x = x * 4;\r
+ g->start_y = y * g->line_size;\r
+ g->max_x = g->start_x + w * 4;\r
+ g->max_y = g->start_y + h * g->line_size;\r
+ g->cur_x = g->start_x;\r
+ g->cur_y = g->start_y;\r
+\r
+ g->lflags = get8(s);\r
+\r
+ if (g->lflags & 0x40) {\r
+ g->step = 8 * g->line_size; // first interlaced spacing\r
+ g->parse = 3;\r
+ } else {\r
+ g->step = g->line_size;\r
+ g->parse = 0;\r
+ }\r
+\r
+ if (g->lflags & 0x80) {\r
+ stbi_gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);\r
+ g->color_table = (uint8 *) g->lpal; \r
+ } else if (g->flags & 0x80) {\r
+ for (i=0; i < 256; ++i) // @OPTIMIZE: reset only the previous transparent\r
+ g->pal[i][3] = 255; \r
+ if (g->transparent >= 0 && (g->eflags & 0x01))\r
+ g->pal[g->transparent][3] = 0;\r
+ g->color_table = (uint8 *) g->pal;\r
+ } else\r
+ return epuc("missing color table", "Corrupt GIF");\r
+ \r
+ o = stbi_process_gif_raster(s, g);\r
+ if (o == NULL) return NULL;\r
+\r
+ if (req_comp && req_comp != 4)\r
+ o = convert_format(o, 4, req_comp, g->w, g->h);\r
+ return o;\r
+ }\r
+\r
+ case 0x21: // Comment Extension.\r
+ {\r
+ int len;\r
+ if (get8(s) == 0xF9) { // Graphic Control Extension.\r
+ len = get8(s);\r
+ if (len == 4) {\r
+ g->eflags = get8(s);\r
+ get16le(s); // delay\r
+ g->transparent = get8(s);\r
+ } else {\r
+ skip(s, len);\r
+ break;\r
+ }\r
+ }\r
+ while ((len = get8(s)) != 0)\r
+ skip(s, len);\r
+ break;\r
+ }\r
+\r
+ case 0x3B: // gif stream termination code\r
+ return (uint8 *) 1;\r
+\r
+ default:\r
+ return epuc("unknown code", "Corrupt GIF");\r
+ }\r
+ }\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+stbi_uc *stbi_gif_load (char const *filename, int *x, int *y, int *comp, int req_comp)\r
+{\r
+ uint8 *data;\r
+ FILE *f = fopen(filename, "rb");\r
+ if (!f) return NULL;\r
+ data = stbi_gif_load_from_file(f, x,y,comp,req_comp);\r
+ fclose(f);\r
+ return data;\r
+}\r
+\r
+stbi_uc *stbi_gif_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp)\r
+{\r
+ uint8 *u = 0;\r
+ stbi s;\r
+ stbi_gif g={0};\r
+ start_file(&s, f);\r
+\r
+ u = stbi_gif_load_next(&s, &g, comp, req_comp);\r
+ if (u == (void *) 1) u = 0; // end of animated gif marker\r
+ if (u) {\r
+ *x = g.w;\r
+ *y = g.h;\r
+ }\r
+\r
+ return u;\r
+}\r
+#endif\r
+\r
+stbi_uc *stbi_gif_load_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)\r
+{\r
+ uint8 *u = 0;\r
+ stbi s;\r
+ stbi_gif g={0};\r
+ start_mem(&s, buffer, len);\r
+ u = stbi_gif_load_next(&s, &g, comp, req_comp);\r
+ if (u == (void *) 1) u = 0; // end of animated gif marker\r
+ if (u) {\r
+ *x = g.w;\r
+ *y = g.h;\r
+ }\r
+ return u;\r
+}\r
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_gif_info (char const *filename, int *x, int *y, int *comp)\r
+{\r
+ int res;\r
+ FILE *f = fopen(filename, "rb");\r
+ if (!f) return 0;\r
+ res = stbi_gif_info_from_file(f, x, y, comp);\r
+ fclose(f);\r
+ return res;\r
+}\r
+\r
+int stbi_gif_info_from_file(FILE *f, int *x, int *y, int *comp)\r
+{\r
+ stbi s;\r
+ int res;\r
+ long n = ftell(f);\r
+ start_file(&s, f);\r
+ res = stbi_gif_info_raw(&s, x, y, comp);\r
+ fseek(f, n, SEEK_SET);\r
+ return res;\r
+}\r
+#endif // !STBI_NO_STDIO\r
+\r
+int stbi_gif_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\r
+{\r
+ stbi s;\r
+ start_mem(&s, buffer, len);\r
+ return stbi_gif_info_raw(&s, x, y, comp);\r
+}\r
+\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
+ const 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 c = '\0';\r
+\r
+ c = (char) 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 = (char) 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
+ for(;;) {\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
+ uint8 rgbe[4];\r
+ rgbe[0] = (uint8) c1;\r
+ rgbe[1] = (uint8) c2;\r
+ rgbe[2] = (uint8) len;\r
+ rgbe[3] = (uint8) get8u(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 makes no sense\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 = get8u(s);\r
+ if (count > 128) {\r
+ // Run\r
+ value = get8u(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] = get8u(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
+\r
+#ifndef STBI_NO_STDIO\r
+int stbi_info(char const *filename, int *x, int *y, int *comp)\r
+{\r
+ FILE *f = fopen(filename, "rb");\r
+ int result;\r
+ if (!f) return e("can't fopen", "Unable to open file");\r
+ result = stbi_info_from_file(f, x, y, comp);\r
+ fclose(f);\r
+ return result;\r
+}\r
+\r
+int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)\r
+{\r
+ if (stbi_jpeg_info_from_file(f, x, y, comp))\r
+ return 1;\r
+ if (stbi_png_info_from_file(f, x, y, comp))\r
+ return 1;\r
+ if (stbi_gif_info_from_file(f, x, y, comp))\r
+ return 1;\r
+ // @TODO: stbi_bmp_info_from_file\r
+ // @TODO: stbi_psd_info_from_file\r
+ #ifndef STBI_NO_HDR\r
+ // @TODO: stbi_hdr_info_from_file\r
+ #endif\r
+ // test tga last because it's a crappy test!\r
+ if (stbi_tga_info_from_file(f, x, y, comp))\r
+ return 1;\r
+ return e("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+#endif // !STBI_NO_STDIO\r
+\r
+int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)\r
+{\r
+ if (stbi_jpeg_info_from_memory(buffer, len, x, y, comp))\r
+ return 1;\r
+ if (stbi_png_info_from_memory(buffer, len, x, y, comp))\r
+ return 1;\r
+ if (stbi_gif_info_from_memory(buffer, len, x, y, comp))\r
+ return 1;\r
+ // @TODO: stbi_bmp_info_from_memory\r
+ // @TODO: stbi_psd_info_from_memory\r
+ #ifndef STBI_NO_HDR\r
+ // @TODO: stbi_hdr_info_from_memory\r
+ #endif\r
+ // test tga last because it's a crappy test!\r
+ if (stbi_tga_info_from_memory(buffer, len, x, y, comp))\r
+ return 1;\r
+ return e("unknown image type", "Image not of any known type, or corrupt");\r
+}\r
+\r
+#endif // STBI_HEADER_FILE_ONLY\r
+\r
+/*\r
+ revision history:\r
+ 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville \r
+ 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)\r
+ 1.27 (2010-08-01)\r
+ cast-to-uint8 to fix warnings\r
+ 1.26 (2010-07-24)\r
+ fix bug in file buffering for PNG reported by SpartanJ\r
+ 1.25 (2010-07-17)\r
+ refix trans_data warning (Won Chun)\r
+ 1.24 (2010-07-12)\r
+ perf improvements reading from files on platforms with lock-heavy fgetc()\r
+ minor perf improvements for jpeg\r
+ deprecated type-specific functions so we'll get feedback if they're needed\r
+ attempt to fix trans_data warning (Won Chun)\r
+ 1.23 fixed bug in iPhone support\r
+ 1.22 (2010-07-10)\r
+ removed image *writing* support\r
+ removed image *writing* support\r
+ stbi_info support from Jetro Lauha\r
+ GIF support from Jean-Marc Lienher\r
+ iPhone PNG-extensions from James Brown\r
+ warning-fixes from Nicolas Schulz and Janez Zemva (i.e. Janez (U+017D)emva)\r
+ 1.21 fix use of 'uint8' in header (reported by jon blow)\r
+ 1.20 added support for Softimage PIC, by Tom Seddon\r
+ 1.19 bug in interlaced PNG corruption check (found by ryg)\r
+ 1.18 2008-08-02\r
+ fix a threading bug (local mutable static)\r
+ 1.17 support interlaced PNG\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\r
+ 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
--- /dev/null
+// stb_truetype.h - v0.3 - public domain - 2009 Sean Barrett / RAD Game Tools\r
+//\r
+// This library processes TrueType files:\r
+// parse files\r
+// extract glyph metrics\r
+// extract glyph shapes\r
+// render glyphs to one-channel bitmaps with antialiasing (box filter)\r
+//\r
+// Todo:\r
+// non-MS cmaps\r
+// crashproof on bad data\r
+// hinting\r
+// subpixel positioning when rendering bitmap\r
+// cleartype-style AA\r
+//\r
+// ADDITIONAL CONTRIBUTORS\r
+//\r
+// Mikko Mononen: compound shape support, more cmap formats\r
+//\r
+// VERSIONS\r
+//\r
+// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM)\r
+// userdata, malloc-from-userdata, non-zero fill (STB)\r
+// 0.2 (2009-03-11) Fix unsigned/signed char warnings\r
+// 0.1 (2009-03-09) First public release\r
+//\r
+// USAGE\r
+//\r
+// Include this file in whatever places neeed to refer to it. In ONE C/C++\r
+// file, write:\r
+// #define STB_TRUETYPE_IMPLEMENTATION\r
+// before the #include of this file. This expands out the actual\r
+// implementation into that C/C++ file.\r
+//\r
+// Look at the header-file sections below for the API, but here's a quick skim:\r
+//\r
+// Simple 3D API (don't ship this, but it's fine for tools and quick start,\r
+// and you can cut and paste from it to move to more advanced)\r
+// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture\r
+// stbtt_GetBakedQuad() -- compute quad to draw for a given char\r
+//\r
+// "Load" a font file from a memory buffer (you have to keep the buffer loaded)\r
+// stbtt_InitFont()\r
+// stbtt_GetFontOffsetForIndex() -- use for TTC font collections\r
+//\r
+// Render a unicode codepoint to a bitmap\r
+// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap\r
+// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide\r
+// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be\r
+//\r
+// Character advance/positioning\r
+// stbtt_GetCodepointHMetrics()\r
+// stbtt_GetFontVMetrics()\r
+//\r
+// NOTES\r
+//\r
+// The system uses the raw data found in the .ttf file without changing it\r
+// and without building auxiliary data structures. This is a bit inefficient\r
+// on little-endian systems (the data is big-endian), but assuming you're\r
+// caching the bitmaps or glyph shapes this shouldn't be a big deal.\r
+//\r
+// It appears to be very hard to programmatically determine what font a\r
+// given file is in a general way. I provide an API for this, but I don't\r
+// recommend it.\r
+//\r
+//\r
+// SOURCE STATISTICS (based on v0.3, 1800 LOC)\r
+//\r
+// Documentation & header file 350 LOC \___ 500 LOC documentation\r
+// Sample code 140 LOC /\r
+// Truetype parsing 580 LOC ---- 600 LOC TrueType\r
+// Software rasterization 240 LOC \ .\r
+// Curve tesselation 120 LOC \__ 500 LOC Bitmap creation\r
+// Bitmap management 70 LOC /\r
+// Baked bitmap interface 70 LOC /\r
+// Font name matching & access 150 LOC ---- 150 \r
+// C runtime library abstraction 60 LOC ---- 60\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//////////////////////////////////////////////////////////////////////////////\r
+////\r
+//// SAMPLE PROGRAMS\r
+////\r
+//\r
+// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless\r
+//\r
+#if 0\r
+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation\r
+#include "stb_truetype.h"\r
+\r
+char ttf_buffer[1<<20];\r
+unsigned char temp_bitmap[512*512];\r
+\r
+stbtt_chardata cdata[96]; // ASCII 32..126 is 95 glyphs\r
+GLstbtt_uint ftex;\r
+\r
+void my_stbtt_initfont(void)\r
+{\r
+ fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));\r
+ stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!\r
+ // can free ttf_buffer at this point\r
+ glGenTextures(1, &ftex);\r
+ glBindTexture(GL_TEXTURE_2D, ftex);\r
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);\r
+ // can free temp_bitmap at this point\r
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r
+}\r
+\r
+void my_stbtt_print(float x, float y, char *text)\r
+{\r
+ // assume orthographic projection with units = screen pixels, origin at top left\r
+ glBindTexture(GL_TEXTURE_2D, ftex);\r
+ glBegin(GL_QUADS);\r
+ while (*text) {\r
+ if (*text >= 32 && *text < 128) {\r
+ stbtt_aligned_quad q;\r
+ stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl,0=old d3d\r
+ glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);\r
+ glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);\r
+ glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);\r
+ glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);\r
+ }\r
+ ++text;\r
+ }\r
+ glEnd();\r
+}\r
+#endif\r
+//\r
+//\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Complete program (this compiles): get a single bitmap, print as ASCII art\r
+//\r
+#if 0\r
+#include <stdio.h>\r
+#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation\r
+#include "stb_truetype.h"\r
+\r
+char ttf_buffer[1<<25];\r
+\r
+int main(int argc, char **argv)\r
+{\r
+ stbtt_fontinfo font;\r
+ unsigned char *bitmap;\r
+ int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);\r
+\r
+ fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));\r
+\r
+ stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));\r
+ bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);\r
+\r
+ for (j=0; j < h; ++j) {\r
+ for (i=0; i < w; ++i)\r
+ putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);\r
+ putchar('\n');\r
+ }\r
+ return 0;\r
+}\r
+#endif \r
+//\r
+// Output:\r
+//\r
+// .ii.\r
+// @@@@@@.\r
+// V@Mio@@o\r
+// :i. V@V\r
+// :oM@@M\r
+// :@@@MM@M\r
+// @@o o@M\r
+// :@@. M@M\r
+// @@@o@@@@\r
+// :M@@V:@@.\r
+// \r
+//////////////////////////////////////////////////////////////////////////////\r
+// \r
+// Complete program: print "Hello World!" banner, with bugs\r
+//\r
+#if 0\r
+int main(int arg, char **argv)\r
+{\r
+ unsigned char screen[20][79];\r
+ int i,j, pos=0;\r
+ float scale;\r
+ char *text = "Heljo World!";\r
+\r
+ fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));\r
+ stbtt_InitFont(&font, buffer, 0);\r
+\r
+ scale = stbtt_ScaleForPixelHeight(&font, 16);\r
+ memset(screen, 0, sizeof(screen));\r
+\r
+ while (*text) {\r
+ int advance,lsb,x0,y0,x1,y1, newpos, baseline=13;\r
+ stbtt_GetCodepointHMetrics(&font, *text, &advance, &lsb);\r
+ stbtt_GetCodepointBitmapBox(&font, *text, scale,scale, &x0,&y0,&x1,&y1);\r
+ newpos = pos + (int) (lsb * scale) + x0;\r
+ stbtt_MakeCodepointBitmap(&font, &screen[baseline + y0][newpos], x1-x0,y1-y0, 79, scale,scale, *text);\r
+ // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong\r
+ // because this API is really for baking character bitmaps into textures\r
+ pos += (int) (advance * scale);\r
+ ++text;\r
+ }\r
+\r
+ for (j=0; j < 20; ++j) {\r
+ for (i=0; i < 79; ++i)\r
+ putchar(" .:ioVM@"[screen[j][i]>>5]);\r
+ putchar('\n');\r
+ }\r
+\r
+ return 0;\r
+}\r
+#endif\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//////////////////////////////////////////////////////////////////////////////\r
+////\r
+//// INTEGRATION WITH RUNTIME LIBRARIES\r
+////\r
+\r
+#ifdef STB_TRUETYPE_IMPLEMENTATION\r
+ // #define your own (u)stbtt_int8/16/32 before including to override this\r
+ #ifndef stbtt_uint8\r
+ typedef unsigned char stbtt_uint8;\r
+ typedef signed char stbtt_int8;\r
+ typedef unsigned short stbtt_uint16;\r
+ typedef signed short stbtt_int16;\r
+ typedef unsigned int stbtt_uint32;\r
+ typedef signed int stbtt_int32;\r
+ #endif\r
+\r
+ typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];\r
+ typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];\r
+\r
+ // #define your own STBTT_sort() to override this to avoid qsort\r
+ #ifndef STBTT_sort\r
+ #include <stdlib.h>\r
+ #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func)\r
+ #endif\r
+\r
+ // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h\r
+ #ifndef STBTT_ifloor\r
+ #include <math.h>\r
+ #define STBTT_ifloor(x) ((int) floor(x))\r
+ #define STBTT_iceil(x) ((int) ceil(x))\r
+ #endif\r
+\r
+ // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h\r
+ #ifndef STBTT_malloc\r
+ #include <malloc.h>\r
+ #define STBTT_malloc(x,u) malloc(x)\r
+ #define STBTT_free(x,u) free(x)\r
+ #endif\r
+\r
+ #ifndef STBTT_assert\r
+ #include <assert.h>\r
+ #define STBTT_assert(x) assert(x)\r
+ #endif\r
+\r
+ #ifndef STBTT_strlen\r
+ #include <string.h>\r
+ #define STBTT_strlen(x) strlen(x)\r
+ #endif\r
+\r
+ #ifndef STBTT_memcpy\r
+ #include <memory.h>\r
+ #define STBTT_memcpy memcpy\r
+ #define STBTT_memset memset\r
+ #endif\r
+#endif\r
+\r
+///////////////////////////////////////////////////////////////////////////////\r
+///////////////////////////////////////////////////////////////////////////////\r
+////\r
+//// INTERFACE\r
+////\r
+////\r
+\r
+#ifndef __STB_INCLUDE_STB_TRUETYPE_H__\r
+#define __STB_INCLUDE_STB_TRUETYPE_H__\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// TEXTURE BAKING API\r
+//\r
+// If you use this API, you only have to call two functions ever.\r
+//\r
+\r
+typedef struct\r
+{\r
+ unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap\r
+ float xoff,yoff,xadvance; \r
+} stbtt_bakedchar;\r
+\r
+extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)\r
+ float pixel_height, // height of font in pixels\r
+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in\r
+ int first_char, int num_chars, // characters to bake\r
+ stbtt_bakedchar *chardata); // you allocate this, it's num_chars long\r
+// if return is positive, the first unused row of the bitmap\r
+// if return is negative, returns the negative of the number of characters that fit\r
+// if return is 0, no characters fit and no rows were used\r
+// This uses a very crappy packing.\r
+\r
+typedef struct\r
+{\r
+ float x0,y0,s0,t0; // top-left\r
+ float x1,y1,s1,t1; // bottom-right\r
+} stbtt_aligned_quad;\r
+\r
+extern void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, // same data as above\r
+ int char_index, // character to display\r
+ float *xpos, float *ypos, // pointers to current position in screen pixel space\r
+ stbtt_aligned_quad *q, // output: quad to draw\r
+ int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier\r
+// Call GetBakedQuad with char_index = 'character - first_char', and it\r
+// creates the quad you need to draw and advances the current position.\r
+// It's inefficient; you might want to c&p it and optimize it.\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// FONT LOADING\r
+//\r
+//\r
+\r
+extern int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);\r
+// Each .ttf file may have more than one font. Each has a sequential index\r
+// number starting from 0. Call this function to get the font offset for a\r
+// given index; it returns -1 if the index is out of range. A regular .ttf\r
+// file will only define one font and it always be at offset 0, so it will\r
+// return '0' for index 0, and -1 for all other indices. You can just skip\r
+// this step if you know it's that kind of font.\r
+\r
+\r
+// The following structure is defined publically so you can declare one on\r
+// the stack or as a global or etc.\r
+typedef struct\r
+{\r
+ void *userdata;\r
+ unsigned char *data; // pointer to .ttf file\r
+ int fontstart; // offset of start of font\r
+\r
+ int numGlyphs; // number of glyphs, needed for range checking\r
+\r
+ int loca,head,glyf,hhea,hmtx; // table locations as offset from start of .ttf\r
+ int index_map; // a cmap mapping for our chosen character encoding\r
+ int indexToLocFormat; // format needed to map from glyph index to glyph\r
+} stbtt_fontinfo;\r
+\r
+extern int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);\r
+// Given an offset into the file that defines a font, this function builds\r
+// the necessary cached info for the rest of the system. You must allocate\r
+// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't\r
+// need to do anything special to free it, because the contents are a pure\r
+// cache with no additional data structures. Returns 0 on failure.\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// CHARACTER TO GLYPH-INDEX CONVERSIOn\r
+\r
+int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);\r
+// If you're going to perform multiple operations on the same character\r
+// and you want a speed-up, call this function with the character you're\r
+// going to process, then use glyph-based functions instead of the\r
+// codepoint-based functions.\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// CHARACTER PROPERTIES\r
+//\r
+\r
+extern float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);\r
+// computes a scale factor to produce a font whose "height" is 'pixels' tall.\r
+// Height is measured as the distance from the highest ascender to the lowest\r
+// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics\r
+// and computing:\r
+// scale = pixels / (ascent - descent)\r
+// so if you prefer to measure height by the ascent only, use a similar calculation.\r
+\r
+extern void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);\r
+// ascent is the coordinate above the baseline the font extends; descent\r
+// is the coordinate below the baseline the font extends (i.e. it is typically negative)\r
+// lineGap is the spacing between one row's descent and the next row's ascent...\r
+// so you should advance the vertical position by "*ascent - *descent + *lineGap"\r
+// these are expressed in unscaled coordinates\r
+\r
+extern void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);\r
+// leftSideBearing is the offset from the current horizontal position to the left edge of the character\r
+// advanceWidth is the offset from the current horizontal position to the next horizontal position\r
+// these are expressed in unscaled coordinates\r
+\r
+extern int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);\r
+// an additional amount to add to the 'advance' value between ch1 and ch2\r
+// @TODO; for now always returns 0!\r
+\r
+extern int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);\r
+// Gets the bounding box of the visible part of the glyph, in unscaled coordinates\r
+\r
+extern void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);\r
+extern int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);\r
+extern int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);\r
+// as above, but takes one or more glyph indices for greater efficiency\r
+\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// GLYPH SHAPES (you probably don't need these, but they have to go before\r
+// the bitmaps for C declaration-order reasons)\r
+//\r
+\r
+#ifndef STBTT_vmove // you can predefine these to use different values (but why?)\r
+ enum {\r
+ STBTT_vmove=1,\r
+ STBTT_vline,\r
+ STBTT_vcurve\r
+ };\r
+#endif\r
+\r
+#ifndef stbtt_vertex // you can predefine this to use different values\r
+ // (we share this with other code at RAD)\r
+ #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file\r
+ typedef struct\r
+ {\r
+ stbtt_vertex_type x,y,cx,cy;\r
+ unsigned char type,padding;\r
+ } stbtt_vertex;\r
+#endif\r
+\r
+extern int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);\r
+extern int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);\r
+// returns # of vertices and fills *vertices with the pointer to them\r
+// these are expressed in "unscaled" coordinates\r
+\r
+extern void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);\r
+// frees the data allocated above\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// BITMAP RENDERING\r
+//\r
+\r
+extern void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);\r
+// frees the bitmap allocated below\r
+\r
+extern unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);\r
+// allocates a large-enough single-channel 8bpp bitmap and renders the\r
+// specified character/glyph at the specified scale into it, with\r
+// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).\r
+// *width & *height are filled out with the width & height of the bitmap,\r
+// which is stored left-to-right, top-to-bottom.\r
+//\r
+// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap\r
+\r
+extern void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);\r
+// the same as above, but you pass in storage for the bitmap in the form\r
+// of 'output', with row spacing of 'out_stride' bytes. the bitmap is\r
+// clipped to out_w/out_h bytes. call the next function to get the\r
+// height and width and positioning info\r
+\r
+extern void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\r
+// get the bbox of the bitmap centered around the glyph origin; so the\r
+// bitmap width is ix1-ix0, height is iy1-iy0, and location to place\r
+// the bitmap top left is (leftSideBearing*scale,iy0).\r
+// (Note that the bitmap uses y-increases-down, but the shape uses\r
+// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)\r
+\r
+extern unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);\r
+extern void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\r
+extern void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);\r
+\r
+//extern void stbtt_get_true_bbox(stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\r
+\r
+// @TODO: don't expose this structure\r
+typedef struct\r
+{\r
+ int w,h,stride;\r
+ unsigned char *pixels;\r
+} stbtt__bitmap;\r
+\r
+extern void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, int x_off, int y_off, int invert, void *userdata);\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// Finding the right font...\r
+//\r
+// You should really just solve this offline, keep your own tables\r
+// of what font is what, and don't try to get it out of the .ttf file.\r
+// That's because getting it out of the .ttf file is really hard, because\r
+// the names in the file can appear in many possible encodings, in many\r
+// possible languages, and e.g. if you need a case-insensitive comparison,\r
+// the details of that depend on the encoding & language in a complex way\r
+// (actually underspecified in truetype, but also gigantic).\r
+//\r
+// But you can use the provided functions in two possible ways:\r
+// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on\r
+// unicode-encoded names to try to find the font you want;\r
+// you can run this before calling stbtt_InitFont()\r
+//\r
+// stbtt_GetFontNameString() lets you get any of the various strings\r
+// from the file yourself and do your own comparisons on them.\r
+// You have to have called stbtt_InitFont() first.\r
+\r
+\r
+extern int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);\r
+// returns the offset (not index) of the font that matches, or -1 if none\r
+// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold".\r
+// if you use any other flag, use a font name like "Arial"; this checks\r
+// the 'macStyle' header field; i don't know if fonts set this consistently\r
+#define STBTT_MACSTYLE_DONTCARE 0\r
+#define STBTT_MACSTYLE_BOLD 1\r
+#define STBTT_MACSTYLE_ITALIC 2\r
+#define STBTT_MACSTYLE_UNDERSCORE 4\r
+#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0\r
+\r
+extern int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);\r
+// returns 1/0 whether the first string interpreted as utf8 is identical to\r
+// the second string interpreted as big-endian utf16... useful for strings from next func\r
+\r
+extern char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);\r
+// returns the string (which may be big-endian double byte, e.g. for unicode)\r
+// and puts the length in bytes in *length.\r
+//\r
+// some of the values for the IDs are below; for more see the truetype spec:\r
+// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html\r
+// http://www.microsoft.com/typography/otspec/name.htm\r
+\r
+enum { // platformID\r
+ STBTT_PLATFORM_ID_UNICODE =0,\r
+ STBTT_PLATFORM_ID_MAC =1,\r
+ STBTT_PLATFORM_ID_ISO =2,\r
+ STBTT_PLATFORM_ID_MICROSOFT =3\r
+};\r
+\r
+enum { // encodingID for STBTT_PLATFORM_ID_UNICODE\r
+ STBTT_UNICODE_EID_UNICODE_1_0 =0,\r
+ STBTT_UNICODE_EID_UNICODE_1_1 =1,\r
+ STBTT_UNICODE_EID_ISO_10646 =2,\r
+ STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,\r
+ STBTT_UNICODE_EID_UNICODE_2_0_FULL=4,\r
+};\r
+\r
+enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT\r
+ STBTT_MS_EID_SYMBOL =0,\r
+ STBTT_MS_EID_UNICODE_BMP =1,\r
+ STBTT_MS_EID_SHIFTJIS =2,\r
+ STBTT_MS_EID_UNICODE_FULL =10,\r
+};\r
+\r
+enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes\r
+ STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4,\r
+ STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5,\r
+ STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6,\r
+ STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7,\r
+};\r
+\r
+enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...\r
+ // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs\r
+ STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410,\r
+ STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411,\r
+ STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412,\r
+ STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419,\r
+ STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409,\r
+ STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D,\r
+};\r
+\r
+enum { // languageID for STBTT_PLATFORM_ID_MAC\r
+ STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11,\r
+ STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23,\r
+ STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32,\r
+ STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 ,\r
+ STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 ,\r
+ STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,\r
+ STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19,\r
+};\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+\r
+#endif // __STB_INCLUDE_STB_TRUETYPE_H__\r
+\r
+///////////////////////////////////////////////////////////////////////////////\r
+///////////////////////////////////////////////////////////////////////////////\r
+////\r
+//// IMPLEMENTATION\r
+////\r
+////\r
+\r
+#ifdef STB_TRUETYPE_IMPLEMENTATION\r
+\r
+//////////////////////////////////////////////////////////////////////////\r
+//\r
+// accessors to parse data from file\r
+//\r
+\r
+// on platforms that don't allow misaligned reads, if we want to allow\r
+// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE\r
+\r
+#define ttBYTE(p) (* (stbtt_uint8 *) (p))\r
+#define ttCHAR(p) (* (stbtt_int8 *) (p))\r
+#define ttFixed(p) ttLONG(p)\r
+\r
+#if defined(STB_TRUETYPE_BIGENDIAN) && !defined(ALLOW_UNALIGNED_TRUETYPE)\r
+\r
+ #define ttUSHORT(p) (* (stbtt_uint16 *) (p))\r
+ #define ttSHORT(p) (* (stbtt_int16 *) (p))\r
+ #define ttULONG(p) (* (stbtt_uint32 *) (p))\r
+ #define ttLONG(p) (* (stbtt_int32 *) (p))\r
+\r
+#else\r
+\r
+ stbtt_uint16 ttUSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }\r
+ stbtt_int16 ttSHORT(const stbtt_uint8 *p) { return p[0]*256 + p[1]; }\r
+ stbtt_uint32 ttULONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\r
+ stbtt_int32 ttLONG(const stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\r
+\r
+#endif\r
+\r
+#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))\r
+#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3])\r
+\r
+static int stbtt__isfont(const stbtt_uint8 *font)\r
+{\r
+ // check the version number\r
+ if (stbtt_tag(font, "1")) return 1; // TrueType 1\r
+ if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this!\r
+ if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF\r
+ if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0\r
+ return 0;\r
+}\r
+\r
+// @OPTIMIZE: binary search\r
+static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, char *tag)\r
+{\r
+ stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);\r
+ stbtt_uint32 tabledir = fontstart + 12;\r
+ stbtt_int32 i;\r
+ for (i=0; i < num_tables; ++i) {\r
+ stbtt_uint32 loc = tabledir + 16*i;\r
+ if (stbtt_tag(data+loc+0, tag))\r
+ return ttULONG(data+loc+8);\r
+ }\r
+ return 0;\r
+}\r
+\r
+int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, int index)\r
+{\r
+ // if it's just a font, there's only one valid index\r
+ if (stbtt__isfont(font_collection))\r
+ return index == 0 ? 0 : -1;\r
+\r
+ // check if it's a TTC\r
+ if (stbtt_tag(font_collection, "ttcf")) {\r
+ // version 1?\r
+ if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {\r
+ stbtt_int32 n = ttLONG(font_collection+8);\r
+ if (index >= n)\r
+ return -1;\r
+ return ttULONG(font_collection+12+index*14);\r
+ }\r
+ }\r
+ return -1;\r
+}\r
+\r
+int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data2, int fontstart)\r
+{\r
+ stbtt_uint8 *data = (stbtt_uint8 *) data2;\r
+ stbtt_uint32 cmap, t;\r
+ stbtt_int32 i,numTables;\r
+\r
+ info->data = data;\r
+ info->fontstart = fontstart;\r
+\r
+ cmap = stbtt__find_table(data, fontstart, "cmap");\r
+ info->loca = stbtt__find_table(data, fontstart, "loca");\r
+ info->head = stbtt__find_table(data, fontstart, "head");\r
+ info->glyf = stbtt__find_table(data, fontstart, "glyf");\r
+ info->hhea = stbtt__find_table(data, fontstart, "hhea");\r
+ info->hmtx = stbtt__find_table(data, fontstart, "hmtx");\r
+ if (!cmap || !info->loca || !info->head || !info->glyf || !info->hhea || !info->hmtx)\r
+ return 0;\r
+\r
+ t = stbtt__find_table(data, fontstart, "maxp");\r
+ if (t)\r
+ info->numGlyphs = ttUSHORT(data+t+4);\r
+ else\r
+ info->numGlyphs = 0xffff;\r
+\r
+ // find a cmap encoding table we understand *now* to avoid searching\r
+ // later. (todo: could make this installable)\r
+ // the same regardless of glyph.\r
+ numTables = ttUSHORT(data + cmap + 2);\r
+ info->index_map = 0;\r
+ for (i=0; i < numTables; ++i) {\r
+ stbtt_uint32 encoding_record = cmap + 4 + 8 * i;\r
+ // find an encoding we understand:\r
+ switch(ttUSHORT(data+encoding_record)) {\r
+ case STBTT_PLATFORM_ID_MICROSOFT:\r
+ switch (ttUSHORT(data+encoding_record+2)) {\r
+ case STBTT_MS_EID_UNICODE_BMP:\r
+ case STBTT_MS_EID_UNICODE_FULL:\r
+ // MS/Unicode\r
+ info->index_map = cmap + ttULONG(data+encoding_record+4);\r
+ break;\r
+ }\r
+ break;\r
+ }\r
+ }\r
+ if (info->index_map == 0)\r
+ return 0;\r
+\r
+ info->indexToLocFormat = ttUSHORT(data+info->head + 50);\r
+ return 1;\r
+}\r
+\r
+int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)\r
+{\r
+ stbtt_uint8 *data = info->data;\r
+ stbtt_uint32 index_map = info->index_map;\r
+\r
+ stbtt_uint16 format = ttUSHORT(data + index_map + 0);\r
+ if (format == 0) { // apple byte encoding\r
+ stbtt_int32 bytes = ttUSHORT(data + index_map + 2);\r
+ if (unicode_codepoint < bytes-6)\r
+ return ttBYTE(data + index_map + 6 + unicode_codepoint);\r
+ return 0;\r
+ } else if (format == 6) {\r
+ stbtt_uint32 first = ttUSHORT(data + index_map + 6);\r
+ stbtt_uint32 count = ttUSHORT(data + index_map + 8);\r
+ if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)\r
+ return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);\r
+ return 0;\r
+ } else if (format == 2) {\r
+ STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean\r
+ return 0;\r
+ } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges\r
+ stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;\r
+ stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;\r
+ stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);\r
+ stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;\r
+ stbtt_uint16 item, offset, start, end;\r
+\r
+ // do a binary search of the segments\r
+ stbtt_uint32 endCount = index_map + 14;\r
+ stbtt_uint32 search = endCount;\r
+\r
+ if (unicode_codepoint > 0xffff)\r
+ return 0;\r
+\r
+ // they lie from endCount .. endCount + segCount\r
+ // but searchRange is the nearest power of two, so...\r
+ if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))\r
+ search += rangeShift*2;\r
+\r
+ // now decrement to bias correctly to find smallest\r
+ search -= 2;\r
+ while (entrySelector) {\r
+ stbtt_uint16 start, end;\r
+ searchRange >>= 1;\r
+ start = ttUSHORT(data + search + 2 + segcount*2 + 2);\r
+ end = ttUSHORT(data + search + 2);\r
+ start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2);\r
+ end = ttUSHORT(data + search + searchRange*2);\r
+ if (unicode_codepoint > end)\r
+ search += searchRange*2;\r
+ --entrySelector;\r
+ }\r
+ search += 2;\r
+\r
+ item = (stbtt_uint16) ((search - endCount) >> 1);\r
+\r
+ STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));\r
+ start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);\r
+ end = ttUSHORT(data + index_map + 14 + 2 + 2*item);\r
+ if (unicode_codepoint < start)\r
+ return 0;\r
+\r
+ offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);\r
+ if (offset == 0)\r
+ return unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item);\r
+\r
+ return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);\r
+ } else if (format == 12) {\r
+ stbtt_uint16 ngroups = ttUSHORT(data+index_map+6);\r
+ stbtt_int32 low,high;\r
+ stbtt_uint16 g = 0;\r
+ low = 0; high = (stbtt_int32)ngroups;\r
+ // Binary search the right group.\r
+ while (low <= high) {\r
+ stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high\r
+ stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);\r
+ stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);\r
+ if ((stbtt_uint32) unicode_codepoint < start_char)\r
+ high = mid-1;\r
+ else if ((stbtt_uint32) unicode_codepoint > end_char)\r
+ low = mid+1;\r
+ else {\r
+ stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);\r
+ return start_glyph + unicode_codepoint-start_char;\r
+ }\r
+ }\r
+ return 0; // not found\r
+ }\r
+ // @TODO\r
+ STBTT_assert(0);\r
+ return 0;\r
+}\r
+\r
+int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)\r
+{\r
+ return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);\r
+}\r
+\r
+static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int16 x, stbtt_int16 y, stbtt_int16 cx, stbtt_int16 cy)\r
+{\r
+ v->type = type;\r
+ v->x = x;\r
+ v->y = y;\r
+ v->cx = cx;\r
+ v->cy = cy;\r
+}\r
+\r
+static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)\r
+{\r
+ int g1,g2;\r
+\r
+ if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range\r
+ if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format\r
+\r
+ if (info->indexToLocFormat == 0) {\r
+ g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;\r
+ g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;\r
+ } else {\r
+ g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);\r
+ g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);\r
+ }\r
+\r
+ return g1==g2 ? -1 : g1; // if length is 0, return -1\r
+}\r
+\r
+int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)\r
+{\r
+ int g = stbtt__GetGlyfOffset(info, glyph_index);\r
+ if (g < 0) return 0;\r
+\r
+ if (x0) *x0 = ttSHORT(info->data + g + 2);\r
+ if (y0) *y0 = ttSHORT(info->data + g + 4);\r
+ if (x1) *x1 = ttSHORT(info->data + g + 6);\r
+ if (y1) *y1 = ttSHORT(info->data + g + 8);\r
+ return 1;\r
+}\r
+\r
+int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)\r
+{\r
+ return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);\r
+}\r
+\r
+int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\r
+{\r
+ stbtt_int16 numberOfContours;\r
+ stbtt_uint8 *endPtsOfContours;\r
+ stbtt_uint8 *data = info->data;\r
+ stbtt_vertex *vertices=0;\r
+ int num_vertices=0;\r
+ int g = stbtt__GetGlyfOffset(info, glyph_index);\r
+\r
+ *pvertices = NULL;\r
+\r
+ if (g < 0) return 0;\r
+\r
+ numberOfContours = ttSHORT(data + g);\r
+\r
+ if (numberOfContours > 0) {\r
+ stbtt_uint8 flags=0,flagcount;\r
+ stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off;\r
+ stbtt_int16 x,y,cx,cy,sx,sy;\r
+ stbtt_uint8 *points;\r
+ endPtsOfContours = (data + g + 10);\r
+ ins = ttUSHORT(data + g + 10 + numberOfContours * 2);\r
+ points = data + g + 10 + numberOfContours * 2 + 2 + ins;\r
+\r
+ n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);\r
+\r
+ m = n + numberOfContours; // a loose bound on how many vertices we might need\r
+ vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);\r
+ if (vertices == 0)\r
+ return 0;\r
+\r
+ next_move = 0;\r
+ flagcount=0;\r
+\r
+ // in first pass, we load uninterpreted data into the allocated array\r
+ // above, shifted to the end of the array so we won't overwrite it when\r
+ // we create our final data starting from the front\r
+\r
+ off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated\r
+\r
+ // first load flags\r
+\r
+ for (i=0; i < n; ++i) {\r
+ if (flagcount == 0) {\r
+ flags = *points++;\r
+ if (flags & 8)\r
+ flagcount = *points++;\r
+ } else\r
+ --flagcount;\r
+ vertices[off+i].type = flags;\r
+ }\r
+\r
+ // now load x coordinates\r
+ x=0;\r
+ for (i=0; i < n; ++i) {\r
+ flags = vertices[off+i].type;\r
+ if (flags & 2) {\r
+ stbtt_int16 dx = *points++;\r
+ x += (flags & 16) ? dx : -dx; // ???\r
+ } else {\r
+ if (!(flags & 16)) {\r
+ x = x + (stbtt_int16) (points[0]*256 + points[1]);\r
+ points += 2;\r
+ }\r
+ }\r
+ vertices[off+i].x = x;\r
+ }\r
+\r
+ // now load y coordinates\r
+ y=0;\r
+ for (i=0; i < n; ++i) {\r
+ flags = vertices[off+i].type;\r
+ if (flags & 4) {\r
+ stbtt_int16 dy = *points++;\r
+ y += (flags & 32) ? dy : -dy; // ???\r
+ } else {\r
+ if (!(flags & 32)) {\r
+ y = y + (stbtt_int16) (points[0]*256 + points[1]);\r
+ points += 2;\r
+ }\r
+ }\r
+ vertices[off+i].y = y;\r
+ }\r
+\r
+ // now convert them to our format\r
+ num_vertices=0;\r
+ sx = sy = cx = cy = 0;\r
+ for (i=0; i < n; ++i) {\r
+ flags = vertices[off+i].type;\r
+ x = (stbtt_int16) vertices[off+i].x;\r
+ y = (stbtt_int16) vertices[off+i].y;\r
+ if (next_move == i) {\r
+ // when we get to the end, we have to close the shape explicitly\r
+ if (i != 0) {\r
+ if (was_off)\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);\r
+ else\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);\r
+ }\r
+\r
+ // now start the new one \r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,x,y,0,0);\r
+ next_move = 1 + ttUSHORT(endPtsOfContours+j*2);\r
+ ++j;\r
+ was_off = 0;\r
+ sx = x;\r
+ sy = y;\r
+ } else {\r
+ if (!(flags & 1)) { // if it's a curve\r
+ if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);\r
+ cx = x;\r
+ cy = y;\r
+ was_off = 1;\r
+ } else {\r
+ if (was_off)\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);\r
+ else\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);\r
+ was_off = 0;\r
+ }\r
+ }\r
+ }\r
+ if (i != 0) {\r
+ if (was_off)\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);\r
+ else\r
+ stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);\r
+ }\r
+ } else if (numberOfContours == -1) {\r
+ // Compound shapes.\r
+ int more = 1;\r
+ stbtt_uint8 *comp = data + g + 10;\r
+ num_vertices = 0;\r
+ vertices = 0;\r
+ while (more) {\r
+ stbtt_uint16 flags, gidx;\r
+ int comp_num_verts = 0, i;\r
+ stbtt_vertex *comp_verts = 0, *tmp = 0;\r
+ float mtx[6] = {1,0,0,1,0,0}, m, n;\r
+ \r
+ flags = ttSHORT(comp); comp+=2;\r
+ gidx = ttSHORT(comp); comp+=2;\r
+\r
+ if (flags & 2) { // XY values\r
+ if (flags & 1) { // shorts\r
+ mtx[4] = ttSHORT(comp); comp+=2;\r
+ mtx[5] = ttSHORT(comp); comp+=2;\r
+ } else {\r
+ mtx[4] = ttCHAR(comp); comp+=1;\r
+ mtx[5] = ttCHAR(comp); comp+=1;\r
+ }\r
+ }\r
+ else {\r
+ // @TODO handle matching point\r
+ STBTT_assert(0);\r
+ }\r
+ if (flags & (1<<3)) { // WE_HAVE_A_SCALE\r
+ mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ mtx[1] = mtx[2] = 0;\r
+ } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE\r
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ mtx[1] = mtx[2] = 0;\r
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO\r
+ mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r
+ }\r
+ \r
+ // Find transformation scales.\r
+ m = (float) sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);\r
+ n = (float) sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);\r
+\r
+ // Get indexed glyph.\r
+ comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);\r
+ if (comp_num_verts > 0) {\r
+ // Transform vertices.\r
+ for (i = 0; i < comp_num_verts; ++i) {\r
+ stbtt_vertex* v = &comp_verts[i];\r
+ stbtt_vertex_type x,y;\r
+ x=v->x; y=v->y;\r
+ v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\r
+ v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\r
+ x=v->cx; y=v->cy;\r
+ v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\r
+ v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\r
+ }\r
+ // Append vertices.\r
+ tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);\r
+ if (!tmp) {\r
+ if (vertices) STBTT_free(vertices, info->userdata);\r
+ if (comp_verts) STBTT_free(comp_verts, info->userdata);\r
+ return 0;\r
+ }\r
+ if (num_vertices > 0) memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex));\r
+ memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));\r
+ if (vertices) STBTT_free(vertices, info->userdata);\r
+ vertices = tmp;\r
+ STBTT_free(comp_verts, info->userdata);\r
+ num_vertices += comp_num_verts;\r
+ }\r
+ // More components ?\r
+ more = flags & (1<<5);\r
+ }\r
+ } else if (numberOfContours < 0) {\r
+ // @TODO other compound variations?\r
+ STBTT_assert(0);\r
+ } else {\r
+ // numberOfCounters == 0, do nothing\r
+ }\r
+\r
+ *pvertices = vertices;\r
+ return num_vertices;\r
+}\r
+\r
+void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)\r
+{\r
+ stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);\r
+ if (glyph_index < numOfLongHorMetrics) {\r
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index);\r
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);\r
+ } else {\r
+ if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));\r
+ if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));\r
+ }\r
+}\r
+\r
+int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)\r
+{\r
+ return 0;\r
+}\r
+\r
+int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)\r
+{\r
+ return 0;\r
+}\r
+\r
+void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)\r
+{\r
+ stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);\r
+}\r
+\r
+void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)\r
+{\r
+ if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4);\r
+ if (descent) *descent = ttSHORT(info->data+info->hhea + 6);\r
+ if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);\r
+}\r
+\r
+float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)\r
+{\r
+ int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);\r
+ return (float) height / fheight;\r
+}\r
+\r
+void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)\r
+{\r
+ STBTT_free(v, info->userdata);\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// antialiasing software rasterizer\r
+//\r
+\r
+void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\r
+{\r
+ int x0,y0,x1,y1;\r
+ if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1))\r
+ x0=y0=x1=y1=0; // e.g. space character\r
+ // now move to integral bboxes (treating pixels as little squares, what pixels get touched)?\r
+ if (ix0) *ix0 = STBTT_ifloor(x0 * scale_x);\r
+ if (iy0) *iy0 = -STBTT_iceil (y1 * scale_y);\r
+ if (ix1) *ix1 = STBTT_iceil (x1 * scale_x);\r
+ if (iy1) *iy1 = -STBTT_ifloor(y0 * scale_y);\r
+}\r
+\r
+void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\r
+{\r
+ stbtt_GetGlyphBitmapBox(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y, ix0,iy0,ix1,iy1);\r
+}\r
+\r
+typedef struct stbtt__edge {\r
+ float x0,y0, x1,y1;\r
+ int invert;\r
+} stbtt__edge;\r
+\r
+typedef struct stbtt__active_edge\r
+{\r
+ int x,dx;\r
+ float ey;\r
+ struct stbtt__active_edge *next;\r
+ int valid;\r
+} stbtt__active_edge;\r
+\r
+#define FIXSHIFT 10\r
+#define FIX (1 << FIXSHIFT)\r
+#define FIXMASK (FIX-1)\r
+\r
+static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata)\r
+{\r
+ stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!!\r
+ float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);\r
+ STBTT_assert(e->y0 <= start_point);\r
+ if (!z) return z;\r
+ // round dx down to avoid going too far\r
+ if (dxdy < 0)\r
+ z->dx = -STBTT_ifloor(FIX * -dxdy);\r
+ else\r
+ z->dx = STBTT_ifloor(FIX * dxdy);\r
+ z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0)));\r
+ z->x -= off_x * FIX;\r
+ z->ey = e->y1;\r
+ z->next = 0;\r
+ z->valid = e->invert ? 1 : -1;\r
+ return z;\r
+}\r
+\r
+// note: this routine clips fills that extend off the edges... ideally this\r
+// wouldn't happen, but it could happen if the truetype glyph bounding boxes\r
+// are wrong, or if the user supplies a too-small bitmap\r
+static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)\r
+{\r
+ // non-zero winding fill\r
+ int x0=0, w=0;\r
+\r
+ while (e) {\r
+ if (w == 0) {\r
+ // if we're currently at zero, we need to record the edge start point\r
+ x0 = e->x; w += e->valid;\r
+ } else {\r
+ int x1 = e->x; w += e->valid;\r
+ // if we went to zero, we need to draw\r
+ if (w == 0) {\r
+ int i = x0 >> FIXSHIFT;\r
+ int j = x1 >> FIXSHIFT;\r
+\r
+ if (i < len && j >= 0) {\r
+ if (i == j) {\r
+ // x0,x1 are the same pixel, so compute combined coverage\r
+ scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT);\r
+ } else {\r
+ if (i >= 0) // add antialiasing for x0\r
+ scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT);\r
+ else\r
+ i = -1; // clip\r
+\r
+ if (j < len) // add antialiasing for x1\r
+ scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT);\r
+ else\r
+ j = len; // clip\r
+\r
+ for (++i; i < j; ++i) // fill pixels between x0 and x1\r
+ scanline[i] = scanline[i] + (stbtt_uint8) max_weight;\r
+ }\r
+ }\r
+ }\r
+ }\r
+ \r
+ e = e->next;\r
+ }\r
+}\r
+\r
+static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)\r
+{\r
+ stbtt__active_edge *active = NULL;\r
+ int y,j=0;\r
+ int max_weight = (255 / vsubsample); // weight per vertical scanline\r
+ int s; // vertical subsample index\r
+ unsigned char scanline_data[512], *scanline;\r
+\r
+ if (result->w > 512)\r
+ scanline = (unsigned char *) STBTT_malloc(result->w, userdata);\r
+ else\r
+ scanline = scanline_data;\r
+\r
+ y = off_y * vsubsample;\r
+ e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;\r
+\r
+ while (j < result->h) {\r
+ STBTT_memset(scanline, 0, result->w);\r
+ for (s=0; s < vsubsample; ++s) {\r
+ // find center of pixel for this scanline\r
+ float scan_y = y + 0.5f;\r
+ stbtt__active_edge **step = &active;\r
+\r
+ // update all active edges;\r
+ // remove all active edges that terminate before the center of this scanline\r
+ while (*step) {\r
+ stbtt__active_edge * z = *step;\r
+ if (z->ey <= scan_y) {\r
+ *step = z->next; // delete from list\r
+ STBTT_assert(z->valid);\r
+ z->valid = 0;\r
+ STBTT_free(z, userdata);\r
+ } else {\r
+ z->x += z->dx; // advance to position for current scanline\r
+ step = &((*step)->next); // advance through list\r
+ }\r
+ }\r
+\r
+ // resort the list if needed\r
+ for(;;) {\r
+ int changed=0;\r
+ step = &active;\r
+ while (*step && (*step)->next) {\r
+ if ((*step)->x > (*step)->next->x) {\r
+ stbtt__active_edge *t = *step;\r
+ stbtt__active_edge *q = t->next;\r
+\r
+ t->next = q->next;\r
+ q->next = t;\r
+ *step = q;\r
+ changed = 1;\r
+ }\r
+ step = &(*step)->next;\r
+ }\r
+ if (!changed) break;\r
+ }\r
+\r
+ // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline\r
+ while (e->y0 <= scan_y) {\r
+ if (e->y1 > scan_y) {\r
+ stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata);\r
+ // find insertion point\r
+ if (active == NULL)\r
+ active = z;\r
+ else if (z->x < active->x) {\r
+ // insert at front\r
+ z->next = active;\r
+ active = z;\r
+ } else {\r
+ // find thing to insert AFTER\r
+ stbtt__active_edge *p = active;\r
+ while (p->next && p->next->x < z->x)\r
+ p = p->next;\r
+ // at this point, p->next->x is NOT < z->x\r
+ z->next = p->next;\r
+ p->next = z;\r
+ }\r
+ }\r
+ ++e;\r
+ }\r
+\r
+ // now process all active edges in XOR fashion\r
+ if (active)\r
+ stbtt__fill_active_edges(scanline, result->w, active, max_weight);\r
+\r
+ ++y;\r
+ }\r
+ STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);\r
+ ++j;\r
+ }\r
+\r
+ while (active) {\r
+ stbtt__active_edge *z = active;\r
+ active = active->next;\r
+ STBTT_free(z, userdata);\r
+ }\r
+\r
+ if (scanline != scanline_data)\r
+ STBTT_free(scanline, userdata);\r
+}\r
+\r
+static int stbtt__edge_compare(const void *p, const void *q)\r
+{\r
+ stbtt__edge *a = (stbtt__edge *) p;\r
+ stbtt__edge *b = (stbtt__edge *) q;\r
+\r
+ if (a->y0 < b->y0) return -1;\r
+ if (a->y0 > b->y0) return 1;\r
+ return 0;\r
+}\r
+\r
+typedef struct\r
+{\r
+ float x,y;\r
+} stbtt__point;\r
+\r
+static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, int off_x, int off_y, int invert, void *userdata)\r
+{\r
+ float y_scale_inv = invert ? -scale_y : scale_y;\r
+ stbtt__edge *e;\r
+ int n,i,j,k,m;\r
+ int vsubsample = result->h < 8 ? 15 : 5;\r
+ // vsubsample should divide 255 evenly; otherwise we won't reach full opacity\r
+\r
+ // now we have to blow out the windings into explicit edge lists\r
+ n = 0;\r
+ for (i=0; i < windings; ++i)\r
+ n += wcount[i];\r
+\r
+ e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel\r
+ if (e == 0) return;\r
+ n = 0;\r
+\r
+ m=0;\r
+ for (i=0; i < windings; ++i) {\r
+ stbtt__point *p = pts + m;\r
+ m += wcount[i];\r
+ j = wcount[i]-1;\r
+ for (k=0; k < wcount[i]; j=k++) {\r
+ int a=k,b=j;\r
+ // skip the edge if horizontal\r
+ if (p[j].y == p[k].y)\r
+ continue;\r
+ // add edge from j to k to the list\r
+ e[n].invert = 0;\r
+ if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {\r
+ e[n].invert = 1;\r
+ a=j,b=k;\r
+ }\r
+ e[n].x0 = p[a].x * scale_x;\r
+ e[n].y0 = p[a].y * y_scale_inv * vsubsample;\r
+ e[n].x1 = p[b].x * scale_x;\r
+ e[n].y1 = p[b].y * y_scale_inv * vsubsample;\r
+ ++n;\r
+ }\r
+ }\r
+\r
+ // now sort the edges by their highest point (should snap to integer, and then by x)\r
+ STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);\r
+\r
+ // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule\r
+ stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);\r
+\r
+ STBTT_free(e, userdata);\r
+}\r
+\r
+static void stbtt__add_point(stbtt__point *points, int n, float x, float y)\r
+{\r
+ if (!points) return; // during first pass, it's unallocated\r
+ points[n].x = x;\r
+ points[n].y = y;\r
+}\r
+\r
+// tesselate until threshhold p is happy... @TODO warped to compensate for non-linear stretching\r
+static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)\r
+{\r
+ // midpoint\r
+ float mx = (x0 + 2*x1 + x2)/4;\r
+ float my = (y0 + 2*y1 + y2)/4;\r
+ // versus directly drawn line\r
+ float dx = (x0+x2)/2 - mx;\r
+ float dy = (y0+y2)/2 - my;\r
+ if (n > 16) // 65536 segments on one curve better be enough!\r
+ return 1;\r
+ if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA\r
+ stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);\r
+ stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);\r
+ } else {\r
+ stbtt__add_point(points, *num_points,x2,y2);\r
+ *num_points = *num_points+1;\r
+ }\r
+ return 1;\r
+}\r
+\r
+// returns number of contours\r
+stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)\r
+{\r
+ stbtt__point *points=0;\r
+ int num_points=0;\r
+\r
+ float objspace_flatness_squared = objspace_flatness * objspace_flatness;\r
+ int i,n=0,start=0, pass;\r
+\r
+ // count how many "moves" there are to get the contour count\r
+ for (i=0; i < num_verts; ++i)\r
+ if (vertices[i].type == STBTT_vmove)\r
+ ++n;\r
+\r
+ *num_contours = n;\r
+ if (n == 0) return 0;\r
+\r
+ *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);\r
+\r
+ if (*contour_lengths == 0) {\r
+ *num_contours = 0;\r
+ return 0;\r
+ }\r
+\r
+ // make two passes through the points so we don't need to realloc\r
+ for (pass=0; pass < 2; ++pass) {\r
+ float x=0,y=0;\r
+ if (pass == 1) {\r
+ points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);\r
+ if (points == NULL) goto error;\r
+ }\r
+ num_points = 0;\r
+ n= -1;\r
+ for (i=0; i < num_verts; ++i) {\r
+ switch (vertices[i].type) {\r
+ case STBTT_vmove:\r
+ // start the next contour\r
+ if (n >= 0)\r
+ (*contour_lengths)[n] = num_points - start;\r
+ ++n;\r
+ start = num_points;\r
+\r
+ x = vertices[i].x, y = vertices[i].y;\r
+ stbtt__add_point(points, num_points++, x,y);\r
+ break;\r
+ case STBTT_vline:\r
+ x = vertices[i].x, y = vertices[i].y;\r
+ stbtt__add_point(points, num_points++, x, y);\r
+ break;\r
+ case STBTT_vcurve:\r
+ stbtt__tesselate_curve(points, &num_points, x,y,\r
+ vertices[i].cx, vertices[i].cy,\r
+ vertices[i].x, vertices[i].y,\r
+ objspace_flatness_squared, 0);\r
+ x = vertices[i].x, y = vertices[i].y;\r
+ break;\r
+ }\r
+ }\r
+ (*contour_lengths)[n] = num_points - start;\r
+ }\r
+\r
+ return points;\r
+error:\r
+ STBTT_free(points, userdata);\r
+ STBTT_free(*contour_lengths, userdata);\r
+ *contour_lengths = 0;\r
+ *num_contours = 0;\r
+ return NULL;\r
+}\r
+\r
+void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, int x_off, int y_off, int invert, void *userdata)\r
+{\r
+ float scale = scale_x > scale_y ? scale_y : scale_x;\r
+ int winding_count, *winding_lengths;\r
+ stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);\r
+ if (windings) {\r
+ stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, x_off, y_off, invert, userdata);\r
+ STBTT_free(winding_lengths, userdata);\r
+ STBTT_free(windings, userdata);\r
+ }\r
+}\r
+\r
+void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)\r
+{\r
+ STBTT_free(bitmap, userdata);\r
+}\r
+\r
+unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)\r
+{\r
+ int ix0,iy0,ix1,iy1;\r
+ stbtt__bitmap gbm;\r
+ stbtt_vertex *vertices; \r
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\r
+\r
+ if (scale_x == 0) scale_x = scale_y;\r
+ if (scale_y == 0) {\r
+ if (scale_x == 0) return NULL;\r
+ scale_y = scale_x;\r
+ }\r
+\r
+ stbtt_GetGlyphBitmapBox(info, glyph, scale_x, scale_y, &ix0,&iy0,&ix1,&iy1);\r
+\r
+ // now we get the size\r
+ gbm.w = (ix1 - ix0);\r
+ gbm.h = (iy1 - iy0);\r
+ gbm.pixels = NULL; // in case we error\r
+\r
+ if (width ) *width = gbm.w;\r
+ if (height) *height = gbm.h;\r
+ if (xoff ) *xoff = ix0;\r
+ if (yoff ) *yoff = iy0;\r
+ \r
+ if (gbm.w && gbm.h) {\r
+ gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);\r
+ if (gbm.pixels) {\r
+ gbm.stride = gbm.w;\r
+\r
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, ix0, iy0, 1, info->userdata);\r
+ }\r
+ }\r
+ STBTT_free(vertices, info->userdata);\r
+ return gbm.pixels;\r
+} \r
+\r
+void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)\r
+{\r
+ int ix0,iy0;\r
+ stbtt_vertex *vertices; \r
+ int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\r
+ stbtt__bitmap gbm; \r
+\r
+ stbtt_GetGlyphBitmapBox(info, glyph, scale_x, scale_y, &ix0,&iy0,0,0);\r
+ gbm.pixels = output;\r
+ gbm.w = out_w;\r
+ gbm.h = out_h;\r
+ gbm.stride = out_stride;\r
+\r
+ if (gbm.w && gbm.h)\r
+ stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, ix0,iy0, 1, info->userdata);\r
+\r
+ STBTT_free(vertices, info->userdata);\r
+}\r
+\r
+unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)\r
+{\r
+ return stbtt_GetGlyphBitmap(info, scale_x, scale_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);\r
+} \r
+\r
+void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)\r
+{\r
+ stbtt_MakeGlyphBitmap(info, output, out_w, out_h, out_stride, scale_x, scale_y, stbtt_FindGlyphIndex(info,codepoint));\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// bitmap baking\r
+//\r
+// This is SUPER-SHITTY packing to keep source code small\r
+\r
+extern int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf)\r
+ float pixel_height, // height of font in pixels\r
+ unsigned char *pixels, int pw, int ph, // bitmap to be filled in\r
+ int first_char, int num_chars, // characters to bake\r
+ stbtt_bakedchar *chardata)\r
+{\r
+ float scale;\r
+ int x,y,bottom_y, i;\r
+ stbtt_fontinfo f;\r
+ stbtt_InitFont(&f, data, offset);\r
+ STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels\r
+ x=y=1;\r
+ bottom_y = 1;\r
+\r
+ scale = stbtt_ScaleForPixelHeight(&f, pixel_height);\r
+\r
+ for (i=0; i < num_chars; ++i) {\r
+ int advance, lsb, x0,y0,x1,y1,gw,gh;\r
+ int g = stbtt_FindGlyphIndex(&f, first_char + i);\r
+ stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);\r
+ stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);\r
+ gw = x1-x0;\r
+ gh = y1-y0;\r
+ if (x + gw + 1 >= pw)\r
+ y = bottom_y, x = 1; // advance to next row\r
+ if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row\r
+ return -i;\r
+ STBTT_assert(x+gw < pw);\r
+ STBTT_assert(y+gh < ph);\r
+ stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);\r
+ chardata[i].x0 = (stbtt_int16) x;\r
+ chardata[i].y0 = (stbtt_int16) y;\r
+ chardata[i].x1 = (stbtt_int16) (x + gw);\r
+ chardata[i].y1 = (stbtt_int16) (y + gh);\r
+ chardata[i].xadvance = scale * advance;\r
+ chardata[i].xoff = (float) x0;\r
+ chardata[i].yoff = (float) y0;\r
+ x = x + gw + 2;\r
+ if (y+gh+2 > bottom_y)\r
+ bottom_y = y+gh+2;\r
+ }\r
+ return bottom_y;\r
+}\r
+\r
+void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)\r
+{\r
+ float d3d_bias = opengl_fillrule ? 0 : -0.5f;\r
+ float ipw = 1.0f / pw, iph = 1.0f / ph;\r
+ stbtt_bakedchar *b = chardata + char_index;\r
+ int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5);\r
+ int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5);\r
+\r
+ q->x0 = round_x + d3d_bias;\r
+ q->y0 = round_y + d3d_bias;\r
+ q->x1 = round_x + b->x1 - b->x0 + d3d_bias;\r
+ q->y1 = round_y + b->y1 - b->y0 + d3d_bias;\r
+\r
+ q->s0 = b->x0 * ipw;\r
+ q->t0 = b->y0 * ipw;\r
+ q->s1 = b->x1 * iph;\r
+ q->t1 = b->y1 * iph;\r
+\r
+ *xpos += b->xadvance;\r
+}\r
+\r
+//////////////////////////////////////////////////////////////////////////////\r
+//\r
+// font name matching -- recommended not to use this\r
+//\r
+\r
+// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string\r
+static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) \r
+{\r
+ stbtt_int32 i=0;\r
+\r
+ // convert utf16 to utf8 and compare the results while converting\r
+ while (len2) {\r
+ stbtt_uint16 ch = s2[0]*256 + s2[1];\r
+ if (ch < 0x80) {\r
+ if (i >= len1) return -1;\r
+ if (s1[i++] != ch) return -1;\r
+ } else if (ch < 0x800) {\r
+ if (i+1 >= len1) return -1;\r
+ if (s1[i++] != 0xc0 + (ch >> 6)) return -1;\r
+ if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;\r
+ } else if (ch >= 0xd800 && ch < 0xdc00) {\r
+ stbtt_uint32 c;\r
+ stbtt_uint16 ch2 = s2[2]*256 + s2[3];\r
+ if (i+3 >= len1) return -1;\r
+ c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;\r
+ if (s1[i++] != 0xf0 + (c >> 18)) return -1;\r
+ if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;\r
+ if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1;\r
+ if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1;\r
+ s2 += 2; // plus another 2 below\r
+ len2 -= 2;\r
+ } else if (ch >= 0xdc00 && ch < 0xe000) {\r
+ return -1;\r
+ } else {\r
+ if (i+2 >= len1) return -1;\r
+ if (s1[i++] != 0xe0 + (ch >> 12)) return -1;\r
+ if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;\r
+ if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1;\r
+ }\r
+ s2 += 2;\r
+ len2 -= 2;\r
+ }\r
+ return i;\r
+}\r
+\r
+int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) \r
+{\r
+ return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);\r
+}\r
+\r
+// returns results in whatever encoding you request... but note that 2-byte encodings\r
+// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare\r
+char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)\r
+{\r
+ stbtt_int32 i,count,stringOffset;\r
+ stbtt_uint8 *fc = font->data;\r
+ stbtt_uint32 offset = font->fontstart;\r
+ stbtt_uint32 nm = stbtt__find_table(fc, offset, "name");\r
+ if (!nm) return NULL;\r
+\r
+ count = ttUSHORT(fc+nm+2);\r
+ stringOffset = nm + ttUSHORT(fc+nm+4);\r
+ for (i=0; i < count; ++i) {\r
+ stbtt_uint32 loc = nm + 6 + 12 * i;\r
+ if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)\r
+ && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {\r
+ *length = ttUSHORT(fc+loc+8);\r
+ return (char *) (fc+stringOffset+ttUSHORT(fc+loc+10));\r
+ }\r
+ }\r
+ return NULL;\r
+}\r
+\r
+static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)\r
+{\r
+ stbtt_int32 i;\r
+ stbtt_int32 count = ttUSHORT(fc+nm+2);\r
+ stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);\r
+\r
+ for (i=0; i < count; ++i) {\r
+ stbtt_uint32 loc = nm + 6 + 12 * i;\r
+ stbtt_int32 id = ttUSHORT(fc+loc+6);\r
+ if (id == target_id) {\r
+ // find the encoding\r
+ stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);\r
+\r
+ // is this a Unicode encoding?\r
+ if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {\r
+ stbtt_int32 slen = ttUSHORT(fc+loc+8), off = ttUSHORT(fc+loc+10);\r
+\r
+ // check if there's a prefix match\r
+ stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);\r
+ if (matchlen >= 0) {\r
+ // check for target_id+1 immediately following, with same encoding & language\r
+ if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {\r
+ stbtt_int32 slen = ttUSHORT(fc+loc+12+8), off = ttUSHORT(fc+loc+12+10);\r
+ if (slen == 0) {\r
+ if (matchlen == nlen)\r
+ return 1;\r
+ } else if (matchlen < nlen && name[matchlen] == ' ') {\r
+ ++matchlen;\r
+ if (stbtt_CompareUTF8toUTF16_bigendian((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))\r
+ return 1;\r
+ }\r
+ } else {\r
+ // if nothing immediately following\r
+ if (matchlen == nlen)\r
+ return 1;\r
+ }\r
+ }\r
+ }\r
+\r
+ // @TODO handle other encodings\r
+ }\r
+ }\r
+ return 0;\r
+}\r
+\r
+static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)\r
+{\r
+ stbtt_int32 nlen = STBTT_strlen((char *) name);\r
+ stbtt_uint32 nm,hd;\r
+ if (!stbtt__isfont(fc+offset)) return 0;\r
+\r
+ // check italics/bold/underline flags in macStyle...\r
+ if (flags) {\r
+ hd = stbtt__find_table(fc, offset, "head");\r
+ if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;\r
+ }\r
+\r
+ nm = stbtt__find_table(fc, offset, "name");\r
+ if (!nm) return 0;\r
+\r
+ if (flags) {\r
+ // if we checked the macStyle flags, then just check the family and ignore the subfamily\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1;\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1;\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;\r
+ } else {\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1;\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1;\r
+ if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1;\r
+ }\r
+\r
+ return 0;\r
+}\r
+\r
+int stbtt_FindMatchingFont(const unsigned char *font_collection, const char *name_utf8, stbtt_int32 flags)\r
+{\r
+ stbtt_int32 i;\r
+ for (i=0;;++i) {\r
+ stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);\r
+ if (off < 0) return off;\r
+ if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))\r
+ return off;\r
+ }\r
+}\r
+\r
+#endif // STB_TRUETYPE_IMPLEMENTATION\r