code
stringlengths
0
56.1M
repo_name
stringlengths
3
57
path
stringlengths
2
176
language
stringclasses
672 values
license
stringclasses
8 values
size
int64
0
56.8M
/* Copyright (C) 2005, 2007, 2008, 2013 by George Williams */ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* modified by Werner Lemberg <wl@gnu.org> */ /* This file is now part of the FreeType library */ #define _XOPEN_SOURCE 600 /* for `kill', `strdup', `random', and `srandom' */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include <dirent.h> #include <signal.h> #include <time.h> #include <ft2build.h> #include <freetype/freetype.h> #include <freetype/ftoutln.h> #define true 1 #define false 0 #define forever for (;;) static int check_outlines = false; static int nohints = false; static int rasterize = false; static char* results_dir = "results"; #define GOOD_FONTS_DIR "/usr/local/share/fonts" static char* default_dir_list[] = { GOOD_FONTS_DIR, NULL }; static char* default_ext_list[] = { "ttf", "otf", "ttc", "cid", "pfb", "pfa", "bdf", "pcf", "pfr", "fon", "otb", "cff", NULL }; static unsigned int error_count = 1; static double error_fraction = 0.0; static FT_F26Dot6 font_size = 12 * 64; static struct fontlist { char* name; long len; unsigned int isbinary: 1; unsigned int isascii: 1; unsigned int ishex: 1; } *fontlist; static unsigned int fcnt; static int FT_MoveTo( const FT_Vector *to, void *user ) { FT_UNUSED( to ); FT_UNUSED( user ); return 0; } static int FT_LineTo( const FT_Vector *to, void *user ) { FT_UNUSED( to ); FT_UNUSED( user ); return 0; } static int FT_ConicTo( const FT_Vector *_cp, const FT_Vector *to, void *user ) { FT_UNUSED( _cp ); FT_UNUSED( to ); FT_UNUSED( user ); return 0; } static int FT_CubicTo( const FT_Vector *cp1, const FT_Vector *cp2, const FT_Vector *to, void *user ) { FT_UNUSED( cp1 ); FT_UNUSED( cp2 ); FT_UNUSED( to ); FT_UNUSED( user ); return 0; } static FT_Outline_Funcs outlinefuncs = { FT_MoveTo, FT_LineTo, FT_ConicTo, FT_CubicTo, 0, 0 /* No shift, no delta */ }; static void TestFace( FT_Face face ) { unsigned int gid; int load_flags = FT_LOAD_DEFAULT; if ( check_outlines && FT_IS_SCALABLE( face ) ) load_flags = FT_LOAD_NO_BITMAP; if ( nohints ) load_flags |= FT_LOAD_NO_HINTING; FT_Set_Char_Size( face, 0, font_size, 72, 72 ); for ( gid = 0; gid < face->num_glyphs; gid++ ) { if ( check_outlines && FT_IS_SCALABLE( face ) ) { if ( !FT_Load_Glyph( face, gid, load_flags ) ) FT_Outline_Decompose( &face->glyph->outline, &outlinefuncs, NULL ); } else FT_Load_Glyph( face, gid, load_flags ); if ( rasterize ) FT_Render_Glyph( face->glyph, ft_render_mode_normal ); } FT_Done_Face( face ); } static void ExecuteTest( char* testfont ) { FT_Library context; FT_Face face; if ( FT_Init_FreeType( &context ) ) { fprintf( stderr, "Can't initialize FreeType.\n" ); exit( 1 ); } if ( FT_New_Face( context, testfont, 0, &face ) ) { /* The font is erroneous, so if this fails that's ok. */ exit( 0 ); } if ( face->num_faces == 1 ) TestFace( face ); else { long i, num; num = face->num_faces; FT_Done_Face( face ); for ( i = 0; i < num; i++ ) { if ( !FT_New_Face( context, testfont, i, &face ) ) TestFace( face ); } } FT_Done_FreeType( context ); exit( 0 ); } static int extmatch( char* filename, char** extensions ) { int i; char* pt; if ( !extensions ) return true; pt = strrchr( filename, '.' ); if ( !pt ) return false; if ( pt < strrchr( filename, '/' ) ) return false; for ( i = 0; extensions[i] != NULL; i++ ) if ( strcasecmp( pt + 1, extensions[i] ) == 0 || strcasecmp( pt, extensions[i] ) == 0 ) return true; return false; } static void figurefiletype( struct fontlist* item ) { FILE* foo; item->isbinary = item->isascii = item->ishex = false; foo = fopen( item->name, "rb" ); if ( foo ) { /* Try to guess the file type from the first few characters... */ int ch1 = getc( foo ); int ch2 = getc( foo ); int ch3 = getc( foo ); int ch4 = getc( foo ); fclose( foo ); if ( ( ch1 == 0 && ch2 == 1 && ch3 == 0 && ch4 == 0 ) || ( ch1 == 'O' && ch2 == 'T' && ch3 == 'T' && ch4 == 'O' ) || ( ch1 == 't' && ch2 == 'r' && ch3 == 'u' && ch4 == 'e' ) || ( ch1 == 't' && ch2 == 't' && ch3 == 'c' && ch4 == 'f' ) ) { /* ttf, otf, ttc files */ item->isbinary = true; } else if ( ch1 == 0x80 && ch2 == '\01' ) { /* PFB header */ item->isbinary = true; } else if ( ch1 == '%' && ch2 == '!' ) { /* Random PostScript */ if ( strstr( item->name, ".pfa" ) || strstr( item->name, ".PFA" ) ) item->ishex = true; else item->isascii = true; } else if ( ch1 == 1 && ch2 == 0 && ch3 == 4 ) { /* Bare CFF */ item->isbinary = true; } else if ( ch1 == 'S' && ch2 == 'T' && ch3 == 'A' && ch4 == 'R' ) { /* BDF */ item->ishex = true; } else if ( ch1 == 'P' && ch2 == 'F' && ch3 == 'R' && ch4 == '0' ) { /* PFR */ item->isbinary = true; } else if ( ( ch1 == '\1' && ch2 == 'f' && ch3 == 'c' && ch4 == 'p' ) || ( ch1 == 'M' && ch2 == 'Z' ) ) { /* Windows FON */ item->isbinary = true; } else { fprintf( stderr, "Can't recognize file type of `%s', assuming binary\n", item->name ); item->isbinary = true; } } else { fprintf( stderr, "Can't open `%s' for typing the file.\n", item->name ); item->isbinary = true; } } static void FindFonts( char** fontdirs, char** extensions ) { int i; unsigned int max; char buffer[1025]; struct stat statb; max = 0; fcnt = 0; for ( i = 0; fontdirs[i] != NULL; i++ ) { DIR* examples; struct dirent* ent; examples = opendir( fontdirs[i] ); if ( !examples ) { fprintf( stderr, "Can't open example font directory `%s'\n", fontdirs[i] ); exit( 1 ); } while ( ( ent = readdir( examples ) ) != NULL ) { snprintf( buffer, sizeof ( buffer ), "%s/%s", fontdirs[i], ent->d_name ); if ( stat( buffer, &statb ) == -1 || S_ISDIR( statb.st_mode ) ) continue; if ( !extensions || extmatch( buffer, extensions ) ) { if ( fcnt >= max ) { max += 100; fontlist = realloc( fontlist, max * sizeof ( struct fontlist ) ); if ( !fontlist ) { fprintf( stderr, "Can't allocate memory\n" ); exit( 1 ); } } fontlist[fcnt].name = strdup( buffer ); fontlist[fcnt].len = statb.st_size; figurefiletype( &fontlist[fcnt] ); fcnt++; } } closedir( examples ); } if ( fcnt == 0 ) { fprintf( stderr, "Can't find matching font files.\n" ); exit( 1 ); } fontlist[fcnt].name = NULL; } static unsigned int getErrorCnt( struct fontlist* item ) { if ( error_count == 0 && error_fraction == 0.0 ) return 0; return error_count + (unsigned int)( error_fraction * item->len ); } static int getRandom( int low, int high ) { if ( low - high < 0x10000L ) return low + ( ( random() >> 8 ) % ( high + 1 - low ) ); return low + ( random() % ( high + 1 - low ) ); } static int copyfont( struct fontlist* item, char* newfont ) { static char buffer[8096]; FILE *good, *newf; size_t len; unsigned int i, err_cnt; good = fopen( item->name, "r" ); if ( !good ) { fprintf( stderr, "Can't open `%s'\n", item->name ); return false; } newf = fopen( newfont, "w+" ); if ( !newf ) { fprintf( stderr, "Can't create temporary output file `%s'\n", newfont ); exit( 1 ); } while ( ( len = fread( buffer, 1, sizeof ( buffer ), good ) ) > 0 ) fwrite( buffer, 1, len, newf ); fclose( good ); err_cnt = getErrorCnt( item ); for ( i = 0; i < err_cnt; i++ ) { fseek( newf, getRandom( 0, (int)( item->len - 1 ) ), SEEK_SET ); if ( item->isbinary ) putc( getRandom( 0, 0xFF ), newf ); else if ( item->isascii ) putc( getRandom( 0x20, 0x7E ), newf ); else { int hex = getRandom( 0, 15 ); if ( hex < 10 ) hex += '0'; else hex += 'A' - 10; putc( hex, newf ); } } if ( ferror( newf ) ) { fclose( newf ); unlink( newfont ); return false; } fclose( newf ); return true; } static int child_pid; static void abort_test( int sig ) { FT_UNUSED( sig ); /* If a time-out happens, then kill the child */ kill( child_pid, SIGFPE ); write( 2, "Timeout... ", 11 ); } static void do_test( void ) { int i = getRandom( 0, (int)( fcnt - 1 ) ); static int test_num = 0; char buffer[1024]; sprintf( buffer, "%s/test%d", results_dir, test_num++ ); if ( copyfont ( &fontlist[i], buffer ) ) { signal( SIGALRM, abort_test ); /* Anything that takes more than 20 seconds */ /* to parse and/or rasterize is an error. */ alarm( 20 ); if ( ( child_pid = fork() ) == 0 ) ExecuteTest( buffer ); else if ( child_pid != -1 ) { int status; waitpid( child_pid, &status, 0 ); alarm( 0 ); if ( WIFSIGNALED ( status ) ) printf( "Error found in file `%s'\n", buffer ); else unlink( buffer ); } else { fprintf( stderr, "Can't fork test case.\n" ); exit( 1 ); } alarm( 0 ); } } static void usage( FILE* out, char* name ) { char** d = default_dir_list; char** e = default_ext_list; fprintf( out, "%s [options] -- Generate random erroneous fonts\n" " and attempt to parse them with FreeType.\n\n", name ); fprintf( out, " --all All non-directory files are assumed to be fonts.\n" ); fprintf( out, " --check-outlines Make sure we can parse the outlines of each glyph.\n" ); fprintf( out, " --dir <path> Append <path> to list of font search directories\n" " (no recursive search).\n" ); fprintf( out, " --error-count <cnt> Introduce <cnt> single byte errors into each font\n" " (default: 1)\n" ); fprintf( out, " --error-fraction <frac> Introduce <frac>*filesize single byte errors\n" " into each font (default: 0.0).\n" ); fprintf( out, " --ext <ext> Add <ext> to list of extensions indicating fonts.\n" ); fprintf( out, " --help Print this.\n" ); fprintf( out, " --nohints Turn off hinting.\n" ); fprintf( out, " --rasterize Attempt to rasterize each glyph.\n" ); fprintf( out, " --results <path> Place the created test fonts into <path>\n" " (default: `results')\n" ); fprintf( out, " --size <float> Use the given font size for the tests.\n" ); fprintf( out, " --test <file> Run a single test on an already existing file.\n" ); fprintf( out, "\n" ); fprintf( out, "Default font extensions:\n" ); fprintf( out, " " ); while ( *e ) fprintf( out, " .%s", *e++ ); fprintf( out, "\n" ); fprintf( out, "Default font directories:\n" ); fprintf( out, " " ); while ( *d ) fprintf( out, " %s", *d++ ); fprintf( out, "\n" ); } int main( int argc, char** argv ) { char **dirs, **exts; int dcnt = 0, ecnt = 0, rset = false, allexts = false; int i; time_t now; char* testfile = NULL; dirs = calloc( (size_t)( argc + 1 ), sizeof ( char ** ) ); exts = calloc( (size_t)( argc + 1 ), sizeof ( char ** ) ); for ( i = 1; i < argc; i++ ) { char* pt = argv[i]; char* end; if ( pt[0] == '-' && pt[1] == '-' ) pt++; if ( strcmp( pt, "-all" ) == 0 ) allexts = true; else if ( strcmp( pt, "-check-outlines" ) == 0 ) check_outlines = true; else if ( strcmp( pt, "-dir" ) == 0 ) dirs[dcnt++] = argv[++i]; else if ( strcmp( pt, "-error-count" ) == 0 ) { if ( !rset ) error_fraction = 0.0; rset = true; error_count = (unsigned int)strtoul( argv[++i], &end, 10 ); if ( *end != '\0' ) { fprintf( stderr, "Bad value for error-count: %s\n", argv[i] ); exit( 1 ); } } else if ( strcmp( pt, "-error-fraction" ) == 0 ) { if ( !rset ) error_count = 0; rset = true; error_fraction = strtod( argv[++i], &end ); if ( *end != '\0' ) { fprintf( stderr, "Bad value for error-fraction: %s\n", argv[i] ); exit( 1 ); } if ( error_fraction < 0.0 || error_fraction > 1.0 ) { fprintf( stderr, "error-fraction must be in the range [0;1]\n" ); exit( 1 ); } } else if ( strcmp( pt, "-ext" ) == 0 ) exts[ecnt++] = argv[++i]; else if ( strcmp( pt, "-help" ) == 0 ) { usage( stdout, argv[0] ); exit( 0 ); } else if ( strcmp( pt, "-nohints" ) == 0 ) nohints = true; else if ( strcmp( pt, "-rasterize" ) == 0 ) rasterize = true; else if ( strcmp( pt, "-results" ) == 0 ) results_dir = argv[++i]; else if ( strcmp( pt, "-size" ) == 0 ) { font_size = (FT_F26Dot6)( strtod( argv[++i], &end ) * 64 ); if ( *end != '\0' || font_size < 64 ) { fprintf( stderr, "Bad value for size: %s\n", argv[i] ); exit( 1 ); } } else if ( strcmp( pt, "-test" ) == 0 ) testfile = argv[++i]; else { usage( stderr, argv[0] ); exit( 1 ); } } if ( allexts ) { free( exts ); exts = NULL; } else if ( ecnt == 0 ) { free( exts ); exts = default_ext_list; } if ( dcnt == 0 ) { free( dirs ); dirs = default_dir_list; } if ( testfile ) ExecuteTest( testfile ); /* This should never return */ time( &now ); srandom( (unsigned int)now ); FindFonts( dirs, exts ); mkdir( results_dir, 0755 ); forever do_test(); return 0; } /* EOF */
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/ftrandom/ftrandom.c
C++
gpl-3.0
17,270
#!/usr/bin/env python # # # FreeType 2 glyph name builder # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. """\ usage: %s <output-file> This python script generates the glyph names tables defined in the `psnames' module. Its single argument is the name of the header file to be created. """ import sys, string, struct, re, os.path # This table lists the glyphs according to the Macintosh specification. # It is used by the TrueType Postscript names table. # # See # # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html # # for the official list. # mac_standard_names = \ [ # 0 ".notdef", ".null", "nonmarkingreturn", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", # 10 "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", # 20 "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", # 30 "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", # 40 "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", # 50 "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", # 60 "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", # 70 "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", # 80 "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", # 90 "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "Adieresis", "Aring", # 100 "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", # 110 "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", # 120 "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex", "udieresis", # 130 "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", "registered", "copyright", # 140 "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", # 150 "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", # 160 "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", # 170 "guillemotright", "ellipsis", "nonbreakingspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", # 180 "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", # 190 "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", # 200 "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", # 210 "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve", # 220 "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "Lslash", "lslash", "Scaron", "scaron", # 230 "Zcaron", "zcaron", "brokenbar", "Eth", "eth", "Yacute", "yacute", "Thorn", "thorn", "minus", # 240 "multiply", "onesuperior", "twosuperior", "threesuperior", "onehalf", "onequarter", "threequarters", "franc", "Gbreve", "gbreve", # 250 "Idotaccent", "Scedilla", "scedilla", "Cacute", "cacute", "Ccaron", "ccaron", "dcroat" ] # The list of standard `SID' glyph names. For the official list, # see Annex A of document at # # https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5176.CFF.pdf . # sid_standard_names = \ [ # 0 ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", # 10 "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", # 20 "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", # 30 "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", # 40 "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", # 50 "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", # 60 "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", # 70 "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", # 80 "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", # 90 "y", "z", "braceleft", "bar", "braceright", "asciitilde", "exclamdown", "cent", "sterling", "fraction", # 100 "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", # 110 "fl", "endash", "dagger", "daggerdbl", "periodcentered", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", # 120 "guillemotright", "ellipsis", "perthousand", "questiondown", "grave", "acute", "circumflex", "tilde", "macron", "breve", # 130 "dotaccent", "dieresis", "ring", "cedilla", "hungarumlaut", "ogonek", "caron", "emdash", "AE", "ordfeminine", # 140 "Lslash", "Oslash", "OE", "ordmasculine", "ae", "dotlessi", "lslash", "oslash", "oe", "germandbls", # 150 "onesuperior", "logicalnot", "mu", "trademark", "Eth", "onehalf", "plusminus", "Thorn", "onequarter", "divide", # 160 "brokenbar", "degree", "thorn", "threequarters", "twosuperior", "registered", "minus", "eth", "multiply", "threesuperior", # 170 "copyright", "Aacute", "Acircumflex", "Adieresis", "Agrave", "Aring", "Atilde", "Ccedilla", "Eacute", "Ecircumflex", # 180 "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Ntilde", "Oacute", "Ocircumflex", "Odieresis", # 190 "Ograve", "Otilde", "Scaron", "Uacute", "Ucircumflex", "Udieresis", "Ugrave", "Yacute", "Ydieresis", "Zcaron", # 200 "aacute", "acircumflex", "adieresis", "agrave", "aring", "atilde", "ccedilla", "eacute", "ecircumflex", "edieresis", # 210 "egrave", "iacute", "icircumflex", "idieresis", "igrave", "ntilde", "oacute", "ocircumflex", "odieresis", "ograve", # 220 "otilde", "scaron", "uacute", "ucircumflex", "udieresis", "ugrave", "yacute", "ydieresis", "zcaron", "exclamsmall", # 230 "Hungarumlautsmall", "dollaroldstyle", "dollarsuperior", "ampersandsmall", "Acutesmall", "parenleftsuperior", "parenrightsuperior", "twodotenleader", "onedotenleader", "zerooldstyle", # 240 "oneoldstyle", "twooldstyle", "threeoldstyle", "fouroldstyle", "fiveoldstyle", "sixoldstyle", "sevenoldstyle", "eightoldstyle", "nineoldstyle", "commasuperior", # 250 "threequartersemdash", "periodsuperior", "questionsmall", "asuperior", "bsuperior", "centsuperior", "dsuperior", "esuperior", "isuperior", "lsuperior", # 260 "msuperior", "nsuperior", "osuperior", "rsuperior", "ssuperior", "tsuperior", "ff", "ffi", "ffl", "parenleftinferior", # 270 "parenrightinferior", "Circumflexsmall", "hyphensuperior", "Gravesmall", "Asmall", "Bsmall", "Csmall", "Dsmall", "Esmall", "Fsmall", # 280 "Gsmall", "Hsmall", "Ismall", "Jsmall", "Ksmall", "Lsmall", "Msmall", "Nsmall", "Osmall", "Psmall", # 290 "Qsmall", "Rsmall", "Ssmall", "Tsmall", "Usmall", "Vsmall", "Wsmall", "Xsmall", "Ysmall", "Zsmall", # 300 "colonmonetary", "onefitted", "rupiah", "Tildesmall", "exclamdownsmall", "centoldstyle", "Lslashsmall", "Scaronsmall", "Zcaronsmall", "Dieresissmall", # 310 "Brevesmall", "Caronsmall", "Dotaccentsmall", "Macronsmall", "figuredash", "hypheninferior", "Ogoneksmall", "Ringsmall", "Cedillasmall", "questiondownsmall", # 320 "oneeighth", "threeeighths", "fiveeighths", "seveneighths", "onethird", "twothirds", "zerosuperior", "foursuperior", "fivesuperior", "sixsuperior", # 330 "sevensuperior", "eightsuperior", "ninesuperior", "zeroinferior", "oneinferior", "twoinferior", "threeinferior", "fourinferior", "fiveinferior", "sixinferior", # 340 "seveninferior", "eightinferior", "nineinferior", "centinferior", "dollarinferior", "periodinferior", "commainferior", "Agravesmall", "Aacutesmall", "Acircumflexsmall", # 350 "Atildesmall", "Adieresissmall", "Aringsmall", "AEsmall", "Ccedillasmall", "Egravesmall", "Eacutesmall", "Ecircumflexsmall", "Edieresissmall", "Igravesmall", # 360 "Iacutesmall", "Icircumflexsmall", "Idieresissmall", "Ethsmall", "Ntildesmall", "Ogravesmall", "Oacutesmall", "Ocircumflexsmall", "Otildesmall", "Odieresissmall", # 370 "OEsmall", "Oslashsmall", "Ugravesmall", "Uacutesmall", "Ucircumflexsmall", "Udieresissmall", "Yacutesmall", "Thornsmall", "Ydieresissmall", "001.000", # 380 "001.001", "001.002", "001.003", "Black", "Bold", "Book", "Light", "Medium", "Regular", "Roman", # 390 "Semibold" ] # This table maps character codes of the Adobe Standard Type 1 # encoding to glyph indices in the sid_standard_names table. # t1_standard_encoding = \ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0 ] # This table maps character codes of the Adobe Expert Type 1 # encoding to glyph indices in the sid_standard_names table. # t1_expert_encoding = \ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 229, 230, 0, 231, 232, 233, 234, 235, 236, 237, 238, 13, 14, 15, 99, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 27, 28, 249, 250, 251, 252, 0, 253, 254, 255, 256, 257, 0, 0, 0, 258, 0, 0, 259, 260, 261, 262, 0, 0, 263, 264, 265, 0, 266, 109, 110, 267, 268, 269, 0, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 304, 305, 306, 0, 0, 307, 308, 309, 310, 311, 0, 312, 0, 0, 313, 0, 0, 314, 315, 0, 0, 316, 317, 318, 0, 0, 0, 158, 155, 163, 319, 320, 321, 322, 323, 324, 325, 0, 0, 326, 150, 164, 169, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378 ] # This data has been taken literally from the files `glyphlist.txt' # and `zapfdingbats.txt' version 2.0, Sept 2002. It is available from # # https://github.com/adobe-type-tools/agl-aglfn # adobe_glyph_list = """\ A;0041 AE;00C6 AEacute;01FC AEmacron;01E2 AEsmall;F7E6 Aacute;00C1 Aacutesmall;F7E1 Abreve;0102 Abreveacute;1EAE Abrevecyrillic;04D0 Abrevedotbelow;1EB6 Abrevegrave;1EB0 Abrevehookabove;1EB2 Abrevetilde;1EB4 Acaron;01CD Acircle;24B6 Acircumflex;00C2 Acircumflexacute;1EA4 Acircumflexdotbelow;1EAC Acircumflexgrave;1EA6 Acircumflexhookabove;1EA8 Acircumflexsmall;F7E2 Acircumflextilde;1EAA Acute;F6C9 Acutesmall;F7B4 Acyrillic;0410 Adblgrave;0200 Adieresis;00C4 Adieresiscyrillic;04D2 Adieresismacron;01DE Adieresissmall;F7E4 Adotbelow;1EA0 Adotmacron;01E0 Agrave;00C0 Agravesmall;F7E0 Ahookabove;1EA2 Aiecyrillic;04D4 Ainvertedbreve;0202 Alpha;0391 Alphatonos;0386 Amacron;0100 Amonospace;FF21 Aogonek;0104 Aring;00C5 Aringacute;01FA Aringbelow;1E00 Aringsmall;F7E5 Asmall;F761 Atilde;00C3 Atildesmall;F7E3 Aybarmenian;0531 B;0042 Bcircle;24B7 Bdotaccent;1E02 Bdotbelow;1E04 Becyrillic;0411 Benarmenian;0532 Beta;0392 Bhook;0181 Blinebelow;1E06 Bmonospace;FF22 Brevesmall;F6F4 Bsmall;F762 Btopbar;0182 C;0043 Caarmenian;053E Cacute;0106 Caron;F6CA Caronsmall;F6F5 Ccaron;010C Ccedilla;00C7 Ccedillaacute;1E08 Ccedillasmall;F7E7 Ccircle;24B8 Ccircumflex;0108 Cdot;010A Cdotaccent;010A Cedillasmall;F7B8 Chaarmenian;0549 Cheabkhasiancyrillic;04BC Checyrillic;0427 Chedescenderabkhasiancyrillic;04BE Chedescendercyrillic;04B6 Chedieresiscyrillic;04F4 Cheharmenian;0543 Chekhakassiancyrillic;04CB Cheverticalstrokecyrillic;04B8 Chi;03A7 Chook;0187 Circumflexsmall;F6F6 Cmonospace;FF23 Coarmenian;0551 Csmall;F763 D;0044 DZ;01F1 DZcaron;01C4 Daarmenian;0534 Dafrican;0189 Dcaron;010E Dcedilla;1E10 Dcircle;24B9 Dcircumflexbelow;1E12 Dcroat;0110 Ddotaccent;1E0A Ddotbelow;1E0C Decyrillic;0414 Deicoptic;03EE Delta;2206 Deltagreek;0394 Dhook;018A Dieresis;F6CB DieresisAcute;F6CC DieresisGrave;F6CD Dieresissmall;F7A8 Digammagreek;03DC Djecyrillic;0402 Dlinebelow;1E0E Dmonospace;FF24 Dotaccentsmall;F6F7 Dslash;0110 Dsmall;F764 Dtopbar;018B Dz;01F2 Dzcaron;01C5 Dzeabkhasiancyrillic;04E0 Dzecyrillic;0405 Dzhecyrillic;040F E;0045 Eacute;00C9 Eacutesmall;F7E9 Ebreve;0114 Ecaron;011A Ecedillabreve;1E1C Echarmenian;0535 Ecircle;24BA Ecircumflex;00CA Ecircumflexacute;1EBE Ecircumflexbelow;1E18 Ecircumflexdotbelow;1EC6 Ecircumflexgrave;1EC0 Ecircumflexhookabove;1EC2 Ecircumflexsmall;F7EA Ecircumflextilde;1EC4 Ecyrillic;0404 Edblgrave;0204 Edieresis;00CB Edieresissmall;F7EB Edot;0116 Edotaccent;0116 Edotbelow;1EB8 Efcyrillic;0424 Egrave;00C8 Egravesmall;F7E8 Eharmenian;0537 Ehookabove;1EBA Eightroman;2167 Einvertedbreve;0206 Eiotifiedcyrillic;0464 Elcyrillic;041B Elevenroman;216A Emacron;0112 Emacronacute;1E16 Emacrongrave;1E14 Emcyrillic;041C Emonospace;FF25 Encyrillic;041D Endescendercyrillic;04A2 Eng;014A Enghecyrillic;04A4 Enhookcyrillic;04C7 Eogonek;0118 Eopen;0190 Epsilon;0395 Epsilontonos;0388 Ercyrillic;0420 Ereversed;018E Ereversedcyrillic;042D Escyrillic;0421 Esdescendercyrillic;04AA Esh;01A9 Esmall;F765 Eta;0397 Etarmenian;0538 Etatonos;0389 Eth;00D0 Ethsmall;F7F0 Etilde;1EBC Etildebelow;1E1A Euro;20AC Ezh;01B7 Ezhcaron;01EE Ezhreversed;01B8 F;0046 Fcircle;24BB Fdotaccent;1E1E Feharmenian;0556 Feicoptic;03E4 Fhook;0191 Fitacyrillic;0472 Fiveroman;2164 Fmonospace;FF26 Fourroman;2163 Fsmall;F766 G;0047 GBsquare;3387 Gacute;01F4 Gamma;0393 Gammaafrican;0194 Gangiacoptic;03EA Gbreve;011E Gcaron;01E6 Gcedilla;0122 Gcircle;24BC Gcircumflex;011C Gcommaaccent;0122 Gdot;0120 Gdotaccent;0120 Gecyrillic;0413 Ghadarmenian;0542 Ghemiddlehookcyrillic;0494 Ghestrokecyrillic;0492 Gheupturncyrillic;0490 Ghook;0193 Gimarmenian;0533 Gjecyrillic;0403 Gmacron;1E20 Gmonospace;FF27 Grave;F6CE Gravesmall;F760 Gsmall;F767 Gsmallhook;029B Gstroke;01E4 H;0048 H18533;25CF H18543;25AA H18551;25AB H22073;25A1 HPsquare;33CB Haabkhasiancyrillic;04A8 Hadescendercyrillic;04B2 Hardsigncyrillic;042A Hbar;0126 Hbrevebelow;1E2A Hcedilla;1E28 Hcircle;24BD Hcircumflex;0124 Hdieresis;1E26 Hdotaccent;1E22 Hdotbelow;1E24 Hmonospace;FF28 Hoarmenian;0540 Horicoptic;03E8 Hsmall;F768 Hungarumlaut;F6CF Hungarumlautsmall;F6F8 Hzsquare;3390 I;0049 IAcyrillic;042F IJ;0132 IUcyrillic;042E Iacute;00CD Iacutesmall;F7ED Ibreve;012C Icaron;01CF Icircle;24BE Icircumflex;00CE Icircumflexsmall;F7EE Icyrillic;0406 Idblgrave;0208 Idieresis;00CF Idieresisacute;1E2E Idieresiscyrillic;04E4 Idieresissmall;F7EF Idot;0130 Idotaccent;0130 Idotbelow;1ECA Iebrevecyrillic;04D6 Iecyrillic;0415 Ifraktur;2111 Igrave;00CC Igravesmall;F7EC Ihookabove;1EC8 Iicyrillic;0418 Iinvertedbreve;020A Iishortcyrillic;0419 Imacron;012A Imacroncyrillic;04E2 Imonospace;FF29 Iniarmenian;053B Iocyrillic;0401 Iogonek;012E Iota;0399 Iotaafrican;0196 Iotadieresis;03AA Iotatonos;038A Ismall;F769 Istroke;0197 Itilde;0128 Itildebelow;1E2C Izhitsacyrillic;0474 Izhitsadblgravecyrillic;0476 J;004A Jaarmenian;0541 Jcircle;24BF Jcircumflex;0134 Jecyrillic;0408 Jheharmenian;054B Jmonospace;FF2A Jsmall;F76A K;004B KBsquare;3385 KKsquare;33CD Kabashkircyrillic;04A0 Kacute;1E30 Kacyrillic;041A Kadescendercyrillic;049A Kahookcyrillic;04C3 Kappa;039A Kastrokecyrillic;049E Kaverticalstrokecyrillic;049C Kcaron;01E8 Kcedilla;0136 Kcircle;24C0 Kcommaaccent;0136 Kdotbelow;1E32 Keharmenian;0554 Kenarmenian;053F Khacyrillic;0425 Kheicoptic;03E6 Khook;0198 Kjecyrillic;040C Klinebelow;1E34 Kmonospace;FF2B Koppacyrillic;0480 Koppagreek;03DE Ksicyrillic;046E Ksmall;F76B L;004C LJ;01C7 LL;F6BF Lacute;0139 Lambda;039B Lcaron;013D Lcedilla;013B Lcircle;24C1 Lcircumflexbelow;1E3C Lcommaaccent;013B Ldot;013F Ldotaccent;013F Ldotbelow;1E36 Ldotbelowmacron;1E38 Liwnarmenian;053C Lj;01C8 Ljecyrillic;0409 Llinebelow;1E3A Lmonospace;FF2C Lslash;0141 Lslashsmall;F6F9 Lsmall;F76C M;004D MBsquare;3386 Macron;F6D0 Macronsmall;F7AF Macute;1E3E Mcircle;24C2 Mdotaccent;1E40 Mdotbelow;1E42 Menarmenian;0544 Mmonospace;FF2D Msmall;F76D Mturned;019C Mu;039C N;004E NJ;01CA Nacute;0143 Ncaron;0147 Ncedilla;0145 Ncircle;24C3 Ncircumflexbelow;1E4A Ncommaaccent;0145 Ndotaccent;1E44 Ndotbelow;1E46 Nhookleft;019D Nineroman;2168 Nj;01CB Njecyrillic;040A Nlinebelow;1E48 Nmonospace;FF2E Nowarmenian;0546 Nsmall;F76E Ntilde;00D1 Ntildesmall;F7F1 Nu;039D O;004F OE;0152 OEsmall;F6FA Oacute;00D3 Oacutesmall;F7F3 Obarredcyrillic;04E8 Obarreddieresiscyrillic;04EA Obreve;014E Ocaron;01D1 Ocenteredtilde;019F Ocircle;24C4 Ocircumflex;00D4 Ocircumflexacute;1ED0 Ocircumflexdotbelow;1ED8 Ocircumflexgrave;1ED2 Ocircumflexhookabove;1ED4 Ocircumflexsmall;F7F4 Ocircumflextilde;1ED6 Ocyrillic;041E Odblacute;0150 Odblgrave;020C Odieresis;00D6 Odieresiscyrillic;04E6 Odieresissmall;F7F6 Odotbelow;1ECC Ogoneksmall;F6FB Ograve;00D2 Ogravesmall;F7F2 Oharmenian;0555 Ohm;2126 Ohookabove;1ECE Ohorn;01A0 Ohornacute;1EDA Ohorndotbelow;1EE2 Ohorngrave;1EDC Ohornhookabove;1EDE Ohorntilde;1EE0 Ohungarumlaut;0150 Oi;01A2 Oinvertedbreve;020E Omacron;014C Omacronacute;1E52 Omacrongrave;1E50 Omega;2126 Omegacyrillic;0460 Omegagreek;03A9 Omegaroundcyrillic;047A Omegatitlocyrillic;047C Omegatonos;038F Omicron;039F Omicrontonos;038C Omonospace;FF2F Oneroman;2160 Oogonek;01EA Oogonekmacron;01EC Oopen;0186 Oslash;00D8 Oslashacute;01FE Oslashsmall;F7F8 Osmall;F76F Ostrokeacute;01FE Otcyrillic;047E Otilde;00D5 Otildeacute;1E4C Otildedieresis;1E4E Otildesmall;F7F5 P;0050 Pacute;1E54 Pcircle;24C5 Pdotaccent;1E56 Pecyrillic;041F Peharmenian;054A Pemiddlehookcyrillic;04A6 Phi;03A6 Phook;01A4 Pi;03A0 Piwrarmenian;0553 Pmonospace;FF30 Psi;03A8 Psicyrillic;0470 Psmall;F770 Q;0051 Qcircle;24C6 Qmonospace;FF31 Qsmall;F771 R;0052 Raarmenian;054C Racute;0154 Rcaron;0158 Rcedilla;0156 Rcircle;24C7 Rcommaaccent;0156 Rdblgrave;0210 Rdotaccent;1E58 Rdotbelow;1E5A Rdotbelowmacron;1E5C Reharmenian;0550 Rfraktur;211C Rho;03A1 Ringsmall;F6FC Rinvertedbreve;0212 Rlinebelow;1E5E Rmonospace;FF32 Rsmall;F772 Rsmallinverted;0281 Rsmallinvertedsuperior;02B6 S;0053 SF010000;250C SF020000;2514 SF030000;2510 SF040000;2518 SF050000;253C SF060000;252C SF070000;2534 SF080000;251C SF090000;2524 SF100000;2500 SF110000;2502 SF190000;2561 SF200000;2562 SF210000;2556 SF220000;2555 SF230000;2563 SF240000;2551 SF250000;2557 SF260000;255D SF270000;255C SF280000;255B SF360000;255E SF370000;255F SF380000;255A SF390000;2554 SF400000;2569 SF410000;2566 SF420000;2560 SF430000;2550 SF440000;256C SF450000;2567 SF460000;2568 SF470000;2564 SF480000;2565 SF490000;2559 SF500000;2558 SF510000;2552 SF520000;2553 SF530000;256B SF540000;256A Sacute;015A Sacutedotaccent;1E64 Sampigreek;03E0 Scaron;0160 Scarondotaccent;1E66 Scaronsmall;F6FD Scedilla;015E Schwa;018F Schwacyrillic;04D8 Schwadieresiscyrillic;04DA Scircle;24C8 Scircumflex;015C Scommaaccent;0218 Sdotaccent;1E60 Sdotbelow;1E62 Sdotbelowdotaccent;1E68 Seharmenian;054D Sevenroman;2166 Shaarmenian;0547 Shacyrillic;0428 Shchacyrillic;0429 Sheicoptic;03E2 Shhacyrillic;04BA Shimacoptic;03EC Sigma;03A3 Sixroman;2165 Smonospace;FF33 Softsigncyrillic;042C Ssmall;F773 Stigmagreek;03DA T;0054 Tau;03A4 Tbar;0166 Tcaron;0164 Tcedilla;0162 Tcircle;24C9 Tcircumflexbelow;1E70 Tcommaaccent;0162 Tdotaccent;1E6A Tdotbelow;1E6C Tecyrillic;0422 Tedescendercyrillic;04AC Tenroman;2169 Tetsecyrillic;04B4 Theta;0398 Thook;01AC Thorn;00DE Thornsmall;F7FE Threeroman;2162 Tildesmall;F6FE Tiwnarmenian;054F Tlinebelow;1E6E Tmonospace;FF34 Toarmenian;0539 Tonefive;01BC Tonesix;0184 Tonetwo;01A7 Tretroflexhook;01AE Tsecyrillic;0426 Tshecyrillic;040B Tsmall;F774 Twelveroman;216B Tworoman;2161 U;0055 Uacute;00DA Uacutesmall;F7FA Ubreve;016C Ucaron;01D3 Ucircle;24CA Ucircumflex;00DB Ucircumflexbelow;1E76 Ucircumflexsmall;F7FB Ucyrillic;0423 Udblacute;0170 Udblgrave;0214 Udieresis;00DC Udieresisacute;01D7 Udieresisbelow;1E72 Udieresiscaron;01D9 Udieresiscyrillic;04F0 Udieresisgrave;01DB Udieresismacron;01D5 Udieresissmall;F7FC Udotbelow;1EE4 Ugrave;00D9 Ugravesmall;F7F9 Uhookabove;1EE6 Uhorn;01AF Uhornacute;1EE8 Uhorndotbelow;1EF0 Uhorngrave;1EEA Uhornhookabove;1EEC Uhorntilde;1EEE Uhungarumlaut;0170 Uhungarumlautcyrillic;04F2 Uinvertedbreve;0216 Ukcyrillic;0478 Umacron;016A Umacroncyrillic;04EE Umacrondieresis;1E7A Umonospace;FF35 Uogonek;0172 Upsilon;03A5 Upsilon1;03D2 Upsilonacutehooksymbolgreek;03D3 Upsilonafrican;01B1 Upsilondieresis;03AB Upsilondieresishooksymbolgreek;03D4 Upsilonhooksymbol;03D2 Upsilontonos;038E Uring;016E Ushortcyrillic;040E Usmall;F775 Ustraightcyrillic;04AE Ustraightstrokecyrillic;04B0 Utilde;0168 Utildeacute;1E78 Utildebelow;1E74 V;0056 Vcircle;24CB Vdotbelow;1E7E Vecyrillic;0412 Vewarmenian;054E Vhook;01B2 Vmonospace;FF36 Voarmenian;0548 Vsmall;F776 Vtilde;1E7C W;0057 Wacute;1E82 Wcircle;24CC Wcircumflex;0174 Wdieresis;1E84 Wdotaccent;1E86 Wdotbelow;1E88 Wgrave;1E80 Wmonospace;FF37 Wsmall;F777 X;0058 Xcircle;24CD Xdieresis;1E8C Xdotaccent;1E8A Xeharmenian;053D Xi;039E Xmonospace;FF38 Xsmall;F778 Y;0059 Yacute;00DD Yacutesmall;F7FD Yatcyrillic;0462 Ycircle;24CE Ycircumflex;0176 Ydieresis;0178 Ydieresissmall;F7FF Ydotaccent;1E8E Ydotbelow;1EF4 Yericyrillic;042B Yerudieresiscyrillic;04F8 Ygrave;1EF2 Yhook;01B3 Yhookabove;1EF6 Yiarmenian;0545 Yicyrillic;0407 Yiwnarmenian;0552 Ymonospace;FF39 Ysmall;F779 Ytilde;1EF8 Yusbigcyrillic;046A Yusbigiotifiedcyrillic;046C Yuslittlecyrillic;0466 Yuslittleiotifiedcyrillic;0468 Z;005A Zaarmenian;0536 Zacute;0179 Zcaron;017D Zcaronsmall;F6FF Zcircle;24CF Zcircumflex;1E90 Zdot;017B Zdotaccent;017B Zdotbelow;1E92 Zecyrillic;0417 Zedescendercyrillic;0498 Zedieresiscyrillic;04DE Zeta;0396 Zhearmenian;053A Zhebrevecyrillic;04C1 Zhecyrillic;0416 Zhedescendercyrillic;0496 Zhedieresiscyrillic;04DC Zlinebelow;1E94 Zmonospace;FF3A Zsmall;F77A Zstroke;01B5 a;0061 aabengali;0986 aacute;00E1 aadeva;0906 aagujarati;0A86 aagurmukhi;0A06 aamatragurmukhi;0A3E aarusquare;3303 aavowelsignbengali;09BE aavowelsigndeva;093E aavowelsigngujarati;0ABE abbreviationmarkarmenian;055F abbreviationsigndeva;0970 abengali;0985 abopomofo;311A abreve;0103 abreveacute;1EAF abrevecyrillic;04D1 abrevedotbelow;1EB7 abrevegrave;1EB1 abrevehookabove;1EB3 abrevetilde;1EB5 acaron;01CE acircle;24D0 acircumflex;00E2 acircumflexacute;1EA5 acircumflexdotbelow;1EAD acircumflexgrave;1EA7 acircumflexhookabove;1EA9 acircumflextilde;1EAB acute;00B4 acutebelowcmb;0317 acutecmb;0301 acutecomb;0301 acutedeva;0954 acutelowmod;02CF acutetonecmb;0341 acyrillic;0430 adblgrave;0201 addakgurmukhi;0A71 adeva;0905 adieresis;00E4 adieresiscyrillic;04D3 adieresismacron;01DF adotbelow;1EA1 adotmacron;01E1 ae;00E6 aeacute;01FD aekorean;3150 aemacron;01E3 afii00208;2015 afii08941;20A4 afii10017;0410 afii10018;0411 afii10019;0412 afii10020;0413 afii10021;0414 afii10022;0415 afii10023;0401 afii10024;0416 afii10025;0417 afii10026;0418 afii10027;0419 afii10028;041A afii10029;041B afii10030;041C afii10031;041D afii10032;041E afii10033;041F afii10034;0420 afii10035;0421 afii10036;0422 afii10037;0423 afii10038;0424 afii10039;0425 afii10040;0426 afii10041;0427 afii10042;0428 afii10043;0429 afii10044;042A afii10045;042B afii10046;042C afii10047;042D afii10048;042E afii10049;042F afii10050;0490 afii10051;0402 afii10052;0403 afii10053;0404 afii10054;0405 afii10055;0406 afii10056;0407 afii10057;0408 afii10058;0409 afii10059;040A afii10060;040B afii10061;040C afii10062;040E afii10063;F6C4 afii10064;F6C5 afii10065;0430 afii10066;0431 afii10067;0432 afii10068;0433 afii10069;0434 afii10070;0435 afii10071;0451 afii10072;0436 afii10073;0437 afii10074;0438 afii10075;0439 afii10076;043A afii10077;043B afii10078;043C afii10079;043D afii10080;043E afii10081;043F afii10082;0440 afii10083;0441 afii10084;0442 afii10085;0443 afii10086;0444 afii10087;0445 afii10088;0446 afii10089;0447 afii10090;0448 afii10091;0449 afii10092;044A afii10093;044B afii10094;044C afii10095;044D afii10096;044E afii10097;044F afii10098;0491 afii10099;0452 afii10100;0453 afii10101;0454 afii10102;0455 afii10103;0456 afii10104;0457 afii10105;0458 afii10106;0459 afii10107;045A afii10108;045B afii10109;045C afii10110;045E afii10145;040F afii10146;0462 afii10147;0472 afii10148;0474 afii10192;F6C6 afii10193;045F afii10194;0463 afii10195;0473 afii10196;0475 afii10831;F6C7 afii10832;F6C8 afii10846;04D9 afii299;200E afii300;200F afii301;200D afii57381;066A afii57388;060C afii57392;0660 afii57393;0661 afii57394;0662 afii57395;0663 afii57396;0664 afii57397;0665 afii57398;0666 afii57399;0667 afii57400;0668 afii57401;0669 afii57403;061B afii57407;061F afii57409;0621 afii57410;0622 afii57411;0623 afii57412;0624 afii57413;0625 afii57414;0626 afii57415;0627 afii57416;0628 afii57417;0629 afii57418;062A afii57419;062B afii57420;062C afii57421;062D afii57422;062E afii57423;062F afii57424;0630 afii57425;0631 afii57426;0632 afii57427;0633 afii57428;0634 afii57429;0635 afii57430;0636 afii57431;0637 afii57432;0638 afii57433;0639 afii57434;063A afii57440;0640 afii57441;0641 afii57442;0642 afii57443;0643 afii57444;0644 afii57445;0645 afii57446;0646 afii57448;0648 afii57449;0649 afii57450;064A afii57451;064B afii57452;064C afii57453;064D afii57454;064E afii57455;064F afii57456;0650 afii57457;0651 afii57458;0652 afii57470;0647 afii57505;06A4 afii57506;067E afii57507;0686 afii57508;0698 afii57509;06AF afii57511;0679 afii57512;0688 afii57513;0691 afii57514;06BA afii57519;06D2 afii57534;06D5 afii57636;20AA afii57645;05BE afii57658;05C3 afii57664;05D0 afii57665;05D1 afii57666;05D2 afii57667;05D3 afii57668;05D4 afii57669;05D5 afii57670;05D6 afii57671;05D7 afii57672;05D8 afii57673;05D9 afii57674;05DA afii57675;05DB afii57676;05DC afii57677;05DD afii57678;05DE afii57679;05DF afii57680;05E0 afii57681;05E1 afii57682;05E2 afii57683;05E3 afii57684;05E4 afii57685;05E5 afii57686;05E6 afii57687;05E7 afii57688;05E8 afii57689;05E9 afii57690;05EA afii57694;FB2A afii57695;FB2B afii57700;FB4B afii57705;FB1F afii57716;05F0 afii57717;05F1 afii57718;05F2 afii57723;FB35 afii57793;05B4 afii57794;05B5 afii57795;05B6 afii57796;05BB afii57797;05B8 afii57798;05B7 afii57799;05B0 afii57800;05B2 afii57801;05B1 afii57802;05B3 afii57803;05C2 afii57804;05C1 afii57806;05B9 afii57807;05BC afii57839;05BD afii57841;05BF afii57842;05C0 afii57929;02BC afii61248;2105 afii61289;2113 afii61352;2116 afii61573;202C afii61574;202D afii61575;202E afii61664;200C afii63167;066D afii64937;02BD agrave;00E0 agujarati;0A85 agurmukhi;0A05 ahiragana;3042 ahookabove;1EA3 aibengali;0990 aibopomofo;311E aideva;0910 aiecyrillic;04D5 aigujarati;0A90 aigurmukhi;0A10 aimatragurmukhi;0A48 ainarabic;0639 ainfinalarabic;FECA aininitialarabic;FECB ainmedialarabic;FECC ainvertedbreve;0203 aivowelsignbengali;09C8 aivowelsigndeva;0948 aivowelsigngujarati;0AC8 akatakana;30A2 akatakanahalfwidth;FF71 akorean;314F alef;05D0 alefarabic;0627 alefdageshhebrew;FB30 aleffinalarabic;FE8E alefhamzaabovearabic;0623 alefhamzaabovefinalarabic;FE84 alefhamzabelowarabic;0625 alefhamzabelowfinalarabic;FE88 alefhebrew;05D0 aleflamedhebrew;FB4F alefmaddaabovearabic;0622 alefmaddaabovefinalarabic;FE82 alefmaksuraarabic;0649 alefmaksurafinalarabic;FEF0 alefmaksurainitialarabic;FEF3 alefmaksuramedialarabic;FEF4 alefpatahhebrew;FB2E alefqamatshebrew;FB2F aleph;2135 allequal;224C alpha;03B1 alphatonos;03AC amacron;0101 amonospace;FF41 ampersand;0026 ampersandmonospace;FF06 ampersandsmall;F726 amsquare;33C2 anbopomofo;3122 angbopomofo;3124 angkhankhuthai;0E5A angle;2220 anglebracketleft;3008 anglebracketleftvertical;FE3F anglebracketright;3009 anglebracketrightvertical;FE40 angleleft;2329 angleright;232A angstrom;212B anoteleia;0387 anudattadeva;0952 anusvarabengali;0982 anusvaradeva;0902 anusvaragujarati;0A82 aogonek;0105 apaatosquare;3300 aparen;249C apostrophearmenian;055A apostrophemod;02BC apple;F8FF approaches;2250 approxequal;2248 approxequalorimage;2252 approximatelyequal;2245 araeaekorean;318E araeakorean;318D arc;2312 arighthalfring;1E9A aring;00E5 aringacute;01FB aringbelow;1E01 arrowboth;2194 arrowdashdown;21E3 arrowdashleft;21E0 arrowdashright;21E2 arrowdashup;21E1 arrowdblboth;21D4 arrowdbldown;21D3 arrowdblleft;21D0 arrowdblright;21D2 arrowdblup;21D1 arrowdown;2193 arrowdownleft;2199 arrowdownright;2198 arrowdownwhite;21E9 arrowheaddownmod;02C5 arrowheadleftmod;02C2 arrowheadrightmod;02C3 arrowheadupmod;02C4 arrowhorizex;F8E7 arrowleft;2190 arrowleftdbl;21D0 arrowleftdblstroke;21CD arrowleftoverright;21C6 arrowleftwhite;21E6 arrowright;2192 arrowrightdblstroke;21CF arrowrightheavy;279E arrowrightoverleft;21C4 arrowrightwhite;21E8 arrowtableft;21E4 arrowtabright;21E5 arrowup;2191 arrowupdn;2195 arrowupdnbse;21A8 arrowupdownbase;21A8 arrowupleft;2196 arrowupleftofdown;21C5 arrowupright;2197 arrowupwhite;21E7 arrowvertex;F8E6 asciicircum;005E asciicircummonospace;FF3E asciitilde;007E asciitildemonospace;FF5E ascript;0251 ascriptturned;0252 asmallhiragana;3041 asmallkatakana;30A1 asmallkatakanahalfwidth;FF67 asterisk;002A asteriskaltonearabic;066D asteriskarabic;066D asteriskmath;2217 asteriskmonospace;FF0A asterisksmall;FE61 asterism;2042 asuperior;F6E9 asymptoticallyequal;2243 at;0040 atilde;00E3 atmonospace;FF20 atsmall;FE6B aturned;0250 aubengali;0994 aubopomofo;3120 audeva;0914 augujarati;0A94 augurmukhi;0A14 aulengthmarkbengali;09D7 aumatragurmukhi;0A4C auvowelsignbengali;09CC auvowelsigndeva;094C auvowelsigngujarati;0ACC avagrahadeva;093D aybarmenian;0561 ayin;05E2 ayinaltonehebrew;FB20 ayinhebrew;05E2 b;0062 babengali;09AC backslash;005C backslashmonospace;FF3C badeva;092C bagujarati;0AAC bagurmukhi;0A2C bahiragana;3070 bahtthai;0E3F bakatakana;30D0 bar;007C barmonospace;FF5C bbopomofo;3105 bcircle;24D1 bdotaccent;1E03 bdotbelow;1E05 beamedsixteenthnotes;266C because;2235 becyrillic;0431 beharabic;0628 behfinalarabic;FE90 behinitialarabic;FE91 behiragana;3079 behmedialarabic;FE92 behmeeminitialarabic;FC9F behmeemisolatedarabic;FC08 behnoonfinalarabic;FC6D bekatakana;30D9 benarmenian;0562 bet;05D1 beta;03B2 betasymbolgreek;03D0 betdagesh;FB31 betdageshhebrew;FB31 bethebrew;05D1 betrafehebrew;FB4C bhabengali;09AD bhadeva;092D bhagujarati;0AAD bhagurmukhi;0A2D bhook;0253 bihiragana;3073 bikatakana;30D3 bilabialclick;0298 bindigurmukhi;0A02 birusquare;3331 blackcircle;25CF blackdiamond;25C6 blackdownpointingtriangle;25BC blackleftpointingpointer;25C4 blackleftpointingtriangle;25C0 blacklenticularbracketleft;3010 blacklenticularbracketleftvertical;FE3B blacklenticularbracketright;3011 blacklenticularbracketrightvertical;FE3C blacklowerlefttriangle;25E3 blacklowerrighttriangle;25E2 blackrectangle;25AC blackrightpointingpointer;25BA blackrightpointingtriangle;25B6 blacksmallsquare;25AA blacksmilingface;263B blacksquare;25A0 blackstar;2605 blackupperlefttriangle;25E4 blackupperrighttriangle;25E5 blackuppointingsmalltriangle;25B4 blackuppointingtriangle;25B2 blank;2423 blinebelow;1E07 block;2588 bmonospace;FF42 bobaimaithai;0E1A bohiragana;307C bokatakana;30DC bparen;249D bqsquare;33C3 braceex;F8F4 braceleft;007B braceleftbt;F8F3 braceleftmid;F8F2 braceleftmonospace;FF5B braceleftsmall;FE5B bracelefttp;F8F1 braceleftvertical;FE37 braceright;007D bracerightbt;F8FE bracerightmid;F8FD bracerightmonospace;FF5D bracerightsmall;FE5C bracerighttp;F8FC bracerightvertical;FE38 bracketleft;005B bracketleftbt;F8F0 bracketleftex;F8EF bracketleftmonospace;FF3B bracketlefttp;F8EE bracketright;005D bracketrightbt;F8FB bracketrightex;F8FA bracketrightmonospace;FF3D bracketrighttp;F8F9 breve;02D8 brevebelowcmb;032E brevecmb;0306 breveinvertedbelowcmb;032F breveinvertedcmb;0311 breveinverteddoublecmb;0361 bridgebelowcmb;032A bridgeinvertedbelowcmb;033A brokenbar;00A6 bstroke;0180 bsuperior;F6EA btopbar;0183 buhiragana;3076 bukatakana;30D6 bullet;2022 bulletinverse;25D8 bulletoperator;2219 bullseye;25CE c;0063 caarmenian;056E cabengali;099A cacute;0107 cadeva;091A cagujarati;0A9A cagurmukhi;0A1A calsquare;3388 candrabindubengali;0981 candrabinducmb;0310 candrabindudeva;0901 candrabindugujarati;0A81 capslock;21EA careof;2105 caron;02C7 caronbelowcmb;032C caroncmb;030C carriagereturn;21B5 cbopomofo;3118 ccaron;010D ccedilla;00E7 ccedillaacute;1E09 ccircle;24D2 ccircumflex;0109 ccurl;0255 cdot;010B cdotaccent;010B cdsquare;33C5 cedilla;00B8 cedillacmb;0327 cent;00A2 centigrade;2103 centinferior;F6DF centmonospace;FFE0 centoldstyle;F7A2 centsuperior;F6E0 chaarmenian;0579 chabengali;099B chadeva;091B chagujarati;0A9B chagurmukhi;0A1B chbopomofo;3114 cheabkhasiancyrillic;04BD checkmark;2713 checyrillic;0447 chedescenderabkhasiancyrillic;04BF chedescendercyrillic;04B7 chedieresiscyrillic;04F5 cheharmenian;0573 chekhakassiancyrillic;04CC cheverticalstrokecyrillic;04B9 chi;03C7 chieuchacirclekorean;3277 chieuchaparenkorean;3217 chieuchcirclekorean;3269 chieuchkorean;314A chieuchparenkorean;3209 chochangthai;0E0A chochanthai;0E08 chochingthai;0E09 chochoethai;0E0C chook;0188 cieucacirclekorean;3276 cieucaparenkorean;3216 cieuccirclekorean;3268 cieuckorean;3148 cieucparenkorean;3208 cieucuparenkorean;321C circle;25CB circlemultiply;2297 circleot;2299 circleplus;2295 circlepostalmark;3036 circlewithlefthalfblack;25D0 circlewithrighthalfblack;25D1 circumflex;02C6 circumflexbelowcmb;032D circumflexcmb;0302 clear;2327 clickalveolar;01C2 clickdental;01C0 clicklateral;01C1 clickretroflex;01C3 club;2663 clubsuitblack;2663 clubsuitwhite;2667 cmcubedsquare;33A4 cmonospace;FF43 cmsquaredsquare;33A0 coarmenian;0581 colon;003A colonmonetary;20A1 colonmonospace;FF1A colonsign;20A1 colonsmall;FE55 colontriangularhalfmod;02D1 colontriangularmod;02D0 comma;002C commaabovecmb;0313 commaaboverightcmb;0315 commaaccent;F6C3 commaarabic;060C commaarmenian;055D commainferior;F6E1 commamonospace;FF0C commareversedabovecmb;0314 commareversedmod;02BD commasmall;FE50 commasuperior;F6E2 commaturnedabovecmb;0312 commaturnedmod;02BB compass;263C congruent;2245 contourintegral;222E control;2303 controlACK;0006 controlBEL;0007 controlBS;0008 controlCAN;0018 controlCR;000D controlDC1;0011 controlDC2;0012 controlDC3;0013 controlDC4;0014 controlDEL;007F controlDLE;0010 controlEM;0019 controlENQ;0005 controlEOT;0004 controlESC;001B controlETB;0017 controlETX;0003 controlFF;000C controlFS;001C controlGS;001D controlHT;0009 controlLF;000A controlNAK;0015 controlRS;001E controlSI;000F controlSO;000E controlSOT;0002 controlSTX;0001 controlSUB;001A controlSYN;0016 controlUS;001F controlVT;000B copyright;00A9 copyrightsans;F8E9 copyrightserif;F6D9 cornerbracketleft;300C cornerbracketlefthalfwidth;FF62 cornerbracketleftvertical;FE41 cornerbracketright;300D cornerbracketrighthalfwidth;FF63 cornerbracketrightvertical;FE42 corporationsquare;337F cosquare;33C7 coverkgsquare;33C6 cparen;249E cruzeiro;20A2 cstretched;0297 curlyand;22CF curlyor;22CE currency;00A4 cyrBreve;F6D1 cyrFlex;F6D2 cyrbreve;F6D4 cyrflex;F6D5 d;0064 daarmenian;0564 dabengali;09A6 dadarabic;0636 dadeva;0926 dadfinalarabic;FEBE dadinitialarabic;FEBF dadmedialarabic;FEC0 dagesh;05BC dageshhebrew;05BC dagger;2020 daggerdbl;2021 dagujarati;0AA6 dagurmukhi;0A26 dahiragana;3060 dakatakana;30C0 dalarabic;062F dalet;05D3 daletdagesh;FB33 daletdageshhebrew;FB33 dalethatafpatah;05D3 05B2 dalethatafpatahhebrew;05D3 05B2 dalethatafsegol;05D3 05B1 dalethatafsegolhebrew;05D3 05B1 dalethebrew;05D3 dalethiriq;05D3 05B4 dalethiriqhebrew;05D3 05B4 daletholam;05D3 05B9 daletholamhebrew;05D3 05B9 daletpatah;05D3 05B7 daletpatahhebrew;05D3 05B7 daletqamats;05D3 05B8 daletqamatshebrew;05D3 05B8 daletqubuts;05D3 05BB daletqubutshebrew;05D3 05BB daletsegol;05D3 05B6 daletsegolhebrew;05D3 05B6 daletsheva;05D3 05B0 daletshevahebrew;05D3 05B0 dalettsere;05D3 05B5 dalettserehebrew;05D3 05B5 dalfinalarabic;FEAA dammaarabic;064F dammalowarabic;064F dammatanaltonearabic;064C dammatanarabic;064C danda;0964 dargahebrew;05A7 dargalefthebrew;05A7 dasiapneumatacyrilliccmb;0485 dblGrave;F6D3 dblanglebracketleft;300A dblanglebracketleftvertical;FE3D dblanglebracketright;300B dblanglebracketrightvertical;FE3E dblarchinvertedbelowcmb;032B dblarrowleft;21D4 dblarrowright;21D2 dbldanda;0965 dblgrave;F6D6 dblgravecmb;030F dblintegral;222C dbllowline;2017 dbllowlinecmb;0333 dbloverlinecmb;033F dblprimemod;02BA dblverticalbar;2016 dblverticallineabovecmb;030E dbopomofo;3109 dbsquare;33C8 dcaron;010F dcedilla;1E11 dcircle;24D3 dcircumflexbelow;1E13 dcroat;0111 ddabengali;09A1 ddadeva;0921 ddagujarati;0AA1 ddagurmukhi;0A21 ddalarabic;0688 ddalfinalarabic;FB89 dddhadeva;095C ddhabengali;09A2 ddhadeva;0922 ddhagujarati;0AA2 ddhagurmukhi;0A22 ddotaccent;1E0B ddotbelow;1E0D decimalseparatorarabic;066B decimalseparatorpersian;066B decyrillic;0434 degree;00B0 dehihebrew;05AD dehiragana;3067 deicoptic;03EF dekatakana;30C7 deleteleft;232B deleteright;2326 delta;03B4 deltaturned;018D denominatorminusonenumeratorbengali;09F8 dezh;02A4 dhabengali;09A7 dhadeva;0927 dhagujarati;0AA7 dhagurmukhi;0A27 dhook;0257 dialytikatonos;0385 dialytikatonoscmb;0344 diamond;2666 diamondsuitwhite;2662 dieresis;00A8 dieresisacute;F6D7 dieresisbelowcmb;0324 dieresiscmb;0308 dieresisgrave;F6D8 dieresistonos;0385 dihiragana;3062 dikatakana;30C2 dittomark;3003 divide;00F7 divides;2223 divisionslash;2215 djecyrillic;0452 dkshade;2593 dlinebelow;1E0F dlsquare;3397 dmacron;0111 dmonospace;FF44 dnblock;2584 dochadathai;0E0E dodekthai;0E14 dohiragana;3069 dokatakana;30C9 dollar;0024 dollarinferior;F6E3 dollarmonospace;FF04 dollaroldstyle;F724 dollarsmall;FE69 dollarsuperior;F6E4 dong;20AB dorusquare;3326 dotaccent;02D9 dotaccentcmb;0307 dotbelowcmb;0323 dotbelowcomb;0323 dotkatakana;30FB dotlessi;0131 dotlessj;F6BE dotlessjstrokehook;0284 dotmath;22C5 dottedcircle;25CC doubleyodpatah;FB1F doubleyodpatahhebrew;FB1F downtackbelowcmb;031E downtackmod;02D5 dparen;249F dsuperior;F6EB dtail;0256 dtopbar;018C duhiragana;3065 dukatakana;30C5 dz;01F3 dzaltone;02A3 dzcaron;01C6 dzcurl;02A5 dzeabkhasiancyrillic;04E1 dzecyrillic;0455 dzhecyrillic;045F e;0065 eacute;00E9 earth;2641 ebengali;098F ebopomofo;311C ebreve;0115 ecandradeva;090D ecandragujarati;0A8D ecandravowelsigndeva;0945 ecandravowelsigngujarati;0AC5 ecaron;011B ecedillabreve;1E1D echarmenian;0565 echyiwnarmenian;0587 ecircle;24D4 ecircumflex;00EA ecircumflexacute;1EBF ecircumflexbelow;1E19 ecircumflexdotbelow;1EC7 ecircumflexgrave;1EC1 ecircumflexhookabove;1EC3 ecircumflextilde;1EC5 ecyrillic;0454 edblgrave;0205 edeva;090F edieresis;00EB edot;0117 edotaccent;0117 edotbelow;1EB9 eegurmukhi;0A0F eematragurmukhi;0A47 efcyrillic;0444 egrave;00E8 egujarati;0A8F eharmenian;0567 ehbopomofo;311D ehiragana;3048 ehookabove;1EBB eibopomofo;311F eight;0038 eightarabic;0668 eightbengali;09EE eightcircle;2467 eightcircleinversesansserif;2791 eightdeva;096E eighteencircle;2471 eighteenparen;2485 eighteenperiod;2499 eightgujarati;0AEE eightgurmukhi;0A6E eighthackarabic;0668 eighthangzhou;3028 eighthnotebeamed;266B eightideographicparen;3227 eightinferior;2088 eightmonospace;FF18 eightoldstyle;F738 eightparen;247B eightperiod;248F eightpersian;06F8 eightroman;2177 eightsuperior;2078 eightthai;0E58 einvertedbreve;0207 eiotifiedcyrillic;0465 ekatakana;30A8 ekatakanahalfwidth;FF74 ekonkargurmukhi;0A74 ekorean;3154 elcyrillic;043B element;2208 elevencircle;246A elevenparen;247E elevenperiod;2492 elevenroman;217A ellipsis;2026 ellipsisvertical;22EE emacron;0113 emacronacute;1E17 emacrongrave;1E15 emcyrillic;043C emdash;2014 emdashvertical;FE31 emonospace;FF45 emphasismarkarmenian;055B emptyset;2205 enbopomofo;3123 encyrillic;043D endash;2013 endashvertical;FE32 endescendercyrillic;04A3 eng;014B engbopomofo;3125 enghecyrillic;04A5 enhookcyrillic;04C8 enspace;2002 eogonek;0119 eokorean;3153 eopen;025B eopenclosed;029A eopenreversed;025C eopenreversedclosed;025E eopenreversedhook;025D eparen;24A0 epsilon;03B5 epsilontonos;03AD equal;003D equalmonospace;FF1D equalsmall;FE66 equalsuperior;207C equivalence;2261 erbopomofo;3126 ercyrillic;0440 ereversed;0258 ereversedcyrillic;044D escyrillic;0441 esdescendercyrillic;04AB esh;0283 eshcurl;0286 eshortdeva;090E eshortvowelsigndeva;0946 eshreversedloop;01AA eshsquatreversed;0285 esmallhiragana;3047 esmallkatakana;30A7 esmallkatakanahalfwidth;FF6A estimated;212E esuperior;F6EC eta;03B7 etarmenian;0568 etatonos;03AE eth;00F0 etilde;1EBD etildebelow;1E1B etnahtafoukhhebrew;0591 etnahtafoukhlefthebrew;0591 etnahtahebrew;0591 etnahtalefthebrew;0591 eturned;01DD eukorean;3161 euro;20AC evowelsignbengali;09C7 evowelsigndeva;0947 evowelsigngujarati;0AC7 exclam;0021 exclamarmenian;055C exclamdbl;203C exclamdown;00A1 exclamdownsmall;F7A1 exclammonospace;FF01 exclamsmall;F721 existential;2203 ezh;0292 ezhcaron;01EF ezhcurl;0293 ezhreversed;01B9 ezhtail;01BA f;0066 fadeva;095E fagurmukhi;0A5E fahrenheit;2109 fathaarabic;064E fathalowarabic;064E fathatanarabic;064B fbopomofo;3108 fcircle;24D5 fdotaccent;1E1F feharabic;0641 feharmenian;0586 fehfinalarabic;FED2 fehinitialarabic;FED3 fehmedialarabic;FED4 feicoptic;03E5 female;2640 ff;FB00 ffi;FB03 ffl;FB04 fi;FB01 fifteencircle;246E fifteenparen;2482 fifteenperiod;2496 figuredash;2012 filledbox;25A0 filledrect;25AC finalkaf;05DA finalkafdagesh;FB3A finalkafdageshhebrew;FB3A finalkafhebrew;05DA finalkafqamats;05DA 05B8 finalkafqamatshebrew;05DA 05B8 finalkafsheva;05DA 05B0 finalkafshevahebrew;05DA 05B0 finalmem;05DD finalmemhebrew;05DD finalnun;05DF finalnunhebrew;05DF finalpe;05E3 finalpehebrew;05E3 finaltsadi;05E5 finaltsadihebrew;05E5 firsttonechinese;02C9 fisheye;25C9 fitacyrillic;0473 five;0035 fivearabic;0665 fivebengali;09EB fivecircle;2464 fivecircleinversesansserif;278E fivedeva;096B fiveeighths;215D fivegujarati;0AEB fivegurmukhi;0A6B fivehackarabic;0665 fivehangzhou;3025 fiveideographicparen;3224 fiveinferior;2085 fivemonospace;FF15 fiveoldstyle;F735 fiveparen;2478 fiveperiod;248C fivepersian;06F5 fiveroman;2174 fivesuperior;2075 fivethai;0E55 fl;FB02 florin;0192 fmonospace;FF46 fmsquare;3399 fofanthai;0E1F fofathai;0E1D fongmanthai;0E4F forall;2200 four;0034 fourarabic;0664 fourbengali;09EA fourcircle;2463 fourcircleinversesansserif;278D fourdeva;096A fourgujarati;0AEA fourgurmukhi;0A6A fourhackarabic;0664 fourhangzhou;3024 fourideographicparen;3223 fourinferior;2084 fourmonospace;FF14 fournumeratorbengali;09F7 fouroldstyle;F734 fourparen;2477 fourperiod;248B fourpersian;06F4 fourroman;2173 foursuperior;2074 fourteencircle;246D fourteenparen;2481 fourteenperiod;2495 fourthai;0E54 fourthtonechinese;02CB fparen;24A1 fraction;2044 franc;20A3 g;0067 gabengali;0997 gacute;01F5 gadeva;0917 gafarabic;06AF gaffinalarabic;FB93 gafinitialarabic;FB94 gafmedialarabic;FB95 gagujarati;0A97 gagurmukhi;0A17 gahiragana;304C gakatakana;30AC gamma;03B3 gammalatinsmall;0263 gammasuperior;02E0 gangiacoptic;03EB gbopomofo;310D gbreve;011F gcaron;01E7 gcedilla;0123 gcircle;24D6 gcircumflex;011D gcommaaccent;0123 gdot;0121 gdotaccent;0121 gecyrillic;0433 gehiragana;3052 gekatakana;30B2 geometricallyequal;2251 gereshaccenthebrew;059C gereshhebrew;05F3 gereshmuqdamhebrew;059D germandbls;00DF gershayimaccenthebrew;059E gershayimhebrew;05F4 getamark;3013 ghabengali;0998 ghadarmenian;0572 ghadeva;0918 ghagujarati;0A98 ghagurmukhi;0A18 ghainarabic;063A ghainfinalarabic;FECE ghaininitialarabic;FECF ghainmedialarabic;FED0 ghemiddlehookcyrillic;0495 ghestrokecyrillic;0493 gheupturncyrillic;0491 ghhadeva;095A ghhagurmukhi;0A5A ghook;0260 ghzsquare;3393 gihiragana;304E gikatakana;30AE gimarmenian;0563 gimel;05D2 gimeldagesh;FB32 gimeldageshhebrew;FB32 gimelhebrew;05D2 gjecyrillic;0453 glottalinvertedstroke;01BE glottalstop;0294 glottalstopinverted;0296 glottalstopmod;02C0 glottalstopreversed;0295 glottalstopreversedmod;02C1 glottalstopreversedsuperior;02E4 glottalstopstroke;02A1 glottalstopstrokereversed;02A2 gmacron;1E21 gmonospace;FF47 gohiragana;3054 gokatakana;30B4 gparen;24A2 gpasquare;33AC gradient;2207 grave;0060 gravebelowcmb;0316 gravecmb;0300 gravecomb;0300 gravedeva;0953 gravelowmod;02CE gravemonospace;FF40 gravetonecmb;0340 greater;003E greaterequal;2265 greaterequalorless;22DB greatermonospace;FF1E greaterorequivalent;2273 greaterorless;2277 greateroverequal;2267 greatersmall;FE65 gscript;0261 gstroke;01E5 guhiragana;3050 guillemotleft;00AB guillemotright;00BB guilsinglleft;2039 guilsinglright;203A gukatakana;30B0 guramusquare;3318 gysquare;33C9 h;0068 haabkhasiancyrillic;04A9 haaltonearabic;06C1 habengali;09B9 hadescendercyrillic;04B3 hadeva;0939 hagujarati;0AB9 hagurmukhi;0A39 haharabic;062D hahfinalarabic;FEA2 hahinitialarabic;FEA3 hahiragana;306F hahmedialarabic;FEA4 haitusquare;332A hakatakana;30CF hakatakanahalfwidth;FF8A halantgurmukhi;0A4D hamzaarabic;0621 hamzadammaarabic;0621 064F hamzadammatanarabic;0621 064C hamzafathaarabic;0621 064E hamzafathatanarabic;0621 064B hamzalowarabic;0621 hamzalowkasraarabic;0621 0650 hamzalowkasratanarabic;0621 064D hamzasukunarabic;0621 0652 hangulfiller;3164 hardsigncyrillic;044A harpoonleftbarbup;21BC harpoonrightbarbup;21C0 hasquare;33CA hatafpatah;05B2 hatafpatah16;05B2 hatafpatah23;05B2 hatafpatah2f;05B2 hatafpatahhebrew;05B2 hatafpatahnarrowhebrew;05B2 hatafpatahquarterhebrew;05B2 hatafpatahwidehebrew;05B2 hatafqamats;05B3 hatafqamats1b;05B3 hatafqamats28;05B3 hatafqamats34;05B3 hatafqamatshebrew;05B3 hatafqamatsnarrowhebrew;05B3 hatafqamatsquarterhebrew;05B3 hatafqamatswidehebrew;05B3 hatafsegol;05B1 hatafsegol17;05B1 hatafsegol24;05B1 hatafsegol30;05B1 hatafsegolhebrew;05B1 hatafsegolnarrowhebrew;05B1 hatafsegolquarterhebrew;05B1 hatafsegolwidehebrew;05B1 hbar;0127 hbopomofo;310F hbrevebelow;1E2B hcedilla;1E29 hcircle;24D7 hcircumflex;0125 hdieresis;1E27 hdotaccent;1E23 hdotbelow;1E25 he;05D4 heart;2665 heartsuitblack;2665 heartsuitwhite;2661 hedagesh;FB34 hedageshhebrew;FB34 hehaltonearabic;06C1 heharabic;0647 hehebrew;05D4 hehfinalaltonearabic;FBA7 hehfinalalttwoarabic;FEEA hehfinalarabic;FEEA hehhamzaabovefinalarabic;FBA5 hehhamzaaboveisolatedarabic;FBA4 hehinitialaltonearabic;FBA8 hehinitialarabic;FEEB hehiragana;3078 hehmedialaltonearabic;FBA9 hehmedialarabic;FEEC heiseierasquare;337B hekatakana;30D8 hekatakanahalfwidth;FF8D hekutaarusquare;3336 henghook;0267 herutusquare;3339 het;05D7 hethebrew;05D7 hhook;0266 hhooksuperior;02B1 hieuhacirclekorean;327B hieuhaparenkorean;321B hieuhcirclekorean;326D hieuhkorean;314E hieuhparenkorean;320D hihiragana;3072 hikatakana;30D2 hikatakanahalfwidth;FF8B hiriq;05B4 hiriq14;05B4 hiriq21;05B4 hiriq2d;05B4 hiriqhebrew;05B4 hiriqnarrowhebrew;05B4 hiriqquarterhebrew;05B4 hiriqwidehebrew;05B4 hlinebelow;1E96 hmonospace;FF48 hoarmenian;0570 hohipthai;0E2B hohiragana;307B hokatakana;30DB hokatakanahalfwidth;FF8E holam;05B9 holam19;05B9 holam26;05B9 holam32;05B9 holamhebrew;05B9 holamnarrowhebrew;05B9 holamquarterhebrew;05B9 holamwidehebrew;05B9 honokhukthai;0E2E hookabovecomb;0309 hookcmb;0309 hookpalatalizedbelowcmb;0321 hookretroflexbelowcmb;0322 hoonsquare;3342 horicoptic;03E9 horizontalbar;2015 horncmb;031B hotsprings;2668 house;2302 hparen;24A3 hsuperior;02B0 hturned;0265 huhiragana;3075 huiitosquare;3333 hukatakana;30D5 hukatakanahalfwidth;FF8C hungarumlaut;02DD hungarumlautcmb;030B hv;0195 hyphen;002D hypheninferior;F6E5 hyphenmonospace;FF0D hyphensmall;FE63 hyphensuperior;F6E6 hyphentwo;2010 i;0069 iacute;00ED iacyrillic;044F ibengali;0987 ibopomofo;3127 ibreve;012D icaron;01D0 icircle;24D8 icircumflex;00EE icyrillic;0456 idblgrave;0209 ideographearthcircle;328F ideographfirecircle;328B ideographicallianceparen;323F ideographiccallparen;323A ideographiccentrecircle;32A5 ideographicclose;3006 ideographiccomma;3001 ideographiccommaleft;FF64 ideographiccongratulationparen;3237 ideographiccorrectcircle;32A3 ideographicearthparen;322F ideographicenterpriseparen;323D ideographicexcellentcircle;329D ideographicfestivalparen;3240 ideographicfinancialcircle;3296 ideographicfinancialparen;3236 ideographicfireparen;322B ideographichaveparen;3232 ideographichighcircle;32A4 ideographiciterationmark;3005 ideographiclaborcircle;3298 ideographiclaborparen;3238 ideographicleftcircle;32A7 ideographiclowcircle;32A6 ideographicmedicinecircle;32A9 ideographicmetalparen;322E ideographicmoonparen;322A ideographicnameparen;3234 ideographicperiod;3002 ideographicprintcircle;329E ideographicreachparen;3243 ideographicrepresentparen;3239 ideographicresourceparen;323E ideographicrightcircle;32A8 ideographicsecretcircle;3299 ideographicselfparen;3242 ideographicsocietyparen;3233 ideographicspace;3000 ideographicspecialparen;3235 ideographicstockparen;3231 ideographicstudyparen;323B ideographicsunparen;3230 ideographicsuperviseparen;323C ideographicwaterparen;322C ideographicwoodparen;322D ideographiczero;3007 ideographmetalcircle;328E ideographmooncircle;328A ideographnamecircle;3294 ideographsuncircle;3290 ideographwatercircle;328C ideographwoodcircle;328D ideva;0907 idieresis;00EF idieresisacute;1E2F idieresiscyrillic;04E5 idotbelow;1ECB iebrevecyrillic;04D7 iecyrillic;0435 ieungacirclekorean;3275 ieungaparenkorean;3215 ieungcirclekorean;3267 ieungkorean;3147 ieungparenkorean;3207 igrave;00EC igujarati;0A87 igurmukhi;0A07 ihiragana;3044 ihookabove;1EC9 iibengali;0988 iicyrillic;0438 iideva;0908 iigujarati;0A88 iigurmukhi;0A08 iimatragurmukhi;0A40 iinvertedbreve;020B iishortcyrillic;0439 iivowelsignbengali;09C0 iivowelsigndeva;0940 iivowelsigngujarati;0AC0 ij;0133 ikatakana;30A4 ikatakanahalfwidth;FF72 ikorean;3163 ilde;02DC iluyhebrew;05AC imacron;012B imacroncyrillic;04E3 imageorapproximatelyequal;2253 imatragurmukhi;0A3F imonospace;FF49 increment;2206 infinity;221E iniarmenian;056B integral;222B integralbottom;2321 integralbt;2321 integralex;F8F5 integraltop;2320 integraltp;2320 intersection;2229 intisquare;3305 invbullet;25D8 invcircle;25D9 invsmileface;263B iocyrillic;0451 iogonek;012F iota;03B9 iotadieresis;03CA iotadieresistonos;0390 iotalatin;0269 iotatonos;03AF iparen;24A4 irigurmukhi;0A72 ismallhiragana;3043 ismallkatakana;30A3 ismallkatakanahalfwidth;FF68 issharbengali;09FA istroke;0268 isuperior;F6ED iterationhiragana;309D iterationkatakana;30FD itilde;0129 itildebelow;1E2D iubopomofo;3129 iucyrillic;044E ivowelsignbengali;09BF ivowelsigndeva;093F ivowelsigngujarati;0ABF izhitsacyrillic;0475 izhitsadblgravecyrillic;0477 j;006A jaarmenian;0571 jabengali;099C jadeva;091C jagujarati;0A9C jagurmukhi;0A1C jbopomofo;3110 jcaron;01F0 jcircle;24D9 jcircumflex;0135 jcrossedtail;029D jdotlessstroke;025F jecyrillic;0458 jeemarabic;062C jeemfinalarabic;FE9E jeeminitialarabic;FE9F jeemmedialarabic;FEA0 jeharabic;0698 jehfinalarabic;FB8B jhabengali;099D jhadeva;091D jhagujarati;0A9D jhagurmukhi;0A1D jheharmenian;057B jis;3004 jmonospace;FF4A jparen;24A5 jsuperior;02B2 k;006B kabashkircyrillic;04A1 kabengali;0995 kacute;1E31 kacyrillic;043A kadescendercyrillic;049B kadeva;0915 kaf;05DB kafarabic;0643 kafdagesh;FB3B kafdageshhebrew;FB3B kaffinalarabic;FEDA kafhebrew;05DB kafinitialarabic;FEDB kafmedialarabic;FEDC kafrafehebrew;FB4D kagujarati;0A95 kagurmukhi;0A15 kahiragana;304B kahookcyrillic;04C4 kakatakana;30AB kakatakanahalfwidth;FF76 kappa;03BA kappasymbolgreek;03F0 kapyeounmieumkorean;3171 kapyeounphieuphkorean;3184 kapyeounpieupkorean;3178 kapyeounssangpieupkorean;3179 karoriisquare;330D kashidaautoarabic;0640 kashidaautonosidebearingarabic;0640 kasmallkatakana;30F5 kasquare;3384 kasraarabic;0650 kasratanarabic;064D kastrokecyrillic;049F katahiraprolongmarkhalfwidth;FF70 kaverticalstrokecyrillic;049D kbopomofo;310E kcalsquare;3389 kcaron;01E9 kcedilla;0137 kcircle;24DA kcommaaccent;0137 kdotbelow;1E33 keharmenian;0584 kehiragana;3051 kekatakana;30B1 kekatakanahalfwidth;FF79 kenarmenian;056F kesmallkatakana;30F6 kgreenlandic;0138 khabengali;0996 khacyrillic;0445 khadeva;0916 khagujarati;0A96 khagurmukhi;0A16 khaharabic;062E khahfinalarabic;FEA6 khahinitialarabic;FEA7 khahmedialarabic;FEA8 kheicoptic;03E7 khhadeva;0959 khhagurmukhi;0A59 khieukhacirclekorean;3278 khieukhaparenkorean;3218 khieukhcirclekorean;326A khieukhkorean;314B khieukhparenkorean;320A khokhaithai;0E02 khokhonthai;0E05 khokhuatthai;0E03 khokhwaithai;0E04 khomutthai;0E5B khook;0199 khorakhangthai;0E06 khzsquare;3391 kihiragana;304D kikatakana;30AD kikatakanahalfwidth;FF77 kiroguramusquare;3315 kiromeetorusquare;3316 kirosquare;3314 kiyeokacirclekorean;326E kiyeokaparenkorean;320E kiyeokcirclekorean;3260 kiyeokkorean;3131 kiyeokparenkorean;3200 kiyeoksioskorean;3133 kjecyrillic;045C klinebelow;1E35 klsquare;3398 kmcubedsquare;33A6 kmonospace;FF4B kmsquaredsquare;33A2 kohiragana;3053 kohmsquare;33C0 kokaithai;0E01 kokatakana;30B3 kokatakanahalfwidth;FF7A kooposquare;331E koppacyrillic;0481 koreanstandardsymbol;327F koroniscmb;0343 kparen;24A6 kpasquare;33AA ksicyrillic;046F ktsquare;33CF kturned;029E kuhiragana;304F kukatakana;30AF kukatakanahalfwidth;FF78 kvsquare;33B8 kwsquare;33BE l;006C labengali;09B2 lacute;013A ladeva;0932 lagujarati;0AB2 lagurmukhi;0A32 lakkhangyaothai;0E45 lamaleffinalarabic;FEFC lamalefhamzaabovefinalarabic;FEF8 lamalefhamzaaboveisolatedarabic;FEF7 lamalefhamzabelowfinalarabic;FEFA lamalefhamzabelowisolatedarabic;FEF9 lamalefisolatedarabic;FEFB lamalefmaddaabovefinalarabic;FEF6 lamalefmaddaaboveisolatedarabic;FEF5 lamarabic;0644 lambda;03BB lambdastroke;019B lamed;05DC lameddagesh;FB3C lameddageshhebrew;FB3C lamedhebrew;05DC lamedholam;05DC 05B9 lamedholamdagesh;05DC 05B9 05BC lamedholamdageshhebrew;05DC 05B9 05BC lamedholamhebrew;05DC 05B9 lamfinalarabic;FEDE lamhahinitialarabic;FCCA laminitialarabic;FEDF lamjeeminitialarabic;FCC9 lamkhahinitialarabic;FCCB lamlamhehisolatedarabic;FDF2 lammedialarabic;FEE0 lammeemhahinitialarabic;FD88 lammeeminitialarabic;FCCC lammeemjeeminitialarabic;FEDF FEE4 FEA0 lammeemkhahinitialarabic;FEDF FEE4 FEA8 largecircle;25EF lbar;019A lbelt;026C lbopomofo;310C lcaron;013E lcedilla;013C lcircle;24DB lcircumflexbelow;1E3D lcommaaccent;013C ldot;0140 ldotaccent;0140 ldotbelow;1E37 ldotbelowmacron;1E39 leftangleabovecmb;031A lefttackbelowcmb;0318 less;003C lessequal;2264 lessequalorgreater;22DA lessmonospace;FF1C lessorequivalent;2272 lessorgreater;2276 lessoverequal;2266 lesssmall;FE64 lezh;026E lfblock;258C lhookretroflex;026D lira;20A4 liwnarmenian;056C lj;01C9 ljecyrillic;0459 ll;F6C0 lladeva;0933 llagujarati;0AB3 llinebelow;1E3B llladeva;0934 llvocalicbengali;09E1 llvocalicdeva;0961 llvocalicvowelsignbengali;09E3 llvocalicvowelsigndeva;0963 lmiddletilde;026B lmonospace;FF4C lmsquare;33D0 lochulathai;0E2C logicaland;2227 logicalnot;00AC logicalnotreversed;2310 logicalor;2228 lolingthai;0E25 longs;017F lowlinecenterline;FE4E lowlinecmb;0332 lowlinedashed;FE4D lozenge;25CA lparen;24A7 lslash;0142 lsquare;2113 lsuperior;F6EE ltshade;2591 luthai;0E26 lvocalicbengali;098C lvocalicdeva;090C lvocalicvowelsignbengali;09E2 lvocalicvowelsigndeva;0962 lxsquare;33D3 m;006D mabengali;09AE macron;00AF macronbelowcmb;0331 macroncmb;0304 macronlowmod;02CD macronmonospace;FFE3 macute;1E3F madeva;092E magujarati;0AAE magurmukhi;0A2E mahapakhhebrew;05A4 mahapakhlefthebrew;05A4 mahiragana;307E maichattawalowleftthai;F895 maichattawalowrightthai;F894 maichattawathai;0E4B maichattawaupperleftthai;F893 maieklowleftthai;F88C maieklowrightthai;F88B maiekthai;0E48 maiekupperleftthai;F88A maihanakatleftthai;F884 maihanakatthai;0E31 maitaikhuleftthai;F889 maitaikhuthai;0E47 maitholowleftthai;F88F maitholowrightthai;F88E maithothai;0E49 maithoupperleftthai;F88D maitrilowleftthai;F892 maitrilowrightthai;F891 maitrithai;0E4A maitriupperleftthai;F890 maiyamokthai;0E46 makatakana;30DE makatakanahalfwidth;FF8F male;2642 mansyonsquare;3347 maqafhebrew;05BE mars;2642 masoracirclehebrew;05AF masquare;3383 mbopomofo;3107 mbsquare;33D4 mcircle;24DC mcubedsquare;33A5 mdotaccent;1E41 mdotbelow;1E43 meemarabic;0645 meemfinalarabic;FEE2 meeminitialarabic;FEE3 meemmedialarabic;FEE4 meemmeeminitialarabic;FCD1 meemmeemisolatedarabic;FC48 meetorusquare;334D mehiragana;3081 meizierasquare;337E mekatakana;30E1 mekatakanahalfwidth;FF92 mem;05DE memdagesh;FB3E memdageshhebrew;FB3E memhebrew;05DE menarmenian;0574 merkhahebrew;05A5 merkhakefulahebrew;05A6 merkhakefulalefthebrew;05A6 merkhalefthebrew;05A5 mhook;0271 mhzsquare;3392 middledotkatakanahalfwidth;FF65 middot;00B7 mieumacirclekorean;3272 mieumaparenkorean;3212 mieumcirclekorean;3264 mieumkorean;3141 mieumpansioskorean;3170 mieumparenkorean;3204 mieumpieupkorean;316E mieumsioskorean;316F mihiragana;307F mikatakana;30DF mikatakanahalfwidth;FF90 minus;2212 minusbelowcmb;0320 minuscircle;2296 minusmod;02D7 minusplus;2213 minute;2032 miribaarusquare;334A mirisquare;3349 mlonglegturned;0270 mlsquare;3396 mmcubedsquare;33A3 mmonospace;FF4D mmsquaredsquare;339F mohiragana;3082 mohmsquare;33C1 mokatakana;30E2 mokatakanahalfwidth;FF93 molsquare;33D6 momathai;0E21 moverssquare;33A7 moverssquaredsquare;33A8 mparen;24A8 mpasquare;33AB mssquare;33B3 msuperior;F6EF mturned;026F mu;00B5 mu1;00B5 muasquare;3382 muchgreater;226B muchless;226A mufsquare;338C mugreek;03BC mugsquare;338D muhiragana;3080 mukatakana;30E0 mukatakanahalfwidth;FF91 mulsquare;3395 multiply;00D7 mumsquare;339B munahhebrew;05A3 munahlefthebrew;05A3 musicalnote;266A musicalnotedbl;266B musicflatsign;266D musicsharpsign;266F mussquare;33B2 muvsquare;33B6 muwsquare;33BC mvmegasquare;33B9 mvsquare;33B7 mwmegasquare;33BF mwsquare;33BD n;006E nabengali;09A8 nabla;2207 nacute;0144 nadeva;0928 nagujarati;0AA8 nagurmukhi;0A28 nahiragana;306A nakatakana;30CA nakatakanahalfwidth;FF85 napostrophe;0149 nasquare;3381 nbopomofo;310B nbspace;00A0 ncaron;0148 ncedilla;0146 ncircle;24DD ncircumflexbelow;1E4B ncommaaccent;0146 ndotaccent;1E45 ndotbelow;1E47 nehiragana;306D nekatakana;30CD nekatakanahalfwidth;FF88 newsheqelsign;20AA nfsquare;338B ngabengali;0999 ngadeva;0919 ngagujarati;0A99 ngagurmukhi;0A19 ngonguthai;0E07 nhiragana;3093 nhookleft;0272 nhookretroflex;0273 nieunacirclekorean;326F nieunaparenkorean;320F nieuncieuckorean;3135 nieuncirclekorean;3261 nieunhieuhkorean;3136 nieunkorean;3134 nieunpansioskorean;3168 nieunparenkorean;3201 nieunsioskorean;3167 nieuntikeutkorean;3166 nihiragana;306B nikatakana;30CB nikatakanahalfwidth;FF86 nikhahitleftthai;F899 nikhahitthai;0E4D nine;0039 ninearabic;0669 ninebengali;09EF ninecircle;2468 ninecircleinversesansserif;2792 ninedeva;096F ninegujarati;0AEF ninegurmukhi;0A6F ninehackarabic;0669 ninehangzhou;3029 nineideographicparen;3228 nineinferior;2089 ninemonospace;FF19 nineoldstyle;F739 nineparen;247C nineperiod;2490 ninepersian;06F9 nineroman;2178 ninesuperior;2079 nineteencircle;2472 nineteenparen;2486 nineteenperiod;249A ninethai;0E59 nj;01CC njecyrillic;045A nkatakana;30F3 nkatakanahalfwidth;FF9D nlegrightlong;019E nlinebelow;1E49 nmonospace;FF4E nmsquare;339A nnabengali;09A3 nnadeva;0923 nnagujarati;0AA3 nnagurmukhi;0A23 nnnadeva;0929 nohiragana;306E nokatakana;30CE nokatakanahalfwidth;FF89 nonbreakingspace;00A0 nonenthai;0E13 nonuthai;0E19 noonarabic;0646 noonfinalarabic;FEE6 noonghunnaarabic;06BA noonghunnafinalarabic;FB9F noonhehinitialarabic;FEE7 FEEC nooninitialarabic;FEE7 noonjeeminitialarabic;FCD2 noonjeemisolatedarabic;FC4B noonmedialarabic;FEE8 noonmeeminitialarabic;FCD5 noonmeemisolatedarabic;FC4E noonnoonfinalarabic;FC8D notcontains;220C notelement;2209 notelementof;2209 notequal;2260 notgreater;226F notgreaternorequal;2271 notgreaternorless;2279 notidentical;2262 notless;226E notlessnorequal;2270 notparallel;2226 notprecedes;2280 notsubset;2284 notsucceeds;2281 notsuperset;2285 nowarmenian;0576 nparen;24A9 nssquare;33B1 nsuperior;207F ntilde;00F1 nu;03BD nuhiragana;306C nukatakana;30CC nukatakanahalfwidth;FF87 nuktabengali;09BC nuktadeva;093C nuktagujarati;0ABC nuktagurmukhi;0A3C numbersign;0023 numbersignmonospace;FF03 numbersignsmall;FE5F numeralsigngreek;0374 numeralsignlowergreek;0375 numero;2116 nun;05E0 nundagesh;FB40 nundageshhebrew;FB40 nunhebrew;05E0 nvsquare;33B5 nwsquare;33BB nyabengali;099E nyadeva;091E nyagujarati;0A9E nyagurmukhi;0A1E o;006F oacute;00F3 oangthai;0E2D obarred;0275 obarredcyrillic;04E9 obarreddieresiscyrillic;04EB obengali;0993 obopomofo;311B obreve;014F ocandradeva;0911 ocandragujarati;0A91 ocandravowelsigndeva;0949 ocandravowelsigngujarati;0AC9 ocaron;01D2 ocircle;24DE ocircumflex;00F4 ocircumflexacute;1ED1 ocircumflexdotbelow;1ED9 ocircumflexgrave;1ED3 ocircumflexhookabove;1ED5 ocircumflextilde;1ED7 ocyrillic;043E odblacute;0151 odblgrave;020D odeva;0913 odieresis;00F6 odieresiscyrillic;04E7 odotbelow;1ECD oe;0153 oekorean;315A ogonek;02DB ogonekcmb;0328 ograve;00F2 ogujarati;0A93 oharmenian;0585 ohiragana;304A ohookabove;1ECF ohorn;01A1 ohornacute;1EDB ohorndotbelow;1EE3 ohorngrave;1EDD ohornhookabove;1EDF ohorntilde;1EE1 ohungarumlaut;0151 oi;01A3 oinvertedbreve;020F okatakana;30AA okatakanahalfwidth;FF75 okorean;3157 olehebrew;05AB omacron;014D omacronacute;1E53 omacrongrave;1E51 omdeva;0950 omega;03C9 omega1;03D6 omegacyrillic;0461 omegalatinclosed;0277 omegaroundcyrillic;047B omegatitlocyrillic;047D omegatonos;03CE omgujarati;0AD0 omicron;03BF omicrontonos;03CC omonospace;FF4F one;0031 onearabic;0661 onebengali;09E7 onecircle;2460 onecircleinversesansserif;278A onedeva;0967 onedotenleader;2024 oneeighth;215B onefitted;F6DC onegujarati;0AE7 onegurmukhi;0A67 onehackarabic;0661 onehalf;00BD onehangzhou;3021 oneideographicparen;3220 oneinferior;2081 onemonospace;FF11 onenumeratorbengali;09F4 oneoldstyle;F731 oneparen;2474 oneperiod;2488 onepersian;06F1 onequarter;00BC oneroman;2170 onesuperior;00B9 onethai;0E51 onethird;2153 oogonek;01EB oogonekmacron;01ED oogurmukhi;0A13 oomatragurmukhi;0A4B oopen;0254 oparen;24AA openbullet;25E6 option;2325 ordfeminine;00AA ordmasculine;00BA orthogonal;221F oshortdeva;0912 oshortvowelsigndeva;094A oslash;00F8 oslashacute;01FF osmallhiragana;3049 osmallkatakana;30A9 osmallkatakanahalfwidth;FF6B ostrokeacute;01FF osuperior;F6F0 otcyrillic;047F otilde;00F5 otildeacute;1E4D otildedieresis;1E4F oubopomofo;3121 overline;203E overlinecenterline;FE4A overlinecmb;0305 overlinedashed;FE49 overlinedblwavy;FE4C overlinewavy;FE4B overscore;00AF ovowelsignbengali;09CB ovowelsigndeva;094B ovowelsigngujarati;0ACB p;0070 paampssquare;3380 paasentosquare;332B pabengali;09AA pacute;1E55 padeva;092A pagedown;21DF pageup;21DE pagujarati;0AAA pagurmukhi;0A2A pahiragana;3071 paiyannoithai;0E2F pakatakana;30D1 palatalizationcyrilliccmb;0484 palochkacyrillic;04C0 pansioskorean;317F paragraph;00B6 parallel;2225 parenleft;0028 parenleftaltonearabic;FD3E parenleftbt;F8ED parenleftex;F8EC parenleftinferior;208D parenleftmonospace;FF08 parenleftsmall;FE59 parenleftsuperior;207D parenlefttp;F8EB parenleftvertical;FE35 parenright;0029 parenrightaltonearabic;FD3F parenrightbt;F8F8 parenrightex;F8F7 parenrightinferior;208E parenrightmonospace;FF09 parenrightsmall;FE5A parenrightsuperior;207E parenrighttp;F8F6 parenrightvertical;FE36 partialdiff;2202 paseqhebrew;05C0 pashtahebrew;0599 pasquare;33A9 patah;05B7 patah11;05B7 patah1d;05B7 patah2a;05B7 patahhebrew;05B7 patahnarrowhebrew;05B7 patahquarterhebrew;05B7 patahwidehebrew;05B7 pazerhebrew;05A1 pbopomofo;3106 pcircle;24DF pdotaccent;1E57 pe;05E4 pecyrillic;043F pedagesh;FB44 pedageshhebrew;FB44 peezisquare;333B pefinaldageshhebrew;FB43 peharabic;067E peharmenian;057A pehebrew;05E4 pehfinalarabic;FB57 pehinitialarabic;FB58 pehiragana;307A pehmedialarabic;FB59 pekatakana;30DA pemiddlehookcyrillic;04A7 perafehebrew;FB4E percent;0025 percentarabic;066A percentmonospace;FF05 percentsmall;FE6A period;002E periodarmenian;0589 periodcentered;00B7 periodhalfwidth;FF61 periodinferior;F6E7 periodmonospace;FF0E periodsmall;FE52 periodsuperior;F6E8 perispomenigreekcmb;0342 perpendicular;22A5 perthousand;2030 peseta;20A7 pfsquare;338A phabengali;09AB phadeva;092B phagujarati;0AAB phagurmukhi;0A2B phi;03C6 phi1;03D5 phieuphacirclekorean;327A phieuphaparenkorean;321A phieuphcirclekorean;326C phieuphkorean;314D phieuphparenkorean;320C philatin;0278 phinthuthai;0E3A phisymbolgreek;03D5 phook;01A5 phophanthai;0E1E phophungthai;0E1C phosamphaothai;0E20 pi;03C0 pieupacirclekorean;3273 pieupaparenkorean;3213 pieupcieuckorean;3176 pieupcirclekorean;3265 pieupkiyeokkorean;3172 pieupkorean;3142 pieupparenkorean;3205 pieupsioskiyeokkorean;3174 pieupsioskorean;3144 pieupsiostikeutkorean;3175 pieupthieuthkorean;3177 pieuptikeutkorean;3173 pihiragana;3074 pikatakana;30D4 pisymbolgreek;03D6 piwrarmenian;0583 plus;002B plusbelowcmb;031F pluscircle;2295 plusminus;00B1 plusmod;02D6 plusmonospace;FF0B plussmall;FE62 plussuperior;207A pmonospace;FF50 pmsquare;33D8 pohiragana;307D pointingindexdownwhite;261F pointingindexleftwhite;261C pointingindexrightwhite;261E pointingindexupwhite;261D pokatakana;30DD poplathai;0E1B postalmark;3012 postalmarkface;3020 pparen;24AB precedes;227A prescription;211E primemod;02B9 primereversed;2035 product;220F projective;2305 prolongedkana;30FC propellor;2318 propersubset;2282 propersuperset;2283 proportion;2237 proportional;221D psi;03C8 psicyrillic;0471 psilipneumatacyrilliccmb;0486 pssquare;33B0 puhiragana;3077 pukatakana;30D7 pvsquare;33B4 pwsquare;33BA q;0071 qadeva;0958 qadmahebrew;05A8 qafarabic;0642 qaffinalarabic;FED6 qafinitialarabic;FED7 qafmedialarabic;FED8 qamats;05B8 qamats10;05B8 qamats1a;05B8 qamats1c;05B8 qamats27;05B8 qamats29;05B8 qamats33;05B8 qamatsde;05B8 qamatshebrew;05B8 qamatsnarrowhebrew;05B8 qamatsqatanhebrew;05B8 qamatsqatannarrowhebrew;05B8 qamatsqatanquarterhebrew;05B8 qamatsqatanwidehebrew;05B8 qamatsquarterhebrew;05B8 qamatswidehebrew;05B8 qarneyparahebrew;059F qbopomofo;3111 qcircle;24E0 qhook;02A0 qmonospace;FF51 qof;05E7 qofdagesh;FB47 qofdageshhebrew;FB47 qofhatafpatah;05E7 05B2 qofhatafpatahhebrew;05E7 05B2 qofhatafsegol;05E7 05B1 qofhatafsegolhebrew;05E7 05B1 qofhebrew;05E7 qofhiriq;05E7 05B4 qofhiriqhebrew;05E7 05B4 qofholam;05E7 05B9 qofholamhebrew;05E7 05B9 qofpatah;05E7 05B7 qofpatahhebrew;05E7 05B7 qofqamats;05E7 05B8 qofqamatshebrew;05E7 05B8 qofqubuts;05E7 05BB qofqubutshebrew;05E7 05BB qofsegol;05E7 05B6 qofsegolhebrew;05E7 05B6 qofsheva;05E7 05B0 qofshevahebrew;05E7 05B0 qoftsere;05E7 05B5 qoftserehebrew;05E7 05B5 qparen;24AC quarternote;2669 qubuts;05BB qubuts18;05BB qubuts25;05BB qubuts31;05BB qubutshebrew;05BB qubutsnarrowhebrew;05BB qubutsquarterhebrew;05BB qubutswidehebrew;05BB question;003F questionarabic;061F questionarmenian;055E questiondown;00BF questiondownsmall;F7BF questiongreek;037E questionmonospace;FF1F questionsmall;F73F quotedbl;0022 quotedblbase;201E quotedblleft;201C quotedblmonospace;FF02 quotedblprime;301E quotedblprimereversed;301D quotedblright;201D quoteleft;2018 quoteleftreversed;201B quotereversed;201B quoteright;2019 quoterightn;0149 quotesinglbase;201A quotesingle;0027 quotesinglemonospace;FF07 r;0072 raarmenian;057C rabengali;09B0 racute;0155 radeva;0930 radical;221A radicalex;F8E5 radoverssquare;33AE radoverssquaredsquare;33AF radsquare;33AD rafe;05BF rafehebrew;05BF ragujarati;0AB0 ragurmukhi;0A30 rahiragana;3089 rakatakana;30E9 rakatakanahalfwidth;FF97 ralowerdiagonalbengali;09F1 ramiddlediagonalbengali;09F0 ramshorn;0264 ratio;2236 rbopomofo;3116 rcaron;0159 rcedilla;0157 rcircle;24E1 rcommaaccent;0157 rdblgrave;0211 rdotaccent;1E59 rdotbelow;1E5B rdotbelowmacron;1E5D referencemark;203B reflexsubset;2286 reflexsuperset;2287 registered;00AE registersans;F8E8 registerserif;F6DA reharabic;0631 reharmenian;0580 rehfinalarabic;FEAE rehiragana;308C rehyehaleflamarabic;0631 FEF3 FE8E 0644 rekatakana;30EC rekatakanahalfwidth;FF9A resh;05E8 reshdageshhebrew;FB48 reshhatafpatah;05E8 05B2 reshhatafpatahhebrew;05E8 05B2 reshhatafsegol;05E8 05B1 reshhatafsegolhebrew;05E8 05B1 reshhebrew;05E8 reshhiriq;05E8 05B4 reshhiriqhebrew;05E8 05B4 reshholam;05E8 05B9 reshholamhebrew;05E8 05B9 reshpatah;05E8 05B7 reshpatahhebrew;05E8 05B7 reshqamats;05E8 05B8 reshqamatshebrew;05E8 05B8 reshqubuts;05E8 05BB reshqubutshebrew;05E8 05BB reshsegol;05E8 05B6 reshsegolhebrew;05E8 05B6 reshsheva;05E8 05B0 reshshevahebrew;05E8 05B0 reshtsere;05E8 05B5 reshtserehebrew;05E8 05B5 reversedtilde;223D reviahebrew;0597 reviamugrashhebrew;0597 revlogicalnot;2310 rfishhook;027E rfishhookreversed;027F rhabengali;09DD rhadeva;095D rho;03C1 rhook;027D rhookturned;027B rhookturnedsuperior;02B5 rhosymbolgreek;03F1 rhotichookmod;02DE rieulacirclekorean;3271 rieulaparenkorean;3211 rieulcirclekorean;3263 rieulhieuhkorean;3140 rieulkiyeokkorean;313A rieulkiyeoksioskorean;3169 rieulkorean;3139 rieulmieumkorean;313B rieulpansioskorean;316C rieulparenkorean;3203 rieulphieuphkorean;313F rieulpieupkorean;313C rieulpieupsioskorean;316B rieulsioskorean;313D rieulthieuthkorean;313E rieultikeutkorean;316A rieulyeorinhieuhkorean;316D rightangle;221F righttackbelowcmb;0319 righttriangle;22BF rihiragana;308A rikatakana;30EA rikatakanahalfwidth;FF98 ring;02DA ringbelowcmb;0325 ringcmb;030A ringhalfleft;02BF ringhalfleftarmenian;0559 ringhalfleftbelowcmb;031C ringhalfleftcentered;02D3 ringhalfright;02BE ringhalfrightbelowcmb;0339 ringhalfrightcentered;02D2 rinvertedbreve;0213 rittorusquare;3351 rlinebelow;1E5F rlongleg;027C rlonglegturned;027A rmonospace;FF52 rohiragana;308D rokatakana;30ED rokatakanahalfwidth;FF9B roruathai;0E23 rparen;24AD rrabengali;09DC rradeva;0931 rragurmukhi;0A5C rreharabic;0691 rrehfinalarabic;FB8D rrvocalicbengali;09E0 rrvocalicdeva;0960 rrvocalicgujarati;0AE0 rrvocalicvowelsignbengali;09C4 rrvocalicvowelsigndeva;0944 rrvocalicvowelsigngujarati;0AC4 rsuperior;F6F1 rtblock;2590 rturned;0279 rturnedsuperior;02B4 ruhiragana;308B rukatakana;30EB rukatakanahalfwidth;FF99 rupeemarkbengali;09F2 rupeesignbengali;09F3 rupiah;F6DD ruthai;0E24 rvocalicbengali;098B rvocalicdeva;090B rvocalicgujarati;0A8B rvocalicvowelsignbengali;09C3 rvocalicvowelsigndeva;0943 rvocalicvowelsigngujarati;0AC3 s;0073 sabengali;09B8 sacute;015B sacutedotaccent;1E65 sadarabic;0635 sadeva;0938 sadfinalarabic;FEBA sadinitialarabic;FEBB sadmedialarabic;FEBC sagujarati;0AB8 sagurmukhi;0A38 sahiragana;3055 sakatakana;30B5 sakatakanahalfwidth;FF7B sallallahoualayhewasallamarabic;FDFA samekh;05E1 samekhdagesh;FB41 samekhdageshhebrew;FB41 samekhhebrew;05E1 saraaathai;0E32 saraaethai;0E41 saraaimaimalaithai;0E44 saraaimaimuanthai;0E43 saraamthai;0E33 saraathai;0E30 saraethai;0E40 saraiileftthai;F886 saraiithai;0E35 saraileftthai;F885 saraithai;0E34 saraothai;0E42 saraueeleftthai;F888 saraueethai;0E37 saraueleftthai;F887 sarauethai;0E36 sarauthai;0E38 sarauuthai;0E39 sbopomofo;3119 scaron;0161 scarondotaccent;1E67 scedilla;015F schwa;0259 schwacyrillic;04D9 schwadieresiscyrillic;04DB schwahook;025A scircle;24E2 scircumflex;015D scommaaccent;0219 sdotaccent;1E61 sdotbelow;1E63 sdotbelowdotaccent;1E69 seagullbelowcmb;033C second;2033 secondtonechinese;02CA section;00A7 seenarabic;0633 seenfinalarabic;FEB2 seeninitialarabic;FEB3 seenmedialarabic;FEB4 segol;05B6 segol13;05B6 segol1f;05B6 segol2c;05B6 segolhebrew;05B6 segolnarrowhebrew;05B6 segolquarterhebrew;05B6 segoltahebrew;0592 segolwidehebrew;05B6 seharmenian;057D sehiragana;305B sekatakana;30BB sekatakanahalfwidth;FF7E semicolon;003B semicolonarabic;061B semicolonmonospace;FF1B semicolonsmall;FE54 semivoicedmarkkana;309C semivoicedmarkkanahalfwidth;FF9F sentisquare;3322 sentosquare;3323 seven;0037 sevenarabic;0667 sevenbengali;09ED sevencircle;2466 sevencircleinversesansserif;2790 sevendeva;096D seveneighths;215E sevengujarati;0AED sevengurmukhi;0A6D sevenhackarabic;0667 sevenhangzhou;3027 sevenideographicparen;3226 seveninferior;2087 sevenmonospace;FF17 sevenoldstyle;F737 sevenparen;247A sevenperiod;248E sevenpersian;06F7 sevenroman;2176 sevensuperior;2077 seventeencircle;2470 seventeenparen;2484 seventeenperiod;2498 seventhai;0E57 sfthyphen;00AD shaarmenian;0577 shabengali;09B6 shacyrillic;0448 shaddaarabic;0651 shaddadammaarabic;FC61 shaddadammatanarabic;FC5E shaddafathaarabic;FC60 shaddafathatanarabic;0651 064B shaddakasraarabic;FC62 shaddakasratanarabic;FC5F shade;2592 shadedark;2593 shadelight;2591 shademedium;2592 shadeva;0936 shagujarati;0AB6 shagurmukhi;0A36 shalshelethebrew;0593 shbopomofo;3115 shchacyrillic;0449 sheenarabic;0634 sheenfinalarabic;FEB6 sheeninitialarabic;FEB7 sheenmedialarabic;FEB8 sheicoptic;03E3 sheqel;20AA sheqelhebrew;20AA sheva;05B0 sheva115;05B0 sheva15;05B0 sheva22;05B0 sheva2e;05B0 shevahebrew;05B0 shevanarrowhebrew;05B0 shevaquarterhebrew;05B0 shevawidehebrew;05B0 shhacyrillic;04BB shimacoptic;03ED shin;05E9 shindagesh;FB49 shindageshhebrew;FB49 shindageshshindot;FB2C shindageshshindothebrew;FB2C shindageshsindot;FB2D shindageshsindothebrew;FB2D shindothebrew;05C1 shinhebrew;05E9 shinshindot;FB2A shinshindothebrew;FB2A shinsindot;FB2B shinsindothebrew;FB2B shook;0282 sigma;03C3 sigma1;03C2 sigmafinal;03C2 sigmalunatesymbolgreek;03F2 sihiragana;3057 sikatakana;30B7 sikatakanahalfwidth;FF7C siluqhebrew;05BD siluqlefthebrew;05BD similar;223C sindothebrew;05C2 siosacirclekorean;3274 siosaparenkorean;3214 sioscieuckorean;317E sioscirclekorean;3266 sioskiyeokkorean;317A sioskorean;3145 siosnieunkorean;317B siosparenkorean;3206 siospieupkorean;317D siostikeutkorean;317C six;0036 sixarabic;0666 sixbengali;09EC sixcircle;2465 sixcircleinversesansserif;278F sixdeva;096C sixgujarati;0AEC sixgurmukhi;0A6C sixhackarabic;0666 sixhangzhou;3026 sixideographicparen;3225 sixinferior;2086 sixmonospace;FF16 sixoldstyle;F736 sixparen;2479 sixperiod;248D sixpersian;06F6 sixroman;2175 sixsuperior;2076 sixteencircle;246F sixteencurrencydenominatorbengali;09F9 sixteenparen;2483 sixteenperiod;2497 sixthai;0E56 slash;002F slashmonospace;FF0F slong;017F slongdotaccent;1E9B smileface;263A smonospace;FF53 sofpasuqhebrew;05C3 softhyphen;00AD softsigncyrillic;044C sohiragana;305D sokatakana;30BD sokatakanahalfwidth;FF7F soliduslongoverlaycmb;0338 solidusshortoverlaycmb;0337 sorusithai;0E29 sosalathai;0E28 sosothai;0E0B sosuathai;0E2A space;0020 spacehackarabic;0020 spade;2660 spadesuitblack;2660 spadesuitwhite;2664 sparen;24AE squarebelowcmb;033B squarecc;33C4 squarecm;339D squarediagonalcrosshatchfill;25A9 squarehorizontalfill;25A4 squarekg;338F squarekm;339E squarekmcapital;33CE squareln;33D1 squarelog;33D2 squaremg;338E squaremil;33D5 squaremm;339C squaremsquared;33A1 squareorthogonalcrosshatchfill;25A6 squareupperlefttolowerrightfill;25A7 squareupperrighttolowerleftfill;25A8 squareverticalfill;25A5 squarewhitewithsmallblack;25A3 srsquare;33DB ssabengali;09B7 ssadeva;0937 ssagujarati;0AB7 ssangcieuckorean;3149 ssanghieuhkorean;3185 ssangieungkorean;3180 ssangkiyeokkorean;3132 ssangnieunkorean;3165 ssangpieupkorean;3143 ssangsioskorean;3146 ssangtikeutkorean;3138 ssuperior;F6F2 sterling;00A3 sterlingmonospace;FFE1 strokelongoverlaycmb;0336 strokeshortoverlaycmb;0335 subset;2282 subsetnotequal;228A subsetorequal;2286 succeeds;227B suchthat;220B suhiragana;3059 sukatakana;30B9 sukatakanahalfwidth;FF7D sukunarabic;0652 summation;2211 sun;263C superset;2283 supersetnotequal;228B supersetorequal;2287 svsquare;33DC syouwaerasquare;337C t;0074 tabengali;09A4 tackdown;22A4 tackleft;22A3 tadeva;0924 tagujarati;0AA4 tagurmukhi;0A24 taharabic;0637 tahfinalarabic;FEC2 tahinitialarabic;FEC3 tahiragana;305F tahmedialarabic;FEC4 taisyouerasquare;337D takatakana;30BF takatakanahalfwidth;FF80 tatweelarabic;0640 tau;03C4 tav;05EA tavdages;FB4A tavdagesh;FB4A tavdageshhebrew;FB4A tavhebrew;05EA tbar;0167 tbopomofo;310A tcaron;0165 tccurl;02A8 tcedilla;0163 tcheharabic;0686 tchehfinalarabic;FB7B tchehinitialarabic;FB7C tchehmedialarabic;FB7D tchehmeeminitialarabic;FB7C FEE4 tcircle;24E3 tcircumflexbelow;1E71 tcommaaccent;0163 tdieresis;1E97 tdotaccent;1E6B tdotbelow;1E6D tecyrillic;0442 tedescendercyrillic;04AD teharabic;062A tehfinalarabic;FE96 tehhahinitialarabic;FCA2 tehhahisolatedarabic;FC0C tehinitialarabic;FE97 tehiragana;3066 tehjeeminitialarabic;FCA1 tehjeemisolatedarabic;FC0B tehmarbutaarabic;0629 tehmarbutafinalarabic;FE94 tehmedialarabic;FE98 tehmeeminitialarabic;FCA4 tehmeemisolatedarabic;FC0E tehnoonfinalarabic;FC73 tekatakana;30C6 tekatakanahalfwidth;FF83 telephone;2121 telephoneblack;260E telishagedolahebrew;05A0 telishaqetanahebrew;05A9 tencircle;2469 tenideographicparen;3229 tenparen;247D tenperiod;2491 tenroman;2179 tesh;02A7 tet;05D8 tetdagesh;FB38 tetdageshhebrew;FB38 tethebrew;05D8 tetsecyrillic;04B5 tevirhebrew;059B tevirlefthebrew;059B thabengali;09A5 thadeva;0925 thagujarati;0AA5 thagurmukhi;0A25 thalarabic;0630 thalfinalarabic;FEAC thanthakhatlowleftthai;F898 thanthakhatlowrightthai;F897 thanthakhatthai;0E4C thanthakhatupperleftthai;F896 theharabic;062B thehfinalarabic;FE9A thehinitialarabic;FE9B thehmedialarabic;FE9C thereexists;2203 therefore;2234 theta;03B8 theta1;03D1 thetasymbolgreek;03D1 thieuthacirclekorean;3279 thieuthaparenkorean;3219 thieuthcirclekorean;326B thieuthkorean;314C thieuthparenkorean;320B thirteencircle;246C thirteenparen;2480 thirteenperiod;2494 thonangmonthothai;0E11 thook;01AD thophuthaothai;0E12 thorn;00FE thothahanthai;0E17 thothanthai;0E10 thothongthai;0E18 thothungthai;0E16 thousandcyrillic;0482 thousandsseparatorarabic;066C thousandsseparatorpersian;066C three;0033 threearabic;0663 threebengali;09E9 threecircle;2462 threecircleinversesansserif;278C threedeva;0969 threeeighths;215C threegujarati;0AE9 threegurmukhi;0A69 threehackarabic;0663 threehangzhou;3023 threeideographicparen;3222 threeinferior;2083 threemonospace;FF13 threenumeratorbengali;09F6 threeoldstyle;F733 threeparen;2476 threeperiod;248A threepersian;06F3 threequarters;00BE threequartersemdash;F6DE threeroman;2172 threesuperior;00B3 threethai;0E53 thzsquare;3394 tihiragana;3061 tikatakana;30C1 tikatakanahalfwidth;FF81 tikeutacirclekorean;3270 tikeutaparenkorean;3210 tikeutcirclekorean;3262 tikeutkorean;3137 tikeutparenkorean;3202 tilde;02DC tildebelowcmb;0330 tildecmb;0303 tildecomb;0303 tildedoublecmb;0360 tildeoperator;223C tildeoverlaycmb;0334 tildeverticalcmb;033E timescircle;2297 tipehahebrew;0596 tipehalefthebrew;0596 tippigurmukhi;0A70 titlocyrilliccmb;0483 tiwnarmenian;057F tlinebelow;1E6F tmonospace;FF54 toarmenian;0569 tohiragana;3068 tokatakana;30C8 tokatakanahalfwidth;FF84 tonebarextrahighmod;02E5 tonebarextralowmod;02E9 tonebarhighmod;02E6 tonebarlowmod;02E8 tonebarmidmod;02E7 tonefive;01BD tonesix;0185 tonetwo;01A8 tonos;0384 tonsquare;3327 topatakthai;0E0F tortoiseshellbracketleft;3014 tortoiseshellbracketleftsmall;FE5D tortoiseshellbracketleftvertical;FE39 tortoiseshellbracketright;3015 tortoiseshellbracketrightsmall;FE5E tortoiseshellbracketrightvertical;FE3A totaothai;0E15 tpalatalhook;01AB tparen;24AF trademark;2122 trademarksans;F8EA trademarkserif;F6DB tretroflexhook;0288 triagdn;25BC triaglf;25C4 triagrt;25BA triagup;25B2 ts;02A6 tsadi;05E6 tsadidagesh;FB46 tsadidageshhebrew;FB46 tsadihebrew;05E6 tsecyrillic;0446 tsere;05B5 tsere12;05B5 tsere1e;05B5 tsere2b;05B5 tserehebrew;05B5 tserenarrowhebrew;05B5 tserequarterhebrew;05B5 tserewidehebrew;05B5 tshecyrillic;045B tsuperior;F6F3 ttabengali;099F ttadeva;091F ttagujarati;0A9F ttagurmukhi;0A1F tteharabic;0679 ttehfinalarabic;FB67 ttehinitialarabic;FB68 ttehmedialarabic;FB69 tthabengali;09A0 tthadeva;0920 tthagujarati;0AA0 tthagurmukhi;0A20 tturned;0287 tuhiragana;3064 tukatakana;30C4 tukatakanahalfwidth;FF82 tusmallhiragana;3063 tusmallkatakana;30C3 tusmallkatakanahalfwidth;FF6F twelvecircle;246B twelveparen;247F twelveperiod;2493 twelveroman;217B twentycircle;2473 twentyhangzhou;5344 twentyparen;2487 twentyperiod;249B two;0032 twoarabic;0662 twobengali;09E8 twocircle;2461 twocircleinversesansserif;278B twodeva;0968 twodotenleader;2025 twodotleader;2025 twodotleadervertical;FE30 twogujarati;0AE8 twogurmukhi;0A68 twohackarabic;0662 twohangzhou;3022 twoideographicparen;3221 twoinferior;2082 twomonospace;FF12 twonumeratorbengali;09F5 twooldstyle;F732 twoparen;2475 twoperiod;2489 twopersian;06F2 tworoman;2171 twostroke;01BB twosuperior;00B2 twothai;0E52 twothirds;2154 u;0075 uacute;00FA ubar;0289 ubengali;0989 ubopomofo;3128 ubreve;016D ucaron;01D4 ucircle;24E4 ucircumflex;00FB ucircumflexbelow;1E77 ucyrillic;0443 udattadeva;0951 udblacute;0171 udblgrave;0215 udeva;0909 udieresis;00FC udieresisacute;01D8 udieresisbelow;1E73 udieresiscaron;01DA udieresiscyrillic;04F1 udieresisgrave;01DC udieresismacron;01D6 udotbelow;1EE5 ugrave;00F9 ugujarati;0A89 ugurmukhi;0A09 uhiragana;3046 uhookabove;1EE7 uhorn;01B0 uhornacute;1EE9 uhorndotbelow;1EF1 uhorngrave;1EEB uhornhookabove;1EED uhorntilde;1EEF uhungarumlaut;0171 uhungarumlautcyrillic;04F3 uinvertedbreve;0217 ukatakana;30A6 ukatakanahalfwidth;FF73 ukcyrillic;0479 ukorean;315C umacron;016B umacroncyrillic;04EF umacrondieresis;1E7B umatragurmukhi;0A41 umonospace;FF55 underscore;005F underscoredbl;2017 underscoremonospace;FF3F underscorevertical;FE33 underscorewavy;FE4F union;222A universal;2200 uogonek;0173 uparen;24B0 upblock;2580 upperdothebrew;05C4 upsilon;03C5 upsilondieresis;03CB upsilondieresistonos;03B0 upsilonlatin;028A upsilontonos;03CD uptackbelowcmb;031D uptackmod;02D4 uragurmukhi;0A73 uring;016F ushortcyrillic;045E usmallhiragana;3045 usmallkatakana;30A5 usmallkatakanahalfwidth;FF69 ustraightcyrillic;04AF ustraightstrokecyrillic;04B1 utilde;0169 utildeacute;1E79 utildebelow;1E75 uubengali;098A uudeva;090A uugujarati;0A8A uugurmukhi;0A0A uumatragurmukhi;0A42 uuvowelsignbengali;09C2 uuvowelsigndeva;0942 uuvowelsigngujarati;0AC2 uvowelsignbengali;09C1 uvowelsigndeva;0941 uvowelsigngujarati;0AC1 v;0076 vadeva;0935 vagujarati;0AB5 vagurmukhi;0A35 vakatakana;30F7 vav;05D5 vavdagesh;FB35 vavdagesh65;FB35 vavdageshhebrew;FB35 vavhebrew;05D5 vavholam;FB4B vavholamhebrew;FB4B vavvavhebrew;05F0 vavyodhebrew;05F1 vcircle;24E5 vdotbelow;1E7F vecyrillic;0432 veharabic;06A4 vehfinalarabic;FB6B vehinitialarabic;FB6C vehmedialarabic;FB6D vekatakana;30F9 venus;2640 verticalbar;007C verticallineabovecmb;030D verticallinebelowcmb;0329 verticallinelowmod;02CC verticallinemod;02C8 vewarmenian;057E vhook;028B vikatakana;30F8 viramabengali;09CD viramadeva;094D viramagujarati;0ACD visargabengali;0983 visargadeva;0903 visargagujarati;0A83 vmonospace;FF56 voarmenian;0578 voicediterationhiragana;309E voicediterationkatakana;30FE voicedmarkkana;309B voicedmarkkanahalfwidth;FF9E vokatakana;30FA vparen;24B1 vtilde;1E7D vturned;028C vuhiragana;3094 vukatakana;30F4 w;0077 wacute;1E83 waekorean;3159 wahiragana;308F wakatakana;30EF wakatakanahalfwidth;FF9C wakorean;3158 wasmallhiragana;308E wasmallkatakana;30EE wattosquare;3357 wavedash;301C wavyunderscorevertical;FE34 wawarabic;0648 wawfinalarabic;FEEE wawhamzaabovearabic;0624 wawhamzaabovefinalarabic;FE86 wbsquare;33DD wcircle;24E6 wcircumflex;0175 wdieresis;1E85 wdotaccent;1E87 wdotbelow;1E89 wehiragana;3091 weierstrass;2118 wekatakana;30F1 wekorean;315E weokorean;315D wgrave;1E81 whitebullet;25E6 whitecircle;25CB whitecircleinverse;25D9 whitecornerbracketleft;300E whitecornerbracketleftvertical;FE43 whitecornerbracketright;300F whitecornerbracketrightvertical;FE44 whitediamond;25C7 whitediamondcontainingblacksmalldiamond;25C8 whitedownpointingsmalltriangle;25BF whitedownpointingtriangle;25BD whiteleftpointingsmalltriangle;25C3 whiteleftpointingtriangle;25C1 whitelenticularbracketleft;3016 whitelenticularbracketright;3017 whiterightpointingsmalltriangle;25B9 whiterightpointingtriangle;25B7 whitesmallsquare;25AB whitesmilingface;263A whitesquare;25A1 whitestar;2606 whitetelephone;260F whitetortoiseshellbracketleft;3018 whitetortoiseshellbracketright;3019 whiteuppointingsmalltriangle;25B5 whiteuppointingtriangle;25B3 wihiragana;3090 wikatakana;30F0 wikorean;315F wmonospace;FF57 wohiragana;3092 wokatakana;30F2 wokatakanahalfwidth;FF66 won;20A9 wonmonospace;FFE6 wowaenthai;0E27 wparen;24B2 wring;1E98 wsuperior;02B7 wturned;028D wynn;01BF x;0078 xabovecmb;033D xbopomofo;3112 xcircle;24E7 xdieresis;1E8D xdotaccent;1E8B xeharmenian;056D xi;03BE xmonospace;FF58 xparen;24B3 xsuperior;02E3 y;0079 yaadosquare;334E yabengali;09AF yacute;00FD yadeva;092F yaekorean;3152 yagujarati;0AAF yagurmukhi;0A2F yahiragana;3084 yakatakana;30E4 yakatakanahalfwidth;FF94 yakorean;3151 yamakkanthai;0E4E yasmallhiragana;3083 yasmallkatakana;30E3 yasmallkatakanahalfwidth;FF6C yatcyrillic;0463 ycircle;24E8 ycircumflex;0177 ydieresis;00FF ydotaccent;1E8F ydotbelow;1EF5 yeharabic;064A yehbarreearabic;06D2 yehbarreefinalarabic;FBAF yehfinalarabic;FEF2 yehhamzaabovearabic;0626 yehhamzaabovefinalarabic;FE8A yehhamzaaboveinitialarabic;FE8B yehhamzaabovemedialarabic;FE8C yehinitialarabic;FEF3 yehmedialarabic;FEF4 yehmeeminitialarabic;FCDD yehmeemisolatedarabic;FC58 yehnoonfinalarabic;FC94 yehthreedotsbelowarabic;06D1 yekorean;3156 yen;00A5 yenmonospace;FFE5 yeokorean;3155 yeorinhieuhkorean;3186 yerahbenyomohebrew;05AA yerahbenyomolefthebrew;05AA yericyrillic;044B yerudieresiscyrillic;04F9 yesieungkorean;3181 yesieungpansioskorean;3183 yesieungsioskorean;3182 yetivhebrew;059A ygrave;1EF3 yhook;01B4 yhookabove;1EF7 yiarmenian;0575 yicyrillic;0457 yikorean;3162 yinyang;262F yiwnarmenian;0582 ymonospace;FF59 yod;05D9 yoddagesh;FB39 yoddageshhebrew;FB39 yodhebrew;05D9 yodyodhebrew;05F2 yodyodpatahhebrew;FB1F yohiragana;3088 yoikorean;3189 yokatakana;30E8 yokatakanahalfwidth;FF96 yokorean;315B yosmallhiragana;3087 yosmallkatakana;30E7 yosmallkatakanahalfwidth;FF6E yotgreek;03F3 yoyaekorean;3188 yoyakorean;3187 yoyakthai;0E22 yoyingthai;0E0D yparen;24B4 ypogegrammeni;037A ypogegrammenigreekcmb;0345 yr;01A6 yring;1E99 ysuperior;02B8 ytilde;1EF9 yturned;028E yuhiragana;3086 yuikorean;318C yukatakana;30E6 yukatakanahalfwidth;FF95 yukorean;3160 yusbigcyrillic;046B yusbigiotifiedcyrillic;046D yuslittlecyrillic;0467 yuslittleiotifiedcyrillic;0469 yusmallhiragana;3085 yusmallkatakana;30E5 yusmallkatakanahalfwidth;FF6D yuyekorean;318B yuyeokorean;318A yyabengali;09DF yyadeva;095F z;007A zaarmenian;0566 zacute;017A zadeva;095B zagurmukhi;0A5B zaharabic;0638 zahfinalarabic;FEC6 zahinitialarabic;FEC7 zahiragana;3056 zahmedialarabic;FEC8 zainarabic;0632 zainfinalarabic;FEB0 zakatakana;30B6 zaqefgadolhebrew;0595 zaqefqatanhebrew;0594 zarqahebrew;0598 zayin;05D6 zayindagesh;FB36 zayindageshhebrew;FB36 zayinhebrew;05D6 zbopomofo;3117 zcaron;017E zcircle;24E9 zcircumflex;1E91 zcurl;0291 zdot;017C zdotaccent;017C zdotbelow;1E93 zecyrillic;0437 zedescendercyrillic;0499 zedieresiscyrillic;04DF zehiragana;305C zekatakana;30BC zero;0030 zeroarabic;0660 zerobengali;09E6 zerodeva;0966 zerogujarati;0AE6 zerogurmukhi;0A66 zerohackarabic;0660 zeroinferior;2080 zeromonospace;FF10 zerooldstyle;F730 zeropersian;06F0 zerosuperior;2070 zerothai;0E50 zerowidthjoiner;FEFF zerowidthnonjoiner;200C zerowidthspace;200B zeta;03B6 zhbopomofo;3113 zhearmenian;056A zhebrevecyrillic;04C2 zhecyrillic;0436 zhedescendercyrillic;0497 zhedieresiscyrillic;04DD zihiragana;3058 zikatakana;30B8 zinorhebrew;05AE zlinebelow;1E95 zmonospace;FF5A zohiragana;305E zokatakana;30BE zparen;24B5 zretroflexhook;0290 zstroke;01B6 zuhiragana;305A zukatakana;30BA a100;275E a101;2761 a102;2762 a103;2763 a104;2764 a105;2710 a106;2765 a107;2766 a108;2767 a109;2660 a10;2721 a110;2665 a111;2666 a112;2663 a117;2709 a118;2708 a119;2707 a11;261B a120;2460 a121;2461 a122;2462 a123;2463 a124;2464 a125;2465 a126;2466 a127;2467 a128;2468 a129;2469 a12;261E a130;2776 a131;2777 a132;2778 a133;2779 a134;277A a135;277B a136;277C a137;277D a138;277E a139;277F a13;270C a140;2780 a141;2781 a142;2782 a143;2783 a144;2784 a145;2785 a146;2786 a147;2787 a148;2788 a149;2789 a14;270D a150;278A a151;278B a152;278C a153;278D a154;278E a155;278F a156;2790 a157;2791 a158;2792 a159;2793 a15;270E a160;2794 a161;2192 a162;27A3 a163;2194 a164;2195 a165;2799 a166;279B a167;279C a168;279D a169;279E a16;270F a170;279F a171;27A0 a172;27A1 a173;27A2 a174;27A4 a175;27A5 a176;27A6 a177;27A7 a178;27A8 a179;27A9 a17;2711 a180;27AB a181;27AD a182;27AF a183;27B2 a184;27B3 a185;27B5 a186;27B8 a187;27BA a188;27BB a189;27BC a18;2712 a190;27BD a191;27BE a192;279A a193;27AA a194;27B6 a195;27B9 a196;2798 a197;27B4 a198;27B7 a199;27AC a19;2713 a1;2701 a200;27AE a201;27B1 a202;2703 a203;2750 a204;2752 a205;276E a206;2770 a20;2714 a21;2715 a22;2716 a23;2717 a24;2718 a25;2719 a26;271A a27;271B a28;271C a29;2722 a2;2702 a30;2723 a31;2724 a32;2725 a33;2726 a34;2727 a35;2605 a36;2729 a37;272A a38;272B a39;272C a3;2704 a40;272D a41;272E a42;272F a43;2730 a44;2731 a45;2732 a46;2733 a47;2734 a48;2735 a49;2736 a4;260E a50;2737 a51;2738 a52;2739 a53;273A a54;273B a55;273C a56;273D a57;273E a58;273F a59;2740 a5;2706 a60;2741 a61;2742 a62;2743 a63;2744 a64;2745 a65;2746 a66;2747 a67;2748 a68;2749 a69;274A a6;271D a70;274B a71;25CF a72;274D a73;25A0 a74;274F a75;2751 a76;25B2 a77;25BC a78;25C6 a79;2756 a7;271E a81;25D7 a82;2758 a83;2759 a84;275A a85;276F a86;2771 a87;2772 a88;2773 a89;2768 a8;271F a90;2769 a91;276C a92;276D a93;276A a94;276B a95;2774 a96;2775 a97;275B a98;275C a99;275D a9;2720 """ # string table management # class StringTable: def __init__( self, name_list, master_table_name ): self.names = name_list self.master_table = master_table_name self.indices = {} index = 0 for name in name_list: self.indices[name] = index index += len( name ) + 1 self.total = index def dump( self, file ): write = file.write write( "#ifndef DEFINE_PS_TABLES_DATA\n" ) write( "#ifdef __cplusplus\n" ) write( ' extern "C"\n' ) write( "#else\n" ) write( " extern\n" ) write( "#endif\n" ) write( "#endif\n" ) write( " const char " + self.master_table + "[" + repr( self.total ) + "]\n" ) write( "#ifdef DEFINE_PS_TABLES_DATA\n" ) write( " =\n" ) write( " {\n" ) line = "" for name in self.names: line += " '" line += string.join( ( re.findall( ".", name ) ), "','" ) line += "', 0,\n" write( line ) write( " }\n" ) write( "#endif /* DEFINE_PS_TABLES_DATA */\n" ) write( " ;\n\n\n" ) def dump_sublist( self, file, table_name, macro_name, sublist ): write = file.write write( "#define " + macro_name + " " + repr( len( sublist ) ) + "\n\n" ) write( " /* Values are offsets into the `" + self.master_table + "' table */\n\n" ) write( "#ifndef DEFINE_PS_TABLES_DATA\n" ) write( "#ifdef __cplusplus\n" ) write( ' extern "C"\n' ) write( "#else\n" ) write( " extern\n" ) write( "#endif\n" ) write( "#endif\n" ) write( " const short " + table_name + "[" + macro_name + "]\n" ) write( "#ifdef DEFINE_PS_TABLES_DATA\n" ) write( " =\n" ) write( " {\n" ) line = " " comma = "" col = 0 for name in sublist: line += comma line += "%4d" % self.indices[name] col += 1 comma = "," if col == 14: col = 0 comma = ",\n " write( line ) write( "\n" ) write( " }\n" ) write( "#endif /* DEFINE_PS_TABLES_DATA */\n" ) write( " ;\n\n\n" ) # We now store the Adobe Glyph List in compressed form. The list is put # into a data structure called `trie' (because it has a tree-like # appearance). Consider, for example, that you want to store the # following name mapping: # # A => 1 # Aacute => 6 # Abalon => 2 # Abstract => 4 # # It is possible to store the entries as follows. # # A => 1 # | # +-acute => 6 # | # +-b # | # +-alon => 2 # | # +-stract => 4 # # We see that each node in the trie has: # # - one or more `letters' # - an optional value # - zero or more child nodes # # The first step is to call # # root = StringNode( "", 0 ) # for word in map.values(): # root.add( word, map[word] ) # # which creates a large trie where each node has only one children. # # Executing # # root = root.optimize() # # optimizes the trie by merging the letters of successive nodes whenever # possible. # # Each node of the trie is stored as follows. # # - First the node's letter, according to the following scheme. We # use the fact that in the AGL no name contains character codes > 127. # # name bitsize description # ---------------------------------------------------------------- # notlast 1 Set to 1 if this is not the last letter # in the word. # ascii 7 The letter's ASCII value. # # - The letter is followed by a children count and the value of the # current key (if any). Again we can do some optimization because all # AGL entries are from the BMP; this means that 16 bits are sufficient # to store its Unicode values. Additionally, no node has more than # 127 children. # # name bitsize description # ----------------------------------------- # hasvalue 1 Set to 1 if a 16-bit Unicode value follows. # num_children 7 Number of children. Can be 0 only if # `hasvalue' is set to 1. # value 16 Optional Unicode value. # # - A node is finished by a list of 16bit absolute offsets to the # children, which must be sorted in increasing order of their first # letter. # # For simplicity, all 16bit quantities are stored in big-endian order. # # The root node has first letter = 0, and no value. # class StringNode: def __init__( self, letter, value ): self.letter = letter self.value = value self.children = {} def __cmp__( self, other ): return ord( self.letter[0] ) - ord( other.letter[0] ) def add( self, word, value ): if len( word ) == 0: self.value = value return letter = word[0] word = word[1:] if self.children.has_key( letter ): child = self.children[letter] else: child = StringNode( letter, 0 ) self.children[letter] = child child.add( word, value ) def optimize( self ): # optimize all children first children = self.children.values() self.children = {} for child in children: self.children[child.letter[0]] = child.optimize() # don't optimize if there's a value, # if we don't have any child or if we # have more than one child if ( self.value != 0 ) or ( not children ) or len( children ) > 1: return self child = children[0] self.letter += child.letter self.value = child.value self.children = child.children return self def dump_debug( self, write, margin ): # this is used during debugging line = margin + "+-" if len( self.letter ) == 0: line += "<NOLETTER>" else: line += self.letter if self.value: line += " => " + repr( self.value ) write( line + "\n" ) if self.children: margin += "| " for child in self.children.values(): child.dump_debug( write, margin ) def locate( self, index ): self.index = index if len( self.letter ) > 0: index += len( self.letter ) + 1 else: index += 2 if self.value != 0: index += 2 children = self.children.values() children.sort() index += 2 * len( children ) for child in children: index = child.locate( index ) return index def store( self, storage ): # write the letters l = len( self.letter ) if l == 0: storage += struct.pack( "B", 0 ) else: for n in range( l ): val = ord( self.letter[n] ) if n < l - 1: val += 128 storage += struct.pack( "B", val ) # write the count children = self.children.values() children.sort() count = len( children ) if self.value != 0: storage += struct.pack( "!BH", count + 128, self.value ) else: storage += struct.pack( "B", count ) for child in children: storage += struct.pack( "!H", child.index ) for child in children: storage = child.store( storage ) return storage def adobe_glyph_values(): """return the list of glyph names and their unicode values""" lines = string.split( adobe_glyph_list, '\n' ) glyphs = [] values = [] for line in lines: if line: fields = string.split( line, ';' ) # print fields[1] + ' - ' + fields[0] subfields = string.split( fields[1], ' ' ) if len( subfields ) == 1: glyphs.append( fields[0] ) values.append( fields[1] ) return glyphs, values def filter_glyph_names( alist, filter ): """filter `alist' by taking _out_ all glyph names that are in `filter'""" count = 0 extras = [] for name in alist: try: filtered_index = filter.index( name ) except: extras.append( name ) return extras def dump_encoding( file, encoding_name, encoding_list ): """dump a given encoding""" write = file.write write( " /* the following are indices into the SID name table */\n" ) write( "#ifndef DEFINE_PS_TABLES_DATA\n" ) write( "#ifdef __cplusplus\n" ) write( ' extern "C"\n' ) write( "#else\n" ) write( " extern\n" ) write( "#endif\n" ) write( "#endif\n" ) write( " const unsigned short " + encoding_name + "[" + repr( len( encoding_list ) ) + "]\n" ) write( "#ifdef DEFINE_PS_TABLES_DATA\n" ) write( " =\n" ) write( " {\n" ) line = " " comma = "" col = 0 for value in encoding_list: line += comma line += "%3d" % value comma = "," col += 1 if col == 16: col = 0 comma = ",\n " write( line ) write( "\n" ) write( " }\n" ) write( "#endif /* DEFINE_PS_TABLES_DATA */\n" ) write( " ;\n\n\n" ) def dump_array( the_array, write, array_name ): """dumps a given encoding""" write( "#ifndef DEFINE_PS_TABLES_DATA\n" ) write( "#ifdef __cplusplus\n" ) write( ' extern "C"\n' ) write( "#else\n" ) write( " extern\n" ) write( "#endif\n" ) write( "#endif\n" ) write( " const unsigned char " + array_name + "[" + repr( len( the_array ) ) + "L]\n" ) write( "#ifdef DEFINE_PS_TABLES_DATA\n" ) write( " =\n" ) write( " {\n" ) line = "" comma = " " col = 0 for value in the_array: line += comma line += "%3d" % ord( value ) comma = "," col += 1 if col == 16: col = 0 comma = ",\n " if len( line ) > 1024: write( line ) line = "" write( line ) write( "\n" ) write( " }\n" ) write( "#endif /* DEFINE_PS_TABLES_DATA */\n" ) write( " ;\n\n\n" ) def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "wb" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not in the SID Standard Names. # mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names ) # `base_list' contains the names of our final glyph names table. # It consists of the `mac_extras' glyph names, followed by the SID # standard names. # mac_extras_count = len( mac_extras ) base_list = mac_extras + sid_standard_names write( "/****************************************************************************\n" ) write( " *\n" ) write( " * %-71s\n" % os.path.basename( sys.argv[1] ) ) write( " *\n" ) write( " * PostScript glyph names.\n" ) write( " *\n" ) write( " * Copyright 2005-2019 by\n" ) write( " * David Turner, Robert Wilhelm, and Werner Lemberg.\n" ) write( " *\n" ) write( " * This file is part of the FreeType project, and may only be used,\n" ) write( " * modified, and distributed under the terms of the FreeType project\n" ) write( " * license, LICENSE.TXT. By continuing to use, modify, or distribute\n" ) write( " * this file you indicate that you have read the license and\n" ) write( " * understand and accept it fully.\n" ) write( " *\n" ) write( " */\n" ) write( "\n" ) write( "\n" ) write( " /* This file has been generated automatically -- do not edit! */\n" ) write( "\n" ) write( "\n" ) # dump final glyph list (mac extras + sid standard names) # st = StringTable( base_list, "ft_standard_glyph_names" ) st.dump( file ) st.dump_sublist( file, "ft_mac_names", "FT_NUM_MAC_NAMES", mac_standard_names ) st.dump_sublist( file, "ft_sid_names", "FT_NUM_SID_NAMES", sid_standard_names ) dump_encoding( file, "t1_standard_encoding", t1_standard_encoding ) dump_encoding( file, "t1_expert_encoding", t1_expert_encoding ) # dump the AGL in its compressed form # agl_glyphs, agl_values = adobe_glyph_values() dict = StringNode( "", 0 ) for g in range( len( agl_glyphs ) ): dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) ) dict = dict.optimize() dict_len = dict.locate( 0 ) dict_array = dict.store( "" ) write( """\ /* * This table is a compressed version of the Adobe Glyph List (AGL), * optimized for efficient searching. It has been generated by the * `glnames.py' python script located in the `src/tools' directory. * * The lookup function to get the Unicode value for a given string * is defined below the table. */ #ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST """ ) dump_array( dict_array, write, "ft_adobe_glyph_list" ) # write the lookup routine now # write( """\ #ifdef DEFINE_PS_TABLES /* * This function searches the compressed table efficiently. */ static unsigned long ft_get_adobe_glyph_index( const char* name, const char* limit ) { int c = 0; int count, min, max; const unsigned char* p = ft_adobe_glyph_list; if ( name == 0 || name >= limit ) goto NotFound; c = *name++; count = p[1]; p += 2; min = 0; max = count; while ( min < max ) { int mid = ( min + max ) >> 1; const unsigned char* q = p + mid * 2; int c2; q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] ); c2 = q[0] & 127; if ( c2 == c ) { p = q; goto Found; } if ( c2 < c ) min = mid + 1; else max = mid; } goto NotFound; Found: for (;;) { /* assert (*p & 127) == c */ if ( name >= limit ) { if ( (p[0] & 128) == 0 && (p[1] & 128) != 0 ) return (unsigned long)( ( (int)p[2] << 8 ) | p[3] ); goto NotFound; } c = *name++; if ( p[0] & 128 ) { p++; if ( c != (p[0] & 127) ) goto NotFound; continue; } p++; count = p[0] & 127; if ( p[0] & 128 ) p += 2; p++; for ( ; count > 0; count--, p += 2 ) { int offset = ( (int)p[0] << 8 ) | p[1]; const unsigned char* q = ft_adobe_glyph_list + offset; if ( c == ( q[0] & 127 ) ) { p = q; goto NextIter; } } goto NotFound; NextIter: ; } NotFound: return 0; } #endif /* DEFINE_PS_TABLES */ #endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */ """ ) if 0: # generate unit test, or don't # # now write the unit test to check that everything works OK # write( "#ifdef TEST\n\n" ) write( "static const char* const the_names[] = {\n" ) for name in agl_glyphs: write( ' "' + name + '",\n' ) write( " 0\n};\n" ) write( "static const unsigned long the_values[] = {\n" ) for val in agl_values: write( ' 0x' + val + ',\n' ) write( " 0\n};\n" ) write( """ #include <stdlib.h> #include <stdio.h> int main( void ) { int result = 0; const char* const* names = the_names; const unsigned long* values = the_values; for ( ; *names; names++, values++ ) { const char* name = *names; unsigned long reference = *values; unsigned long value; value = ft_get_adobe_glyph_index( name, name + strlen( name ) ); if ( value != reference ) { result = 1; fprintf( stderr, "name '%s' => %04x instead of %04x\\n", name, value, reference ); } } return result; } """ ) write( "#endif /* TEST */\n" ) write("\n/* END */\n") # Now run the main routine # main() # END
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/glnames.py
Python
gpl-3.0
106,054
#!/usr/bin/env python3 """Generate distribution archives for a given FreeType 2 release.""" from __future__ import print_function import argparse import atexit import os import shutil import subprocess import sys import tempfile _TOP_DIR = os.path.abspath(os.path.join(__file__, "..", "..", "..")) _SCRIPT_DIR = os.path.dirname(os.path.join(_TOP_DIR, "builds", "meson", "")) def get_cmd_output(cmd, cwd=None): """Run a command and return its output as a string.""" if cwd is not None: out = subprocess.check_output(cmd, cwd=cwd) else: out = subprocess.check_output(cmd) return out.decode("utf-8").rstrip() def is_git_dir_clean(git_dir): """Return True iff |git_dir| is a git directory in clean state.""" out = get_cmd_output(["git", "status", "--porcelain"], cwd=git_dir) return len(out) == 0 def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--source_dir", default=_TOP_DIR, help="Source directory path." ) parser.add_argument( "--version", help=( "Specify alternate FreeType version (it is otherwise extracted" " from current sources by default)." ), ) parser.add_argument( "--gnu-config-dir", help=( "Path of input directory containing recent `config.guess` and" " `config.sub` files from GNU config." ), ) parser.add_argument( "--build-dir", help="Specify build directory. Only used for debugging this script.", ) parser.add_argument( "--ignore-clean-check", action="store_true", help=( "Do not check for a clean source git repository. Only used for" " debugging this script." ), ) parser.add_argument( "output_dir", help="Output directory for generated archives." ) args = parser.parse_args() git_dir = args.source_dir if args.source_dir else _TOP_DIR if not args.ignore_clean_check and not is_git_dir_clean(git_dir): sys.stderr.write( "ERROR: Your git repository is not in a clean state: %s\n" % git_dir ) return 1 if args.version: version = args.version else: # Extract FreeType version from sources. version = get_cmd_output( [ sys.executable, os.path.join(_SCRIPT_DIR, "extract_freetype_version.py"), os.path.join(_TOP_DIR, "include", "freetype", "freetype.h"), ] ) # Determine the build directory. This will be a temporary file that is # cleaned up on script exit by default, unless --build-dir=DIR is used, # in which case we only create and empty the directory, but never remove # its content on exit. if args.build_dir: build_dir = args.build_dir if not os.path.exists(build_dir): os.makedirs(build_dir) else: # Remove anything from the build directory, if any. for item in os.listdir(build_dir): file_path = os.path.join(build_dir, item) if os.path.isdir(file_path): shutil.rmtree(file_path) else: os.unlink(file_path) else: # Create a temporary directory, and ensure it is removed on exit. build_dir = tempfile.mkdtemp(prefix="freetype-dist-") def clean_build_dir(): shutil.rmtree(build_dir) atexit.register(clean_build_dir) # Copy all source files known to git into $BUILD_DIR/freetype-$VERSION # with the exception of .gitignore and .mailmap files. source_files = [ f for f in get_cmd_output(["git", "ls-files"], cwd=git_dir).split("\n") if os.path.basename(f) not in (".gitignore", ".mailmap") ] freetype_dir = "freetype-" + version tmp_src_dir = os.path.join(build_dir, freetype_dir) os.makedirs(tmp_src_dir) for src in source_files: dst = os.path.join(tmp_src_dir, src) dst_dir = os.path.dirname(dst) if not os.path.exists(dst_dir): os.makedirs(dst_dir) shutil.copy(os.path.join(git_dir, src), dst) # Run autogen.sh in directory. subprocess.check_call(["/bin/sh", "autogen.sh"], cwd=tmp_src_dir) shutil.rmtree( os.path.join(tmp_src_dir, "builds", "unix", "autom4te.cache") ) # Copy config.guess and config.sub if possible! if args.gnu_config_dir: for f in ("config.guess", "config.sub"): shutil.copy( os.path.join(args.gnu_config_dir, f), os.path.join(tmp_src_dir, "builds", "unix", f), ) # Generate reference documentation under docs/ subprocess.check_call( [ sys.executable, os.path.join(_SCRIPT_DIR, "generate_reference_docs.py"), "--input-dir", tmp_src_dir, "--version", version, "--output-dir", os.path.join(tmp_src_dir, "docs"), ] ) shutil.rmtree(os.path.join(tmp_src_dir, "docs", "markdown")) os.unlink(os.path.join(tmp_src_dir, "docs", "mkdocs.yml")) # Generate our archives freetype_tar = freetype_dir + ".tar" subprocess.check_call( ["tar", "-H", "ustar", "-chf", freetype_tar, freetype_dir], cwd=build_dir, ) subprocess.check_call( ["gzip", "-9", "--keep", freetype_tar], cwd=build_dir ) subprocess.check_call(["xz", "--keep", freetype_tar], cwd=build_dir) ftwinversion = "ft" + "".join(version.split(".")) subprocess.check_call( ["zip", "-qlr9", ftwinversion + ".zip", freetype_dir], cwd=build_dir ) # Copy file to output directory now. if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) for f in ( freetype_tar + ".gz", freetype_tar + ".xz", ftwinversion + ".zip", ): shutil.copy( os.path.join(build_dir, f), os.path.join(args.output_dir, f) ) # Done! return 0 if __name__ == "__main__": sys.exit(main())
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/make_distribution_archives.py
Python
gpl-3.0
6,188
# Files that don't get a copyright, or which are taken from elsewhere. # # All lines in this file are patterns, including the comment lines; this # means that e.g. `FTL.TXT' matches all files that have this string in # the file name (including the path relative to the current directory, # always starting with `./'). # # Don't put empty lines into this file! # builds/unix/pkg.m4 # docs/FTL.TXT docs/GPLv2.TXT # include/freetype/internal/fthash.h # src/base/fthash.c src/base/md5.c src/base/md5.h # src/bdf/bdf.c src/bdf/bdf.h src/bdf/bdfdrivr.c src/bdf/bdfdrivr.h src/bdf/bdferror.h src/bdf/bdflib.c src/bdf/module.mk src/bdf/README src/bdf/rules.mk # src/pcf/module.mk src/pcf/pcf.c src/pcf/pcf.h src/pcf/pcfdrivr.c src/pcf/pcfdrivr.h src/pcf/pcferror.h src/pcf/pcfread.c src/pcf/pcfread.h src/pcf/pcfutil.c src/pcf/pcfutil.h src/pcf/README src/pcf/rules.mk # src/gzip/adler32.c src/gzip/infblock.c src/gzip/infblock.h src/gzip/infcodes.c src/gzip/infcodes.h src/gzip/inffixed.h src/gzip/inflate.c src/gzip/inftrees.c src/gzip/inftrees.h src/gzip/infutil.c src/gzip/infutil.h src/gzip/zconf.h src/gzip/zlib.h src/gzip/zutil.c src/gzip/zutil.h # src/tools/apinames.c src/tools/ftrandom/ftrandom.c # subprojects/dlg # # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/no-copyright
none
gpl-3.0
1,225
/* * gcc -DFT2_BUILD_LIBRARY -I../../include -o test_afm test_afm.c \ * -L../../objs/.libs -lfreetype -lz -static */ #include <freetype/freetype.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/psaux.h> void dump_fontinfo( AFM_FontInfo fi ) { FT_UInt i; printf( "This AFM is for %sCID font.\n\n", ( fi->IsCIDFont ) ? "" : "non-" ); printf( "FontBBox: %.2f %.2f %.2f %.2f\n", fi->FontBBox.xMin / 65536., fi->FontBBox.yMin / 65536., fi->FontBBox.xMax / 65536., fi->FontBBox.yMax / 65536. ); printf( "Ascender: %.2f\n", fi->Ascender / 65536. ); printf( "Descender: %.2f\n\n", fi->Descender / 65536. ); if ( fi->NumTrackKern ) printf( "There are %d sets of track kernings:\n", fi->NumTrackKern ); else printf( "There is no track kerning.\n" ); for ( i = 0; i < fi->NumTrackKern; i++ ) { AFM_TrackKern tk = fi->TrackKerns + i; printf( "\t%2d: %5.2f %5.2f %5.2f %5.2f\n", tk->degree, tk->min_ptsize / 65536., tk->min_kern / 65536., tk->max_ptsize / 65536., tk->max_kern / 65536. ); } printf( "\n" ); if ( fi->NumKernPair ) printf( "There are %d kerning pairs:\n", fi->NumKernPair ); else printf( "There is no kerning pair.\n" ); for ( i = 0; i < fi->NumKernPair; i++ ) { AFM_KernPair kp = fi->KernPairs + i; printf( "\t%3d + %3d => (%4d, %4d)\n", kp->index1, kp->index2, kp->x, kp->y ); } } int dummy_get_index( const char* name, FT_Offset len, void* user_data ) { if ( len ) return name[0]; else return 0; } FT_Error parse_afm( FT_Library library, FT_Stream stream, AFM_FontInfo fi ) { PSAux_Service psaux; AFM_ParserRec parser; FT_Error error = FT_Err_Ok; psaux = (PSAux_Service)FT_Get_Module_Interface( library, "psaux" ); if ( !psaux || !psaux->afm_parser_funcs ) return -1; error = FT_Stream_EnterFrame( stream, stream->size ); if ( error ) return error; error = psaux->afm_parser_funcs->init( &parser, library->memory, stream->cursor, stream->limit ); if ( error ) return error; parser.FontInfo = fi; parser.get_index = dummy_get_index; error = psaux->afm_parser_funcs->parse( &parser ); psaux->afm_parser_funcs->done( &parser ); return error; } int main( int argc, char** argv ) { FT_Library library; FT_StreamRec stream; FT_Error error = FT_Err_Ok; AFM_FontInfoRec fi; if ( argc < 2 ) return FT_ERR( Invalid_Argument ); error = FT_Init_FreeType( &library ); if ( error ) return error; FT_ZERO( &stream ); error = FT_Stream_Open( &stream, argv[1] ); if ( error ) goto Exit; stream.memory = library->memory; FT_ZERO( &fi ); error = parse_afm( library, &stream, &fi ); if ( !error ) { FT_Memory memory = library->memory; dump_fontinfo( &fi ); if ( fi.KernPairs ) FT_FREE( fi.KernPairs ); if ( fi.TrackKerns ) FT_FREE( fi.TrackKerns ); } else printf( "parse error\n" ); FT_Stream_Close( &stream ); Exit: FT_Done_FreeType( library ); return error; }
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/test_afm.c
C++
gpl-3.0
3,969
#include <freetype/freetype.h> #include <freetype/ftbbox.h> #include <time.h> /* for clock() */ /* SunOS 4.1.* does not define CLOCKS_PER_SEC, so include <sys/param.h> */ /* to get the HZ macro which is the equivalent. */ #if defined(__sun__) && !defined(SVR4) && !defined(__SVR4) #include <sys/param.h> #define CLOCKS_PER_SEC HZ #endif static long get_time( void ) { return clock() * 10000L / CLOCKS_PER_SEC; } /* test bbox computations */ #define XSCALE 65536 #define XX(x) ((FT_Pos)(x*XSCALE)) #define XVEC(x,y) { XX(x), XX(y) } #define XVAL(x) ((x)/(1.0*XSCALE)) /* dummy outline #1 */ static FT_Vector dummy_vec_1[4] = { #if 1 XVEC( 408.9111, 535.3164 ), XVEC( 455.8887, 634.396 ), XVEC( -37.8765, 786.2207 ), XVEC( 164.6074, 535.3164 ) #else { (FT_Int32)0x0198E93DL , (FT_Int32)0x021750FFL }, /* 408.9111, 535.3164 */ { (FT_Int32)0x01C7E312L , (FT_Int32)0x027A6560L }, /* 455.8887, 634.3960 */ { (FT_Int32)0xFFDA1F9EL , (FT_Int32)0x0312387FL }, /* -37.8765, 786.2207 */ { (FT_Int32)0x00A49B7EL , (FT_Int32)0x021750FFL } /* 164.6074, 535.3164 */ #endif }; static char dummy_tag_1[4] = { FT_CURVE_TAG_ON, FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_ON }; static short dummy_contour_1[1] = { 3 }; static FT_Outline dummy_outline_1 = { 1, 4, dummy_vec_1, dummy_tag_1, dummy_contour_1, 0 }; /* dummy outline #2 */ static FT_Vector dummy_vec_2[4] = { XVEC( 100.0, 100.0 ), XVEC( 100.0, 200.0 ), XVEC( 200.0, 200.0 ), XVEC( 200.0, 133.0 ) }; static FT_Outline dummy_outline_2 = { 1, 4, dummy_vec_2, dummy_tag_1, dummy_contour_1, 0 }; /* dummy outline #3 with bbox of [0 100 128 128] precisely */ static FT_Vector dummy_vec_3[4] = { XVEC( 100.0, 127.0 ), XVEC( 200.0, 127.0 ), XVEC( 0.0, 136.0 ), XVEC( 0.0, 100.0 ) }; static FT_Outline dummy_outline_3 = { 1, 4, dummy_vec_3, dummy_tag_1, dummy_contour_1, 0 }; static void dump_outline( FT_Outline* outline ) { FT_BBox bbox; /* compute and display cbox */ FT_Outline_Get_CBox( outline, &bbox ); printf( "cbox = [%.2f %.2f %.2f %.2f]\n", XVAL( bbox.xMin ), XVAL( bbox.yMin ), XVAL( bbox.xMax ), XVAL( bbox.yMax ) ); /* compute and display bbox */ FT_Outline_Get_BBox( outline, &bbox ); printf( "bbox = [%.2f %.2f %.2f %.2f]\n", XVAL( bbox.xMin ), XVAL( bbox.yMin ), XVAL( bbox.xMax ), XVAL( bbox.yMax ) ); } static void profile_outline( FT_Outline* outline, long repeat ) { FT_BBox bbox; long count; long time0; time0 = get_time(); for ( count = repeat; count > 0; count-- ) FT_Outline_Get_CBox( outline, &bbox ); time0 = get_time() - time0; printf( "time = %6.3f cbox = [%8.4f %8.4f %8.4f %8.4f]\n", ((double)time0/10000.0), XVAL( bbox.xMin ), XVAL( bbox.yMin ), XVAL( bbox.xMax ), XVAL( bbox.yMax ) ); printf( "cbox_hex = [%08X %08X %08X %08X]\n", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax ); time0 = get_time(); for ( count = repeat; count > 0; count-- ) FT_Outline_Get_BBox( outline, &bbox ); time0 = get_time() - time0; printf( "time = %6.3f bbox = [%8.4f %8.4f %8.4f %8.4f]\n", ((double)time0/10000.0), XVAL( bbox.xMin ), XVAL( bbox.yMin ), XVAL( bbox.xMax ), XVAL( bbox.yMax ) ); printf( "bbox_hex = [%08X %08X %08X %08X]\n", bbox.xMin, bbox.yMin, bbox.xMax, bbox.yMax ); } #define REPEAT 1000000L int main( int argc, char** argv ) { printf( "outline #1\n" ); profile_outline( &dummy_outline_1, REPEAT ); printf( "outline #2\n" ); profile_outline( &dummy_outline_2, REPEAT ); printf( "outline #3\n" ); profile_outline( &dummy_outline_3, REPEAT ); return 0; }
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/test_bbox.c
C++
gpl-3.0
4,191
#include <freetype/freetype.h> #include <freetype/fttrigon.h> #include <math.h> #include <stdio.h> #define PI 3.14159265358979323846 #define SPI (PI/FT_ANGLE_PI) /* the precision in 16.16 fixed-point checks. Expect between 2 and 5 */ /* noise LSB bits during operations, due to rounding errors.. */ #define THRESHOLD 64 static error = 0; static void test_cos( void ) { int i; for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Fixed f1, f2; double d2; f1 = FT_Cos(i); d2 = cos( i*SPI ); f2 = (FT_Fixed)(d2*65536.0); if ( abs( f2-f1 ) > THRESHOLD ) { error = 1; printf( "FT_Cos[%3d] = %.7f cos[%3d] = %.7f\n", (i >> 16), f1/65536.0, (i >> 16), d2 ); } } } static void test_sin( void ) { int i; for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Fixed f1, f2; double d2; f1 = FT_Sin(i); d2 = sin( i*SPI ); f2 = (FT_Fixed)(d2*65536.0); if ( abs( f2-f1 ) > THRESHOLD ) { error = 1; printf( "FT_Sin[%3d] = %.7f sin[%3d] = %.7f\n", (i >> 16), f1/65536.0, (i >> 16), d2 ); } } } static void test_tan( void ) { int i; for ( i = 0; i < FT_ANGLE_PI2 - 0x2000000L; i += 0x10000L ) { FT_Fixed f1, f2; double d2; f1 = FT_Tan(i); d2 = tan( i*SPI ); f2 = (FT_Fixed)(d2*65536.0); if ( abs( f2-f1 ) > THRESHOLD ) { error = 1; printf( "FT_Tan[%3d] = %.7f tan[%3d] = %.7f\n", (i >> 16), f1/65536.0, (i >> 16), d2 ); } } } static void test_atan2( void ) { int i; for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Fixed c2, s2; double l, a, c1, s1; int j; l = 5.0; a = i*SPI; c1 = l * cos(a); s1 = l * sin(a); c2 = (FT_Fixed)(c1*65536.0); s2 = (FT_Fixed)(s1*65536.0); j = FT_Atan2( c2, s2 ); if ( j < 0 ) j += FT_ANGLE_2PI; if ( abs( i - j ) > 1 ) { printf( "FT_Atan2( %.7f, %.7f ) = %.5f, atan = %.5f\n", c2/65536.0, s2/65536.0, j/65536.0, i/65536.0 ); } } } static void test_unit( void ) { int i; for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Vector v; double a, c1, s1; FT_Fixed c2, s2; FT_Vector_Unit( &v, i ); a = ( i*SPI ); c1 = cos(a); s1 = sin(a); c2 = (FT_Fixed)(c1*65536.0); s2 = (FT_Fixed)(s1*65536.0); if ( abs( v.x-c2 ) > THRESHOLD || abs( v.y-s2 ) > THRESHOLD ) { error = 1; printf( "FT_Vector_Unit[%3d] = ( %.7f, %.7f ) vec = ( %.7f, %.7f )\n", (i >> 16), v.x/65536.0, v.y/65536.0, c1, s1 ); } } } static void test_length( void ) { int i; for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Vector v; FT_Fixed l, l2; l = (FT_Fixed)(500.0*65536.0); v.x = (FT_Fixed)( l * cos( i*SPI ) ); v.y = (FT_Fixed)( l * sin( i*SPI ) ); l2 = FT_Vector_Length( &v ); if ( abs( l2-l ) > THRESHOLD ) { error = 1; printf( "FT_Length( %.7f, %.7f ) = %.5f, length = %.5f\n", v.x/65536.0, v.y/65536.0, l2/65536.0, l/65536.0 ); } } } static void test_rotate( void ) { int rotate; for ( rotate = 0; rotate < FT_ANGLE_2PI; rotate += 0x10000L ) { double ra, cra, sra; int i; ra = rotate*SPI; cra = cos( ra ); sra = sin( ra ); for ( i = 0; i < FT_ANGLE_2PI; i += 0x10000L ) { FT_Fixed c2, s2, c4, s4; FT_Vector v; double l, a, c1, s1, c3, s3; l = 500.0; a = i*SPI; c1 = l * cos(a); s1 = l * sin(a); v.x = c2 = (FT_Fixed)(c1*65536.0); v.y = s2 = (FT_Fixed)(s1*65536.0); FT_Vector_Rotate( &v, rotate ); c3 = c1 * cra - s1 * sra; s3 = c1 * sra + s1 * cra; c4 = (FT_Fixed)(c3*65536.0); s4 = (FT_Fixed)(s3*65536.0); if ( abs( c4 - v.x ) > THRESHOLD || abs( s4 - v.y ) > THRESHOLD ) { error = 1; printf( "FT_Rotate( (%.7f,%.7f), %.5f ) = ( %.7f, %.7f ), rot = ( %.7f, %.7f )\n", c1, s1, ra, c2/65536.0, s2/65536.0, c4/65536.0, s4/65536.0 ); } } } } int main( void ) { test_cos(); test_sin(); test_tan(); test_atan2(); test_unit(); test_length(); test_rotate(); if (!error) printf( "trigonometry test ok !\n" ); return !error; }
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/test_trig.c
C++
gpl-3.0
4,826
#!/bin/sh # Run the `update-copyright-year' script on all files in the git repository, # taking care of exceptions stored in file `no-copyright'. topdir=`git rev-parse --show-toplevel` toolsdir=$topdir/src/tools git ls-files --full-name $topdir \ | sed 's|^|../../|' \ | grep -vFf $toolsdir/no-copyright \ | xargs $toolsdir/update-copyright-year # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/update-copyright
none
gpl-3.0
388
eval '(exit $?0)' && eval 'exec perl -wS -i "$0" ${1+"$@"}' & eval 'exec perl -wS -i "$0" $argv:q' if 0; # Copyright (C) 2015-2022 by # Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # [Note: This script is expected to be called by the shell, which in turn # calls perl automatically. The nifty start-up code above is based on # gnulib's `update-copyright' script; it is a more portable replacement for # the shebang, using the first `perl' program in the shell's path instead.] # Usage: # # update-copyright-year file1 [file2 ...] # This script handles copyright entries like # # Copyright 2000 by # foobar # # or # # /* Copyright (c) 2000, 2001, 2004-2007 by */ # /* foobar */ # # and replaces them uniformly with # # Copyright (C) 2000-2021 # foobar # # and # # /* Copyright (C) 2000-2021 by */ # /* foobar */ # # (assuming that the current year is 2021). As can be seen, the line length # is retained if there is non-whitespace after the word `by' on the same # line. use strict; my (undef, undef, undef, undef, undef, $year, undef, undef, undef) = localtime(time); $year += 1900; my $replaced = 0; # Loop over all input files; option `-i' (issued at the very beginning of # this script) makes perl edit them in-place. while (<>) { # Only handle the first copyright notice in a file. if (!$replaced) { # First try: Search multiple copyright years. s { (?<begin>.*) Copyright (?<space1>(\ + | \ +\(C\)\ +)) (?<first>[12][0-9][0-9][0-9]) (?<middle>.+) (?<last>[12][0-9][0-9][0-9]) (?<space2>\ +) by (?<space3>\ *) (?<end>.*) } { # Fill line to the same length (if appropriate); we skip the middle # part but insert `(C)', three spaces, and `-'. my $space = length($+{space1}) + length($+{middle}) + length($+{space2}) + length($+{space3}) - (length("(C)") + 3 + 1); print "$+{begin}"; print "Copyright\ (C)\ $+{first}-$year\ by"; print ' ' x $space if length($+{end}); print "$+{end}\n"; $replaced = 1; }ex || # Second try: Search a single copyright year. s { (?<begin>.*) Copyright (?<space1>(\ + | \ +\(C\)\ +)) (?<first>[12][0-9][0-9][0-9]) (?<space2>\ +) by (?<space3>\ *) (?<end>.*) } { if ($+{first} < $year) { # Fill line to the same length (if appropriate); we insert three # spaces, the string `(C)', a `-', and the current year. my $space = length($+{space1}) + length($+{space2}) + length($+{space3}) - (length($year) + length("(C)") + 3 + 1); print "$+{begin}"; print "Copyright\ (C)\ $+{first}-$year\ by"; # If $space is negative this inserts nothing. print ' ' x $space if length($+{end}); print "$+{end}\n"; $replaced = 1; } else { # Fill line to the same length (if appropriate); we insert three # spaces and the string `(C)'. my $space = length($+{space1}) + length($+{space2}) + length($+{space3}) - (length("(C)") + 3); print "$+{begin}"; print "Copyright\ (C)\ $+{first}\ by"; # If $space is negative this inserts nothing. print ' ' x $space if length($+{end}); print "$+{end}\n"; $replaced = 1; } }ex || # Otherwise print line unaltered. print; } else { print; } } continue { # Reset $replaced before processing the next file. $replaced = 0 if eof; } # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/tools/update-copyright-year
none
gpl-3.0
4,272
# # FreeType 2 TrueType module definition # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += TRUETYPE_DRIVER define TRUETYPE_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, tt_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)truetype $(ECHO_DRIVER_DESC)Windows/Mac font files with extension *.ttf or *.ttc$(ECHO_DRIVER_DONE) endef # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/module.mk
mk
gpl-3.0
687
# # FreeType 2 TrueType driver configuration rules # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # TrueType driver directory # TT_DIR := $(SRC_DIR)/truetype # compilation flags for the driver # TT_COMPILE := $(CC) $(ANSIFLAGS) \ $I$(subst /,$(COMPILER_SEP),$(TT_DIR)) \ $(INCLUDE_FLAGS) \ $(FT_CFLAGS) # TrueType driver sources (i.e., C files) # TT_DRV_SRC := $(TT_DIR)/ttdriver.c \ $(TT_DIR)/ttgload.c \ $(TT_DIR)/ttgxvar.c \ $(TT_DIR)/ttinterp.c \ $(TT_DIR)/ttobjs.c \ $(TT_DIR)/ttpload.c \ $(TT_DIR)/ttsubpix.c # TrueType driver headers # TT_DRV_H := $(TT_DRV_SRC:%.c=%.h) \ $(TT_DIR)/tterrors.h # TrueType driver object(s) # # TT_DRV_OBJ_M is used during `multi' builds # TT_DRV_OBJ_S is used during `single' builds # TT_DRV_OBJ_M := $(TT_DRV_SRC:$(TT_DIR)/%.c=$(OBJ_DIR)/%.$O) TT_DRV_OBJ_S := $(OBJ_DIR)/truetype.$O # TrueType driver source file for single build # TT_DRV_SRC_S := $(TT_DIR)/truetype.c # TrueType driver - single object # $(TT_DRV_OBJ_S): $(TT_DRV_SRC_S) $(TT_DRV_SRC) $(FREETYPE_H) $(TT_DRV_H) $(TT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(TT_DRV_SRC_S)) # driver - multiple objects # $(OBJ_DIR)/%.$O: $(TT_DIR)/%.c $(FREETYPE_H) $(TT_DRV_H) $(TT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(TT_DRV_OBJ_S) DRV_OBJS_M += $(TT_DRV_OBJ_M) # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/rules.mk
mk
gpl-3.0
1,888
/**************************************************************************** * * truetype.c * * FreeType TrueType driver component (body only). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #define FT_MAKE_OPTION_SINGLE_OBJECT #include "ttdriver.c" /* driver interface */ #include "ttgload.c" /* glyph loader */ #include "ttgxvar.c" /* gx distortable font */ #include "ttinterp.c" #include "ttobjs.c" /* object manager */ #include "ttpload.c" /* tables loader */ #include "ttsubpix.c" /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/truetype.c
C++
gpl-3.0
896
/**************************************************************************** * * ttdriver.c * * TrueType font driver implementation (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/sfnt.h> #include <freetype/internal/services/svfntfmt.h> #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include <freetype/ftmm.h> #include <freetype/internal/services/svmm.h> #include <freetype/internal/services/svmetric.h> #endif #include <freetype/internal/services/svtteng.h> #include <freetype/internal/services/svttglyf.h> #include <freetype/internal/services/svprop.h> #include <freetype/ftdriver.h> #include "ttdriver.h" #include "ttgload.h" #include "ttpload.h" #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include "ttgxvar.h" #endif #include "tterrors.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttdriver /* * PROPERTY SERVICE * */ static FT_Error tt_property_set( FT_Module module, /* TT_Driver */ const char* property_name, const void* value, FT_Bool value_is_string ) { FT_Error error = FT_Err_Ok; TT_Driver driver = (TT_Driver)module; #ifndef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES FT_UNUSED( value_is_string ); #endif if ( !ft_strcmp( property_name, "interpreter-version" ) ) { FT_UInt interpreter_version; #ifdef FT_CONFIG_OPTION_ENVIRONMENT_PROPERTIES if ( value_is_string ) { const char* s = (const char*)value; interpreter_version = (FT_UInt)ft_strtol( s, NULL, 10 ); } else #endif { FT_UInt* iv = (FT_UInt*)value; interpreter_version = *iv; } if ( interpreter_version == TT_INTERPRETER_VERSION_35 #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY || interpreter_version == TT_INTERPRETER_VERSION_38 #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL || interpreter_version == TT_INTERPRETER_VERSION_40 #endif ) driver->interpreter_version = interpreter_version; else error = FT_ERR( Unimplemented_Feature ); return error; } FT_TRACE2(( "tt_property_set: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } static FT_Error tt_property_get( FT_Module module, /* TT_Driver */ const char* property_name, const void* value ) { FT_Error error = FT_Err_Ok; TT_Driver driver = (TT_Driver)module; FT_UInt interpreter_version = driver->interpreter_version; if ( !ft_strcmp( property_name, "interpreter-version" ) ) { FT_UInt* val = (FT_UInt*)value; *val = interpreter_version; return error; } FT_TRACE2(( "tt_property_get: missing property `%s'\n", property_name )); return FT_THROW( Missing_Property ); } FT_DEFINE_SERVICE_PROPERTIESREC( tt_service_properties, (FT_Properties_SetFunc)tt_property_set, /* set_property */ (FT_Properties_GetFunc)tt_property_get /* get_property */ ) /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** F A C E S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * @Function: * tt_get_kerning * * @Description: * A driver method used to return the kerning vector between two * glyphs of the same face. * * @Input: * face :: * A handle to the source face object. * * left_glyph :: * The index of the left glyph in the kern pair. * * right_glyph :: * The index of the right glyph in the kern pair. * * @Output: * kerning :: * The kerning vector. This is in font units for * scalable formats, and in pixels for fixed-sizes * formats. * * @Return: * FreeType error code. 0 means success. * * @Note: * Only horizontal layouts (left-to-right & right-to-left) are * supported by this function. Other layouts, or more sophisticated * kernings, are out of scope of this method (the basic driver * interface is meant to be simple). * * They can be implemented by format-specific interfaces. */ static FT_Error tt_get_kerning( FT_Face ttface, /* TT_Face */ FT_UInt left_glyph, FT_UInt right_glyph, FT_Vector* kerning ) { TT_Face face = (TT_Face)ttface; SFNT_Service sfnt = (SFNT_Service)face->sfnt; kerning->x = 0; kerning->y = 0; if ( sfnt ) kerning->x = sfnt->get_kerning( face, left_glyph, right_glyph ); return 0; } static FT_Error tt_get_advances( FT_Face ttface, FT_UInt start, FT_UInt count, FT_Int32 flags, FT_Fixed *advances ) { FT_UInt nn; TT_Face face = (TT_Face)ttface; /* XXX: TODO: check for sbits */ if ( flags & FT_LOAD_VERTICAL_LAYOUT ) { #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /* no fast retrieval for blended MM fonts without VVAR table */ if ( ( FT_IS_NAMED_INSTANCE( ttface ) || FT_IS_VARIATION( ttface ) ) && !( face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) return FT_THROW( Unimplemented_Feature ); #endif for ( nn = 0; nn < count; nn++ ) { FT_Short tsb; FT_UShort ah; /* since we don't need `tsb', we use zero for `yMax' parameter */ TT_Get_VMetrics( face, start + nn, 0, &tsb, &ah ); advances[nn] = ah; } } else { #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /* no fast retrieval for blended MM fonts without HVAR table */ if ( ( FT_IS_NAMED_INSTANCE( ttface ) || FT_IS_VARIATION( ttface ) ) && !( face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) return FT_THROW( Unimplemented_Feature ); #endif for ( nn = 0; nn < count; nn++ ) { FT_Short lsb; FT_UShort aw; TT_Get_HMetrics( face, start + nn, &lsb, &aw ); advances[nn] = aw; } } return FT_Err_Ok; } /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** S I Z E S ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS static FT_Error tt_size_select( FT_Size size, FT_ULong strike_index ) { TT_Face ttface = (TT_Face)size->face; TT_Size ttsize = (TT_Size)size; FT_Error error = FT_Err_Ok; ttsize->strike_index = strike_index; if ( FT_IS_SCALABLE( size->face ) ) { /* use the scaled metrics, even when tt_size_reset fails */ FT_Select_Metrics( size->face, strike_index ); tt_size_reset( ttsize, 0 ); /* ignore return value */ } else { SFNT_Service sfnt = (SFNT_Service)ttface->sfnt; FT_Size_Metrics* size_metrics = &size->metrics; error = sfnt->load_strike_metrics( ttface, strike_index, size_metrics ); if ( error ) ttsize->strike_index = 0xFFFFFFFFUL; } return error; } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ static FT_Error tt_size_request( FT_Size size, FT_Size_Request req ) { TT_Size ttsize = (TT_Size)size; FT_Error error = FT_Err_Ok; #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS if ( FT_HAS_FIXED_SIZES( size->face ) ) { TT_Face ttface = (TT_Face)size->face; SFNT_Service sfnt = (SFNT_Service)ttface->sfnt; FT_ULong strike_index; error = sfnt->set_sbit_strike( ttface, req, &strike_index ); if ( error ) ttsize->strike_index = 0xFFFFFFFFUL; else return tt_size_select( size, strike_index ); } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ { FT_Error err = FT_Request_Metrics( size->face, req ); if ( err ) { error = err; goto Exit; } } if ( FT_IS_SCALABLE( size->face ) ) { error = tt_size_reset( ttsize, 0 ); #ifdef TT_USE_BYTECODE_INTERPRETER /* for the `MPS' bytecode instruction we need the point size */ if ( !error ) { FT_UInt resolution = ttsize->metrics->x_ppem > ttsize->metrics->y_ppem ? req->horiResolution : req->vertResolution; /* if we don't have a resolution value, assume 72dpi */ if ( req->type == FT_SIZE_REQUEST_TYPE_SCALES || !resolution ) resolution = 72; ttsize->point_size = FT_MulDiv( ttsize->ttmetrics.ppem, 64 * 72, resolution ); } #endif } Exit: return error; } /************************************************************************** * * @Function: * tt_glyph_load * * @Description: * A driver method used to load a glyph within a given glyph slot. * * @Input: * slot :: * A handle to the target slot object where the glyph * will be loaded. * * size :: * A handle to the source face size at which the glyph * must be scaled, loaded, etc. * * glyph_index :: * The index of the glyph in the font file. * * load_flags :: * A flag indicating what to load for this glyph. The * FT_LOAD_XXX constants can be used to control the * glyph loading process (e.g., whether the outline * should be scaled, whether to load bitmaps or not, * whether to hint the outline, etc). * * @Return: * FreeType error code. 0 means success. */ static FT_Error tt_glyph_load( FT_GlyphSlot ttslot, /* TT_GlyphSlot */ FT_Size ttsize, /* TT_Size */ FT_UInt glyph_index, FT_Int32 load_flags ) { TT_GlyphSlot slot = (TT_GlyphSlot)ttslot; TT_Size size = (TT_Size)ttsize; FT_Face face = ttslot->face; FT_Error error; if ( !slot ) return FT_THROW( Invalid_Slot_Handle ); if ( !size ) return FT_THROW( Invalid_Size_Handle ); if ( !face ) return FT_THROW( Invalid_Face_Handle ); #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_index >= (FT_UInt)face->num_glyphs && !face->internal->incremental_interface ) #else if ( glyph_index >= (FT_UInt)face->num_glyphs ) #endif return FT_THROW( Invalid_Argument ); if ( load_flags & FT_LOAD_NO_HINTING ) { /* both FT_LOAD_NO_HINTING and FT_LOAD_NO_AUTOHINT */ /* are necessary to disable hinting for tricky fonts */ if ( FT_IS_TRICKY( face ) ) load_flags &= ~FT_LOAD_NO_HINTING; if ( load_flags & FT_LOAD_NO_AUTOHINT ) load_flags |= FT_LOAD_NO_HINTING; } if ( load_flags & ( FT_LOAD_NO_RECURSE | FT_LOAD_NO_SCALE ) ) { load_flags |= FT_LOAD_NO_BITMAP | FT_LOAD_NO_SCALE; if ( !FT_IS_TRICKY( face ) ) load_flags |= FT_LOAD_NO_HINTING; } /* use hinted metrics only if we load a glyph with hinting */ size->metrics = ( load_flags & FT_LOAD_NO_HINTING ) ? &ttsize->metrics : &size->hinted_metrics; /* now fill in the glyph slot with outline/bitmap/layered */ error = TT_Load_Glyph( size, slot, glyph_index, load_flags ); /* force drop-out mode to 2 - irrelevant now */ /* slot->outline.dropout_mode = 2; */ return error; } /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /**** ****/ /**** ****/ /**** D R I V E R I N T E R F A C E ****/ /**** ****/ /**** ****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_DEFINE_SERVICE_MULTIMASTERSREC( tt_service_gx_multi_masters, (FT_Get_MM_Func) NULL, /* get_mm */ (FT_Set_MM_Design_Func) NULL, /* set_mm_design */ (FT_Set_MM_Blend_Func) TT_Set_MM_Blend, /* set_mm_blend */ (FT_Get_MM_Blend_Func) TT_Get_MM_Blend, /* get_mm_blend */ (FT_Get_MM_Var_Func) TT_Get_MM_Var, /* get_mm_var */ (FT_Set_Var_Design_Func) TT_Set_Var_Design, /* set_var_design */ (FT_Get_Var_Design_Func) TT_Get_Var_Design, /* get_var_design */ (FT_Set_Instance_Func) TT_Set_Named_Instance, /* set_instance */ (FT_Set_MM_WeightVector_Func)NULL, /* set_mm_weightvector */ (FT_Get_MM_WeightVector_Func)NULL, /* get_mm_weightvector */ (FT_Get_Var_Blend_Func) tt_get_var_blend, /* get_var_blend */ (FT_Done_Blend_Func) tt_done_blend /* done_blend */ ) FT_DEFINE_SERVICE_METRICSVARIATIONSREC( tt_service_metrics_variations, (FT_HAdvance_Adjust_Func)tt_hadvance_adjust, /* hadvance_adjust */ (FT_LSB_Adjust_Func) NULL, /* lsb_adjust */ (FT_RSB_Adjust_Func) NULL, /* rsb_adjust */ (FT_VAdvance_Adjust_Func)tt_vadvance_adjust, /* vadvance_adjust */ (FT_TSB_Adjust_Func) NULL, /* tsb_adjust */ (FT_BSB_Adjust_Func) NULL, /* bsb_adjust */ (FT_VOrg_Adjust_Func) NULL, /* vorg_adjust */ (FT_Metrics_Adjust_Func) tt_apply_mvar /* metrics_adjust */ ) #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ static const FT_Service_TrueTypeEngineRec tt_service_truetype_engine = { #ifdef TT_USE_BYTECODE_INTERPRETER FT_TRUETYPE_ENGINE_TYPE_PATENTED #else /* !TT_USE_BYTECODE_INTERPRETER */ FT_TRUETYPE_ENGINE_TYPE_NONE #endif /* TT_USE_BYTECODE_INTERPRETER */ }; FT_DEFINE_SERVICE_TTGLYFREC( tt_service_truetype_glyf, (TT_Glyf_GetLocationFunc)tt_face_get_location /* get_location */ ) #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_DEFINE_SERVICEDESCREC6( tt_services, FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_TRUETYPE, FT_SERVICE_ID_MULTI_MASTERS, &tt_service_gx_multi_masters, FT_SERVICE_ID_METRICS_VARIATIONS, &tt_service_metrics_variations, FT_SERVICE_ID_TRUETYPE_ENGINE, &tt_service_truetype_engine, FT_SERVICE_ID_TT_GLYF, &tt_service_truetype_glyf, FT_SERVICE_ID_PROPERTIES, &tt_service_properties ) #else FT_DEFINE_SERVICEDESCREC4( tt_services, FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_TRUETYPE, FT_SERVICE_ID_TRUETYPE_ENGINE, &tt_service_truetype_engine, FT_SERVICE_ID_TT_GLYF, &tt_service_truetype_glyf, FT_SERVICE_ID_PROPERTIES, &tt_service_properties ) #endif FT_CALLBACK_DEF( FT_Module_Interface ) tt_get_interface( FT_Module driver, /* TT_Driver */ const char* tt_interface ) { FT_Library library; FT_Module_Interface result; FT_Module sfntd; SFNT_Service sfnt; result = ft_service_list_lookup( tt_services, tt_interface ); if ( result ) return result; if ( !driver ) return NULL; library = driver->library; if ( !library ) return NULL; /* only return the default interface from the SFNT module */ sfntd = FT_Get_Module( library, "sfnt" ); if ( sfntd ) { sfnt = (SFNT_Service)( sfntd->clazz->module_interface ); if ( sfnt ) return sfnt->get_interface( driver, tt_interface ); } return 0; } /* The FT_DriverInterface structure is defined in ftdriver.h. */ #ifdef TT_USE_BYTECODE_INTERPRETER #define TT_HINTER_FLAG FT_MODULE_DRIVER_HAS_HINTER #else #define TT_HINTER_FLAG 0 #endif #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS #define TT_SIZE_SELECT tt_size_select #else #define TT_SIZE_SELECT 0 #endif FT_DEFINE_DRIVER( tt_driver_class, FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_SCALABLE | TT_HINTER_FLAG, sizeof ( TT_DriverRec ), "truetype", /* driver name */ 0x10000L, /* driver version == 1.0 */ 0x20000L, /* driver requires FreeType 2.0 or above */ NULL, /* module-specific interface */ tt_driver_init, /* FT_Module_Constructor module_init */ tt_driver_done, /* FT_Module_Destructor module_done */ tt_get_interface, /* FT_Module_Requester get_interface */ sizeof ( TT_FaceRec ), sizeof ( TT_SizeRec ), sizeof ( FT_GlyphSlotRec ), tt_face_init, /* FT_Face_InitFunc init_face */ tt_face_done, /* FT_Face_DoneFunc done_face */ tt_size_init, /* FT_Size_InitFunc init_size */ tt_size_done, /* FT_Size_DoneFunc done_size */ tt_slot_init, /* FT_Slot_InitFunc init_slot */ NULL, /* FT_Slot_DoneFunc done_slot */ tt_glyph_load, /* FT_Slot_LoadFunc load_glyph */ tt_get_kerning, /* FT_Face_GetKerningFunc get_kerning */ NULL, /* FT_Face_AttachFunc attach_file */ tt_get_advances, /* FT_Face_GetAdvancesFunc get_advances */ tt_size_request, /* FT_Size_RequestFunc request_size */ TT_SIZE_SELECT /* FT_Size_SelectFunc select_size */ ) /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttdriver.c
C++
gpl-3.0
20,532
/**************************************************************************** * * ttdriver.h * * High-level TrueType driver interface (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTDRIVER_H_ #define TTDRIVER_H_ #include <freetype/internal/ftdrv.h> FT_BEGIN_HEADER FT_DECLARE_DRIVER( tt_driver_class ) FT_END_HEADER #endif /* TTDRIVER_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttdriver.h
C++
gpl-3.0
748
/**************************************************************************** * * tterrors.h * * TrueType error codes (specification only). * * Copyright (C) 2001-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This file is used to define the TrueType error enumeration * constants. * */ #ifndef TTERRORS_H_ #define TTERRORS_H_ #include <freetype/ftmoderr.h> #undef FTERRORS_H_ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX TT_Err_ #define FT_ERR_BASE FT_Mod_Err_TrueType #include <freetype/fterrors.h> #endif /* TTERRORS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/tterrors.h
C++
gpl-3.0
981
/**************************************************************************** * * ttgload.c * * TrueType Glyph Loader (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <ft2build.h> #include <freetype/internal/ftdebug.h> #include FT_CONFIG_CONFIG_H #include <freetype/internal/ftcalc.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/sfnt.h> #include <freetype/tttags.h> #include <freetype/ftoutln.h> #include <freetype/ftdriver.h> #include <freetype/ftlist.h> #include "ttgload.h" #include "ttpload.h" #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include "ttgxvar.h" #endif #include "tterrors.h" #include "ttsubpix.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttgload /************************************************************************** * * Simple glyph flags. */ #define ON_CURVE_POINT 0x01 /* same value as FT_CURVE_TAG_ON */ #define X_SHORT_VECTOR 0x02 #define Y_SHORT_VECTOR 0x04 #define REPEAT_FLAG 0x08 #define X_POSITIVE 0x10 /* two meanings depending on X_SHORT_VECTOR */ #define SAME_X 0x10 #define Y_POSITIVE 0x20 /* two meanings depending on Y_SHORT_VECTOR */ #define SAME_Y 0x20 #define OVERLAP_SIMPLE 0x40 /* retained as FT_OUTLINE_OVERLAP */ /************************************************************************** * * Composite glyph flags. */ #define ARGS_ARE_WORDS 0x0001 #define ARGS_ARE_XY_VALUES 0x0002 #define ROUND_XY_TO_GRID 0x0004 #define WE_HAVE_A_SCALE 0x0008 /* reserved 0x0010 */ #define MORE_COMPONENTS 0x0020 #define WE_HAVE_AN_XY_SCALE 0x0040 #define WE_HAVE_A_2X2 0x0080 #define WE_HAVE_INSTR 0x0100 #define USE_MY_METRICS 0x0200 #define OVERLAP_COMPOUND 0x0400 /* retained as FT_OUTLINE_OVERLAP */ #define SCALED_COMPONENT_OFFSET 0x0800 #define UNSCALED_COMPONENT_OFFSET 0x1000 #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #define IS_DEFAULT_INSTANCE( _face ) \ ( !( FT_IS_NAMED_INSTANCE( _face ) || \ FT_IS_VARIATION( _face ) ) ) #else #define IS_DEFAULT_INSTANCE( _face ) 1 #endif /************************************************************************** * * Return the horizontal metrics in font units for a given glyph. */ FT_LOCAL_DEF( void ) TT_Get_HMetrics( TT_Face face, FT_UInt idx, FT_Short* lsb, FT_UShort* aw ) { ( (SFNT_Service)face->sfnt )->get_metrics( face, 0, idx, lsb, aw ); FT_TRACE5(( " advance width (font units): %d\n", *aw )); FT_TRACE5(( " left side bearing (font units): %d\n", *lsb )); } /************************************************************************** * * Return the vertical metrics in font units for a given glyph. * See function `tt_loader_set_pp' below for explanations. */ FT_LOCAL_DEF( void ) TT_Get_VMetrics( TT_Face face, FT_UInt idx, FT_Pos yMax, FT_Short* tsb, FT_UShort* ah ) { if ( face->vertical_info ) ( (SFNT_Service)face->sfnt )->get_metrics( face, 1, idx, tsb, ah ); else if ( face->os2.version != 0xFFFFU ) { *tsb = (FT_Short)( face->os2.sTypoAscender - yMax ); *ah = (FT_UShort)FT_ABS( face->os2.sTypoAscender - face->os2.sTypoDescender ); } else { *tsb = (FT_Short)( face->horizontal.Ascender - yMax ); *ah = (FT_UShort)FT_ABS( face->horizontal.Ascender - face->horizontal.Descender ); } #ifdef FT_DEBUG_LEVEL_TRACE if ( !face->vertical_info ) FT_TRACE5(( " [vertical metrics missing, computing values]\n" )); #endif FT_TRACE5(( " advance height (font units): %d\n", *ah )); FT_TRACE5(( " top side bearing (font units): %d\n", *tsb )); } static FT_Error tt_get_metrics( TT_Loader loader, FT_UInt glyph_index ) { TT_Face face = loader->face; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( face ); #endif FT_Error error; FT_Stream stream = loader->stream; FT_Short left_bearing = 0, top_bearing = 0; FT_UShort advance_width = 0, advance_height = 0; /* we must preserve the stream position */ /* (which gets altered by the metrics functions) */ FT_ULong pos = FT_STREAM_POS(); TT_Get_HMetrics( face, glyph_index, &left_bearing, &advance_width ); TT_Get_VMetrics( face, glyph_index, loader->bbox.yMax, &top_bearing, &advance_height ); if ( FT_STREAM_SEEK( pos ) ) return error; loader->left_bearing = left_bearing; loader->advance = advance_width; loader->top_bearing = top_bearing; loader->vadvance = advance_height; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 && loader->exec ) { loader->exec->sph_tweak_flags = 0; /* This may not be the right place for this, but it works... */ /* Note that we have to unconditionally load the tweaks since */ /* it is possible that glyphs individually switch ClearType's */ /* backward compatibility mode on and off. */ sph_set_tweaks( loader, glyph_index ); } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef FT_CONFIG_OPTION_INCREMENTAL /* With the incremental interface, these values are set by */ /* a call to `tt_get_metrics_incremental'. */ if ( face->root.internal->incremental_interface == NULL ) #endif { if ( !loader->linear_def ) { loader->linear_def = 1; loader->linear = advance_width; } } return FT_Err_Ok; } #ifdef FT_CONFIG_OPTION_INCREMENTAL static void tt_get_metrics_incremental( TT_Loader loader, FT_UInt glyph_index ) { TT_Face face = loader->face; FT_Short left_bearing = 0, top_bearing = 0; FT_UShort advance_width = 0, advance_height = 0; /* If this is an incrementally loaded font check whether there are */ /* overriding metrics for this glyph. */ if ( face->root.internal->incremental_interface && face->root.internal->incremental_interface->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec incr_metrics; FT_Error error; incr_metrics.bearing_x = loader->left_bearing; incr_metrics.bearing_y = 0; incr_metrics.advance = loader->advance; incr_metrics.advance_v = 0; error = face->root.internal->incremental_interface->funcs->get_glyph_metrics( face->root.internal->incremental_interface->object, glyph_index, FALSE, &incr_metrics ); if ( error ) goto Exit; left_bearing = (FT_Short)incr_metrics.bearing_x; advance_width = (FT_UShort)incr_metrics.advance; #if 0 /* GWW: Do I do the same for vertical metrics? */ incr_metrics.bearing_x = 0; incr_metrics.bearing_y = loader->top_bearing; incr_metrics.advance = loader->vadvance; error = face->root.internal->incremental_interface->funcs->get_glyph_metrics( face->root.internal->incremental_interface->object, glyph_index, TRUE, &incr_metrics ); if ( error ) goto Exit; top_bearing = (FT_Short)incr_metrics.bearing_y; advance_height = (FT_UShort)incr_metrics.advance; #endif /* 0 */ loader->left_bearing = left_bearing; loader->advance = advance_width; loader->top_bearing = top_bearing; loader->vadvance = advance_height; if ( !loader->linear_def ) { loader->linear_def = 1; loader->linear = advance_width; } } Exit: return; } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /************************************************************************** * * The following functions are used by default with TrueType fonts. * However, they can be replaced by alternatives if we need to support * TrueType-compressed formats (like MicroType) in the future. * */ FT_CALLBACK_DEF( FT_Error ) TT_Access_Glyph_Frame( TT_Loader loader, FT_UInt glyph_index, FT_ULong offset, FT_UInt byte_count ) { FT_Error error; FT_Stream stream = loader->stream; FT_UNUSED( glyph_index ); /* the following line sets the `error' variable through macros! */ if ( FT_STREAM_SEEK( offset ) || FT_FRAME_ENTER( byte_count ) ) return error; loader->cursor = stream->cursor; loader->limit = stream->limit; return FT_Err_Ok; } FT_CALLBACK_DEF( void ) TT_Forget_Glyph_Frame( TT_Loader loader ) { FT_Stream stream = loader->stream; FT_FRAME_EXIT(); } FT_CALLBACK_DEF( FT_Error ) TT_Load_Glyph_Header( TT_Loader loader ) { FT_Byte* p = loader->cursor; FT_Byte* limit = loader->limit; if ( p + 10 > limit ) return FT_THROW( Invalid_Outline ); loader->n_contours = FT_NEXT_SHORT( p ); loader->bbox.xMin = FT_NEXT_SHORT( p ); loader->bbox.yMin = FT_NEXT_SHORT( p ); loader->bbox.xMax = FT_NEXT_SHORT( p ); loader->bbox.yMax = FT_NEXT_SHORT( p ); FT_TRACE5(( " # of contours: %d\n", loader->n_contours )); FT_TRACE5(( " xMin: %4ld xMax: %4ld\n", loader->bbox.xMin, loader->bbox.xMax )); FT_TRACE5(( " yMin: %4ld yMax: %4ld\n", loader->bbox.yMin, loader->bbox.yMax )); loader->cursor = p; return FT_Err_Ok; } FT_CALLBACK_DEF( FT_Error ) TT_Load_Simple_Glyph( TT_Loader load ) { FT_Error error; FT_Byte* p = load->cursor; FT_Byte* limit = load->limit; FT_GlyphLoader gloader = load->gloader; FT_Int n_contours = load->n_contours; FT_Outline* outline; FT_UShort n_ins; FT_Int n_points; FT_Byte *flag, *flag_limit; FT_Byte c, count; FT_Vector *vec, *vec_limit; FT_Pos x, y; FT_Short *cont, *cont_limit, prev_cont; FT_Int xy_size = 0; /* check that we can add the contours to the glyph */ error = FT_GLYPHLOADER_CHECK_POINTS( gloader, 0, n_contours ); if ( error ) goto Fail; /* reading the contours' endpoints & number of points */ cont = gloader->current.outline.contours; cont_limit = cont + n_contours; /* check space for contours array + instructions count */ if ( n_contours >= 0xFFF || p + ( n_contours + 1 ) * 2 > limit ) goto Invalid_Outline; prev_cont = FT_NEXT_SHORT( p ); if ( n_contours > 0 ) cont[0] = prev_cont; if ( prev_cont < 0 ) goto Invalid_Outline; for ( cont++; cont < cont_limit; cont++ ) { cont[0] = FT_NEXT_SHORT( p ); if ( cont[0] <= prev_cont ) { /* unordered contours: this is invalid */ goto Invalid_Outline; } prev_cont = cont[0]; } n_points = 0; if ( n_contours > 0 ) { n_points = cont[-1] + 1; if ( n_points < 0 ) goto Invalid_Outline; } FT_TRACE5(( " # of points: %d\n", n_points )); /* note that we will add four phantom points later */ error = FT_GLYPHLOADER_CHECK_POINTS( gloader, n_points + 4, 0 ); if ( error ) goto Fail; /* reading the bytecode instructions */ load->glyph->control_len = 0; load->glyph->control_data = NULL; if ( p + 2 > limit ) goto Invalid_Outline; n_ins = FT_NEXT_USHORT( p ); FT_TRACE5(( " Instructions size: %u\n", n_ins )); #ifdef TT_USE_BYTECODE_INTERPRETER if ( IS_HINTED( load->load_flags ) ) { FT_ULong tmp; /* check instructions size */ if ( ( limit - p ) < n_ins ) { FT_TRACE1(( "TT_Load_Simple_Glyph: instruction count mismatch\n" )); error = FT_THROW( Too_Many_Hints ); goto Fail; } /* we don't trust `maxSizeOfInstructions' in the `maxp' table */ /* and thus update the bytecode array size by ourselves */ tmp = load->exec->glyphSize; error = Update_Max( load->exec->memory, &tmp, sizeof ( FT_Byte ), (void*)&load->exec->glyphIns, n_ins ); load->exec->glyphSize = (FT_UInt)tmp; if ( error ) return error; load->glyph->control_len = n_ins; load->glyph->control_data = load->exec->glyphIns; if ( n_ins ) FT_MEM_COPY( load->exec->glyphIns, p, (FT_Long)n_ins ); } #endif /* TT_USE_BYTECODE_INTERPRETER */ p += n_ins; outline = &gloader->current.outline; /* reading the point tags */ flag = (FT_Byte*)outline->tags; flag_limit = flag + n_points; FT_ASSERT( flag ); while ( flag < flag_limit ) { if ( p + 1 > limit ) goto Invalid_Outline; *flag++ = c = FT_NEXT_BYTE( p ); if ( c & REPEAT_FLAG ) { if ( p + 1 > limit ) goto Invalid_Outline; count = FT_NEXT_BYTE( p ); if ( flag + (FT_Int)count > flag_limit ) goto Invalid_Outline; for ( ; count > 0; count-- ) *flag++ = c; } } /* retain the overlap flag */ if ( n_points && outline->tags[0] & OVERLAP_SIMPLE ) gloader->base.outline.flags |= FT_OUTLINE_OVERLAP; /* reading the X coordinates */ vec = outline->points; vec_limit = vec + n_points; flag = (FT_Byte*)outline->tags; x = 0; if ( p + xy_size > limit ) goto Invalid_Outline; for ( ; vec < vec_limit; vec++, flag++ ) { FT_Pos delta = 0; FT_Byte f = *flag; if ( f & X_SHORT_VECTOR ) { if ( p + 1 > limit ) goto Invalid_Outline; delta = (FT_Pos)FT_NEXT_BYTE( p ); if ( !( f & X_POSITIVE ) ) delta = -delta; } else if ( !( f & SAME_X ) ) { if ( p + 2 > limit ) goto Invalid_Outline; delta = (FT_Pos)FT_NEXT_SHORT( p ); } x += delta; vec->x = x; } /* reading the Y coordinates */ vec = gloader->current.outline.points; vec_limit = vec + n_points; flag = (FT_Byte*)outline->tags; y = 0; for ( ; vec < vec_limit; vec++, flag++ ) { FT_Pos delta = 0; FT_Byte f = *flag; if ( f & Y_SHORT_VECTOR ) { if ( p + 1 > limit ) goto Invalid_Outline; delta = (FT_Pos)FT_NEXT_BYTE( p ); if ( !( f & Y_POSITIVE ) ) delta = -delta; } else if ( !( f & SAME_Y ) ) { if ( p + 2 > limit ) goto Invalid_Outline; delta = (FT_Pos)FT_NEXT_SHORT( p ); } y += delta; vec->y = y; /* the cast is for stupid compilers */ *flag = (FT_Byte)( f & ON_CURVE_POINT ); } outline->n_points = (FT_Short)n_points; outline->n_contours = (FT_Short)n_contours; load->cursor = p; Fail: return error; Invalid_Outline: error = FT_THROW( Invalid_Outline ); goto Fail; } FT_CALLBACK_DEF( FT_Error ) TT_Load_Composite_Glyph( TT_Loader loader ) { FT_Error error; FT_Byte* p = loader->cursor; FT_Byte* limit = loader->limit; FT_GlyphLoader gloader = loader->gloader; FT_Long num_glyphs = loader->face->root.num_glyphs; FT_SubGlyph subglyph; FT_UInt num_subglyphs; num_subglyphs = 0; do { FT_Fixed xx, xy, yy, yx; FT_UInt count; /* check that we can load a new subglyph */ error = FT_GlyphLoader_CheckSubGlyphs( gloader, num_subglyphs + 1 ); if ( error ) goto Fail; /* check space */ if ( p + 4 > limit ) goto Invalid_Composite; subglyph = gloader->current.subglyphs + num_subglyphs; subglyph->arg1 = subglyph->arg2 = 0; subglyph->flags = FT_NEXT_USHORT( p ); subglyph->index = FT_NEXT_USHORT( p ); /* we reject composites that have components */ /* with invalid glyph indices */ if ( subglyph->index >= num_glyphs ) goto Invalid_Composite; /* check space */ count = 2; if ( subglyph->flags & ARGS_ARE_WORDS ) count += 2; if ( subglyph->flags & WE_HAVE_A_SCALE ) count += 2; else if ( subglyph->flags & WE_HAVE_AN_XY_SCALE ) count += 4; else if ( subglyph->flags & WE_HAVE_A_2X2 ) count += 8; if ( p + count > limit ) goto Invalid_Composite; /* read arguments */ if ( subglyph->flags & ARGS_ARE_XY_VALUES ) { if ( subglyph->flags & ARGS_ARE_WORDS ) { subglyph->arg1 = FT_NEXT_SHORT( p ); subglyph->arg2 = FT_NEXT_SHORT( p ); } else { subglyph->arg1 = FT_NEXT_CHAR( p ); subglyph->arg2 = FT_NEXT_CHAR( p ); } } else { if ( subglyph->flags & ARGS_ARE_WORDS ) { subglyph->arg1 = (FT_Int)FT_NEXT_USHORT( p ); subglyph->arg2 = (FT_Int)FT_NEXT_USHORT( p ); } else { subglyph->arg1 = (FT_Int)FT_NEXT_BYTE( p ); subglyph->arg2 = (FT_Int)FT_NEXT_BYTE( p ); } } /* read transform */ xx = yy = 0x10000L; xy = yx = 0; if ( subglyph->flags & WE_HAVE_A_SCALE ) { xx = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; yy = xx; } else if ( subglyph->flags & WE_HAVE_AN_XY_SCALE ) { xx = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; yy = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; } else if ( subglyph->flags & WE_HAVE_A_2X2 ) { xx = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; yx = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; xy = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; yy = (FT_Fixed)FT_NEXT_SHORT( p ) * 4; } subglyph->transform.xx = xx; subglyph->transform.xy = xy; subglyph->transform.yx = yx; subglyph->transform.yy = yy; num_subglyphs++; } while ( subglyph->flags & MORE_COMPONENTS ); gloader->current.num_subglyphs = num_subglyphs; FT_TRACE5(( " %d component%s\n", num_subglyphs, num_subglyphs > 1 ? "s" : "" )); #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt i; subglyph = gloader->current.subglyphs; for ( i = 0; i < num_subglyphs; i++ ) { if ( num_subglyphs > 1 ) FT_TRACE7(( " subglyph %d:\n", i )); FT_TRACE7(( " glyph index: %d\n", subglyph->index )); if ( subglyph->flags & ARGS_ARE_XY_VALUES ) FT_TRACE7(( " offset: x=%d, y=%d\n", subglyph->arg1, subglyph->arg2 )); else FT_TRACE7(( " matching points: base=%d, component=%d\n", subglyph->arg1, subglyph->arg2 )); if ( subglyph->flags & WE_HAVE_A_SCALE ) FT_TRACE7(( " scaling: %f\n", subglyph->transform.xx / 65536.0 )); else if ( subglyph->flags & WE_HAVE_AN_XY_SCALE ) FT_TRACE7(( " scaling: x=%f, y=%f\n", subglyph->transform.xx / 65536.0, subglyph->transform.yy / 65536.0 )); else if ( subglyph->flags & WE_HAVE_A_2X2 ) { FT_TRACE7(( " scaling: xx=%f, yx=%f\n", subglyph->transform.xx / 65536.0, subglyph->transform.yx / 65536.0 )); FT_TRACE7(( " xy=%f, yy=%f\n", subglyph->transform.xy / 65536.0, subglyph->transform.yy / 65536.0 )); } subglyph++; } } #endif /* FT_DEBUG_LEVEL_TRACE */ #ifdef TT_USE_BYTECODE_INTERPRETER { FT_Stream stream = loader->stream; /* we must undo the FT_FRAME_ENTER in order to point */ /* to the composite instructions, if we find some. */ /* We will process them later. */ /* */ loader->ins_pos = (FT_ULong)( FT_STREAM_POS() + p - limit ); } #endif loader->cursor = p; Fail: return error; Invalid_Composite: error = FT_THROW( Invalid_Composite ); goto Fail; } FT_LOCAL_DEF( void ) TT_Init_Glyph_Loading( TT_Face face ) { face->access_glyph_frame = TT_Access_Glyph_Frame; face->read_glyph_header = TT_Load_Glyph_Header; face->read_simple_glyph = TT_Load_Simple_Glyph; face->read_composite_glyph = TT_Load_Composite_Glyph; face->forget_glyph_frame = TT_Forget_Glyph_Frame; } static void tt_prepare_zone( TT_GlyphZone zone, FT_GlyphLoad load, FT_UInt start_point, FT_UInt start_contour ) { zone->n_points = (FT_UShort)load->outline.n_points - (FT_UShort)start_point; zone->n_contours = load->outline.n_contours - (FT_Short)start_contour; zone->org = load->extra_points + start_point; zone->cur = load->outline.points + start_point; zone->orus = load->extra_points2 + start_point; zone->tags = (FT_Byte*)load->outline.tags + start_point; zone->contours = (FT_UShort*)load->outline.contours + start_contour; zone->first_point = (FT_UShort)start_point; } /************************************************************************** * * @Function: * TT_Hint_Glyph * * @Description: * Hint the glyph using the zone prepared by the caller. Note that * the zone is supposed to include four phantom points. */ static FT_Error TT_Hint_Glyph( TT_Loader loader, FT_Bool is_composite ) { #if defined TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY || \ defined TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL TT_Face face = loader->face; TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( face ); #endif TT_GlyphZone zone = &loader->zone; #ifdef TT_USE_BYTECODE_INTERPRETER FT_Long n_ins; #else FT_UNUSED( is_composite ); #endif #ifdef TT_USE_BYTECODE_INTERPRETER n_ins = loader->glyph->control_len; /* save original point positions in `org' array */ if ( n_ins > 0 ) FT_ARRAY_COPY( zone->org, zone->cur, zone->n_points ); /* Reset graphics state. */ loader->exec->GS = loader->size->GS; /* XXX: UNDOCUMENTED! Hinting instructions of a composite glyph */ /* completely refer to the (already) hinted subglyphs. */ if ( is_composite ) { loader->exec->metrics.x_scale = 1 << 16; loader->exec->metrics.y_scale = 1 << 16; FT_ARRAY_COPY( zone->orus, zone->cur, zone->n_points ); } else { loader->exec->metrics.x_scale = loader->size->metrics->x_scale; loader->exec->metrics.y_scale = loader->size->metrics->y_scale; } #endif /* round phantom points */ zone->cur[zone->n_points - 4].x = FT_PIX_ROUND( zone->cur[zone->n_points - 4].x ); zone->cur[zone->n_points - 3].x = FT_PIX_ROUND( zone->cur[zone->n_points - 3].x ); zone->cur[zone->n_points - 2].y = FT_PIX_ROUND( zone->cur[zone->n_points - 2].y ); zone->cur[zone->n_points - 1].y = FT_PIX_ROUND( zone->cur[zone->n_points - 1].y ); #ifdef TT_USE_BYTECODE_INTERPRETER if ( n_ins > 0 ) { FT_Error error; FT_GlyphLoader gloader = loader->gloader; FT_Outline current_outline = gloader->current.outline; TT_Set_CodeRange( loader->exec, tt_coderange_glyph, loader->exec->glyphIns, n_ins ); loader->exec->is_composite = is_composite; loader->exec->pts = *zone; error = TT_Run_Context( loader->exec ); if ( error && loader->exec->pedantic_hinting ) return error; /* store drop-out mode in bits 5-7; set bit 2 also as a marker */ current_outline.tags[0] |= ( loader->exec->GS.scan_type << 5 ) | FT_CURVE_TAG_HAS_SCANMODE; } #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* Save possibly modified glyph phantom points unless in v40 backward */ /* compatibility mode, where no movement on the x axis means no reason */ /* to change bearings or advance widths. */ if ( !( driver->interpreter_version == TT_INTERPRETER_VERSION_40 && loader->exec->backward_compatibility ) ) { #endif loader->pp1 = zone->cur[zone->n_points - 4]; loader->pp2 = zone->cur[zone->n_points - 3]; loader->pp3 = zone->cur[zone->n_points - 2]; loader->pp4 = zone->cur[zone->n_points - 1]; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL } #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 ) { if ( loader->exec->sph_tweak_flags & SPH_TWEAK_DEEMBOLDEN ) FT_Outline_EmboldenXY( &loader->gloader->current.outline, -24, 0 ); else if ( loader->exec->sph_tweak_flags & SPH_TWEAK_EMBOLDEN ) FT_Outline_EmboldenXY( &loader->gloader->current.outline, 24, 0 ); } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Process_Simple_Glyph * * @Description: * Once a simple glyph has been loaded, it needs to be processed. * Usually, this means scaling and hinting through bytecode * interpretation. */ static FT_Error TT_Process_Simple_Glyph( TT_Loader loader ) { FT_GlyphLoader gloader = loader->gloader; FT_Error error = FT_Err_Ok; FT_Outline* outline; FT_Int n_points; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_Memory memory = loader->face->root.memory; FT_Vector* unrounded = NULL; #endif outline = &gloader->current.outline; n_points = outline->n_points; /* set phantom points */ outline->points[n_points ] = loader->pp1; outline->points[n_points + 1] = loader->pp2; outline->points[n_points + 2] = loader->pp3; outline->points[n_points + 3] = loader->pp4; outline->tags[n_points ] = 0; outline->tags[n_points + 1] = 0; outline->tags[n_points + 2] = 0; outline->tags[n_points + 3] = 0; n_points += 4; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !IS_DEFAULT_INSTANCE( FT_FACE( loader->face ) ) ) { if ( FT_NEW_ARRAY( unrounded, n_points ) ) goto Exit; /* Deltas apply to the unscaled data. */ error = TT_Vary_Apply_Glyph_Deltas( loader->face, loader->glyph_index, outline, unrounded, (FT_UInt)n_points ); /* recalculate linear horizontal and vertical advances */ /* if we don't have HVAR and VVAR, respectively */ /* XXX: change all FreeType modules to store `linear' and `vadvance' */ /* in 26.6 format before the `base' module scales them to 16.16 */ if ( !( loader->face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) loader->linear = FT_PIX_ROUND( unrounded[n_points - 3].x - unrounded[n_points - 4].x ) / 64; if ( !( loader->face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) loader->vadvance = FT_PIX_ROUND( unrounded[n_points - 1].x - unrounded[n_points - 2].x ) / 64; if ( error ) goto Exit; } #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ if ( IS_HINTED( loader->load_flags ) ) { tt_prepare_zone( &loader->zone, &gloader->current, 0, 0 ); FT_ARRAY_COPY( loader->zone.orus, loader->zone.cur, loader->zone.n_points + 4 ); } { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY TT_Face face = loader->face; TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( face ); FT_String* family = face->root.family_name; FT_UInt ppem = loader->size->metrics->x_ppem; FT_String* style = face->root.style_name; FT_UInt x_scale_factor = 1000; #endif FT_Vector* vec = outline->points; FT_Vector* limit = outline->points + n_points; FT_Fixed x_scale = 0; /* pacify compiler */ FT_Fixed y_scale = 0; FT_Bool do_scale = FALSE; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 ) { /* scale, but only if enabled and only if TT hinting is being used */ if ( IS_HINTED( loader->load_flags ) ) x_scale_factor = sph_test_tweak_x_scaling( face, family, ppem, style, loader->glyph_index ); /* scale the glyph */ if ( ( loader->load_flags & FT_LOAD_NO_SCALE ) == 0 || x_scale_factor != 1000 ) { x_scale = FT_MulDiv( loader->size->metrics->x_scale, (FT_Long)x_scale_factor, 1000 ); y_scale = loader->size->metrics->y_scale; /* compensate for any scaling by de/emboldening; */ /* the amount was determined via experimentation */ if ( x_scale_factor != 1000 && ppem > 11 ) { #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_Vector* orig_points = outline->points; if ( !IS_DEFAULT_INSTANCE( FT_FACE( loader->face ) ) ) outline->points = unrounded; #endif FT_Outline_EmboldenXY( outline, FT_MulFix( 1280 * ppem, 1000 - x_scale_factor ), 0 ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !IS_DEFAULT_INSTANCE( FT_FACE( loader->face ) ) ) outline->points = orig_points; #endif } do_scale = TRUE; } } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ { /* scale the glyph */ if ( ( loader->load_flags & FT_LOAD_NO_SCALE ) == 0 ) { x_scale = loader->size->metrics->x_scale; y_scale = loader->size->metrics->y_scale; do_scale = TRUE; } } if ( do_scale ) { #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( !IS_DEFAULT_INSTANCE( FT_FACE( loader->face ) ) ) { FT_Vector* u = unrounded; for ( ; vec < limit; vec++, u++ ) { vec->x = ( FT_MulFix( u->x, x_scale ) + 32 ) >> 6; vec->y = ( FT_MulFix( u->y, y_scale ) + 32 ) >> 6; } } else #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ { for ( ; vec < limit; vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } } } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /* if we have a HVAR table, `pp1' and/or `pp2' */ /* are already adjusted but unscaled */ if ( ( loader->face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) && IS_HINTED( loader->load_flags ) ) { loader->pp1.x = FT_MulFix( loader->pp1.x, x_scale ); loader->pp2.x = FT_MulFix( loader->pp2.x, x_scale ); /* pp1.y and pp2.y are always zero */ } else #endif { loader->pp1 = outline->points[n_points - 4]; loader->pp2 = outline->points[n_points - 3]; } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /* if we have a VVAR table, `pp3' and/or `pp4' */ /* are already adjusted but unscaled */ if ( ( loader->face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) && IS_HINTED( loader->load_flags ) ) { loader->pp3.x = FT_MulFix( loader->pp3.x, x_scale ); loader->pp3.y = FT_MulFix( loader->pp3.y, y_scale ); loader->pp4.x = FT_MulFix( loader->pp4.x, x_scale ); loader->pp4.y = FT_MulFix( loader->pp4.y, y_scale ); } else #endif { loader->pp3 = outline->points[n_points - 2]; loader->pp4 = outline->points[n_points - 1]; } } if ( IS_HINTED( loader->load_flags ) ) { loader->zone.n_points += 4; error = TT_Hint_Glyph( loader, 0 ); } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT Exit: FT_FREE( unrounded ); #endif return error; } /************************************************************************** * * @Function: * TT_Process_Composite_Component * * @Description: * Once a composite component has been loaded, it needs to be * processed. Usually, this means transforming and translating. */ static FT_Error TT_Process_Composite_Component( TT_Loader loader, FT_SubGlyph subglyph, FT_UInt start_point, FT_UInt num_base_points ) { FT_GlyphLoader gloader = loader->gloader; FT_Outline current; FT_Bool have_scale; FT_Pos x, y; current.points = gloader->base.outline.points + num_base_points; current.n_points = gloader->base.outline.n_points - (short)num_base_points; have_scale = FT_BOOL( subglyph->flags & ( WE_HAVE_A_SCALE | WE_HAVE_AN_XY_SCALE | WE_HAVE_A_2X2 ) ); /* perform the transform required for this subglyph */ if ( have_scale ) FT_Outline_Transform( &current, &subglyph->transform ); /* get offset */ if ( !( subglyph->flags & ARGS_ARE_XY_VALUES ) ) { FT_UInt num_points = (FT_UInt)gloader->base.outline.n_points; FT_UInt k = (FT_UInt)subglyph->arg1; FT_UInt l = (FT_UInt)subglyph->arg2; FT_Vector* p1; FT_Vector* p2; /* match l-th point of the newly loaded component to the k-th point */ /* of the previously loaded components. */ /* change to the point numbers used by our outline */ k += start_point; l += num_base_points; if ( k >= num_base_points || l >= num_points ) return FT_THROW( Invalid_Composite ); p1 = gloader->base.outline.points + k; p2 = gloader->base.outline.points + l; x = p1->x - p2->x; y = p1->y - p2->y; } else { x = subglyph->arg1; y = subglyph->arg2; if ( !x && !y ) return FT_Err_Ok; /* Use a default value dependent on */ /* TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED. This is useful for old */ /* TT fonts which don't set the xxx_COMPONENT_OFFSET bit. */ if ( have_scale && #ifdef TT_CONFIG_OPTION_COMPONENT_OFFSET_SCALED !( subglyph->flags & UNSCALED_COMPONENT_OFFSET ) ) #else ( subglyph->flags & SCALED_COMPONENT_OFFSET ) ) #endif { #if 0 /******************************************************************** * * This algorithm is what Apple documents. But it doesn't work. */ int a = subglyph->transform.xx > 0 ? subglyph->transform.xx : -subglyph->transform.xx; int b = subglyph->transform.yx > 0 ? subglyph->transform.yx : -subglyph->transform.yx; int c = subglyph->transform.xy > 0 ? subglyph->transform.xy : -subglyph->transform.xy; int d = subglyph->transform.yy > 0 ? subglyph->transform.yy : -subglyph->transform.yy; int m = a > b ? a : b; int n = c > d ? c : d; if ( a - b <= 33 && a - b >= -33 ) m *= 2; if ( c - d <= 33 && c - d >= -33 ) n *= 2; x = FT_MulFix( x, m ); y = FT_MulFix( y, n ); #else /* 1 */ /******************************************************************** * * This algorithm is a guess and works much better than the above. */ FT_Fixed mac_xscale = FT_Hypot( subglyph->transform.xx, subglyph->transform.xy ); FT_Fixed mac_yscale = FT_Hypot( subglyph->transform.yy, subglyph->transform.yx ); x = FT_MulFix( x, mac_xscale ); y = FT_MulFix( y, mac_yscale ); #endif /* 1 */ } if ( !( loader->load_flags & FT_LOAD_NO_SCALE ) ) { FT_Fixed x_scale = loader->size->metrics->x_scale; FT_Fixed y_scale = loader->size->metrics->y_scale; x = FT_MulFix( x, x_scale ); y = FT_MulFix( y, y_scale ); if ( subglyph->flags & ROUND_XY_TO_GRID ) { TT_Face face = loader->face; TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( face ); if ( IS_HINTED( loader->load_flags ) ) { /* * We round the horizontal offset only if there is hinting along * the x axis; this corresponds to integer advance width values. * * Theoretically, a glyph's bytecode can toggle ClearType's * `backward compatibility' mode, which would allow modification * of the advance width. In reality, however, applications * neither allow nor expect modified advance widths if subpixel * rendering is active. * */ if ( driver->interpreter_version == TT_INTERPRETER_VERSION_35 ) x = FT_PIX_ROUND( x ); y = FT_PIX_ROUND( y ); } } } } if ( x || y ) FT_Outline_Translate( &current, x, y ); return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Process_Composite_Glyph * * @Description: * This is slightly different from TT_Process_Simple_Glyph, in that * its sole purpose is to hint the glyph. Thus this function is * only available when bytecode interpreter is enabled. */ static FT_Error TT_Process_Composite_Glyph( TT_Loader loader, FT_UInt start_point, FT_UInt start_contour ) { FT_Error error; FT_Outline* outline; FT_UInt i; outline = &loader->gloader->base.outline; /* make room for phantom points */ error = FT_GLYPHLOADER_CHECK_POINTS( loader->gloader, outline->n_points + 4, 0 ); if ( error ) return error; outline->points[outline->n_points ] = loader->pp1; outline->points[outline->n_points + 1] = loader->pp2; outline->points[outline->n_points + 2] = loader->pp3; outline->points[outline->n_points + 3] = loader->pp4; outline->tags[outline->n_points ] = 0; outline->tags[outline->n_points + 1] = 0; outline->tags[outline->n_points + 2] = 0; outline->tags[outline->n_points + 3] = 0; #ifdef TT_USE_BYTECODE_INTERPRETER { FT_Stream stream = loader->stream; FT_UShort n_ins, max_ins; FT_ULong tmp; /* TT_Load_Composite_Glyph only gives us the offset of instructions */ /* so we read them here */ if ( FT_STREAM_SEEK( loader->ins_pos ) || FT_READ_USHORT( n_ins ) ) return error; FT_TRACE5(( " Instructions size = %hu\n", n_ins )); /* check it */ max_ins = loader->face->max_profile.maxSizeOfInstructions; if ( n_ins > max_ins ) { /* don't trust `maxSizeOfInstructions'; */ /* only do a rough safety check */ if ( n_ins > loader->byte_len ) { FT_TRACE1(( "TT_Process_Composite_Glyph:" " too many instructions (%hu) for glyph with length %u\n", n_ins, loader->byte_len )); return FT_THROW( Too_Many_Hints ); } tmp = loader->exec->glyphSize; error = Update_Max( loader->exec->memory, &tmp, sizeof ( FT_Byte ), (void*)&loader->exec->glyphIns, n_ins ); loader->exec->glyphSize = (FT_UShort)tmp; if ( error ) return error; } else if ( n_ins == 0 ) return FT_Err_Ok; if ( FT_STREAM_READ( loader->exec->glyphIns, n_ins ) ) return error; loader->glyph->control_data = loader->exec->glyphIns; loader->glyph->control_len = n_ins; } #endif tt_prepare_zone( &loader->zone, &loader->gloader->base, start_point, start_contour ); /* Some points are likely touched during execution of */ /* instructions on components. So let's untouch them. */ for ( i = 0; i < loader->zone.n_points; i++ ) loader->zone.tags[i] &= ~FT_CURVE_TAG_TOUCH_BOTH; loader->zone.n_points += 4; return TT_Hint_Glyph( loader, 1 ); } /* * Calculate the phantom points * * Defining the right side bearing (rsb) as * * rsb = aw - (lsb + xmax - xmin) * * (with `aw' the advance width, `lsb' the left side bearing, and `xmin' * and `xmax' the glyph's minimum and maximum x value), the OpenType * specification defines the initial position of horizontal phantom points * as * * pp1 = (round(xmin - lsb), 0) , * pp2 = (round(pp1 + aw), 0) . * * Note that the rounding to the grid (in the device space) is not * documented currently in the specification. * * However, the specification lacks the precise definition of vertical * phantom points. Greg Hitchcock provided the following explanation. * * - a `vmtx' table is present * * For any glyph, the minimum and maximum y values (`ymin' and `ymax') * are given in the `glyf' table, the top side bearing (tsb) and advance * height (ah) are given in the `vmtx' table. The bottom side bearing * (bsb) is then calculated as * * bsb = ah - (tsb + ymax - ymin) , * * and the initial position of vertical phantom points is * * pp3 = (x, round(ymax + tsb)) , * pp4 = (x, round(pp3 - ah)) . * * See below for value `x'. * * - no `vmtx' table in the font * * If there is an `OS/2' table, we set * * DefaultAscender = sTypoAscender , * DefaultDescender = sTypoDescender , * * otherwise we use data from the `hhea' table: * * DefaultAscender = Ascender , * DefaultDescender = Descender . * * With these two variables we can now set * * ah = DefaultAscender - sDefaultDescender , * tsb = DefaultAscender - yMax , * * and proceed as if a `vmtx' table was present. * * Usually we have * * x = aw / 2 , (1) * * but there is one compatibility case where it can be set to * * x = -DefaultDescender - * ((DefaultAscender - DefaultDescender - aw) / 2) . (2) * * and another one with * * x = 0 . (3) * * In Windows, the history of those values is quite complicated, * depending on the hinting engine (that is, the graphics framework). * * framework from to formula * ---------------------------------------------------------- * GDI Windows 98 current (1) * (Windows 2000 for NT) * GDI+ Windows XP Windows 7 (2) * GDI+ Windows 8 current (3) * DWrite Windows 7 current (3) * * For simplicity, FreeType uses (1) for grayscale subpixel hinting and * (3) for everything else. * */ static void tt_loader_set_pp( TT_Loader loader ) { FT_Bool subpixel_hinting = 0; FT_Bool grayscale = 0; FT_Bool use_aw_2 = 0; #ifdef TT_CONFIG_OPTION_SUBPIXEL_HINTING TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( loader->face ); #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 ) { subpixel_hinting = loader->exec ? loader->exec->subpixel_hinting : 0; grayscale = loader->exec ? loader->exec->grayscale : 0; } #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( driver->interpreter_version == TT_INTERPRETER_VERSION_40 ) { subpixel_hinting = loader->exec ? loader->exec->subpixel_hinting_lean : 0; grayscale = loader->exec ? loader->exec->grayscale_cleartype : 0; } #endif use_aw_2 = FT_BOOL( subpixel_hinting && grayscale ); loader->pp1.x = loader->bbox.xMin - loader->left_bearing; loader->pp1.y = 0; loader->pp2.x = loader->pp1.x + loader->advance; loader->pp2.y = 0; loader->pp3.x = use_aw_2 ? loader->advance / 2 : 0; loader->pp3.y = loader->bbox.yMax + loader->top_bearing; loader->pp4.x = use_aw_2 ? loader->advance / 2 : 0; loader->pp4.y = loader->pp3.y - loader->vadvance; } /* a utility function to retrieve i-th node from given FT_List */ static FT_ListNode ft_list_get_node_at( FT_List list, FT_UInt idx ) { FT_ListNode cur; if ( !list ) return NULL; for ( cur = list->head; cur; cur = cur->next ) { if ( !idx ) return cur; idx--; } return NULL; } /************************************************************************** * * @Function: * load_truetype_glyph * * @Description: * Loads a given truetype glyph. Handles composites and uses a * TT_Loader object. */ static FT_Error load_truetype_glyph( TT_Loader loader, FT_UInt glyph_index, FT_UInt recurse_count, FT_Bool header_only ) { FT_Error error = FT_Err_Ok; FT_Fixed x_scale, y_scale; FT_ULong offset; TT_Face face = loader->face; FT_GlyphLoader gloader = loader->gloader; FT_Bool opened_frame = 0; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_StreamRec inc_stream; FT_Data glyph_data; FT_Bool glyph_data_loaded = 0; #endif #ifdef FT_DEBUG_LEVEL_TRACE if ( recurse_count ) FT_TRACE5(( " nesting level: %d\n", recurse_count )); #endif /* some fonts have an incorrect value of `maxComponentDepth' */ if ( recurse_count > face->max_profile.maxComponentDepth ) { FT_TRACE1(( "load_truetype_glyph: maxComponentDepth set to %d\n", recurse_count )); face->max_profile.maxComponentDepth = (FT_UShort)recurse_count; } #ifndef FT_CONFIG_OPTION_INCREMENTAL /* check glyph index */ if ( glyph_index >= (FT_UInt)face->root.num_glyphs ) { error = FT_THROW( Invalid_Glyph_Index ); goto Exit; } #endif loader->glyph_index = glyph_index; if ( loader->load_flags & FT_LOAD_NO_SCALE ) { x_scale = 0x10000L; y_scale = 0x10000L; } else { x_scale = loader->size->metrics->x_scale; y_scale = loader->size->metrics->y_scale; } /* Set `offset' to the start of the glyph relative to the start of */ /* the `glyf' table, and `byte_len' to the length of the glyph in */ /* bytes. */ #ifdef FT_CONFIG_OPTION_INCREMENTAL /* If we are loading glyph data via the incremental interface, set */ /* the loader stream to a memory stream reading the data returned */ /* by the interface. */ if ( face->root.internal->incremental_interface ) { error = face->root.internal->incremental_interface->funcs->get_glyph_data( face->root.internal->incremental_interface->object, glyph_index, &glyph_data ); if ( error ) goto Exit; glyph_data_loaded = 1; offset = 0; loader->byte_len = glyph_data.length; FT_ZERO( &inc_stream ); FT_Stream_OpenMemory( &inc_stream, glyph_data.pointer, glyph_data.length ); loader->stream = &inc_stream; } else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ offset = tt_face_get_location( face, glyph_index, &loader->byte_len ); if ( loader->byte_len > 0 ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL /* for the incremental interface, `glyf_offset' is always zero */ if ( !face->glyf_offset && !face->root.internal->incremental_interface ) #else if ( !face->glyf_offset ) #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { FT_TRACE2(( "no `glyf' table but non-zero `loca' entry\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } error = face->access_glyph_frame( loader, glyph_index, face->glyf_offset + offset, loader->byte_len ); if ( error ) goto Exit; /* read glyph header first */ error = face->read_glyph_header( loader ); face->forget_glyph_frame( loader ); if ( error ) goto Exit; } /* a space glyph */ if ( loader->byte_len == 0 || loader->n_contours == 0 ) { loader->bbox.xMin = 0; loader->bbox.xMax = 0; loader->bbox.yMin = 0; loader->bbox.yMax = 0; } /* the metrics must be computed after loading the glyph header */ /* since we need the glyph's `yMax' value in case the vertical */ /* metrics must be emulated */ error = tt_get_metrics( loader, glyph_index ); if ( error ) goto Exit; if ( header_only ) goto Exit; if ( loader->byte_len == 0 || loader->n_contours == 0 ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL tt_get_metrics_incremental( loader, glyph_index ); #endif tt_loader_set_pp( loader ); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( FT_IS_NAMED_INSTANCE( FT_FACE( face ) ) || FT_IS_VARIATION( FT_FACE( face ) ) ) { /* a small outline structure with four elements for */ /* communication with `TT_Vary_Apply_Glyph_Deltas' */ FT_Vector points[4]; char tags[4] = { 1, 1, 1, 1 }; short contours[4] = { 0, 1, 2, 3 }; FT_Outline outline; /* unrounded values */ FT_Vector unrounded[4] = { {0, 0}, {0, 0}, {0, 0}, {0, 0} }; points[0].x = loader->pp1.x; points[0].y = loader->pp1.y; points[1].x = loader->pp2.x; points[1].y = loader->pp2.y; points[2].x = loader->pp3.x; points[2].y = loader->pp3.y; points[3].x = loader->pp4.x; points[3].y = loader->pp4.y; outline.n_points = 4; outline.n_contours = 4; outline.points = points; outline.tags = tags; outline.contours = contours; /* this must be done before scaling */ error = TT_Vary_Apply_Glyph_Deltas( loader->face, glyph_index, &outline, unrounded, (FT_UInt)outline.n_points ); if ( error ) goto Exit; loader->pp1.x = points[0].x; loader->pp1.y = points[0].y; loader->pp2.x = points[1].x; loader->pp2.y = points[1].y; loader->pp3.x = points[2].x; loader->pp3.y = points[2].y; loader->pp4.x = points[3].x; loader->pp4.y = points[3].y; /* recalculate linear horizontal and vertical advances */ /* if we don't have HVAR and VVAR, respectively */ if ( !( loader->face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) loader->linear = FT_PIX_ROUND( unrounded[1].x - unrounded[0].x ) / 64; if ( !( loader->face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) loader->vadvance = FT_PIX_ROUND( unrounded[3].x - unrounded[2].x ) / 64; } #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ /* scale phantom points, if necessary; */ /* they get rounded in `TT_Hint_Glyph' */ if ( ( loader->load_flags & FT_LOAD_NO_SCALE ) == 0 ) { loader->pp1.x = FT_MulFix( loader->pp1.x, x_scale ); loader->pp2.x = FT_MulFix( loader->pp2.x, x_scale ); /* pp1.y and pp2.y are always zero */ loader->pp3.x = FT_MulFix( loader->pp3.x, x_scale ); loader->pp3.y = FT_MulFix( loader->pp3.y, y_scale ); loader->pp4.x = FT_MulFix( loader->pp4.x, x_scale ); loader->pp4.y = FT_MulFix( loader->pp4.y, y_scale ); } error = FT_Err_Ok; goto Exit; } #ifdef FT_CONFIG_OPTION_INCREMENTAL tt_get_metrics_incremental( loader, glyph_index ); #endif tt_loader_set_pp( loader ); /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /* we now open a frame again, right after the glyph header */ /* (which consists of 10 bytes) */ error = face->access_glyph_frame( loader, glyph_index, face->glyf_offset + offset + 10, loader->byte_len - 10 ); if ( error ) goto Exit; opened_frame = 1; /* if it is a simple glyph, load it */ if ( loader->n_contours > 0 ) { error = face->read_simple_glyph( loader ); if ( error ) goto Exit; /* all data have been read */ face->forget_glyph_frame( loader ); opened_frame = 0; error = TT_Process_Simple_Glyph( loader ); if ( error ) goto Exit; FT_GlyphLoader_Add( gloader ); } /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ /* otherwise, load a composite! */ else if ( loader->n_contours < 0 ) { FT_Memory memory = face->root.memory; FT_UInt start_point; FT_UInt start_contour; FT_ULong ins_pos; /* position of composite instructions, if any */ FT_ListNode node, node2; /* normalize the `n_contours' value */ loader->n_contours = -1; /* * We store the glyph index directly in the `node->data' pointer, * following the glib solution (cf. macro `GUINT_TO_POINTER') with a * double cast to make this portable. Note, however, that this needs * pointers with a width of at least 32 bits. */ /* clear the nodes filled by sibling chains */ node = ft_list_get_node_at( &loader->composites, recurse_count ); for ( node2 = node; node2; node2 = node2->next ) node2->data = (void*)-1; /* check whether we already have a composite glyph with this index */ if ( FT_List_Find( &loader->composites, FT_UINT_TO_POINTER( glyph_index ) ) ) { FT_TRACE1(( "TT_Load_Composite_Glyph:" " infinite recursion detected\n" )); error = FT_THROW( Invalid_Composite ); goto Exit; } else if ( node ) node->data = FT_UINT_TO_POINTER( glyph_index ); else { if ( FT_QNEW( node ) ) goto Exit; node->data = FT_UINT_TO_POINTER( glyph_index ); FT_List_Add( &loader->composites, node ); } start_point = (FT_UInt)gloader->base.outline.n_points; start_contour = (FT_UInt)gloader->base.outline.n_contours; /* for each subglyph, read composite header */ error = face->read_composite_glyph( loader ); if ( error ) goto Exit; /* store the offset of instructions */ ins_pos = loader->ins_pos; /* all data we need are read */ face->forget_glyph_frame( loader ); opened_frame = 0; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( FT_IS_NAMED_INSTANCE( FT_FACE( face ) ) || FT_IS_VARIATION( FT_FACE( face ) ) ) { short i, limit; FT_SubGlyph subglyph; FT_Outline outline; FT_Vector* points = NULL; char* tags = NULL; short* contours = NULL; FT_Vector* unrounded = NULL; limit = (short)gloader->current.num_subglyphs; /* construct an outline structure for */ /* communication with `TT_Vary_Apply_Glyph_Deltas' */ outline.n_points = (short)( gloader->current.num_subglyphs + 4 ); outline.n_contours = outline.n_points; outline.points = NULL; outline.tags = NULL; outline.contours = NULL; if ( FT_NEW_ARRAY( points, outline.n_points ) || FT_NEW_ARRAY( tags, outline.n_points ) || FT_NEW_ARRAY( contours, outline.n_points ) || FT_NEW_ARRAY( unrounded, outline.n_points ) ) goto Exit1; subglyph = gloader->current.subglyphs; for ( i = 0; i < limit; i++, subglyph++ ) { /* applying deltas for anchor points doesn't make sense, */ /* but we don't have to specially check this since */ /* unused delta values are zero anyways */ points[i].x = subglyph->arg1; points[i].y = subglyph->arg2; tags[i] = 1; contours[i] = i; } points[i].x = loader->pp1.x; points[i].y = loader->pp1.y; tags[i] = 1; contours[i] = i; i++; points[i].x = loader->pp2.x; points[i].y = loader->pp2.y; tags[i] = 1; contours[i] = i; i++; points[i].x = loader->pp3.x; points[i].y = loader->pp3.y; tags[i] = 1; contours[i] = i; i++; points[i].x = loader->pp4.x; points[i].y = loader->pp4.y; tags[i] = 1; contours[i] = i; outline.points = points; outline.tags = tags; outline.contours = contours; /* this call provides additional offsets */ /* for each component's translation */ if ( FT_SET_ERROR( TT_Vary_Apply_Glyph_Deltas( face, glyph_index, &outline, unrounded, (FT_UInt)outline.n_points ) ) ) goto Exit1; subglyph = gloader->current.subglyphs; for ( i = 0; i < limit; i++, subglyph++ ) { if ( subglyph->flags & ARGS_ARE_XY_VALUES ) { subglyph->arg1 = (FT_Int16)points[i].x; subglyph->arg2 = (FT_Int16)points[i].y; } } loader->pp1.x = points[i + 0].x; loader->pp1.y = points[i + 0].y; loader->pp2.x = points[i + 1].x; loader->pp2.y = points[i + 1].y; loader->pp3.x = points[i + 2].x; loader->pp3.y = points[i + 2].y; loader->pp4.x = points[i + 3].x; loader->pp4.y = points[i + 3].y; /* recalculate linear horizontal and vertical advances */ /* if we don't have HVAR and VVAR, respectively */ if ( !( face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) loader->linear = FT_PIX_ROUND( unrounded[outline.n_points - 3].x - unrounded[outline.n_points - 4].x ) / 64; if ( !( face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) loader->vadvance = FT_PIX_ROUND( unrounded[outline.n_points - 1].x - unrounded[outline.n_points - 2].x ) / 64; Exit1: FT_FREE( outline.points ); FT_FREE( outline.tags ); FT_FREE( outline.contours ); FT_FREE( unrounded ); if ( error ) goto Exit; } #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ /* scale phantom points, if necessary; */ /* they get rounded in `TT_Hint_Glyph' */ if ( ( loader->load_flags & FT_LOAD_NO_SCALE ) == 0 ) { loader->pp1.x = FT_MulFix( loader->pp1.x, x_scale ); loader->pp2.x = FT_MulFix( loader->pp2.x, x_scale ); /* pp1.y and pp2.y are always zero */ loader->pp3.x = FT_MulFix( loader->pp3.x, x_scale ); loader->pp3.y = FT_MulFix( loader->pp3.y, y_scale ); loader->pp4.x = FT_MulFix( loader->pp4.x, x_scale ); loader->pp4.y = FT_MulFix( loader->pp4.y, y_scale ); } /* if the flag FT_LOAD_NO_RECURSE is set, we return the subglyph */ /* `as is' in the glyph slot (the client application will be */ /* responsible for interpreting these data)... */ if ( loader->load_flags & FT_LOAD_NO_RECURSE ) { FT_GlyphLoader_Add( gloader ); loader->glyph->format = FT_GLYPH_FORMAT_COMPOSITE; goto Exit; } /*********************************************************************/ /*********************************************************************/ /*********************************************************************/ { FT_UInt n, num_base_points; FT_SubGlyph subglyph = NULL; FT_UInt num_points = start_point; FT_UInt num_subglyphs = gloader->current.num_subglyphs; FT_UInt num_base_subgs = gloader->base.num_subglyphs; FT_Stream old_stream = loader->stream; FT_UInt old_byte_len = loader->byte_len; FT_GlyphLoader_Add( gloader ); /* read each subglyph independently */ for ( n = 0; n < num_subglyphs; n++ ) { FT_Vector pp[4]; FT_Int linear_hadvance; FT_Int linear_vadvance; /* Each time we call `load_truetype_glyph' in this loop, the */ /* value of `gloader.base.subglyphs' can change due to table */ /* reallocations. We thus need to recompute the subglyph */ /* pointer on each iteration. */ subglyph = gloader->base.subglyphs + num_base_subgs + n; pp[0] = loader->pp1; pp[1] = loader->pp2; pp[2] = loader->pp3; pp[3] = loader->pp4; linear_hadvance = loader->linear; linear_vadvance = loader->vadvance; num_base_points = (FT_UInt)gloader->base.outline.n_points; error = load_truetype_glyph( loader, (FT_UInt)subglyph->index, recurse_count + 1, FALSE ); if ( error ) goto Exit; /* restore subglyph pointer */ subglyph = gloader->base.subglyphs + num_base_subgs + n; /* restore phantom points if necessary */ if ( !( subglyph->flags & USE_MY_METRICS ) ) { loader->pp1 = pp[0]; loader->pp2 = pp[1]; loader->pp3 = pp[2]; loader->pp4 = pp[3]; loader->linear = linear_hadvance; loader->vadvance = linear_vadvance; } num_points = (FT_UInt)gloader->base.outline.n_points; if ( num_points == num_base_points ) continue; /* gloader->base.outline consists of three parts: */ /* */ /* 0 ----> start_point ----> num_base_points ----> n_points */ /* (1) (2) (3) */ /* */ /* (1) points that exist from the beginning */ /* (2) component points that have been loaded so far */ /* (3) points of the newly loaded component */ error = TT_Process_Composite_Component( loader, subglyph, start_point, num_base_points ); if ( error ) goto Exit; } loader->stream = old_stream; loader->byte_len = old_byte_len; /* process the glyph */ loader->ins_pos = ins_pos; if ( IS_HINTED( loader->load_flags ) && #ifdef TT_USE_BYTECODE_INTERPRETER subglyph && subglyph->flags & WE_HAVE_INSTR && #endif num_points > start_point ) { error = TT_Process_Composite_Glyph( loader, start_point, start_contour ); if ( error ) goto Exit; } } /* retain the overlap flag */ if ( gloader->base.num_subglyphs && gloader->base.subglyphs[0].flags & OVERLAP_COMPOUND ) gloader->base.outline.flags |= FT_OUTLINE_OVERLAP; } /***********************************************************************/ /***********************************************************************/ /***********************************************************************/ Exit: if ( opened_frame ) face->forget_glyph_frame( loader ); #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_data_loaded ) face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &glyph_data ); #endif return error; } static FT_Error compute_glyph_metrics( TT_Loader loader, FT_UInt glyph_index ) { TT_Face face = loader->face; FT_BBox bbox; FT_Fixed y_scale; TT_GlyphSlot glyph = loader->glyph; TT_Size size = loader->size; y_scale = 0x10000L; if ( ( loader->load_flags & FT_LOAD_NO_SCALE ) == 0 ) y_scale = size->metrics->y_scale; if ( glyph->format != FT_GLYPH_FORMAT_COMPOSITE ) FT_Outline_Get_CBox( &glyph->outline, &bbox ); else bbox = loader->bbox; /* get the device-independent horizontal advance; it is scaled later */ /* by the base layer. */ glyph->linearHoriAdvance = loader->linear; glyph->metrics.horiBearingX = bbox.xMin; glyph->metrics.horiBearingY = bbox.yMax; if ( loader->widthp ) glyph->metrics.horiAdvance = loader->widthp[glyph_index] * 64; else glyph->metrics.horiAdvance = SUB_LONG(loader->pp2.x, loader->pp1.x); /* set glyph dimensions */ glyph->metrics.width = SUB_LONG( bbox.xMax, bbox.xMin ); glyph->metrics.height = SUB_LONG( bbox.yMax, bbox.yMin ); /* Now take care of vertical metrics. In the case where there is */ /* no vertical information within the font (relatively common), */ /* create some metrics manually */ { FT_Pos top; /* scaled vertical top side bearing */ FT_Pos advance; /* scaled vertical advance height */ /* Get the unscaled top bearing and advance height. */ if ( face->vertical_info && face->vertical.number_Of_VMetrics > 0 ) { top = (FT_Short)FT_DivFix( SUB_LONG( loader->pp3.y, bbox.yMax ), y_scale ); if ( loader->pp3.y <= loader->pp4.y ) advance = 0; else advance = (FT_UShort)FT_DivFix( SUB_LONG( loader->pp3.y, loader->pp4.y ), y_scale ); } else { FT_Pos height; /* XXX Compute top side bearing and advance height in */ /* Get_VMetrics instead of here. */ /* NOTE: The OS/2 values are the only `portable' ones, */ /* which is why we use them, if there is an OS/2 */ /* table in the font. Otherwise, we use the */ /* values defined in the horizontal header. */ height = (FT_Short)FT_DivFix( SUB_LONG( bbox.yMax, bbox.yMin ), y_scale ); if ( face->os2.version != 0xFFFFU ) advance = (FT_Pos)( face->os2.sTypoAscender - face->os2.sTypoDescender ); else advance = (FT_Pos)( face->horizontal.Ascender - face->horizontal.Descender ); top = ( advance - height ) / 2; } #ifdef FT_CONFIG_OPTION_INCREMENTAL { FT_Incremental_InterfaceRec* incr; FT_Incremental_MetricsRec incr_metrics; FT_Error error; incr = face->root.internal->incremental_interface; /* If this is an incrementally loaded font see if there are */ /* overriding metrics for this glyph. */ if ( incr && incr->funcs->get_glyph_metrics ) { incr_metrics.bearing_x = 0; incr_metrics.bearing_y = top; incr_metrics.advance = advance; error = incr->funcs->get_glyph_metrics( incr->object, glyph_index, TRUE, &incr_metrics ); if ( error ) return error; top = incr_metrics.bearing_y; advance = incr_metrics.advance; } } /* GWW: Do vertical metrics get loaded incrementally too? */ #endif /* FT_CONFIG_OPTION_INCREMENTAL */ glyph->linearVertAdvance = advance; /* scale the metrics */ if ( !( loader->load_flags & FT_LOAD_NO_SCALE ) ) { top = FT_MulFix( top, y_scale ); advance = FT_MulFix( advance, y_scale ); } /* XXX: for now, we have no better algorithm for the lsb, but it */ /* should work fine. */ /* */ glyph->metrics.vertBearingX = SUB_LONG( glyph->metrics.horiBearingX, glyph->metrics.horiAdvance / 2 ); glyph->metrics.vertBearingY = top; glyph->metrics.vertAdvance = advance; } return FT_Err_Ok; } #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS static FT_Error load_sbit_image( TT_Size size, TT_GlyphSlot glyph, FT_UInt glyph_index, FT_Int32 load_flags ) { TT_Face face; SFNT_Service sfnt; FT_Stream stream; FT_Error error; TT_SBit_MetricsRec sbit_metrics; face = (TT_Face)glyph->face; sfnt = (SFNT_Service)face->sfnt; stream = face->root.stream; error = sfnt->load_sbit_image( face, size->strike_index, glyph_index, (FT_UInt)load_flags, stream, &glyph->bitmap, &sbit_metrics ); if ( !error ) { glyph->outline.n_points = 0; glyph->outline.n_contours = 0; glyph->metrics.width = (FT_Pos)sbit_metrics.width * 64; glyph->metrics.height = (FT_Pos)sbit_metrics.height * 64; glyph->metrics.horiBearingX = (FT_Pos)sbit_metrics.horiBearingX * 64; glyph->metrics.horiBearingY = (FT_Pos)sbit_metrics.horiBearingY * 64; glyph->metrics.horiAdvance = (FT_Pos)sbit_metrics.horiAdvance * 64; glyph->metrics.vertBearingX = (FT_Pos)sbit_metrics.vertBearingX * 64; glyph->metrics.vertBearingY = (FT_Pos)sbit_metrics.vertBearingY * 64; glyph->metrics.vertAdvance = (FT_Pos)sbit_metrics.vertAdvance * 64; glyph->format = FT_GLYPH_FORMAT_BITMAP; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { glyph->bitmap_left = sbit_metrics.vertBearingX; glyph->bitmap_top = sbit_metrics.vertBearingY; } else { glyph->bitmap_left = sbit_metrics.horiBearingX; glyph->bitmap_top = sbit_metrics.horiBearingY; } } return error; } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ static FT_Error tt_loader_init( TT_Loader loader, TT_Size size, TT_GlyphSlot glyph, FT_Int32 load_flags, FT_Bool glyf_table_only ) { TT_Face face; FT_Stream stream; #ifdef TT_USE_BYTECODE_INTERPRETER FT_Error error; FT_Bool pedantic = FT_BOOL( load_flags & FT_LOAD_PEDANTIC ); #if defined TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY || \ defined TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( (TT_Face)glyph->face ); #endif #endif face = (TT_Face)glyph->face; stream = face->root.stream; FT_ZERO( loader ); #ifdef TT_USE_BYTECODE_INTERPRETER /* load execution context */ if ( IS_HINTED( load_flags ) && !glyf_table_only ) { TT_ExecContext exec; FT_Bool grayscale = TRUE; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL FT_Bool subpixel_hinting_lean; FT_Bool grayscale_cleartype; #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY FT_Bool subpixel_hinting = FALSE; #if 0 /* not used yet */ FT_Bool compatible_widths; FT_Bool symmetrical_smoothing; FT_Bool bgr; FT_Bool vertical_lcd; FT_Bool subpixel_positioned; FT_Bool gray_cleartype; #endif #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ FT_Bool reexecute = FALSE; if ( size->bytecode_ready < 0 || size->cvt_ready < 0 ) { error = tt_size_ready_bytecode( size, pedantic ); if ( error ) return error; } else if ( size->bytecode_ready ) return size->bytecode_ready; else if ( size->cvt_ready ) return size->cvt_ready; /* query new execution context */ exec = size->context; if ( !exec ) return FT_THROW( Could_Not_Find_Context ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( driver->interpreter_version == TT_INTERPRETER_VERSION_40 ) { subpixel_hinting_lean = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != FT_RENDER_MODE_MONO ); grayscale_cleartype = FT_BOOL( subpixel_hinting_lean && !( ( load_flags & FT_LOAD_TARGET_LCD ) || ( load_flags & FT_LOAD_TARGET_LCD_V ) ) ); exec->vertical_lcd_lean = FT_BOOL( subpixel_hinting_lean && ( load_flags & FT_LOAD_TARGET_LCD_V ) ); } else { subpixel_hinting_lean = FALSE; grayscale_cleartype = FALSE; exec->vertical_lcd_lean = FALSE; } #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 ) { subpixel_hinting = FT_BOOL( ( FT_LOAD_TARGET_MODE( load_flags ) != FT_RENDER_MODE_MONO ) && SPH_OPTION_SET_SUBPIXEL ); if ( subpixel_hinting ) grayscale = FALSE; else if ( SPH_OPTION_SET_GRAYSCALE ) { grayscale = TRUE; subpixel_hinting = FALSE; } else grayscale = FALSE; if ( FT_IS_TRICKY( glyph->face ) ) subpixel_hinting = FALSE; exec->ignore_x_mode = subpixel_hinting || grayscale; exec->rasterizer_version = SPH_OPTION_SET_RASTERIZER_VERSION; if ( exec->sph_tweak_flags & SPH_TWEAK_RASTERIZER_35 ) exec->rasterizer_version = TT_INTERPRETER_VERSION_35; #if 1 exec->compatible_widths = SPH_OPTION_SET_COMPATIBLE_WIDTHS; exec->symmetrical_smoothing = TRUE; exec->bgr = FALSE; exec->vertical_lcd = FALSE; exec->subpixel_positioned = TRUE; exec->gray_cleartype = FALSE; #else /* 0 */ exec->compatible_widths = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_COMPATIBLE_WIDTHS ); exec->symmetrical_smoothing = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_SYMMETRICAL_SMOOTHING ); exec->bgr = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_BGR ); exec->vertical_lcd = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_VERTICAL_LCD ); exec->subpixel_positioned = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_SUBPIXEL_POSITIONED ); exec->gray_cleartype = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != TT_LOAD_GRAY_CLEARTYPE ); #endif /* 0 */ } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( driver->interpreter_version == TT_INTERPRETER_VERSION_40 ) grayscale = FT_BOOL( !subpixel_hinting_lean && FT_LOAD_TARGET_MODE( load_flags ) != FT_RENDER_MODE_MONO ); else #endif grayscale = FT_BOOL( FT_LOAD_TARGET_MODE( load_flags ) != FT_RENDER_MODE_MONO ); error = TT_Load_Context( exec, face, size ); if ( error ) return error; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 ) { /* a change from mono to subpixel rendering (and vice versa) */ /* requires a re-execution of the CVT program */ if ( subpixel_hinting != exec->subpixel_hinting ) { FT_TRACE4(( "tt_loader_init: subpixel hinting change," " re-executing `prep' table\n" )); exec->subpixel_hinting = subpixel_hinting; reexecute = TRUE; } /* a change from mono to grayscale rendering (and vice versa) */ /* requires a re-execution of the CVT program */ if ( grayscale != exec->grayscale ) { FT_TRACE4(( "tt_loader_init: grayscale hinting change," " re-executing `prep' table\n" )); exec->grayscale = grayscale; reexecute = TRUE; } } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( driver->interpreter_version == TT_INTERPRETER_VERSION_40 ) { /* a change from mono to subpixel rendering (and vice versa) */ /* requires a re-execution of the CVT program */ if ( subpixel_hinting_lean != exec->subpixel_hinting_lean ) { FT_TRACE4(( "tt_loader_init: subpixel hinting change," " re-executing `prep' table\n" )); exec->subpixel_hinting_lean = subpixel_hinting_lean; reexecute = TRUE; } /* a change from colored to grayscale subpixel rendering (and */ /* vice versa) requires a re-execution of the CVT program */ if ( grayscale_cleartype != exec->grayscale_cleartype ) { FT_TRACE4(( "tt_loader_init: grayscale subpixel hinting change," " re-executing `prep' table\n" )); exec->grayscale_cleartype = grayscale_cleartype; reexecute = TRUE; } } #endif /* a change from mono to grayscale rendering (and vice versa) */ /* requires a re-execution of the CVT program */ if ( grayscale != exec->grayscale ) { FT_TRACE4(( "tt_loader_init: grayscale hinting change," " re-executing `prep' table\n" )); exec->grayscale = grayscale; reexecute = TRUE; } } if ( reexecute ) { error = tt_size_run_prep( size, pedantic ); if ( error ) return error; error = TT_Load_Context( exec, face, size ); if ( error ) return error; } /* check whether the cvt program has disabled hinting */ if ( exec->GS.instruct_control & 1 ) load_flags |= FT_LOAD_NO_HINTING; /* load default graphics state -- if needed */ if ( exec->GS.instruct_control & 2 ) exec->GS = tt_default_graphics_state; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* check whether we have a font hinted for ClearType -- */ /* note that this flag can also be modified in a glyph's bytecode */ if ( driver->interpreter_version == TT_INTERPRETER_VERSION_38 && exec->GS.instruct_control & 4 ) exec->ignore_x_mode = FALSE; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* * Toggle backward compatibility according to what font wants, except * when * * 1) we have a `tricky' font that heavily relies on the interpreter to * render glyphs correctly, for example DFKai-SB, or * 2) FT_RENDER_MODE_MONO (i.e, monochome rendering) is requested. * * In those cases, backward compatibility needs to be turned off to get * correct rendering. The rendering is then completely up to the * font's programming. * */ if ( driver->interpreter_version == TT_INTERPRETER_VERSION_40 && subpixel_hinting_lean && !FT_IS_TRICKY( glyph->face ) ) exec->backward_compatibility = !( exec->GS.instruct_control & 4 ); else exec->backward_compatibility = FALSE; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL */ exec->pedantic_hinting = FT_BOOL( load_flags & FT_LOAD_PEDANTIC ); loader->exec = exec; loader->instructions = exec->glyphIns; /* Use the hdmx table if any unless FT_LOAD_COMPUTE_METRICS */ /* is set or backward compatibility mode of the v38 or v40 */ /* interpreters is active. See `ttinterp.h' for details on */ /* backward compatibility mode. */ if ( IS_HINTED( loader->load_flags ) && !( loader->load_flags & FT_LOAD_COMPUTE_METRICS ) && #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL !( driver->interpreter_version == TT_INTERPRETER_VERSION_40 && exec->backward_compatibility ) && #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY !( driver->interpreter_version == TT_INTERPRETER_VERSION_38 && !SPH_OPTION_BITMAP_WIDTHS && FT_LOAD_TARGET_MODE( loader->load_flags ) != FT_RENDER_MODE_MONO && exec->compatible_widths ) && #endif !face->postscript.isFixedPitch ) { loader->widthp = size->widthp; } else loader->widthp = NULL; } #endif /* TT_USE_BYTECODE_INTERPRETER */ /* get face's glyph loader */ if ( !glyf_table_only ) { FT_GlyphLoader gloader = glyph->internal->loader; FT_GlyphLoader_Rewind( gloader ); loader->gloader = gloader; } loader->load_flags = (FT_ULong)load_flags; loader->face = face; loader->size = size; loader->glyph = (FT_GlyphSlot)glyph; loader->stream = stream; loader->composites.head = NULL; loader->composites.tail = NULL; return FT_Err_Ok; } static void tt_loader_done( TT_Loader loader ) { FT_List_Finalize( &loader->composites, NULL, loader->face->root.memory, NULL ); } /************************************************************************** * * @Function: * TT_Load_Glyph * * @Description: * A function used to load a single glyph within a given glyph slot, * for a given size. * * @InOut: * glyph :: * A handle to a target slot object where the glyph * will be loaded. * * @Input: * size :: * A handle to the source face size at which the glyph * must be scaled/loaded. * * glyph_index :: * The index of the glyph in the font file. * * load_flags :: * A flag indicating what to load for this glyph. The * FT_LOAD_XXX constants can be used to control the * glyph loading process (e.g., whether the outline * should be scaled, whether to load bitmaps or not, * whether to hint the outline, etc). * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Load_Glyph( TT_Size size, TT_GlyphSlot glyph, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; TT_LoaderRec loader; FT_TRACE1(( "TT_Load_Glyph: glyph index %d\n", glyph_index )); #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS /* try to load embedded bitmap (if any) */ if ( size->strike_index != 0xFFFFFFFFUL && ( load_flags & FT_LOAD_NO_BITMAP ) == 0 && IS_DEFAULT_INSTANCE( glyph->face ) ) { FT_Fixed x_scale = size->root.metrics.x_scale; FT_Fixed y_scale = size->root.metrics.y_scale; error = load_sbit_image( size, glyph, glyph_index, load_flags ); if ( FT_ERR_EQ( error, Missing_Bitmap ) ) { /* the bitmap strike is incomplete and misses the requested glyph; */ /* if we have a bitmap-only font, return an empty glyph */ if ( !FT_IS_SCALABLE( glyph->face ) ) { TT_Face face = (TT_Face)glyph->face; FT_Short left_bearing = 0; FT_Short top_bearing = 0; FT_UShort advance_width = 0; FT_UShort advance_height = 0; /* to return an empty glyph, however, we need metrics data */ /* from the `hmtx' (or `vmtx') table; the assumption is that */ /* empty glyphs are missing intentionally, representing */ /* whitespace - not having at least horizontal metrics is */ /* thus considered an error */ if ( !face->horz_metrics_size ) return error; /* we now construct an empty bitmap glyph */ TT_Get_HMetrics( face, glyph_index, &left_bearing, &advance_width ); TT_Get_VMetrics( face, glyph_index, 0, &top_bearing, &advance_height ); glyph->outline.n_points = 0; glyph->outline.n_contours = 0; glyph->metrics.width = 0; glyph->metrics.height = 0; glyph->metrics.horiBearingX = FT_MulFix( left_bearing, x_scale ); glyph->metrics.horiBearingY = 0; glyph->metrics.horiAdvance = FT_MulFix( advance_width, x_scale ); glyph->metrics.vertBearingX = 0; glyph->metrics.vertBearingY = FT_MulFix( top_bearing, y_scale ); glyph->metrics.vertAdvance = FT_MulFix( advance_height, y_scale ); glyph->format = FT_GLYPH_FORMAT_BITMAP; glyph->bitmap.pixel_mode = FT_PIXEL_MODE_MONO; glyph->bitmap_left = 0; glyph->bitmap_top = 0; return FT_Err_Ok; } } else if ( error ) { /* return error if font is not scalable */ if ( !FT_IS_SCALABLE( glyph->face ) ) return error; } else { if ( FT_IS_SCALABLE( glyph->face ) || FT_HAS_SBIX( glyph->face ) ) { TT_Face face = (TT_Face)glyph->face; /* for the bbox we need the header only */ (void)tt_loader_init( &loader, size, glyph, load_flags, TRUE ); (void)load_truetype_glyph( &loader, glyph_index, 0, TRUE ); tt_loader_done( &loader ); glyph->linearHoriAdvance = loader.linear; glyph->linearVertAdvance = loader.vadvance; /* Bitmaps from the 'sbix' table need special treatment: */ /* if there is a glyph contour, the bitmap origin must be */ /* shifted to be relative to the lower left corner of the */ /* glyph bounding box, also taking the left-side bearing */ /* (or top bearing) into account. */ if ( face->sbit_table_type == TT_SBIT_TABLE_TYPE_SBIX && loader.n_contours > 0 ) { FT_Int bitmap_left; FT_Int bitmap_top; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* This is a guess, since Apple's CoreText engine doesn't */ /* really do vertical typesetting. */ bitmap_left = loader.bbox.xMin; bitmap_top = loader.top_bearing; } else { bitmap_left = loader.left_bearing; bitmap_top = loader.bbox.yMin; } glyph->bitmap_left += FT_MulFix( bitmap_left, x_scale ) >> 6; glyph->bitmap_top += FT_MulFix( bitmap_top, y_scale ) >> 6; } /* sanity checks: if `xxxAdvance' in the sbit metric */ /* structure isn't set, use `linearXXXAdvance' */ if ( !glyph->metrics.horiAdvance && glyph->linearHoriAdvance ) glyph->metrics.horiAdvance = FT_MulFix( glyph->linearHoriAdvance, x_scale ); if ( !glyph->metrics.vertAdvance && glyph->linearVertAdvance ) glyph->metrics.vertAdvance = FT_MulFix( glyph->linearVertAdvance, y_scale ); } return FT_Err_Ok; } } if ( load_flags & FT_LOAD_SBITS_ONLY ) { error = FT_THROW( Invalid_Argument ); goto Exit; } #endif /* TT_CONFIG_OPTION_EMBEDDED_BITMAPS */ /* if FT_LOAD_NO_SCALE is not set, `ttmetrics' must be valid */ if ( !( load_flags & FT_LOAD_NO_SCALE ) && !size->ttmetrics.valid ) { error = FT_THROW( Invalid_Size_Handle ); goto Exit; } #ifdef FT_CONFIG_OPTION_SVG /* check for OT-SVG */ if ( ( load_flags & FT_LOAD_COLOR ) && ( (TT_Face)glyph->face )->svg ) { SFNT_Service sfnt; FT_Short leftBearing; FT_Short topBearing; FT_UShort advanceX; FT_UShort advanceY; FT_TRACE3(( "Trying to load SVG glyph\n" )); sfnt = (SFNT_Service)( (TT_Face)glyph->face )->sfnt; error = sfnt->load_svg_doc( glyph, glyph_index ); if ( !error ) { TT_Face face = (TT_Face)glyph->face; FT_TRACE3(( "Successfully loaded SVG glyph\n" )); glyph->format = FT_GLYPH_FORMAT_SVG; sfnt->get_metrics( face, FALSE, glyph_index, &leftBearing, &advanceX ); sfnt->get_metrics( face, TRUE, glyph_index, &topBearing, &advanceY ); advanceX = (FT_UShort)FT_MulDiv( advanceX, glyph->face->size->metrics.x_ppem, glyph->face->units_per_EM ); advanceY = (FT_UShort)FT_MulDiv( advanceY, glyph->face->size->metrics.y_ppem, glyph->face->units_per_EM ); glyph->metrics.horiAdvance = advanceX << 6; glyph->metrics.vertAdvance = advanceY << 6; return error; } FT_TRACE3(( "Failed to load SVG glyph\n" )); } /* return immediately if we only want SVG glyphs */ if ( load_flags & FT_LOAD_SVG_ONLY ) { error = FT_THROW( Invalid_Argument ); goto Exit; } #endif /* FT_CONFIG_OPTION_SVG */ error = tt_loader_init( &loader, size, glyph, load_flags, FALSE ); if ( error ) goto Exit; /* done if we are only interested in the `hdmx` advance */ if ( load_flags & FT_LOAD_ADVANCE_ONLY && !( load_flags & FT_LOAD_VERTICAL_LAYOUT ) && loader.widthp ) { glyph->metrics.horiAdvance = loader.widthp[glyph_index] * 64; goto Done; } glyph->format = FT_GLYPH_FORMAT_OUTLINE; glyph->num_subglyphs = 0; glyph->outline.flags = 0; /* main loading loop */ error = load_truetype_glyph( &loader, glyph_index, 0, FALSE ); if ( !error ) { if ( glyph->format == FT_GLYPH_FORMAT_COMPOSITE ) { glyph->num_subglyphs = loader.gloader->base.num_subglyphs; glyph->subglyphs = loader.gloader->base.subglyphs; } else { glyph->outline = loader.gloader->base.outline; glyph->outline.flags &= ~FT_OUTLINE_SINGLE_PASS; /* Translate array so that (0,0) is the glyph's origin. Note */ /* that this behaviour is independent on the value of bit 1 of */ /* the `flags' field in the `head' table -- at least major */ /* applications like Acroread indicate that. */ if ( loader.pp1.x ) FT_Outline_Translate( &glyph->outline, -loader.pp1.x, 0 ); } #ifdef TT_USE_BYTECODE_INTERPRETER if ( IS_HINTED( load_flags ) ) { if ( loader.exec->GS.scan_control ) { /* convert scan conversion mode to FT_OUTLINE_XXX flags */ switch ( loader.exec->GS.scan_type ) { case 0: /* simple drop-outs including stubs */ glyph->outline.flags |= FT_OUTLINE_INCLUDE_STUBS; break; case 1: /* simple drop-outs excluding stubs */ /* nothing; it's the default rendering mode */ break; case 4: /* smart drop-outs including stubs */ glyph->outline.flags |= FT_OUTLINE_SMART_DROPOUTS | FT_OUTLINE_INCLUDE_STUBS; break; case 5: /* smart drop-outs excluding stubs */ glyph->outline.flags |= FT_OUTLINE_SMART_DROPOUTS; break; default: /* no drop-out control */ glyph->outline.flags |= FT_OUTLINE_IGNORE_DROPOUTS; break; } } else glyph->outline.flags |= FT_OUTLINE_IGNORE_DROPOUTS; } #endif /* TT_USE_BYTECODE_INTERPRETER */ error = compute_glyph_metrics( &loader, glyph_index ); } /* Set the `high precision' bit flag. */ /* This is _critical_ to get correct output for monochrome */ /* TrueType glyphs at all sizes using the bytecode interpreter. */ /* */ if ( !( load_flags & FT_LOAD_NO_SCALE ) && size->metrics->y_ppem < 24 ) glyph->outline.flags |= FT_OUTLINE_HIGH_PRECISION; FT_TRACE1(( " subglyphs = %u, contours = %hd, points = %hd," " flags = 0x%.3x\n", loader.gloader->base.num_subglyphs, glyph->outline.n_contours, glyph->outline.n_points, glyph->outline.flags )); Done: tt_loader_done( &loader ); Exit: #ifdef FT_DEBUG_LEVEL_TRACE if ( error ) FT_TRACE1(( " failed (error code 0x%x)\n", error )); #endif return error; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttgload.c
C++
gpl-3.0
99,559
/**************************************************************************** * * ttgload.h * * TrueType Glyph Loader (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTGLOAD_H_ #define TTGLOAD_H_ #include "ttobjs.h" #ifdef TT_USE_BYTECODE_INTERPRETER #include "ttinterp.h" #endif FT_BEGIN_HEADER FT_LOCAL( void ) TT_Init_Glyph_Loading( TT_Face face ); FT_LOCAL( void ) TT_Get_HMetrics( TT_Face face, FT_UInt idx, FT_Short* lsb, FT_UShort* aw ); FT_LOCAL( void ) TT_Get_VMetrics( TT_Face face, FT_UInt idx, FT_Pos yMax, FT_Short* tsb, FT_UShort* ah ); FT_LOCAL( FT_Error ) TT_Load_Glyph( TT_Size size, TT_GlyphSlot glyph, FT_UInt glyph_index, FT_Int32 load_flags ); FT_END_HEADER #endif /* TTGLOAD_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttgload.h
C++
gpl-3.0
1,358
/**************************************************************************** * * ttgxvar.c * * TrueType GX Font Variation loader * * Copyright (C) 2004-2022 by * David Turner, Robert Wilhelm, Werner Lemberg, and George Williams. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * Apple documents the `fvar', `gvar', `cvar', and `avar' tables at * * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6[fgca]var.html * * The documentation for `gvar' is not intelligible; `cvar' refers you * to `gvar' and is thus also incomprehensible. * * The documentation for `avar' appears correct, but Apple has no fonts * with an `avar' table, so it is hard to test. * * Many thanks to John Jenkins (at Apple) in figuring this out. * * * Apple's `kern' table has some references to tuple indices, but as * there is no indication where these indices are defined, nor how to * interpolate the kerning values (different tuples have different * classes) this issue is ignored. * */ #include <ft2build.h> #include <freetype/internal/ftdebug.h> #include FT_CONFIG_CONFIG_H #include <freetype/internal/ftstream.h> #include <freetype/internal/sfnt.h> #include <freetype/tttags.h> #include <freetype/ttnameid.h> #include <freetype/ftmm.h> #include <freetype/ftlist.h> #include "ttpload.h" #include "ttgxvar.h" #include "tterrors.h" #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #define FT_Stream_FTell( stream ) \ (FT_ULong)( (stream)->cursor - (stream)->base ) #define FT_Stream_SeekSet( stream, off ) \ (stream)->cursor = \ ( (off) < (FT_ULong)( (stream)->limit - (stream)->base ) ) \ ? (stream)->base + (off) \ : (stream)->limit /* some macros we need */ #define FT_fdot14ToFixed( x ) \ ( (FT_Fixed)( (FT_ULong)(x) << 2 ) ) #define FT_intToFixed( i ) \ ( (FT_Fixed)( (FT_ULong)(i) << 16 ) ) #define FT_fdot6ToFixed( i ) \ ( (FT_Fixed)( (FT_ULong)(i) << 10 ) ) #define FT_fixedToInt( x ) \ ( (FT_Short)( ( (x) + 0x8000U ) >> 16 ) ) #define FT_fixedToFdot6( x ) \ ( (FT_Pos)( ( (x) + 0x200 ) >> 10 ) ) /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttgxvar /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** Internal Routines *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * The macro ALL_POINTS is used in `ft_var_readpackedpoints'. It * indicates that there is a delta for every point without needing to * enumerate all of them. */ /* ensure that value `0' has the same width as a pointer */ #define ALL_POINTS (FT_UShort*)~(FT_PtrDist)0 #define GX_PT_POINTS_ARE_WORDS 0x80U #define GX_PT_POINT_RUN_COUNT_MASK 0x7FU /************************************************************************** * * @Function: * ft_var_readpackedpoints * * @Description: * Read a set of points to which the following deltas will apply. * Points are packed with a run length encoding. * * @Input: * stream :: * The data stream. * * size :: * The size of the table holding the data. * * @Output: * point_cnt :: * The number of points read. A zero value means that * all points in the glyph will be affected, without * enumerating them individually. * * @Return: * An array of FT_UShort containing the affected points or the * special value ALL_POINTS. */ static FT_UShort* ft_var_readpackedpoints( FT_Stream stream, FT_ULong size, FT_UInt *point_cnt ) { FT_UShort *points = NULL; FT_UInt n; FT_UInt runcnt; FT_UInt i, j; FT_UShort first; FT_Memory memory = stream->memory; FT_Error error; *point_cnt = 0; n = FT_GET_BYTE(); if ( n == 0 ) return ALL_POINTS; if ( n & GX_PT_POINTS_ARE_WORDS ) { n &= GX_PT_POINT_RUN_COUNT_MASK; n <<= 8; n |= FT_GET_BYTE(); } if ( n > size ) { FT_TRACE1(( "ft_var_readpackedpoints: number of points too large\n" )); return NULL; } /* in the nested loops below we increase `i' twice; */ /* it is faster to simply allocate one more slot */ /* than to add another test within the loop */ if ( FT_QNEW_ARRAY( points, n + 1 ) ) return NULL; *point_cnt = n; first = 0; i = 0; while ( i < n ) { runcnt = FT_GET_BYTE(); if ( runcnt & GX_PT_POINTS_ARE_WORDS ) { runcnt &= GX_PT_POINT_RUN_COUNT_MASK; first += FT_GET_USHORT(); points[i++] = first; /* first point not included in run count */ for ( j = 0; j < runcnt; j++ ) { first += FT_GET_USHORT(); points[i++] = first; if ( i >= n ) break; } } else { first += FT_GET_BYTE(); points[i++] = first; for ( j = 0; j < runcnt; j++ ) { first += FT_GET_BYTE(); points[i++] = first; if ( i >= n ) break; } } } return points; } #define GX_DT_DELTAS_ARE_ZERO 0x80U #define GX_DT_DELTAS_ARE_WORDS 0x40U #define GX_DT_DELTA_RUN_COUNT_MASK 0x3FU /************************************************************************** * * @Function: * ft_var_readpackeddeltas * * @Description: * Read a set of deltas. These are packed slightly differently than * points. In particular there is no overall count. * * @Input: * stream :: * The data stream. * * size :: * The size of the table holding the data. * * delta_cnt :: * The number of deltas to be read. * * @Return: * An array of FT_Fixed containing the deltas for the affected * points. (This only gets the deltas for one dimension. It will * generally be called twice, once for x, once for y. When used in * cvt table, it will only be called once.) * * We use FT_Fixed to avoid accumulation errors while summing up all * deltas (the rounding to integer values happens as the very last * step). */ static FT_Fixed* ft_var_readpackeddeltas( FT_Stream stream, FT_ULong size, FT_UInt delta_cnt ) { FT_Fixed *deltas = NULL; FT_UInt runcnt, cnt; FT_UInt i, j; FT_UInt bytes_used; FT_Memory memory = stream->memory; FT_Error error; if ( FT_QNEW_ARRAY( deltas, delta_cnt ) ) return NULL; i = 0; bytes_used = 0; while ( i < delta_cnt && bytes_used < size ) { runcnt = FT_GET_BYTE(); cnt = runcnt & GX_DT_DELTA_RUN_COUNT_MASK; bytes_used++; if ( runcnt & GX_DT_DELTAS_ARE_ZERO ) { /* `cnt` + 1 zeroes get added */ for ( j = 0; j <= cnt && i < delta_cnt; j++ ) deltas[i++] = 0; } else if ( runcnt & GX_DT_DELTAS_ARE_WORDS ) { /* `cnt` + 1 shorts from the stack */ bytes_used += 2 * ( cnt + 1 ); if ( bytes_used > size ) { FT_TRACE1(( "ft_var_readpackeddeltas:" " number of short deltas too large\n" )); goto Fail; } for ( j = 0; j <= cnt && i < delta_cnt; j++ ) deltas[i++] = FT_intToFixed( FT_GET_SHORT() ); } else { /* `cnt` + 1 signed bytes from the stack */ bytes_used += cnt + 1; if ( bytes_used > size ) { FT_TRACE1(( "ft_var_readpackeddeltas:" " number of byte deltas too large\n" )); goto Fail; } for ( j = 0; j <= cnt && i < delta_cnt; j++ ) deltas[i++] = FT_intToFixed( FT_GET_CHAR() ); } if ( j <= cnt ) { FT_TRACE1(( "ft_var_readpackeddeltas:" " number of deltas too large\n" )); goto Fail; } } if ( i < delta_cnt ) { FT_TRACE1(( "ft_var_readpackeddeltas: not enough deltas\n" )); goto Fail; } return deltas; Fail: FT_FREE( deltas ); return NULL; } /************************************************************************** * * @Function: * ft_var_load_avar * * @Description: * Parse the `avar' table if present. It need not be, so we return * nothing. * * @InOut: * face :: * The font face. */ static void ft_var_load_avar( TT_Face face ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; GX_Blend blend = face->blend; GX_AVarSegment segment; FT_Error error; FT_Long version; FT_Long axisCount; FT_Int i, j; FT_ULong table_len; FT_TRACE2(( "AVAR " )); blend->avar_loaded = TRUE; error = face->goto_table( face, TTAG_avar, stream, &table_len ); if ( error ) { FT_TRACE2(( "is missing\n" )); return; } if ( FT_FRAME_ENTER( table_len ) ) return; version = FT_GET_LONG(); axisCount = FT_GET_LONG(); if ( version != 0x00010000L ) { FT_TRACE2(( "bad table version\n" )); goto Exit; } FT_TRACE2(( "loaded\n" )); if ( axisCount != (FT_Long)blend->mmvar->num_axis ) { FT_TRACE2(( "ft_var_load_avar:" " number of axes in `avar' and `fvar'\n" )); FT_TRACE2(( " table are different\n" )); goto Exit; } if ( FT_QNEW_ARRAY( blend->avar_segment, axisCount ) ) goto Exit; segment = &blend->avar_segment[0]; for ( i = 0; i < axisCount; i++, segment++ ) { FT_TRACE5(( " axis %d:\n", i )); segment->pairCount = FT_GET_USHORT(); if ( (FT_ULong)segment->pairCount * 4 > table_len || FT_QNEW_ARRAY( segment->correspondence, segment->pairCount ) ) { /* Failure. Free everything we have done so far. We must do */ /* it right now since loading the `avar' table is optional. */ for ( j = i - 1; j >= 0; j-- ) FT_FREE( blend->avar_segment[j].correspondence ); FT_FREE( blend->avar_segment ); goto Exit; } for ( j = 0; j < segment->pairCount; j++ ) { segment->correspondence[j].fromCoord = FT_fdot14ToFixed( FT_GET_SHORT() ); segment->correspondence[j].toCoord = FT_fdot14ToFixed( FT_GET_SHORT() ); FT_TRACE5(( " mapping %.5f to %.5f\n", segment->correspondence[j].fromCoord / 65536.0, segment->correspondence[j].toCoord / 65536.0 )); } FT_TRACE5(( "\n" )); } Exit: FT_FRAME_EXIT(); } static FT_Error ft_var_load_item_variation_store( TT_Face face, FT_ULong offset, GX_ItemVarStore itemStore ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; FT_Error error; FT_UShort format; FT_ULong region_offset; FT_UInt i, j, k; FT_UInt wordDeltaCount; FT_Bool long_words; GX_Blend blend = face->blend; GX_ItemVarData varData; FT_ULong* dataOffsetArray = NULL; if ( FT_STREAM_SEEK( offset ) || FT_READ_USHORT( format ) ) goto Exit; if ( format != 1 ) { FT_TRACE2(( "ft_var_load_item_variation_store: bad store format %d\n", format )); error = FT_THROW( Invalid_Table ); goto Exit; } /* read top level fields */ if ( FT_READ_ULONG( region_offset ) || FT_READ_USHORT( itemStore->dataCount ) ) goto Exit; /* we need at least one entry in `itemStore->varData' */ if ( !itemStore->dataCount ) { FT_TRACE2(( "ft_var_load_item_variation_store: missing varData\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } /* make temporary copy of item variation data offsets; */ /* we will parse region list first, then come back */ if ( FT_QNEW_ARRAY( dataOffsetArray, itemStore->dataCount ) ) goto Exit; for ( i = 0; i < itemStore->dataCount; i++ ) { if ( FT_READ_ULONG( dataOffsetArray[i] ) ) goto Exit; } /* parse array of region records (region list) */ if ( FT_STREAM_SEEK( offset + region_offset ) ) goto Exit; if ( FT_READ_USHORT( itemStore->axisCount ) || FT_READ_USHORT( itemStore->regionCount ) ) goto Exit; if ( itemStore->axisCount != (FT_Long)blend->mmvar->num_axis ) { FT_TRACE2(( "ft_var_load_item_variation_store:" " number of axes in item variation store\n" )); FT_TRACE2(( " " " and `fvar' table are different\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } /* new constraint in OpenType 1.8.4 */ if ( itemStore->regionCount >= 32768U ) { FT_TRACE2(( "ft_var_load_item_variation_store:" " too many variation region tables\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( FT_NEW_ARRAY( itemStore->varRegionList, itemStore->regionCount ) ) goto Exit; for ( i = 0; i < itemStore->regionCount; i++ ) { GX_AxisCoords axisCoords; if ( FT_NEW_ARRAY( itemStore->varRegionList[i].axisList, itemStore->axisCount ) ) goto Exit; axisCoords = itemStore->varRegionList[i].axisList; for ( j = 0; j < itemStore->axisCount; j++ ) { FT_Short start, peak, end; if ( FT_READ_SHORT( start ) || FT_READ_SHORT( peak ) || FT_READ_SHORT( end ) ) goto Exit; axisCoords[j].startCoord = FT_fdot14ToFixed( start ); axisCoords[j].peakCoord = FT_fdot14ToFixed( peak ); axisCoords[j].endCoord = FT_fdot14ToFixed( end ); } } /* end of region list parse */ /* use dataOffsetArray now to parse varData items */ if ( FT_NEW_ARRAY( itemStore->varData, itemStore->dataCount ) ) goto Exit; for ( i = 0; i < itemStore->dataCount; i++ ) { varData = &itemStore->varData[i]; if ( FT_STREAM_SEEK( offset + dataOffsetArray[i] ) ) goto Exit; if ( FT_READ_USHORT( varData->itemCount ) || FT_READ_USHORT( wordDeltaCount ) || FT_READ_USHORT( varData->regionIdxCount ) ) goto Exit; long_words = !!( wordDeltaCount & 0x8000 ); wordDeltaCount &= 0x7FFF; /* check some data consistency */ if ( wordDeltaCount > varData->regionIdxCount ) { FT_TRACE2(( "bad short count %d or region count %d\n", wordDeltaCount, varData->regionIdxCount )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( varData->regionIdxCount > itemStore->regionCount ) { FT_TRACE2(( "inconsistent regionCount %d in varData[%d]\n", varData->regionIdxCount, i )); error = FT_THROW( Invalid_Table ); goto Exit; } /* parse region indices */ if ( FT_NEW_ARRAY( varData->regionIndices, varData->regionIdxCount ) ) goto Exit; for ( j = 0; j < varData->regionIdxCount; j++ ) { if ( FT_READ_USHORT( varData->regionIndices[j] ) ) goto Exit; if ( varData->regionIndices[j] >= itemStore->regionCount ) { FT_TRACE2(( "bad region index %d\n", varData->regionIndices[j] )); error = FT_THROW( Invalid_Table ); goto Exit; } } /* Parse delta set. */ /* */ /* On input, deltas are (wordDeltaCount + regionIdxCount) bytes */ /* each if `long_words` isn't set, and twice as much otherwise. */ /* */ /* On output, deltas are expanded to `regionIdxCount` shorts each. */ if ( FT_NEW_ARRAY( varData->deltaSet, varData->regionIdxCount * varData->itemCount ) ) goto Exit; /* the delta set is stored as a 2-dimensional array of shorts */ if ( long_words ) { /* new in OpenType 1.9, currently for 'COLR' table only; */ /* the deltas are interpreted as 16.16 fixed-point scaling values */ /* not supported yet */ error = FT_THROW( Invalid_Table ); goto Exit; } else { for ( j = 0; j < varData->itemCount * varData->regionIdxCount; ) { for ( k = 0; k < wordDeltaCount; k++, j++ ) { /* read the short deltas */ FT_Short delta; if ( FT_READ_SHORT( delta ) ) goto Exit; varData->deltaSet[j] = delta; } for ( ; k < varData->regionIdxCount; k++, j++ ) { /* read the (signed) byte deltas */ FT_Char delta; if ( FT_READ_CHAR( delta ) ) goto Exit; varData->deltaSet[j] = delta; } } } } Exit: FT_FREE( dataOffsetArray ); return error; } static FT_Error ft_var_load_delta_set_index_mapping( TT_Face face, FT_ULong offset, GX_DeltaSetIdxMap map, GX_ItemVarStore itemStore, FT_ULong table_len ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; FT_Error error; FT_Byte format; FT_Byte entryFormat; FT_UInt entrySize; FT_UInt innerBitCount; FT_UInt innerIndexMask; FT_ULong i; FT_UInt j; if ( FT_STREAM_SEEK( offset ) || FT_READ_BYTE( format ) || FT_READ_BYTE( entryFormat ) ) goto Exit; if ( format == 0 ) { if ( FT_READ_USHORT( map->mapCount ) ) goto Exit; } else if ( format == 1 ) /* new in OpenType 1.9 */ { if ( FT_READ_ULONG( map->mapCount ) ) goto Exit; } else { FT_TRACE2(( "bad map format %d\n", format )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( entryFormat & 0xC0 ) { FT_TRACE2(( "bad entry format %d\n", format )); error = FT_THROW( Invalid_Table ); goto Exit; } /* bytes per entry: 1, 2, 3, or 4 */ entrySize = ( ( entryFormat & 0x30 ) >> 4 ) + 1; innerBitCount = ( entryFormat & 0x0F ) + 1; innerIndexMask = ( 1 << innerBitCount ) - 1; /* rough sanity check */ if ( map->mapCount * entrySize > table_len ) { FT_TRACE1(( "ft_var_load_delta_set_index_mapping:" " invalid number of delta-set index mappings\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( FT_NEW_ARRAY( map->innerIndex, map->mapCount ) ) goto Exit; if ( FT_NEW_ARRAY( map->outerIndex, map->mapCount ) ) goto Exit; for ( i = 0; i < map->mapCount; i++ ) { FT_UInt mapData = 0; FT_UInt outerIndex, innerIndex; /* read map data one unsigned byte at a time, big endian */ for ( j = 0; j < entrySize; j++ ) { FT_Byte data; if ( FT_READ_BYTE( data ) ) goto Exit; mapData = ( mapData << 8 ) | data; } outerIndex = mapData >> innerBitCount; if ( outerIndex >= itemStore->dataCount ) { FT_TRACE2(( "outerIndex[%ld] == %d out of range\n", i, outerIndex )); error = FT_THROW( Invalid_Table ); goto Exit; } map->outerIndex[i] = outerIndex; innerIndex = mapData & innerIndexMask; if ( innerIndex >= itemStore->varData[outerIndex].itemCount ) { FT_TRACE2(( "innerIndex[%ld] == %d out of range\n", i, innerIndex )); error = FT_THROW( Invalid_Table ); goto Exit; } map->innerIndex[i] = innerIndex; } Exit: return error; } /************************************************************************** * * @Function: * ft_var_load_hvvar * * @Description: * If `vertical' is zero, parse the `HVAR' table and set * `blend->hvar_loaded' to TRUE. On success, `blend->hvar_checked' * is set to TRUE. * * If `vertical' is not zero, parse the `VVAR' table and set * `blend->vvar_loaded' to TRUE. On success, `blend->vvar_checked' * is set to TRUE. * * Some memory may remain allocated on error; it is always freed in * `tt_done_blend', however. * * @InOut: * face :: * The font face. * * @Return: * FreeType error code. 0 means success. */ static FT_Error ft_var_load_hvvar( TT_Face face, FT_Bool vertical ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; GX_Blend blend = face->blend; GX_HVVarTable table; FT_Error error; FT_UShort majorVersion; FT_ULong table_len; FT_ULong table_offset; FT_ULong store_offset; FT_ULong widthMap_offset; if ( vertical ) { blend->vvar_loaded = TRUE; FT_TRACE2(( "VVAR " )); error = face->goto_table( face, TTAG_VVAR, stream, &table_len ); } else { blend->hvar_loaded = TRUE; FT_TRACE2(( "HVAR " )); error = face->goto_table( face, TTAG_HVAR, stream, &table_len ); } if ( error ) { FT_TRACE2(( "is missing\n" )); goto Exit; } table_offset = FT_STREAM_POS(); /* skip minor version */ if ( FT_READ_USHORT( majorVersion ) || FT_STREAM_SKIP( 2 ) ) goto Exit; if ( majorVersion != 1 ) { FT_TRACE2(( "bad table version %d\n", majorVersion )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( FT_READ_ULONG( store_offset ) || FT_READ_ULONG( widthMap_offset ) ) goto Exit; if ( vertical ) { if ( FT_NEW( blend->vvar_table ) ) goto Exit; table = blend->vvar_table; } else { if ( FT_NEW( blend->hvar_table ) ) goto Exit; table = blend->hvar_table; } error = ft_var_load_item_variation_store( face, table_offset + store_offset, &table->itemStore ); if ( error ) goto Exit; if ( widthMap_offset ) { error = ft_var_load_delta_set_index_mapping( face, table_offset + widthMap_offset, &table->widthMap, &table->itemStore, table_len ); if ( error ) goto Exit; } FT_TRACE2(( "loaded\n" )); error = FT_Err_Ok; Exit: if ( !error ) { if ( vertical ) { blend->vvar_checked = TRUE; /* FreeType doesn't provide functions to quickly retrieve */ /* TSB, BSB, or VORG values; we thus don't have to implement */ /* support for those three item variation stores. */ face->variation_support |= TT_FACE_FLAG_VAR_VADVANCE; } else { blend->hvar_checked = TRUE; /* FreeType doesn't provide functions to quickly retrieve */ /* LSB or RSB values; we thus don't have to implement */ /* support for those two item variation stores. */ face->variation_support |= TT_FACE_FLAG_VAR_HADVANCE; } } return error; } static FT_Int ft_var_get_item_delta( TT_Face face, GX_ItemVarStore itemStore, FT_UInt outerIndex, FT_UInt innerIndex ) { GX_ItemVarData varData; FT_Short* deltaSet; FT_UInt master, j; FT_Fixed netAdjustment = 0; /* accumulated adjustment */ FT_Fixed scaledDelta; FT_Fixed delta; /* See pseudo code from `Font Variations Overview' */ /* in the OpenType specification. */ varData = &itemStore->varData[outerIndex]; deltaSet = &varData->deltaSet[varData->regionIdxCount * innerIndex]; /* outer loop steps through master designs to be blended */ for ( master = 0; master < varData->regionIdxCount; master++ ) { FT_Fixed scalar = 0x10000L; FT_UInt regionIndex = varData->regionIndices[master]; GX_AxisCoords axis = itemStore->varRegionList[regionIndex].axisList; /* inner loop steps through axes in this region */ for ( j = 0; j < itemStore->axisCount; j++, axis++ ) { /* compute the scalar contribution of this axis; */ /* ignore invalid ranges */ if ( axis->startCoord > axis->peakCoord || axis->peakCoord > axis->endCoord ) continue; else if ( axis->startCoord < 0 && axis->endCoord > 0 && axis->peakCoord != 0 ) continue; /* peak of 0 means ignore this axis */ else if ( axis->peakCoord == 0 ) continue; else if ( face->blend->normalizedcoords[j] == axis->peakCoord ) continue; /* ignore this region if coords are out of range */ else if ( face->blend->normalizedcoords[j] <= axis->startCoord || face->blend->normalizedcoords[j] >= axis->endCoord ) { scalar = 0; break; } /* cumulative product of all the axis scalars */ else if ( face->blend->normalizedcoords[j] < axis->peakCoord ) scalar = FT_MulDiv( scalar, face->blend->normalizedcoords[j] - axis->startCoord, axis->peakCoord - axis->startCoord ); else scalar = FT_MulDiv( scalar, axis->endCoord - face->blend->normalizedcoords[j], axis->endCoord - axis->peakCoord ); } /* per-axis loop */ /* get the scaled delta for this region */ delta = FT_intToFixed( deltaSet[master] ); scaledDelta = FT_MulFix( scalar, delta ); /* accumulate the adjustments from each region */ netAdjustment = netAdjustment + scaledDelta; } /* per-region loop */ return FT_fixedToInt( netAdjustment ); } /************************************************************************** * * @Function: * tt_hvadvance_adjust * * @Description: * Apply `HVAR' advance width or `VVAR' advance height adjustment of * a given glyph. * * @Input: * gindex :: * The glyph index. * * vertical :: * If set, handle `VVAR' table. * * @InOut: * face :: * The font face. * * adelta :: * Points to width or height value that gets modified. */ static FT_Error tt_hvadvance_adjust( TT_Face face, FT_UInt gindex, FT_Int *avalue, FT_Bool vertical ) { FT_Error error = FT_Err_Ok; FT_UInt innerIndex, outerIndex; FT_Int delta; GX_HVVarTable table; if ( !face->doblend || !face->blend ) goto Exit; if ( vertical ) { if ( !face->blend->vvar_loaded ) { /* initialize vvar table */ face->blend->vvar_error = ft_var_load_hvvar( face, 1 ); } if ( !face->blend->vvar_checked ) { error = face->blend->vvar_error; goto Exit; } table = face->blend->vvar_table; } else { if ( !face->blend->hvar_loaded ) { /* initialize hvar table */ face->blend->hvar_error = ft_var_load_hvvar( face, 0 ); } if ( !face->blend->hvar_checked ) { error = face->blend->hvar_error; goto Exit; } table = face->blend->hvar_table; } /* advance width or height adjustments are always present in an */ /* `HVAR' or `VVAR' table; no need to test for this capability */ if ( table->widthMap.innerIndex ) { FT_UInt idx = gindex; if ( idx >= table->widthMap.mapCount ) idx = table->widthMap.mapCount - 1; /* trust that HVAR parser has checked indices */ outerIndex = table->widthMap.outerIndex[idx]; innerIndex = table->widthMap.innerIndex[idx]; } else { GX_ItemVarData varData; /* no widthMap data */ outerIndex = 0; innerIndex = gindex; varData = &table->itemStore.varData[outerIndex]; if ( gindex >= varData->itemCount ) { FT_TRACE2(( "gindex %d out of range\n", gindex )); error = FT_THROW( Invalid_Argument ); goto Exit; } } delta = ft_var_get_item_delta( face, &table->itemStore, outerIndex, innerIndex ); FT_TRACE5(( "%s value %d adjusted by %d unit%s (%s)\n", vertical ? "vertical height" : "horizontal width", *avalue, delta, delta == 1 ? "" : "s", vertical ? "VVAR" : "HVAR" )); *avalue += delta; Exit: return error; } FT_LOCAL_DEF( FT_Error ) tt_hadvance_adjust( TT_Face face, FT_UInt gindex, FT_Int *avalue ) { return tt_hvadvance_adjust( face, gindex, avalue, 0 ); } FT_LOCAL_DEF( FT_Error ) tt_vadvance_adjust( TT_Face face, FT_UInt gindex, FT_Int *avalue ) { return tt_hvadvance_adjust( face, gindex, avalue, 1 ); } #define GX_VALUE_SIZE 8 /* all values are FT_Short or FT_UShort entities; */ /* we treat them consistently as FT_Short */ #define GX_VALUE_CASE( tag, dflt ) \ case MVAR_TAG_ ## tag : \ p = (FT_Short*)&face->dflt; \ break #define GX_GASP_CASE( idx ) \ case MVAR_TAG_GASP_ ## idx : \ if ( idx < face->gasp.numRanges - 1 ) \ p = (FT_Short*)&face->gasp.gaspRanges[idx].maxPPEM; \ else \ p = NULL; \ break static FT_Short* ft_var_get_value_pointer( TT_Face face, FT_ULong mvar_tag ) { FT_Short* p; switch ( mvar_tag ) { GX_GASP_CASE( 0 ); GX_GASP_CASE( 1 ); GX_GASP_CASE( 2 ); GX_GASP_CASE( 3 ); GX_GASP_CASE( 4 ); GX_GASP_CASE( 5 ); GX_GASP_CASE( 6 ); GX_GASP_CASE( 7 ); GX_GASP_CASE( 8 ); GX_GASP_CASE( 9 ); GX_VALUE_CASE( CPHT, os2.sCapHeight ); GX_VALUE_CASE( HASC, os2.sTypoAscender ); GX_VALUE_CASE( HCLA, os2.usWinAscent ); GX_VALUE_CASE( HCLD, os2.usWinDescent ); GX_VALUE_CASE( HCOF, horizontal.caret_Offset ); GX_VALUE_CASE( HCRN, horizontal.caret_Slope_Run ); GX_VALUE_CASE( HCRS, horizontal.caret_Slope_Rise ); GX_VALUE_CASE( HDSC, os2.sTypoDescender ); GX_VALUE_CASE( HLGP, os2.sTypoLineGap ); GX_VALUE_CASE( SBXO, os2.ySubscriptXOffset); GX_VALUE_CASE( SBXS, os2.ySubscriptXSize ); GX_VALUE_CASE( SBYO, os2.ySubscriptYOffset ); GX_VALUE_CASE( SBYS, os2.ySubscriptYSize ); GX_VALUE_CASE( SPXO, os2.ySuperscriptXOffset ); GX_VALUE_CASE( SPXS, os2.ySuperscriptXSize ); GX_VALUE_CASE( SPYO, os2.ySuperscriptYOffset ); GX_VALUE_CASE( SPYS, os2.ySuperscriptYSize ); GX_VALUE_CASE( STRO, os2.yStrikeoutPosition ); GX_VALUE_CASE( STRS, os2.yStrikeoutSize ); GX_VALUE_CASE( UNDO, postscript.underlinePosition ); GX_VALUE_CASE( UNDS, postscript.underlineThickness ); GX_VALUE_CASE( VASC, vertical.Ascender ); GX_VALUE_CASE( VCOF, vertical.caret_Offset ); GX_VALUE_CASE( VCRN, vertical.caret_Slope_Run ); GX_VALUE_CASE( VCRS, vertical.caret_Slope_Rise ); GX_VALUE_CASE( VDSC, vertical.Descender ); GX_VALUE_CASE( VLGP, vertical.Line_Gap ); GX_VALUE_CASE( XHGT, os2.sxHeight ); default: /* ignore unknown tag */ p = NULL; } return p; } /************************************************************************** * * @Function: * ft_var_load_mvar * * @Description: * Parse the `MVAR' table. * * Some memory may remain allocated on error; it is always freed in * `tt_done_blend', however. * * @InOut: * face :: * The font face. */ static void ft_var_load_mvar( TT_Face face ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; GX_Blend blend = face->blend; GX_ItemVarStore itemStore; GX_Value value, limit; FT_Error error; FT_UShort majorVersion; FT_ULong table_len; FT_ULong table_offset; FT_UShort store_offset; FT_ULong records_offset; FT_TRACE2(( "MVAR " )); error = face->goto_table( face, TTAG_MVAR, stream, &table_len ); if ( error ) { FT_TRACE2(( "is missing\n" )); return; } table_offset = FT_STREAM_POS(); /* skip minor version */ if ( FT_READ_USHORT( majorVersion ) || FT_STREAM_SKIP( 2 ) ) return; if ( majorVersion != 1 ) { FT_TRACE2(( "bad table version %d\n", majorVersion )); return; } if ( FT_NEW( blend->mvar_table ) ) return; /* skip reserved entry and value record size */ if ( FT_STREAM_SKIP( 4 ) || FT_READ_USHORT( blend->mvar_table->valueCount ) || FT_READ_USHORT( store_offset ) ) return; records_offset = FT_STREAM_POS(); error = ft_var_load_item_variation_store( face, table_offset + store_offset, &blend->mvar_table->itemStore ); if ( error ) return; if ( FT_NEW_ARRAY( blend->mvar_table->values, blend->mvar_table->valueCount ) ) return; if ( FT_STREAM_SEEK( records_offset ) || FT_FRAME_ENTER( blend->mvar_table->valueCount * GX_VALUE_SIZE ) ) return; value = blend->mvar_table->values; limit = value + blend->mvar_table->valueCount; itemStore = &blend->mvar_table->itemStore; for ( ; value < limit; value++ ) { value->tag = FT_GET_ULONG(); value->outerIndex = FT_GET_USHORT(); value->innerIndex = FT_GET_USHORT(); if ( value->outerIndex >= itemStore->dataCount || value->innerIndex >= itemStore->varData[value->outerIndex] .itemCount ) { error = FT_THROW( Invalid_Table ); break; } } FT_FRAME_EXIT(); if ( error ) return; FT_TRACE2(( "loaded\n" )); value = blend->mvar_table->values; limit = value + blend->mvar_table->valueCount; /* save original values of the data MVAR is going to modify */ for ( ; value < limit; value++ ) { FT_Short* p = ft_var_get_value_pointer( face, value->tag ); if ( p ) value->unmodified = *p; #ifdef FT_DEBUG_LEVEL_TRACE else FT_TRACE1(( "ft_var_load_mvar: Ignoring unknown tag `%c%c%c%c'\n", (FT_Char)( value->tag >> 24 ), (FT_Char)( value->tag >> 16 ), (FT_Char)( value->tag >> 8 ), (FT_Char)( value->tag ) )); #endif } face->variation_support |= TT_FACE_FLAG_VAR_MVAR; } static FT_Error tt_size_reset_iterator( FT_ListNode node, void* user ) { TT_Size size = (TT_Size)node->data; FT_UNUSED( user ); tt_size_reset( size, 1 ); return FT_Err_Ok; } /************************************************************************** * * @Function: * tt_apply_mvar * * @Description: * Apply `MVAR' table adjustments. * * @InOut: * face :: * The font face. */ FT_LOCAL_DEF( void ) tt_apply_mvar( TT_Face face ) { GX_Blend blend = face->blend; GX_Value value, limit; FT_Short mvar_hasc_delta = 0; FT_Short mvar_hdsc_delta = 0; FT_Short mvar_hlgp_delta = 0; if ( !( face->variation_support & TT_FACE_FLAG_VAR_MVAR ) ) return; value = blend->mvar_table->values; limit = value + blend->mvar_table->valueCount; for ( ; value < limit; value++ ) { FT_Short* p = ft_var_get_value_pointer( face, value->tag ); FT_Int delta; delta = ft_var_get_item_delta( face, &blend->mvar_table->itemStore, value->outerIndex, value->innerIndex ); if ( p ) { FT_TRACE5(( "value %c%c%c%c (%d unit%s) adjusted by %d unit%s (MVAR)\n", (FT_Char)( value->tag >> 24 ), (FT_Char)( value->tag >> 16 ), (FT_Char)( value->tag >> 8 ), (FT_Char)( value->tag ), value->unmodified, value->unmodified == 1 ? "" : "s", delta, delta == 1 ? "" : "s" )); /* since we handle both signed and unsigned values as FT_Short, */ /* ensure proper overflow arithmetic */ *p = (FT_Short)( value->unmodified + (FT_Short)delta ); /* Treat hasc, hdsc and hlgp specially, see below. */ if ( value->tag == MVAR_TAG_HASC ) mvar_hasc_delta = (FT_Short)delta; else if ( value->tag == MVAR_TAG_HDSC ) mvar_hdsc_delta = (FT_Short)delta; else if ( value->tag == MVAR_TAG_HLGP ) mvar_hlgp_delta = (FT_Short)delta; } } /* adjust all derived values */ { FT_Face root = &face->root; /* * Apply the deltas of hasc, hdsc and hlgp to the FT_Face's ascender, * descender and height attributes, no matter how they were originally * computed. * * (Code that ignores those and accesses the font's metrics values * directly is already served by the delta application code above.) * * The MVAR table supports variations for both typo and win metrics. * According to Behdad Esfahbod, the thinking of the working group was * that no one uses win metrics anymore for setting line metrics (the * specification even calls these metrics "horizontal clipping * ascent/descent", probably for their role on the Windows platform in * computing clipping boxes), and new fonts should use typo metrics, so * typo deltas should be applied to whatever sfnt_load_face decided the * line metrics should be. * * Before, the following led to different line metrics between default * outline and instances, visible when e.g. the default outlines were * used as the regular face and instances for everything else: * * 1. sfnt_load_face applied the hhea metrics by default. * 2. This code later applied the typo metrics by default, regardless of * whether they were actually changed or the font had the OS/2 table's * fsSelection's bit 7 (USE_TYPO_METRICS) set. */ FT_Short current_line_gap = root->height - root->ascender + root->descender; root->ascender = root->ascender + mvar_hasc_delta; root->descender = root->descender + mvar_hdsc_delta; root->height = root->ascender - root->descender + current_line_gap + mvar_hlgp_delta; root->underline_position = face->postscript.underlinePosition - face->postscript.underlineThickness / 2; root->underline_thickness = face->postscript.underlineThickness; /* iterate over all FT_Size objects and call `tt_size_reset' */ /* to propagate the metrics changes */ FT_List_Iterate( &root->sizes_list, tt_size_reset_iterator, NULL ); } } typedef struct GX_GVar_Head_ { FT_Long version; FT_UShort axisCount; FT_UShort globalCoordCount; FT_ULong offsetToCoord; FT_UShort glyphCount; FT_UShort flags; FT_ULong offsetToData; } GX_GVar_Head; /************************************************************************** * * @Function: * ft_var_load_gvar * * @Description: * Parse the `gvar' table if present. If `fvar' is there, `gvar' had * better be there too. * * @InOut: * face :: * The font face. * * @Return: * FreeType error code. 0 means success. */ static FT_Error ft_var_load_gvar( TT_Face face ) { FT_Stream stream = FT_FACE_STREAM( face ); FT_Memory memory = stream->memory; GX_Blend blend = face->blend; FT_Error error; FT_UInt i, j; FT_ULong table_len; FT_ULong gvar_start; FT_ULong offsetToData; FT_ULong offsets_len; GX_GVar_Head gvar_head; static const FT_Frame_Field gvar_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE GX_GVar_Head FT_FRAME_START( 20 ), FT_FRAME_LONG ( version ), FT_FRAME_USHORT( axisCount ), FT_FRAME_USHORT( globalCoordCount ), FT_FRAME_ULONG ( offsetToCoord ), FT_FRAME_USHORT( glyphCount ), FT_FRAME_USHORT( flags ), FT_FRAME_ULONG ( offsetToData ), FT_FRAME_END }; FT_TRACE2(( "GVAR " )); if ( FT_SET_ERROR( face->goto_table( face, TTAG_gvar, stream, &table_len ) ) ) { FT_TRACE2(( "is missing\n" )); goto Exit; } gvar_start = FT_STREAM_POS( ); if ( FT_STREAM_READ_FIELDS( gvar_fields, &gvar_head ) ) goto Exit; if ( gvar_head.version != 0x00010000L ) { FT_TRACE1(( "bad table version\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } if ( gvar_head.axisCount != (FT_UShort)blend->mmvar->num_axis ) { FT_TRACE1(( "ft_var_load_gvar:" " number of axes in `gvar' and `cvar'\n" )); FT_TRACE1(( " table are different\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } /* rough sanity check, ignoring offsets */ if ( (FT_ULong)gvar_head.globalCoordCount * gvar_head.axisCount > table_len / 2 ) { FT_TRACE1(( "ft_var_load_gvar:" " invalid number of global coordinates\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } /* offsets can be either 2 or 4 bytes */ /* (one more offset than glyphs, to mark size of last) */ offsets_len = ( gvar_head.glyphCount + 1 ) * ( ( gvar_head.flags & 1 ) ? 4L : 2L ); /* rough sanity check */ if (offsets_len > table_len ) { FT_TRACE1(( "ft_var_load_gvar: invalid number of glyphs\n" )); error = FT_THROW( Invalid_Table ); goto Exit; } FT_TRACE2(( "loaded\n" )); blend->gvar_size = table_len; offsetToData = gvar_start + gvar_head.offsetToData; FT_TRACE5(( "gvar: there %s %d shared coordinate%s:\n", gvar_head.globalCoordCount == 1 ? "is" : "are", gvar_head.globalCoordCount, gvar_head.globalCoordCount == 1 ? "" : "s" )); if ( FT_FRAME_ENTER( offsets_len ) ) goto Exit; /* offsets (one more offset than glyphs, to mark size of last) */ if ( FT_QNEW_ARRAY( blend->glyphoffsets, gvar_head.glyphCount + 1 ) ) goto Fail2; if ( gvar_head.flags & 1 ) { FT_ULong limit = gvar_start + table_len; FT_ULong max_offset = 0; for ( i = 0; i <= gvar_head.glyphCount; i++ ) { blend->glyphoffsets[i] = offsetToData + FT_GET_ULONG(); if ( max_offset <= blend->glyphoffsets[i] ) max_offset = blend->glyphoffsets[i]; else { FT_TRACE2(( "ft_var_load_gvar:" " glyph variation data offset %d not monotonic\n", i )); blend->glyphoffsets[i] = max_offset; } /* use `<', not `<=' */ if ( limit < blend->glyphoffsets[i] ) { FT_TRACE2(( "ft_var_load_gvar:" " glyph variation data offset %d out of range\n", i )); blend->glyphoffsets[i] = limit; } } } else { FT_ULong limit = gvar_start + table_len; FT_ULong max_offset = 0; for ( i = 0; i <= gvar_head.glyphCount; i++ ) { blend->glyphoffsets[i] = offsetToData + FT_GET_USHORT() * 2; if ( max_offset <= blend->glyphoffsets[i] ) max_offset = blend->glyphoffsets[i]; else { FT_TRACE2(( "ft_var_load_gvar:" " glyph variation data offset %d not monotonic\n", i )); blend->glyphoffsets[i] = max_offset; } /* use `<', not `<=' */ if ( limit < blend->glyphoffsets[i] ) { FT_TRACE2(( "ft_var_load_gvar:" " glyph variation data offset %d out of range\n", i )); blend->glyphoffsets[i] = limit; } } } blend->gv_glyphcnt = gvar_head.glyphCount; FT_FRAME_EXIT(); if ( gvar_head.globalCoordCount != 0 ) { if ( FT_STREAM_SEEK( gvar_start + gvar_head.offsetToCoord ) || FT_FRAME_ENTER( gvar_head.globalCoordCount * gvar_head.axisCount * 2L ) ) { FT_TRACE2(( "ft_var_load_gvar:" " glyph variation shared tuples missing\n" )); goto Fail; } if ( FT_QNEW_ARRAY( blend->tuplecoords, gvar_head.axisCount * gvar_head.globalCoordCount ) ) goto Fail2; for ( i = 0; i < gvar_head.globalCoordCount; i++ ) { FT_TRACE5(( " [ " )); for ( j = 0; j < (FT_UInt)gvar_head.axisCount; j++ ) { blend->tuplecoords[i * gvar_head.axisCount + j] = FT_fdot14ToFixed( FT_GET_SHORT() ); FT_TRACE5(( "%.5f ", blend->tuplecoords[i * gvar_head.axisCount + j] / 65536.0 )); } FT_TRACE5(( "]\n" )); } blend->tuplecount = gvar_head.globalCoordCount; FT_TRACE5(( "\n" )); FT_FRAME_EXIT(); } Exit: return error; Fail2: FT_FRAME_EXIT(); Fail: FT_FREE( blend->glyphoffsets ); blend->gv_glyphcnt = 0; goto Exit; } /************************************************************************** * * @Function: * ft_var_apply_tuple * * @Description: * Figure out whether a given tuple (design) applies to the current * blend, and if so, what is the scaling factor. * * @Input: * blend :: * The current blend of the font. * * tupleIndex :: * A flag saying whether this is an intermediate * tuple or not. * * tuple_coords :: * The coordinates of the tuple in normalized axis * units. * * im_start_coords :: * The initial coordinates where this tuple starts * to apply (for intermediate coordinates). * * im_end_coords :: * The final coordinates after which this tuple no * longer applies (for intermediate coordinates). * * @Return: * An FT_Fixed value containing the scaling factor. */ static FT_Fixed ft_var_apply_tuple( GX_Blend blend, FT_UShort tupleIndex, FT_Fixed* tuple_coords, FT_Fixed* im_start_coords, FT_Fixed* im_end_coords ) { FT_UInt i; FT_Fixed apply = 0x10000L; for ( i = 0; i < blend->num_axis; i++ ) { FT_TRACE6(( " axis %d coordinate %.5f:\n", i, blend->normalizedcoords[i] / 65536.0 )); /* It's not clear why (for intermediate tuples) we don't need */ /* to check against start/end -- the documentation says we don't. */ /* Similarly, it's unclear why we don't need to scale along the */ /* axis. */ if ( tuple_coords[i] == 0 ) { FT_TRACE6(( " tuple coordinate is zero, ignore\n" )); continue; } if ( blend->normalizedcoords[i] == 0 ) { FT_TRACE6(( " axis coordinate is zero, stop\n" )); apply = 0; break; } if ( blend->normalizedcoords[i] == tuple_coords[i] ) { FT_TRACE6(( " tuple coordinate %.5f fits perfectly\n", tuple_coords[i] / 65536.0 )); /* `apply' does not change */ continue; } if ( !( tupleIndex & GX_TI_INTERMEDIATE_TUPLE ) ) { /* not an intermediate tuple */ if ( blend->normalizedcoords[i] < FT_MIN( 0, tuple_coords[i] ) || blend->normalizedcoords[i] > FT_MAX( 0, tuple_coords[i] ) ) { FT_TRACE6(( " tuple coordinate %.5f is exceeded, stop\n", tuple_coords[i] / 65536.0 )); apply = 0; break; } FT_TRACE6(( " tuple coordinate %.5f fits\n", tuple_coords[i] / 65536.0 )); apply = FT_MulDiv( apply, blend->normalizedcoords[i], tuple_coords[i] ); } else { /* intermediate tuple */ if ( blend->normalizedcoords[i] <= im_start_coords[i] || blend->normalizedcoords[i] >= im_end_coords[i] ) { FT_TRACE6(( " intermediate tuple range ]%.5f;%.5f[ is exceeded," " stop\n", im_start_coords[i] / 65536.0, im_end_coords[i] / 65536.0 )); apply = 0; break; } FT_TRACE6(( " intermediate tuple range ]%.5f;%.5f[ fits\n", im_start_coords[i] / 65536.0, im_end_coords[i] / 65536.0 )); if ( blend->normalizedcoords[i] < tuple_coords[i] ) apply = FT_MulDiv( apply, blend->normalizedcoords[i] - im_start_coords[i], tuple_coords[i] - im_start_coords[i] ); else apply = FT_MulDiv( apply, im_end_coords[i] - blend->normalizedcoords[i], im_end_coords[i] - tuple_coords[i] ); } } FT_TRACE6(( " apply factor is %.5f\n", apply / 65536.0 )); return apply; } /* convert from design coordinates to normalized coordinates */ static void ft_var_to_normalized( TT_Face face, FT_UInt num_coords, FT_Fixed* coords, FT_Fixed* normalized ) { GX_Blend blend; FT_MM_Var* mmvar; FT_UInt i, j; FT_Var_Axis* a; GX_AVarSegment av; blend = face->blend; mmvar = blend->mmvar; if ( num_coords > mmvar->num_axis ) { FT_TRACE2(( "ft_var_to_normalized:" " only using first %d of %d coordinates\n", mmvar->num_axis, num_coords )); num_coords = mmvar->num_axis; } /* Axis normalization is a two-stage process. First we normalize */ /* based on the [min,def,max] values for the axis to be [-1,0,1]. */ /* Then, if there's an `avar' table, we renormalize this range. */ a = mmvar->axis; for ( i = 0; i < num_coords; i++, a++ ) { FT_Fixed coord = coords[i]; FT_TRACE5(( " %d: %.5f\n", i, coord / 65536.0 )); if ( coord > a->maximum || coord < a->minimum ) { FT_TRACE1(( "ft_var_to_normalized: design coordinate %.5f\n", coord / 65536.0 )); FT_TRACE1(( " is out of range [%.5f;%.5f];" " clamping\n", a->minimum / 65536.0, a->maximum / 65536.0 )); } if ( coord > a->def ) normalized[i] = coord >= a->maximum ? 0x10000L : FT_DivFix( SUB_LONG( coord, a->def ), SUB_LONG( a->maximum, a->def ) ); else if ( coord < a->def ) normalized[i] = coord <= a->minimum ? -0x10000L : FT_DivFix( SUB_LONG( coord, a->def ), SUB_LONG( a->def, a->minimum ) ); else normalized[i] = 0; } FT_TRACE5(( "\n" )); for ( ; i < mmvar->num_axis; i++ ) normalized[i] = 0; if ( blend->avar_segment ) { FT_TRACE5(( "normalized design coordinates" " before applying `avar' data:\n" )); av = blend->avar_segment; for ( i = 0; i < mmvar->num_axis; i++, av++ ) { for ( j = 1; j < (FT_UInt)av->pairCount; j++ ) { if ( normalized[i] < av->correspondence[j].fromCoord ) { FT_TRACE5(( " %.5f\n", normalized[i] / 65536.0 )); normalized[i] = FT_MulDiv( normalized[i] - av->correspondence[j - 1].fromCoord, av->correspondence[j].toCoord - av->correspondence[j - 1].toCoord, av->correspondence[j].fromCoord - av->correspondence[j - 1].fromCoord ) + av->correspondence[j - 1].toCoord; break; } } } } } /* convert from normalized coordinates to design coordinates */ static void ft_var_to_design( TT_Face face, FT_UInt num_coords, FT_Fixed* coords, FT_Fixed* design ) { GX_Blend blend; FT_MM_Var* mmvar; FT_Var_Axis* a; FT_UInt i, j, nc; blend = face->blend; nc = num_coords; if ( num_coords > blend->num_axis ) { FT_TRACE2(( "ft_var_to_design:" " only using first %d of %d coordinates\n", blend->num_axis, num_coords )); nc = blend->num_axis; } for ( i = 0; i < nc; i++ ) design[i] = coords[i]; for ( ; i < num_coords; i++ ) design[i] = 0; if ( blend->avar_segment ) { GX_AVarSegment av = blend->avar_segment; FT_TRACE5(( "design coordinates" " after removing `avar' distortion:\n" )); for ( i = 0; i < nc; i++, av++ ) { for ( j = 1; j < (FT_UInt)av->pairCount; j++ ) { if ( design[i] < av->correspondence[j].toCoord ) { design[i] = FT_MulDiv( design[i] - av->correspondence[j - 1].toCoord, av->correspondence[j].fromCoord - av->correspondence[j - 1].fromCoord, av->correspondence[j].toCoord - av->correspondence[j - 1].toCoord ) + av->correspondence[j - 1].fromCoord; FT_TRACE5(( " %.5f\n", design[i] / 65536.0 )); break; } } } } mmvar = blend->mmvar; a = mmvar->axis; for ( i = 0; i < nc; i++, a++ ) { if ( design[i] < 0 ) design[i] = a->def + FT_MulFix( design[i], a->def - a->minimum ); else if ( design[i] > 0 ) design[i] = a->def + FT_MulFix( design[i], a->maximum - a->def ); else design[i] = a->def; } } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** MULTIPLE MASTERS SERVICE FUNCTIONS *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ typedef struct GX_FVar_Head_ { FT_Long version; FT_UShort offsetToData; FT_UShort axisCount; FT_UShort axisSize; FT_UShort instanceCount; FT_UShort instanceSize; } GX_FVar_Head; typedef struct fvar_axis_ { FT_ULong axisTag; FT_Fixed minValue; FT_Fixed defaultValue; FT_Fixed maxValue; FT_UShort flags; FT_UShort nameID; } GX_FVar_Axis; /************************************************************************** * * @Function: * TT_Get_MM_Var * * @Description: * Check that the font's `fvar' table is valid, parse it, and return * those data. It also loads (and parses) the `MVAR' table, if * possible. * * @InOut: * face :: * The font face. * TT_Get_MM_Var initializes the blend structure. * * @Output: * master :: * The `fvar' data (must be freed by caller). Can be NULL, * which makes this function simply load MM support. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Get_MM_Var( TT_Face face, FT_MM_Var* *master ) { FT_Stream stream = face->root.stream; FT_Memory memory = face->root.memory; FT_ULong table_len; FT_Error error = FT_Err_Ok; FT_ULong fvar_start = 0; FT_UInt i, j; FT_MM_Var* mmvar = NULL; FT_Fixed* next_coords; FT_Fixed* nsc; FT_String* next_name; FT_Var_Axis* a; FT_Fixed* c; FT_Var_Named_Style* ns; GX_FVar_Head fvar_head = { 0, 0, 0, 0, 0, 0 }; FT_Bool usePsName = 0; FT_UInt num_instances; FT_UInt num_axes; FT_UShort* axis_flags; FT_Offset mmvar_size; FT_Offset axis_flags_size; FT_Offset axis_size; FT_Offset namedstyle_size; FT_Offset next_coords_size; FT_Offset next_name_size; FT_Bool need_init; static const FT_Frame_Field fvar_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE GX_FVar_Head FT_FRAME_START( 16 ), FT_FRAME_LONG ( version ), FT_FRAME_USHORT ( offsetToData ), FT_FRAME_SKIP_SHORT, FT_FRAME_USHORT ( axisCount ), FT_FRAME_USHORT ( axisSize ), FT_FRAME_USHORT ( instanceCount ), FT_FRAME_USHORT ( instanceSize ), FT_FRAME_END }; static const FT_Frame_Field fvaraxis_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE GX_FVar_Axis FT_FRAME_START( 20 ), FT_FRAME_ULONG ( axisTag ), FT_FRAME_LONG ( minValue ), FT_FRAME_LONG ( defaultValue ), FT_FRAME_LONG ( maxValue ), FT_FRAME_USHORT( flags ), FT_FRAME_USHORT( nameID ), FT_FRAME_END }; /* read the font data and set up the internal representation */ /* if not already done */ need_init = !face->blend; if ( need_init ) { FT_TRACE2(( "FVAR " )); /* both `fvar' and `gvar' must be present */ if ( FT_SET_ERROR( face->goto_table( face, TTAG_gvar, stream, &table_len ) ) ) { /* CFF2 is an alternate to gvar here */ if ( FT_SET_ERROR( face->goto_table( face, TTAG_CFF2, stream, &table_len ) ) ) { FT_TRACE1(( "\n" )); FT_TRACE1(( "TT_Get_MM_Var: `gvar' or `CFF2' table is missing\n" )); goto Exit; } } if ( FT_SET_ERROR( face->goto_table( face, TTAG_fvar, stream, &table_len ) ) ) { FT_TRACE1(( "is missing\n" )); goto Exit; } fvar_start = FT_STREAM_POS( ); /* the validity of the `fvar' header data was already checked */ /* in function `sfnt_init_face' */ if ( FT_STREAM_READ_FIELDS( fvar_fields, &fvar_head ) ) goto Exit; usePsName = FT_BOOL( fvar_head.instanceSize == 6 + 4 * fvar_head.axisCount ); FT_TRACE2(( "loaded\n" )); FT_TRACE5(( "%d variation ax%s\n", fvar_head.axisCount, fvar_head.axisCount == 1 ? "is" : "es" )); if ( FT_NEW( face->blend ) ) goto Exit; num_axes = fvar_head.axisCount; face->blend->num_axis = num_axes; } else num_axes = face->blend->num_axis; /* `num_instances' holds the number of all named instances, */ /* including the default instance which might be missing */ /* in fvar's table of named instances */ num_instances = (FT_UInt)face->root.style_flags >> 16; /* prepare storage area for MM data; this cannot overflow */ /* 32-bit arithmetic because of the size limits used in the */ /* `fvar' table validity check in `sfnt_init_face' */ /* the various `*_size' variables, which we also use as */ /* offsets into the `mmvar' array, must be multiples of the */ /* pointer size (except the last one); without such an */ /* alignment there might be runtime errors due to */ /* misaligned addresses */ #undef ALIGN_SIZE #define ALIGN_SIZE( n ) \ ( ( (n) + sizeof (void*) - 1 ) & ~( sizeof (void*) - 1 ) ) mmvar_size = ALIGN_SIZE( sizeof ( FT_MM_Var ) ); axis_flags_size = ALIGN_SIZE( num_axes * sizeof ( FT_UShort ) ); axis_size = ALIGN_SIZE( num_axes * sizeof ( FT_Var_Axis ) ); namedstyle_size = ALIGN_SIZE( num_instances * sizeof ( FT_Var_Named_Style ) ); next_coords_size = ALIGN_SIZE( num_instances * num_axes * sizeof ( FT_Fixed ) ); next_name_size = num_axes * 5; if ( need_init ) { face->blend->mmvar_len = mmvar_size + axis_flags_size + axis_size + namedstyle_size + next_coords_size + next_name_size; if ( FT_ALLOC( mmvar, face->blend->mmvar_len ) ) goto Exit; face->blend->mmvar = mmvar; /* set up pointers and offsets into the `mmvar' array; */ /* the data gets filled in later on */ mmvar->num_axis = num_axes; mmvar->num_designs = ~0U; /* meaningless in this context; each glyph */ /* may have a different number of designs */ /* (or tuples, as called by Apple) */ mmvar->num_namedstyles = num_instances; /* alas, no public field in `FT_Var_Axis' for axis flags */ axis_flags = (FT_UShort*)( (char*)mmvar + mmvar_size ); mmvar->axis = (FT_Var_Axis*)( (char*)axis_flags + axis_flags_size ); mmvar->namedstyle = (FT_Var_Named_Style*)( (char*)mmvar->axis + axis_size ); next_coords = (FT_Fixed*)( (char*)mmvar->namedstyle + namedstyle_size ); for ( i = 0; i < num_instances; i++ ) { mmvar->namedstyle[i].coords = next_coords; next_coords += num_axes; } next_name = (FT_String*)( (char*)mmvar->namedstyle + namedstyle_size + next_coords_size ); for ( i = 0; i < num_axes; i++ ) { mmvar->axis[i].name = next_name; next_name += 5; } /* now fill in the data */ if ( FT_STREAM_SEEK( fvar_start + fvar_head.offsetToData ) ) goto Exit; a = mmvar->axis; for ( i = 0; i < num_axes; i++ ) { GX_FVar_Axis axis_rec; #ifdef FT_DEBUG_LEVEL_TRACE int invalid = 0; #endif if ( FT_STREAM_READ_FIELDS( fvaraxis_fields, &axis_rec ) ) goto Exit; a->tag = axis_rec.axisTag; a->minimum = axis_rec.minValue; a->def = axis_rec.defaultValue; a->maximum = axis_rec.maxValue; a->strid = axis_rec.nameID; a->name[0] = (FT_String)( a->tag >> 24 ); a->name[1] = (FT_String)( ( a->tag >> 16 ) & 0xFF ); a->name[2] = (FT_String)( ( a->tag >> 8 ) & 0xFF ); a->name[3] = (FT_String)( ( a->tag ) & 0xFF ); a->name[4] = '\0'; *axis_flags = axis_rec.flags; if ( a->minimum > a->def || a->def > a->maximum ) { a->minimum = a->def; a->maximum = a->def; #ifdef FT_DEBUG_LEVEL_TRACE invalid = 1; #endif } #ifdef FT_DEBUG_LEVEL_TRACE if ( i == 0 ) FT_TRACE5(( " idx tag " /* " XXX `XXXX'" */ " minimum default maximum flags\n" )); /* " XXXX.XXXXX XXXX.XXXXX XXXX.XXXXX 0xXXXX" */ FT_TRACE5(( " %3d `%s'" " %10.5f %10.5f %10.5f 0x%04X%s\n", i, a->name, a->minimum / 65536.0, a->def / 65536.0, a->maximum / 65536.0, *axis_flags, invalid ? " (invalid, disabled)" : "" )); #endif a++; axis_flags++; } FT_TRACE5(( "\n" )); /* named instance coordinates are stored as design coordinates; */ /* we have to convert them to normalized coordinates also */ if ( FT_NEW_ARRAY( face->blend->normalized_stylecoords, num_axes * num_instances ) ) goto Exit; if ( fvar_head.instanceCount && !face->blend->avar_loaded ) { FT_ULong offset = FT_STREAM_POS(); ft_var_load_avar( face ); if ( FT_STREAM_SEEK( offset ) ) goto Exit; } FT_TRACE5(( "%d instance%s\n", fvar_head.instanceCount, fvar_head.instanceCount == 1 ? "" : "s" )); ns = mmvar->namedstyle; nsc = face->blend->normalized_stylecoords; for ( i = 0; i < fvar_head.instanceCount; i++, ns++ ) { /* PostScript names add 2 bytes to the instance record size */ if ( FT_FRAME_ENTER( ( usePsName ? 6L : 4L ) + 4L * num_axes ) ) goto Exit; ns->strid = FT_GET_USHORT(); (void) /* flags = */ FT_GET_USHORT(); c = ns->coords; for ( j = 0; j < num_axes; j++, c++ ) *c = FT_GET_LONG(); /* valid psid values are 6, [256;32767], and 0xFFFF */ if ( usePsName ) ns->psid = FT_GET_USHORT(); else ns->psid = 0xFFFF; #ifdef FT_DEBUG_LEVEL_TRACE { SFNT_Service sfnt = (SFNT_Service)face->sfnt; FT_String* strname = NULL; FT_String* psname = NULL; FT_ULong pos; pos = FT_STREAM_POS(); if ( ns->strid != 0xFFFF ) { (void)sfnt->get_name( face, (FT_UShort)ns->strid, &strname ); if ( strname && !ft_strcmp( strname, ".notdef" ) ) strname = NULL; } if ( ns->psid != 0xFFFF ) { (void)sfnt->get_name( face, (FT_UShort)ns->psid, &psname ); if ( psname && !ft_strcmp( psname, ".notdef" ) ) psname = NULL; } (void)FT_STREAM_SEEK( pos ); FT_TRACE5(( " instance %d (%s%s%s, %s%s%s)\n", i, strname ? "name: `" : "", strname ? strname : "unnamed", strname ? "'" : "", psname ? "PS name: `" : "", psname ? psname : "no PS name", psname ? "'" : "" )); FT_FREE( strname ); FT_FREE( psname ); } #endif /* FT_DEBUG_LEVEL_TRACE */ ft_var_to_normalized( face, num_axes, ns->coords, nsc ); nsc += num_axes; FT_FRAME_EXIT(); } if ( num_instances != fvar_head.instanceCount ) { SFNT_Service sfnt = (SFNT_Service)face->sfnt; FT_Int found, dummy1, dummy2; FT_UInt strid = ~0U; /* the default instance is missing in array the */ /* of named instances; try to synthesize an entry */ found = sfnt->get_name_id( face, TT_NAME_ID_TYPOGRAPHIC_SUBFAMILY, &dummy1, &dummy2 ); if ( found ) strid = TT_NAME_ID_TYPOGRAPHIC_SUBFAMILY; else { found = sfnt->get_name_id( face, TT_NAME_ID_FONT_SUBFAMILY, &dummy1, &dummy2 ); if ( found ) strid = TT_NAME_ID_FONT_SUBFAMILY; } if ( found ) { found = sfnt->get_name_id( face, TT_NAME_ID_PS_NAME, &dummy1, &dummy2 ); if ( found ) { FT_TRACE5(( "TT_Get_MM_Var:" " Adding default instance to named instances\n" )); ns = &mmvar->namedstyle[fvar_head.instanceCount]; ns->strid = strid; ns->psid = TT_NAME_ID_PS_NAME; a = mmvar->axis; c = ns->coords; for ( j = 0; j < num_axes; j++, a++, c++ ) *c = a->def; } } } ft_var_load_mvar( face ); } /* fill the output array if requested */ if ( master ) { FT_UInt n; if ( FT_ALLOC( mmvar, face->blend->mmvar_len ) ) goto Exit; FT_MEM_COPY( mmvar, face->blend->mmvar, face->blend->mmvar_len ); axis_flags = (FT_UShort*)( (char*)mmvar + mmvar_size ); mmvar->axis = (FT_Var_Axis*)( (char*)axis_flags + axis_flags_size ); mmvar->namedstyle = (FT_Var_Named_Style*)( (char*)mmvar->axis+ axis_size ); next_coords = (FT_Fixed*)( (char*)mmvar->namedstyle + namedstyle_size ); for ( n = 0; n < mmvar->num_namedstyles; n++ ) { mmvar->namedstyle[n].coords = next_coords; next_coords += num_axes; } a = mmvar->axis; next_name = (FT_String*)( (char*)mmvar->namedstyle + namedstyle_size + next_coords_size ); for ( n = 0; n < num_axes; n++ ) { a->name = next_name; /* standard PostScript names for some standard apple tags */ if ( a->tag == TTAG_wght ) a->name = (char*)"Weight"; else if ( a->tag == TTAG_wdth ) a->name = (char*)"Width"; else if ( a->tag == TTAG_opsz ) a->name = (char*)"OpticalSize"; else if ( a->tag == TTAG_slnt ) a->name = (char*)"Slant"; next_name += 5; a++; } *master = mmvar; } Exit: return error; } static FT_Error tt_set_mm_blend( TT_Face face, FT_UInt num_coords, FT_Fixed* coords, FT_Bool set_design_coords ) { FT_Error error = FT_Err_Ok; GX_Blend blend; FT_MM_Var* mmvar; FT_UInt i; FT_Bool all_design_coords = FALSE; FT_Memory memory = face->root.memory; enum { mcvt_retain, mcvt_modify, mcvt_load } manageCvt; face->doblend = FALSE; if ( !face->blend ) { if ( FT_SET_ERROR( TT_Get_MM_Var( face, NULL ) ) ) goto Exit; } blend = face->blend; mmvar = blend->mmvar; if ( num_coords > mmvar->num_axis ) { FT_TRACE2(( "TT_Set_MM_Blend:" " only using first %d of %d coordinates\n", mmvar->num_axis, num_coords )); num_coords = mmvar->num_axis; } FT_TRACE5(( "TT_Set_MM_Blend:\n" )); FT_TRACE5(( " normalized design coordinates:\n" )); for ( i = 0; i < num_coords; i++ ) { FT_TRACE5(( " %.5f\n", coords[i] / 65536.0 )); if ( coords[i] < -0x00010000L || coords[i] > 0x00010000L ) { FT_TRACE1(( "TT_Set_MM_Blend: normalized design coordinate %.5f\n", coords[i] / 65536.0 )); FT_TRACE1(( " is out of range [-1;1]\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } } FT_TRACE5(( "\n" )); if ( !face->is_cff2 && !blend->glyphoffsets ) if ( FT_SET_ERROR( ft_var_load_gvar( face ) ) ) goto Exit; if ( !blend->coords ) { if ( FT_NEW_ARRAY( blend->coords, mmvar->num_axis ) ) goto Exit; /* the first time we have to compute all design coordinates */ all_design_coords = TRUE; } if ( !blend->normalizedcoords ) { if ( FT_NEW_ARRAY( blend->normalizedcoords, mmvar->num_axis ) ) goto Exit; manageCvt = mcvt_modify; /* If we have not set the blend coordinates before this, then the */ /* cvt table will still be what we read from the `cvt ' table and */ /* we don't need to reload it. We may need to change it though... */ } else { FT_Bool have_diff = 0; FT_UInt j; FT_Fixed* c; FT_Fixed* n; manageCvt = mcvt_retain; for ( i = 0; i < num_coords; i++ ) { if ( blend->normalizedcoords[i] != coords[i] ) { manageCvt = mcvt_load; have_diff = 1; break; } } if ( FT_IS_NAMED_INSTANCE( FT_FACE( face ) ) ) { FT_UInt instance_index = (FT_UInt)face->root.face_index >> 16; c = blend->normalizedcoords + i; n = blend->normalized_stylecoords + ( instance_index - 1 ) * mmvar->num_axis + i; for ( j = i; j < mmvar->num_axis; j++, n++, c++ ) if ( *c != *n ) have_diff = 1; } else { c = blend->normalizedcoords + i; for ( j = i; j < mmvar->num_axis; j++, c++ ) if ( *c != 0 ) have_diff = 1; } /* return value -1 indicates `no change' */ if ( !have_diff ) { face->doblend = TRUE; return -1; } for ( ; i < mmvar->num_axis; i++ ) { if ( blend->normalizedcoords[i] != 0 ) { manageCvt = mcvt_load; break; } } /* If we don't change the blend coords then we don't need to do */ /* anything to the cvt table. It will be correct. Otherwise we */ /* no longer have the original cvt (it was modified when we set */ /* the blend last time), so we must reload and then modify it. */ } blend->num_axis = mmvar->num_axis; if ( coords ) FT_MEM_COPY( blend->normalizedcoords, coords, num_coords * sizeof ( FT_Fixed ) ); if ( set_design_coords ) ft_var_to_design( face, all_design_coords ? blend->num_axis : num_coords, blend->normalizedcoords, blend->coords ); face->doblend = TRUE; if ( face->cvt ) { switch ( manageCvt ) { case mcvt_load: /* The cvt table has been loaded already; every time we change the */ /* blend we may need to reload and remodify the cvt table. */ FT_FREE( face->cvt ); error = tt_face_load_cvt( face, face->root.stream ); break; case mcvt_modify: /* The original cvt table is in memory. All we need to do is */ /* apply the `cvar' table (if any). */ error = tt_face_vary_cvt( face, face->root.stream ); break; case mcvt_retain: /* The cvt table is correct for this set of coordinates. */ break; } } /* enforce recomputation of the PostScript name; */ FT_FREE( face->postscript_name ); Exit: return error; } /************************************************************************** * * @Function: * TT_Set_MM_Blend * * @Description: * Set the blend (normalized) coordinates for this instance of the * font. Check that the `gvar' table is reasonable and does some * initial preparation. * * @InOut: * face :: * The font. * Initialize the blend structure with `gvar' data. * * @Input: * num_coords :: * The number of available coordinates. If it is * larger than the number of axes, ignore the excess * values. If it is smaller than the number of axes, * use the default value (0) for the remaining axes. * * coords :: * An array of `num_coords', each between [-1,1]. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Set_MM_Blend( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Error error; error = tt_set_mm_blend( face, num_coords, coords, 1 ); if ( error ) return error; if ( num_coords ) face->root.face_flags |= FT_FACE_FLAG_VARIATION; else face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Get_MM_Blend * * @Description: * Get the blend (normalized) coordinates for this instance of the * font. * * @InOut: * face :: * The font. * Initialize the blend structure with `gvar' data. * * @Input: * num_coords :: * The number of available coordinates. If it is * larger than the number of axes, set the excess * values to 0. * * coords :: * An array of `num_coords', each between [-1,1]. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Get_MM_Blend( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Error error = FT_Err_Ok; GX_Blend blend; FT_UInt i, nc; if ( !face->blend ) { if ( FT_SET_ERROR( TT_Get_MM_Var( face, NULL ) ) ) return error; } blend = face->blend; if ( !blend->coords ) { /* select default instance coordinates */ /* if no instance is selected yet */ if ( FT_SET_ERROR( tt_set_mm_blend( face, 0, NULL, 1 ) ) ) return error; } nc = num_coords; if ( num_coords > blend->num_axis ) { FT_TRACE2(( "TT_Get_MM_Blend:" " only using first %d of %d coordinates\n", blend->num_axis, num_coords )); nc = blend->num_axis; } if ( face->doblend ) { for ( i = 0; i < nc; i++ ) coords[i] = blend->normalizedcoords[i]; } else { for ( i = 0; i < nc; i++ ) coords[i] = 0; } for ( ; i < num_coords; i++ ) coords[i] = 0; return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Set_Var_Design * * @Description: * Set the coordinates for the instance, measured in the user * coordinate system. Parse the `avar' table (if present) to convert * from user to normalized coordinates. * * @InOut: * face :: * The font face. * Initialize the blend struct with `gvar' data. * * @Input: * num_coords :: * The number of available coordinates. If it is * larger than the number of axes, ignore the excess * values. If it is smaller than the number of axes, * use the default values for the remaining axes. * * coords :: * A coordinate array with `num_coords' elements. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Set_Var_Design( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Error error = FT_Err_Ok; GX_Blend blend; FT_MM_Var* mmvar; FT_UInt i; FT_Memory memory = face->root.memory; FT_Fixed* c; FT_Fixed* n; FT_Fixed* normalized = NULL; FT_Bool have_diff = 0; if ( !face->blend ) { if ( FT_SET_ERROR( TT_Get_MM_Var( face, NULL ) ) ) goto Exit; } blend = face->blend; mmvar = blend->mmvar; if ( num_coords > mmvar->num_axis ) { FT_TRACE2(( "TT_Set_Var_Design:" " only using first %d of %d coordinates\n", mmvar->num_axis, num_coords )); num_coords = mmvar->num_axis; } if ( !blend->coords ) { if ( FT_NEW_ARRAY( blend->coords, mmvar->num_axis ) ) goto Exit; } c = blend->coords; n = coords; for ( i = 0; i < num_coords; i++, n++, c++ ) { if ( *c != *n ) { *c = *n; have_diff = 1; } } if ( FT_IS_NAMED_INSTANCE( FT_FACE( face ) ) ) { FT_UInt instance_index; FT_Var_Named_Style* named_style; instance_index = (FT_UInt)face->root.face_index >> 16; named_style = mmvar->namedstyle + instance_index - 1; n = named_style->coords + num_coords; for ( ; i < mmvar->num_axis; i++, n++, c++ ) { if ( *c != *n ) { *c = *n; have_diff = 1; } } } else { FT_Var_Axis* a; a = mmvar->axis + num_coords; for ( ; i < mmvar->num_axis; i++, a++, c++ ) { if ( *c != a->def ) { *c = a->def; have_diff = 1; } } } /* return value -1 indicates `no change'; */ /* we can exit early if `normalizedcoords' is already computed */ if ( blend->normalizedcoords && !have_diff ) return -1; if ( FT_NEW_ARRAY( normalized, mmvar->num_axis ) ) goto Exit; if ( !face->blend->avar_loaded ) ft_var_load_avar( face ); FT_TRACE5(( "TT_Set_Var_Design:\n" )); FT_TRACE5(( " normalized design coordinates:\n" )); ft_var_to_normalized( face, num_coords, blend->coords, normalized ); error = tt_set_mm_blend( face, mmvar->num_axis, normalized, 0 ); if ( error ) goto Exit; if ( num_coords ) face->root.face_flags |= FT_FACE_FLAG_VARIATION; else face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; Exit: FT_FREE( normalized ); return error; } /************************************************************************** * * @Function: * TT_Get_Var_Design * * @Description: * Get the design coordinates of the currently selected interpolated * font. * * @Input: * face :: * A handle to the source face. * * num_coords :: * The number of design coordinates to retrieve. If it * is larger than the number of axes, set the excess * values to~0. * * @Output: * coords :: * The design coordinates array. * * @Return: * FreeType error code. 0~means success. */ FT_LOCAL_DEF( FT_Error ) TT_Get_Var_Design( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Error error = FT_Err_Ok; GX_Blend blend; FT_UInt i, nc; if ( !face->blend ) { if ( FT_SET_ERROR( TT_Get_MM_Var( face, NULL ) ) ) return error; } blend = face->blend; if ( !blend->coords ) { /* select default instance coordinates */ /* if no instance is selected yet */ if ( FT_SET_ERROR( tt_set_mm_blend( face, 0, NULL, 1 ) ) ) return error; } nc = num_coords; if ( num_coords > blend->num_axis ) { FT_TRACE2(( "TT_Get_Var_Design:" " only using first %d of %d coordinates\n", blend->num_axis, num_coords )); nc = blend->num_axis; } if ( face->doblend ) { for ( i = 0; i < nc; i++ ) coords[i] = blend->coords[i]; } else { for ( i = 0; i < nc; i++ ) coords[i] = 0; } for ( ; i < num_coords; i++ ) coords[i] = 0; return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Set_Named_Instance * * @Description: * Set the given named instance, also resetting any further * variation. * * @Input: * face :: * A handle to the source face. * * instance_index :: * The instance index, starting with value 1. * Value 0 indicates to not use an instance. * * @Return: * FreeType error code. 0~means success. */ FT_LOCAL_DEF( FT_Error ) TT_Set_Named_Instance( TT_Face face, FT_UInt instance_index ) { FT_Error error; GX_Blend blend; FT_MM_Var* mmvar; FT_UInt num_instances; if ( !face->blend ) { if ( FT_SET_ERROR( TT_Get_MM_Var( face, NULL ) ) ) goto Exit; } blend = face->blend; mmvar = blend->mmvar; num_instances = (FT_UInt)face->root.style_flags >> 16; /* `instance_index' starts with value 1, thus `>' */ if ( instance_index > num_instances ) { error = FT_ERR( Invalid_Argument ); goto Exit; } if ( instance_index > 0 ) { FT_Memory memory = face->root.memory; SFNT_Service sfnt = (SFNT_Service)face->sfnt; FT_Var_Named_Style* named_style; FT_String* style_name; named_style = mmvar->namedstyle + instance_index - 1; error = sfnt->get_name( face, (FT_UShort)named_style->strid, &style_name ); if ( error ) goto Exit; /* set (or replace) style name */ FT_FREE( face->root.style_name ); face->root.style_name = style_name; /* finally, select the named instance */ error = TT_Set_Var_Design( face, mmvar->num_axis, named_style->coords ); if ( error ) { /* internal error code -1 means `no change' */ if ( error == -1 ) error = FT_Err_Ok; goto Exit; } } else error = TT_Set_Var_Design( face, 0, NULL ); face->root.face_index = ( instance_index << 16 ) | ( face->root.face_index & 0xFFFFL ); face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; Exit: return error; } /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** GX VAR PARSING ROUTINES *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER static FT_Error tt_cvt_ready_iterator( FT_ListNode node, void* user ) { TT_Size size = (TT_Size)node->data; FT_UNUSED( user ); size->cvt_ready = -1; return FT_Err_Ok; } #endif /* TT_CONFIG_OPTION_BYTECODE_INTERPRETER */ /************************************************************************** * * @Function: * tt_face_vary_cvt * * @Description: * Modify the loaded cvt table according to the `cvar' table and the * font's blend. * * @InOut: * face :: * A handle to the target face object. * * @Input: * stream :: * A handle to the input stream. * * @Return: * FreeType error code. 0 means success. * * Most errors are ignored. It is perfectly valid not to have a * `cvar' table even if there is a `gvar' and `fvar' table. */ FT_LOCAL_DEF( FT_Error ) tt_face_vary_cvt( TT_Face face, FT_Stream stream ) { #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER FT_Error error; FT_Memory memory = stream->memory; FT_Face root = &face->root; FT_ULong table_start; FT_ULong table_len; FT_UInt tupleCount; FT_ULong offsetToData; FT_ULong here; FT_UInt i, j; FT_Fixed* tuple_coords = NULL; FT_Fixed* im_start_coords = NULL; FT_Fixed* im_end_coords = NULL; GX_Blend blend = face->blend; FT_UInt point_count; FT_UInt spoint_count = 0; FT_UShort* sharedpoints = NULL; FT_UShort* localpoints = NULL; FT_UShort* points; FT_Fixed* deltas = NULL; FT_Fixed* cvt_deltas = NULL; FT_TRACE2(( "CVAR " )); if ( !blend ) { FT_TRACE2(( "\n" )); FT_TRACE2(( "tt_face_vary_cvt: no blend specified\n" )); error = FT_Err_Ok; goto Exit; } if ( !face->cvt ) { FT_TRACE2(( "\n" )); FT_TRACE2(( "tt_face_vary_cvt: no `cvt ' table\n" )); error = FT_Err_Ok; goto Exit; } error = face->goto_table( face, TTAG_cvar, stream, &table_len ); if ( error ) { FT_TRACE2(( "is missing\n" )); error = FT_Err_Ok; goto Exit; } if ( FT_FRAME_ENTER( table_len ) ) { error = FT_Err_Ok; goto Exit; } table_start = FT_Stream_FTell( stream ); if ( FT_GET_LONG() != 0x00010000L ) { FT_TRACE2(( "bad table version\n" )); error = FT_Err_Ok; goto FExit; } FT_TRACE2(( "loaded\n" )); if ( FT_NEW_ARRAY( tuple_coords, blend->num_axis ) || FT_NEW_ARRAY( im_start_coords, blend->num_axis ) || FT_NEW_ARRAY( im_end_coords, blend->num_axis ) ) goto FExit; tupleCount = FT_GET_USHORT(); offsetToData = FT_GET_USHORT(); /* rough sanity test */ if ( offsetToData + ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) * 4 > table_len ) { FT_TRACE2(( "tt_face_vary_cvt:" " invalid CVT variation array header\n" )); error = FT_THROW( Invalid_Table ); goto FExit; } offsetToData += table_start; if ( tupleCount & GX_TC_TUPLES_SHARE_POINT_NUMBERS ) { here = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, offsetToData ); sharedpoints = ft_var_readpackedpoints( stream, table_len, &spoint_count ); offsetToData = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, here ); } FT_TRACE5(( "cvar: there %s %d tuple%s:\n", ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) == 1 ? "is" : "are", tupleCount & GX_TC_TUPLE_COUNT_MASK, ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) == 1 ? "" : "s" )); if ( FT_NEW_ARRAY( cvt_deltas, face->cvt_size ) ) goto FExit; for ( i = 0; i < ( tupleCount & GX_TC_TUPLE_COUNT_MASK ); i++ ) { FT_UInt tupleDataSize; FT_UInt tupleIndex; FT_Fixed apply; FT_TRACE6(( " tuple %d:\n", i )); tupleDataSize = FT_GET_USHORT(); tupleIndex = FT_GET_USHORT(); if ( tupleIndex & GX_TI_EMBEDDED_TUPLE_COORD ) { for ( j = 0; j < blend->num_axis; j++ ) tuple_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); } else if ( ( tupleIndex & GX_TI_TUPLE_INDEX_MASK ) >= blend->tuplecount ) { FT_TRACE2(( "tt_face_vary_cvt:" " invalid tuple index\n" )); error = FT_THROW( Invalid_Table ); goto FExit; } else { if ( !blend->tuplecoords ) { FT_TRACE2(( "tt_face_vary_cvt:" " no valid tuple coordinates available\n" )); error = FT_THROW( Invalid_Table ); goto FExit; } FT_MEM_COPY( tuple_coords, blend->tuplecoords + ( tupleIndex & GX_TI_TUPLE_INDEX_MASK ) * blend->num_axis, blend->num_axis * sizeof ( FT_Fixed ) ); } if ( tupleIndex & GX_TI_INTERMEDIATE_TUPLE ) { for ( j = 0; j < blend->num_axis; j++ ) im_start_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); for ( j = 0; j < blend->num_axis; j++ ) im_end_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); } apply = ft_var_apply_tuple( blend, (FT_UShort)tupleIndex, tuple_coords, im_start_coords, im_end_coords ); if ( apply == 0 ) /* tuple isn't active for our blend */ { offsetToData += tupleDataSize; continue; } here = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, offsetToData ); if ( tupleIndex & GX_TI_PRIVATE_POINT_NUMBERS ) { localpoints = ft_var_readpackedpoints( stream, table_len, &point_count ); points = localpoints; } else { localpoints = NULL; points = sharedpoints; point_count = spoint_count; } deltas = ft_var_readpackeddeltas( stream, table_len, point_count == 0 ? face->cvt_size : point_count ); if ( !points || !deltas ) ; /* failure, ignore it */ else if ( localpoints == ALL_POINTS ) { #ifdef FT_DEBUG_LEVEL_TRACE int count = 0; #endif FT_TRACE7(( " CVT deltas:\n" )); /* this means that there are deltas for every entry in cvt */ for ( j = 0; j < face->cvt_size; j++ ) { FT_Fixed old_cvt_delta; old_cvt_delta = cvt_deltas[j]; cvt_deltas[j] = old_cvt_delta + FT_MulFix( deltas[j], apply ); #ifdef FT_DEBUG_LEVEL_TRACE if ( old_cvt_delta != cvt_deltas[j] ) { FT_TRACE7(( " %d: %f -> %f\n", j, ( FT_fdot6ToFixed( face->cvt[j] ) + old_cvt_delta ) / 65536.0, ( FT_fdot6ToFixed( face->cvt[j] ) + cvt_deltas[j] ) / 65536.0 )); count++; } #endif } #ifdef FT_DEBUG_LEVEL_TRACE if ( !count ) FT_TRACE7(( " none\n" )); #endif } else { #ifdef FT_DEBUG_LEVEL_TRACE int count = 0; #endif FT_TRACE7(( " CVT deltas:\n" )); for ( j = 0; j < point_count; j++ ) { int pindex; FT_Fixed old_cvt_delta; pindex = points[j]; if ( (FT_ULong)pindex >= face->cvt_size ) continue; old_cvt_delta = cvt_deltas[pindex]; cvt_deltas[pindex] = old_cvt_delta + FT_MulFix( deltas[j], apply ); #ifdef FT_DEBUG_LEVEL_TRACE if ( old_cvt_delta != cvt_deltas[pindex] ) { FT_TRACE7(( " %d: %f -> %f\n", pindex, ( FT_fdot6ToFixed( face->cvt[pindex] ) + old_cvt_delta ) / 65536.0, ( FT_fdot6ToFixed( face->cvt[pindex] ) + cvt_deltas[pindex] ) / 65536.0 )); count++; } #endif } #ifdef FT_DEBUG_LEVEL_TRACE if ( !count ) FT_TRACE7(( " none\n" )); #endif } if ( localpoints != ALL_POINTS ) FT_FREE( localpoints ); FT_FREE( deltas ); offsetToData += tupleDataSize; FT_Stream_SeekSet( stream, here ); } FT_TRACE5(( "\n" )); for ( i = 0; i < face->cvt_size; i++ ) face->cvt[i] += FT_fixedToFdot6( cvt_deltas[i] ); FExit: FT_FRAME_EXIT(); Exit: if ( sharedpoints != ALL_POINTS ) FT_FREE( sharedpoints ); FT_FREE( tuple_coords ); FT_FREE( im_start_coords ); FT_FREE( im_end_coords ); FT_FREE( cvt_deltas ); /* iterate over all FT_Size objects and set `cvt_ready' to -1 */ /* to trigger rescaling of all CVT values */ FT_List_Iterate( &root->sizes_list, tt_cvt_ready_iterator, NULL ); return error; #else /* !TT_CONFIG_OPTION_BYTECODE_INTERPRETER */ FT_UNUSED( face ); FT_UNUSED( stream ); return FT_Err_Ok; #endif /* !TT_CONFIG_OPTION_BYTECODE_INTERPRETER */ } /* Shift the original coordinates of all points between indices `p1' */ /* and `p2', using the same difference as given by index `ref'. */ /* modeled after `af_iup_shift' */ static void tt_delta_shift( int p1, int p2, int ref, FT_Vector* in_points, FT_Vector* out_points ) { int p; FT_Vector delta; delta.x = out_points[ref].x - in_points[ref].x; delta.y = out_points[ref].y - in_points[ref].y; if ( delta.x == 0 && delta.y == 0 ) return; for ( p = p1; p < ref; p++ ) { out_points[p].x += delta.x; out_points[p].y += delta.y; } for ( p = ref + 1; p <= p2; p++ ) { out_points[p].x += delta.x; out_points[p].y += delta.y; } } /* Interpolate the original coordinates of all points with indices */ /* between `p1' and `p2', using `ref1' and `ref2' as the reference */ /* point indices. */ /* modeled after `af_iup_interp', `_iup_worker_interpolate', and */ /* `Ins_IUP' with spec differences in handling ill-defined cases. */ static void tt_delta_interpolate( int p1, int p2, int ref1, int ref2, FT_Vector* in_points, FT_Vector* out_points ) { int p, i; FT_Pos out, in1, in2, out1, out2, d1, d2; if ( p1 > p2 ) return; /* handle both horizontal and vertical coordinates */ for ( i = 0; i <= 1; i++ ) { /* shift array pointers so that we can access `foo.y' as `foo.x' */ in_points = (FT_Vector*)( (FT_Pos*)in_points + i ); out_points = (FT_Vector*)( (FT_Pos*)out_points + i ); if ( in_points[ref1].x > in_points[ref2].x ) { p = ref1; ref1 = ref2; ref2 = p; } in1 = in_points[ref1].x; in2 = in_points[ref2].x; out1 = out_points[ref1].x; out2 = out_points[ref2].x; d1 = out1 - in1; d2 = out2 - in2; /* If the reference points have the same coordinate but different */ /* delta, inferred delta is zero. Otherwise interpolate. */ if ( in1 != in2 || out1 == out2 ) { FT_Fixed scale = in1 != in2 ? FT_DivFix( out2 - out1, in2 - in1 ) : 0; for ( p = p1; p <= p2; p++ ) { out = in_points[p].x; if ( out <= in1 ) out += d1; else if ( out >= in2 ) out += d2; else out = out1 + FT_MulFix( out - in1, scale ); out_points[p].x = out; } } } } /* Interpolate points without delta values, similar to */ /* the `IUP' hinting instruction. */ /* modeled after `Ins_IUP */ static void tt_interpolate_deltas( FT_Outline* outline, FT_Vector* out_points, FT_Vector* in_points, FT_Bool* has_delta ) { FT_Int first_point; FT_Int end_point; FT_Int first_delta; FT_Int cur_delta; FT_Int point; FT_Short contour; /* ignore empty outlines */ if ( !outline->n_contours ) return; contour = 0; point = 0; do { end_point = outline->contours[contour]; first_point = point; /* search first point that has a delta */ while ( point <= end_point && !has_delta[point] ) point++; if ( point <= end_point ) { first_delta = point; cur_delta = point; point++; while ( point <= end_point ) { /* search next point that has a delta */ /* and interpolate intermediate points */ if ( has_delta[point] ) { tt_delta_interpolate( cur_delta + 1, point - 1, cur_delta, point, in_points, out_points ); cur_delta = point; } point++; } /* shift contour if we only have a single delta */ if ( cur_delta == first_delta ) tt_delta_shift( first_point, end_point, cur_delta, in_points, out_points ); else { /* otherwise handle remaining points */ /* at the end and beginning of the contour */ tt_delta_interpolate( cur_delta + 1, end_point, cur_delta, first_delta, in_points, out_points ); if ( first_delta > 0 ) tt_delta_interpolate( first_point, first_delta - 1, cur_delta, first_delta, in_points, out_points ); } } contour++; } while ( contour < outline->n_contours ); } /************************************************************************** * * @Function: * TT_Vary_Apply_Glyph_Deltas * * @Description: * Apply the appropriate deltas to the current glyph. * * @Input: * face :: * A handle to the target face object. * * glyph_index :: * The index of the glyph being modified. * * n_points :: * The number of the points in the glyph, including * phantom points. * * @InOut: * outline :: * The outline to change. * * @Output: * unrounded :: * An array with `n_points' elements that is filled with unrounded * point coordinates (in 26.6 format). * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Vary_Apply_Glyph_Deltas( TT_Face face, FT_UInt glyph_index, FT_Outline* outline, FT_Vector* unrounded, FT_UInt n_points ) { FT_Error error; FT_Stream stream = face->root.stream; FT_Memory memory = stream->memory; FT_Vector* points_org = NULL; /* coordinates in 16.16 format */ FT_Vector* points_out = NULL; /* coordinates in 16.16 format */ FT_Bool* has_delta = NULL; FT_ULong glyph_start; FT_UInt tupleCount; FT_ULong offsetToData; FT_ULong dataSize; FT_ULong here; FT_UInt i, j; FT_Fixed* tuple_coords = NULL; FT_Fixed* im_start_coords = NULL; FT_Fixed* im_end_coords = NULL; GX_Blend blend = face->blend; FT_UInt point_count; FT_UInt spoint_count = 0; FT_UShort* sharedpoints = NULL; FT_UShort* localpoints = NULL; FT_UShort* points; FT_Fixed* deltas_x = NULL; FT_Fixed* deltas_y = NULL; FT_Fixed* point_deltas_x = NULL; FT_Fixed* point_deltas_y = NULL; if ( !face->doblend || !blend ) return FT_THROW( Invalid_Argument ); for ( i = 0; i < n_points; i++ ) { unrounded[i].x = INT_TO_F26DOT6( outline->points[i].x ); unrounded[i].y = INT_TO_F26DOT6( outline->points[i].y ); } if ( glyph_index >= blend->gv_glyphcnt || blend->glyphoffsets[glyph_index] == blend->glyphoffsets[glyph_index + 1] ) { FT_TRACE2(( "TT_Vary_Apply_Glyph_Deltas:" " no variation data for glyph %d\n", glyph_index )); return FT_Err_Ok; } if ( FT_NEW_ARRAY( points_org, n_points ) || FT_NEW_ARRAY( points_out, n_points ) || FT_NEW_ARRAY( has_delta, n_points ) ) goto Fail1; dataSize = blend->glyphoffsets[glyph_index + 1] - blend->glyphoffsets[glyph_index]; if ( FT_STREAM_SEEK( blend->glyphoffsets[glyph_index] ) || FT_FRAME_ENTER( dataSize ) ) goto Fail1; glyph_start = FT_Stream_FTell( stream ); /* each set of glyph variation data is formatted similarly to `cvar' */ if ( FT_NEW_ARRAY( tuple_coords, blend->num_axis ) || FT_NEW_ARRAY( im_start_coords, blend->num_axis ) || FT_NEW_ARRAY( im_end_coords, blend->num_axis ) ) goto Fail2; tupleCount = FT_GET_USHORT(); offsetToData = FT_GET_USHORT(); /* rough sanity test */ if ( offsetToData > dataSize || ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) * 4 > dataSize ) { FT_TRACE2(( "TT_Vary_Apply_Glyph_Deltas:" " invalid glyph variation array header\n" )); error = FT_THROW( Invalid_Table ); goto Fail2; } offsetToData += glyph_start; if ( tupleCount & GX_TC_TUPLES_SHARE_POINT_NUMBERS ) { here = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, offsetToData ); sharedpoints = ft_var_readpackedpoints( stream, blend->gvar_size, &spoint_count ); offsetToData = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, here ); } FT_TRACE5(( "gvar: there %s %d tuple%s:\n", ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) == 1 ? "is" : "are", tupleCount & GX_TC_TUPLE_COUNT_MASK, ( tupleCount & GX_TC_TUPLE_COUNT_MASK ) == 1 ? "" : "s" )); if ( FT_NEW_ARRAY( point_deltas_x, n_points ) || FT_NEW_ARRAY( point_deltas_y, n_points ) ) goto Fail3; for ( j = 0; j < n_points; j++ ) { points_org[j].x = FT_intToFixed( outline->points[j].x ); points_org[j].y = FT_intToFixed( outline->points[j].y ); } for ( i = 0; i < ( tupleCount & GX_TC_TUPLE_COUNT_MASK ); i++ ) { FT_UInt tupleDataSize; FT_UInt tupleIndex; FT_Fixed apply; FT_TRACE6(( " tuple %d:\n", i )); tupleDataSize = FT_GET_USHORT(); tupleIndex = FT_GET_USHORT(); if ( tupleIndex & GX_TI_EMBEDDED_TUPLE_COORD ) { for ( j = 0; j < blend->num_axis; j++ ) tuple_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); } else if ( ( tupleIndex & GX_TI_TUPLE_INDEX_MASK ) >= blend->tuplecount ) { FT_TRACE2(( "TT_Vary_Apply_Glyph_Deltas:" " invalid tuple index\n" )); error = FT_THROW( Invalid_Table ); goto Fail3; } else FT_MEM_COPY( tuple_coords, blend->tuplecoords + ( tupleIndex & GX_TI_TUPLE_INDEX_MASK ) * blend->num_axis, blend->num_axis * sizeof ( FT_Fixed ) ); if ( tupleIndex & GX_TI_INTERMEDIATE_TUPLE ) { for ( j = 0; j < blend->num_axis; j++ ) im_start_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); for ( j = 0; j < blend->num_axis; j++ ) im_end_coords[j] = FT_fdot14ToFixed( FT_GET_SHORT() ); } apply = ft_var_apply_tuple( blend, (FT_UShort)tupleIndex, tuple_coords, im_start_coords, im_end_coords ); if ( apply == 0 ) /* tuple isn't active for our blend */ { offsetToData += tupleDataSize; continue; } here = FT_Stream_FTell( stream ); FT_Stream_SeekSet( stream, offsetToData ); if ( tupleIndex & GX_TI_PRIVATE_POINT_NUMBERS ) { localpoints = ft_var_readpackedpoints( stream, blend->gvar_size, &point_count ); points = localpoints; } else { points = sharedpoints; point_count = spoint_count; } deltas_x = ft_var_readpackeddeltas( stream, blend->gvar_size, point_count == 0 ? n_points : point_count ); deltas_y = ft_var_readpackeddeltas( stream, blend->gvar_size, point_count == 0 ? n_points : point_count ); if ( !points || !deltas_y || !deltas_x ) ; /* failure, ignore it */ else if ( points == ALL_POINTS ) { #ifdef FT_DEBUG_LEVEL_TRACE int count = 0; #endif FT_TRACE7(( " point deltas:\n" )); /* this means that there are deltas for every point in the glyph */ for ( j = 0; j < n_points; j++ ) { FT_Fixed old_point_delta_x = point_deltas_x[j]; FT_Fixed old_point_delta_y = point_deltas_y[j]; FT_Fixed point_delta_x = FT_MulFix( deltas_x[j], apply ); FT_Fixed point_delta_y = FT_MulFix( deltas_y[j], apply ); if ( j < n_points - 4 ) { point_deltas_x[j] = old_point_delta_x + point_delta_x; point_deltas_y[j] = old_point_delta_y + point_delta_y; } else { /* To avoid double adjustment of advance width or height, */ /* adjust phantom points only if there is no HVAR or VVAR */ /* support, respectively. */ if ( j == ( n_points - 4 ) && !( face->variation_support & TT_FACE_FLAG_VAR_LSB ) ) point_deltas_x[j] = old_point_delta_x + point_delta_x; else if ( j == ( n_points - 3 ) && !( face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) point_deltas_x[j] = old_point_delta_x + point_delta_x; else if ( j == ( n_points - 2 ) && !( face->variation_support & TT_FACE_FLAG_VAR_TSB ) ) point_deltas_y[j] = old_point_delta_y + point_delta_y; else if ( j == ( n_points - 1 ) && !( face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) point_deltas_y[j] = old_point_delta_y + point_delta_y; } #ifdef FT_DEBUG_LEVEL_TRACE if ( point_delta_x || point_delta_y ) { FT_TRACE7(( " %d: (%f, %f) -> (%f, %f)\n", j, ( FT_intToFixed( outline->points[j].x ) + old_point_delta_x ) / 65536.0, ( FT_intToFixed( outline->points[j].y ) + old_point_delta_y ) / 65536.0, ( FT_intToFixed( outline->points[j].x ) + point_deltas_x[j] ) / 65536.0, ( FT_intToFixed( outline->points[j].y ) + point_deltas_y[j] ) / 65536.0 )); count++; } #endif } #ifdef FT_DEBUG_LEVEL_TRACE if ( !count ) FT_TRACE7(( " none\n" )); #endif } else { #ifdef FT_DEBUG_LEVEL_TRACE int count = 0; #endif /* we have to interpolate the missing deltas similar to the */ /* IUP bytecode instruction */ for ( j = 0; j < n_points; j++ ) { has_delta[j] = FALSE; points_out[j] = points_org[j]; } for ( j = 0; j < point_count; j++ ) { FT_UShort idx = points[j]; if ( idx >= n_points ) continue; has_delta[idx] = TRUE; points_out[idx].x += FT_MulFix( deltas_x[j], apply ); points_out[idx].y += FT_MulFix( deltas_y[j], apply ); } /* no need to handle phantom points here, */ /* since solitary points can't be interpolated */ tt_interpolate_deltas( outline, points_out, points_org, has_delta ); FT_TRACE7(( " point deltas:\n" )); for ( j = 0; j < n_points; j++ ) { FT_Fixed old_point_delta_x = point_deltas_x[j]; FT_Fixed old_point_delta_y = point_deltas_y[j]; FT_Pos point_delta_x = points_out[j].x - points_org[j].x; FT_Pos point_delta_y = points_out[j].y - points_org[j].y; if ( j < n_points - 4 ) { point_deltas_x[j] = old_point_delta_x + point_delta_x; point_deltas_y[j] = old_point_delta_y + point_delta_y; } else { /* To avoid double adjustment of advance width or height, */ /* adjust phantom points only if there is no HVAR or VVAR */ /* support, respectively. */ if ( j == ( n_points - 4 ) && !( face->variation_support & TT_FACE_FLAG_VAR_LSB ) ) point_deltas_x[j] = old_point_delta_x + point_delta_x; else if ( j == ( n_points - 3 ) && !( face->variation_support & TT_FACE_FLAG_VAR_HADVANCE ) ) point_deltas_x[j] = old_point_delta_x + point_delta_x; else if ( j == ( n_points - 2 ) && !( face->variation_support & TT_FACE_FLAG_VAR_TSB ) ) point_deltas_y[j] = old_point_delta_y + point_delta_y; else if ( j == ( n_points - 1 ) && !( face->variation_support & TT_FACE_FLAG_VAR_VADVANCE ) ) point_deltas_y[j] = old_point_delta_y + point_delta_y; } #ifdef FT_DEBUG_LEVEL_TRACE if ( point_delta_x || point_delta_y ) { FT_TRACE7(( " %d: (%f, %f) -> (%f, %f)\n", j, ( FT_intToFixed( outline->points[j].x ) + old_point_delta_x ) / 65536.0, ( FT_intToFixed( outline->points[j].y ) + old_point_delta_y ) / 65536.0, ( FT_intToFixed( outline->points[j].x ) + point_deltas_x[j] ) / 65536.0, ( FT_intToFixed( outline->points[j].y ) + point_deltas_y[j] ) / 65536.0 )); count++; } #endif } #ifdef FT_DEBUG_LEVEL_TRACE if ( !count ) FT_TRACE7(( " none\n" )); #endif } if ( localpoints != ALL_POINTS ) FT_FREE( localpoints ); FT_FREE( deltas_x ); FT_FREE( deltas_y ); offsetToData += tupleDataSize; FT_Stream_SeekSet( stream, here ); } FT_TRACE5(( "\n" )); for ( i = 0; i < n_points; i++ ) { unrounded[i].x += FT_fixedToFdot6( point_deltas_x[i] ); unrounded[i].y += FT_fixedToFdot6( point_deltas_y[i] ); outline->points[i].x += FT_fixedToInt( point_deltas_x[i] ); outline->points[i].y += FT_fixedToInt( point_deltas_y[i] ); } Fail3: FT_FREE( point_deltas_x ); FT_FREE( point_deltas_y ); Fail2: if ( sharedpoints != ALL_POINTS ) FT_FREE( sharedpoints ); FT_FREE( tuple_coords ); FT_FREE( im_start_coords ); FT_FREE( im_end_coords ); FT_FRAME_EXIT(); Fail1: FT_FREE( points_org ); FT_FREE( points_out ); FT_FREE( has_delta ); return error; } /************************************************************************** * * @Function: * tt_get_var_blend * * @Description: * An extended internal version of `TT_Get_MM_Blend' that returns * pointers instead of copying data, without any initialization of * the MM machinery in case it isn't loaded yet. */ FT_LOCAL_DEF( FT_Error ) tt_get_var_blend( TT_Face face, FT_UInt *num_coords, FT_Fixed* *coords, FT_Fixed* *normalizedcoords, FT_MM_Var* *mm_var ) { if ( face->blend ) { if ( num_coords ) *num_coords = face->blend->num_axis; if ( coords ) *coords = face->blend->coords; if ( normalizedcoords ) *normalizedcoords = face->blend->normalizedcoords; if ( mm_var ) *mm_var = face->blend->mmvar; } else { if ( num_coords ) *num_coords = 0; if ( coords ) *coords = NULL; if ( mm_var ) *mm_var = NULL; } return FT_Err_Ok; } static void ft_var_done_item_variation_store( TT_Face face, GX_ItemVarStore itemStore ) { FT_Memory memory = FT_FACE_MEMORY( face ); FT_UInt i; if ( itemStore->varData ) { for ( i = 0; i < itemStore->dataCount; i++ ) { FT_FREE( itemStore->varData[i].regionIndices ); FT_FREE( itemStore->varData[i].deltaSet ); } FT_FREE( itemStore->varData ); } if ( itemStore->varRegionList ) { for ( i = 0; i < itemStore->regionCount; i++ ) FT_FREE( itemStore->varRegionList[i].axisList ); FT_FREE( itemStore->varRegionList ); } } /************************************************************************** * * @Function: * tt_done_blend * * @Description: * Free the blend internal data structure. */ FT_LOCAL_DEF( void ) tt_done_blend( TT_Face face ) { FT_Memory memory = FT_FACE_MEMORY( face ); GX_Blend blend = face->blend; if ( blend ) { FT_UInt i, num_axes; /* blend->num_axis might not be set up yet */ num_axes = blend->mmvar->num_axis; FT_FREE( blend->coords ); FT_FREE( blend->normalizedcoords ); FT_FREE( blend->normalized_stylecoords ); FT_FREE( blend->mmvar ); if ( blend->avar_segment ) { for ( i = 0; i < num_axes; i++ ) FT_FREE( blend->avar_segment[i].correspondence ); FT_FREE( blend->avar_segment ); } if ( blend->hvar_table ) { ft_var_done_item_variation_store( face, &blend->hvar_table->itemStore ); FT_FREE( blend->hvar_table->widthMap.innerIndex ); FT_FREE( blend->hvar_table->widthMap.outerIndex ); FT_FREE( blend->hvar_table ); } if ( blend->vvar_table ) { ft_var_done_item_variation_store( face, &blend->vvar_table->itemStore ); FT_FREE( blend->vvar_table->widthMap.innerIndex ); FT_FREE( blend->vvar_table->widthMap.outerIndex ); FT_FREE( blend->vvar_table ); } if ( blend->mvar_table ) { ft_var_done_item_variation_store( face, &blend->mvar_table->itemStore ); FT_FREE( blend->mvar_table->values ); FT_FREE( blend->mvar_table ); } FT_FREE( blend->tuplecoords ); FT_FREE( blend->glyphoffsets ); FT_FREE( blend ); } } #else /* !TT_CONFIG_OPTION_GX_VAR_SUPPORT */ /* ANSI C doesn't like empty source files */ typedef int _tt_gxvar_dummy; #endif /* !TT_CONFIG_OPTION_GX_VAR_SUPPORT */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttgxvar.c
C++
gpl-3.0
124,102
/**************************************************************************** * * ttgxvar.h * * TrueType GX Font Variation loader (specification) * * Copyright (C) 2004-2022 by * David Turner, Robert Wilhelm, Werner Lemberg and George Williams. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTGXVAR_H_ #define TTGXVAR_H_ #include "ttobjs.h" FT_BEGIN_HEADER #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /************************************************************************** * * @Struct: * GX_AVarCorrespondenceRec * * @Description: * A data structure representing `shortFracCorrespondence' in `avar' * table according to the specifications from Apple. */ typedef struct GX_AVarCorrespondenceRec_ { FT_Fixed fromCoord; FT_Fixed toCoord; } GX_AVarCorrespondenceRec_, *GX_AVarCorrespondence; /************************************************************************** * * @Struct: * GX_AVarRec * * @Description: * Data from the segment field of `avar' table. * There is one of these for each axis. */ typedef struct GX_AVarSegmentRec_ { FT_UShort pairCount; GX_AVarCorrespondence correspondence; /* array with pairCount entries */ } GX_AVarSegmentRec, *GX_AVarSegment; typedef struct GX_ItemVarDataRec_ { FT_UInt itemCount; /* number of delta sets per item */ FT_UInt regionIdxCount; /* number of region indices in this data */ FT_UInt* regionIndices; /* array of `regionCount' indices; */ /* these index `varRegionList' */ FT_Short* deltaSet; /* array of `itemCount' deltas */ /* use `innerIndex' for this array */ } GX_ItemVarDataRec, *GX_ItemVarData; /* contribution of one axis to a region */ typedef struct GX_AxisCoordsRec_ { FT_Fixed startCoord; FT_Fixed peakCoord; /* zero means no effect (factor = 1) */ FT_Fixed endCoord; } GX_AxisCoordsRec, *GX_AxisCoords; typedef struct GX_VarRegionRec_ { GX_AxisCoords axisList; /* array of axisCount records */ } GX_VarRegionRec, *GX_VarRegion; /* item variation store */ typedef struct GX_ItemVarStoreRec_ { FT_UInt dataCount; GX_ItemVarData varData; /* array of dataCount records; */ /* use `outerIndex' for this array */ FT_UShort axisCount; FT_UInt regionCount; /* total number of regions defined */ GX_VarRegion varRegionList; } GX_ItemVarStoreRec, *GX_ItemVarStore; typedef struct GX_DeltaSetIdxMapRec_ { FT_ULong mapCount; FT_UInt* outerIndex; /* indices to item var data */ FT_UInt* innerIndex; /* indices to delta set */ } GX_DeltaSetIdxMapRec, *GX_DeltaSetIdxMap; /************************************************************************** * * @Struct: * GX_HVVarTableRec * * @Description: * Data from either the `HVAR' or `VVAR' table. */ typedef struct GX_HVVarTableRec_ { GX_ItemVarStoreRec itemStore; /* Item Variation Store */ GX_DeltaSetIdxMapRec widthMap; /* Advance Width Mapping */ #if 0 GX_DeltaSetIdxMapRec lsbMap; /* not implemented */ GX_DeltaSetIdxMapRec rsbMap; /* not implemented */ GX_DeltaSetIdxMapRec tsbMap; /* not implemented */ GX_DeltaSetIdxMapRec bsbMap; /* not implemented */ GX_DeltaSetIdxMapRec vorgMap; /* not implemented */ #endif } GX_HVVarTableRec, *GX_HVVarTable; #define MVAR_TAG_GASP_0 FT_MAKE_TAG( 'g', 's', 'p', '0' ) #define MVAR_TAG_GASP_1 FT_MAKE_TAG( 'g', 's', 'p', '1' ) #define MVAR_TAG_GASP_2 FT_MAKE_TAG( 'g', 's', 'p', '2' ) #define MVAR_TAG_GASP_3 FT_MAKE_TAG( 'g', 's', 'p', '3' ) #define MVAR_TAG_GASP_4 FT_MAKE_TAG( 'g', 's', 'p', '4' ) #define MVAR_TAG_GASP_5 FT_MAKE_TAG( 'g', 's', 'p', '5' ) #define MVAR_TAG_GASP_6 FT_MAKE_TAG( 'g', 's', 'p', '6' ) #define MVAR_TAG_GASP_7 FT_MAKE_TAG( 'g', 's', 'p', '7' ) #define MVAR_TAG_GASP_8 FT_MAKE_TAG( 'g', 's', 'p', '8' ) #define MVAR_TAG_GASP_9 FT_MAKE_TAG( 'g', 's', 'p', '9' ) #define MVAR_TAG_CPHT FT_MAKE_TAG( 'c', 'p', 'h', 't' ) #define MVAR_TAG_HASC FT_MAKE_TAG( 'h', 'a', 's', 'c' ) #define MVAR_TAG_HCLA FT_MAKE_TAG( 'h', 'c', 'l', 'a' ) #define MVAR_TAG_HCLD FT_MAKE_TAG( 'h', 'c', 'l', 'd' ) #define MVAR_TAG_HCOF FT_MAKE_TAG( 'h', 'c', 'o', 'f' ) #define MVAR_TAG_HCRN FT_MAKE_TAG( 'h', 'c', 'r', 'n' ) #define MVAR_TAG_HCRS FT_MAKE_TAG( 'h', 'c', 'r', 's' ) #define MVAR_TAG_HDSC FT_MAKE_TAG( 'h', 'd', 's', 'c' ) #define MVAR_TAG_HLGP FT_MAKE_TAG( 'h', 'l', 'g', 'p' ) #define MVAR_TAG_SBXO FT_MAKE_TAG( 's', 'b', 'x', 'o' ) #define MVAR_TAG_SBXS FT_MAKE_TAG( 's', 'b', 'x', 's' ) #define MVAR_TAG_SBYO FT_MAKE_TAG( 's', 'b', 'y', 'o' ) #define MVAR_TAG_SBYS FT_MAKE_TAG( 's', 'b', 'y', 's' ) #define MVAR_TAG_SPXO FT_MAKE_TAG( 's', 'p', 'x', 'o' ) #define MVAR_TAG_SPXS FT_MAKE_TAG( 's', 'p', 'x', 's' ) #define MVAR_TAG_SPYO FT_MAKE_TAG( 's', 'p', 'y', 'o' ) #define MVAR_TAG_SPYS FT_MAKE_TAG( 's', 'p', 'y', 's' ) #define MVAR_TAG_STRO FT_MAKE_TAG( 's', 't', 'r', 'o' ) #define MVAR_TAG_STRS FT_MAKE_TAG( 's', 't', 'r', 's' ) #define MVAR_TAG_UNDO FT_MAKE_TAG( 'u', 'n', 'd', 'o' ) #define MVAR_TAG_UNDS FT_MAKE_TAG( 'u', 'n', 'd', 's' ) #define MVAR_TAG_VASC FT_MAKE_TAG( 'v', 'a', 's', 'c' ) #define MVAR_TAG_VCOF FT_MAKE_TAG( 'v', 'c', 'o', 'f' ) #define MVAR_TAG_VCRN FT_MAKE_TAG( 'v', 'c', 'r', 'n' ) #define MVAR_TAG_VCRS FT_MAKE_TAG( 'v', 'c', 'r', 's' ) #define MVAR_TAG_VDSC FT_MAKE_TAG( 'v', 'd', 's', 'c' ) #define MVAR_TAG_VLGP FT_MAKE_TAG( 'v', 'l', 'g', 'p' ) #define MVAR_TAG_XHGT FT_MAKE_TAG( 'x', 'h', 'g', 't' ) typedef struct GX_ValueRec_ { FT_ULong tag; FT_UShort outerIndex; FT_UShort innerIndex; FT_Short unmodified; /* values are either FT_Short or FT_UShort */ } GX_ValueRec, *GX_Value; /************************************************************************** * * @Struct: * GX_MVarTableRec * * @Description: * Data from the `MVAR' table. */ typedef struct GX_MVarTableRec_ { FT_UShort valueCount; GX_ItemVarStoreRec itemStore; /* Item Variation Store */ GX_Value values; /* Value Records */ } GX_MVarTableRec, *GX_MVarTable; /************************************************************************** * * @Struct: * GX_BlendRec * * @Description: * Data for interpolating a font from a distortable font specified * by the GX *var tables ([fgcahvm]var). * * @Fields: * num_axis :: * The number of axes along which interpolation may happen. * * coords :: * An array of design coordinates (in user space) indicating the * contribution along each axis to the final interpolated font. * `normalizedcoords' holds the same values. * * normalizedcoords :: * An array of normalized values (between [-1,1]) indicating the * contribution along each axis to the final interpolated font. * `coords' holds the same values. * * mmvar :: * Data from the `fvar' table. * * mmvar_len :: * The length of the `mmvar' structure. * * normalized_stylecoords :: * A two-dimensional array that holds the named instance data from * `mmvar' as normalized values. * * avar_loaded :: * A Boolean; if set, FreeType tried to load (and parse) the `avar' * table. * * avar_segment :: * Data from the `avar' table. * * hvar_loaded :: * A Boolean; if set, FreeType tried to load (and parse) the `hvar' * table. * * hvar_checked :: * A Boolean; if set, FreeType successfully loaded and parsed the * `hvar' table. * * hvar_error :: * If loading and parsing of the `hvar' table failed, this field * holds the corresponding error code. * * hvar_table :: * Data from the `hvar' table. * * vvar_loaded :: * A Boolean; if set, FreeType tried to load (and parse) the `vvar' * table. * * vvar_checked :: * A Boolean; if set, FreeType successfully loaded and parsed the * `vvar' table. * * vvar_error :: * If loading and parsing of the `vvar' table failed, this field * holds the corresponding error code. * * vvar_table :: * Data from the `vvar' table. * * mvar_table :: * Data from the `mvar' table. * * tuplecount :: * The number of shared tuples in the `gvar' table. * * tuplecoords :: * A two-dimensional array that holds the shared tuple coordinates * in the `gvar' table. * * gv_glyphcnt :: * The number of glyphs handled in the `gvar' table. * * glyphoffsets :: * Offsets into the glyph variation data array. * * gvar_size :: * The size of the `gvar' table. */ typedef struct GX_BlendRec_ { FT_UInt num_axis; FT_Fixed* coords; FT_Fixed* normalizedcoords; FT_MM_Var* mmvar; FT_Offset mmvar_len; FT_Fixed* normalized_stylecoords; /* normalized_stylecoords[num_namedstyles][num_axis] */ FT_Bool avar_loaded; GX_AVarSegment avar_segment; /* avar_segment[num_axis] */ FT_Bool hvar_loaded; FT_Bool hvar_checked; FT_Error hvar_error; GX_HVVarTable hvar_table; FT_Bool vvar_loaded; FT_Bool vvar_checked; FT_Error vvar_error; GX_HVVarTable vvar_table; GX_MVarTable mvar_table; FT_UInt tuplecount; FT_Fixed* tuplecoords; /* tuplecoords[tuplecount][num_axis] */ FT_UInt gv_glyphcnt; FT_ULong* glyphoffsets; /* glyphoffsets[gv_glyphcnt + 1] */ FT_ULong gvar_size; } GX_BlendRec; /************************************************************************** * * @enum: * GX_TupleCountFlags * * @Description: * Flags used within the `TupleCount' field of the `gvar' table. */ typedef enum GX_TupleCountFlags_ { GX_TC_TUPLES_SHARE_POINT_NUMBERS = 0x8000, GX_TC_RESERVED_TUPLE_FLAGS = 0x7000, GX_TC_TUPLE_COUNT_MASK = 0x0FFF } GX_TupleCountFlags; /************************************************************************** * * @enum: * GX_TupleIndexFlags * * @Description: * Flags used within the `TupleIndex' field of the `gvar' and `cvar' * tables. */ typedef enum GX_TupleIndexFlags_ { GX_TI_EMBEDDED_TUPLE_COORD = 0x8000, GX_TI_INTERMEDIATE_TUPLE = 0x4000, GX_TI_PRIVATE_POINT_NUMBERS = 0x2000, GX_TI_RESERVED_TUPLE_FLAG = 0x1000, GX_TI_TUPLE_INDEX_MASK = 0x0FFF } GX_TupleIndexFlags; #define TTAG_wght FT_MAKE_TAG( 'w', 'g', 'h', 't' ) #define TTAG_wdth FT_MAKE_TAG( 'w', 'd', 't', 'h' ) #define TTAG_opsz FT_MAKE_TAG( 'o', 'p', 's', 'z' ) #define TTAG_slnt FT_MAKE_TAG( 's', 'l', 'n', 't' ) FT_LOCAL( FT_Error ) TT_Set_MM_Blend( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) TT_Get_MM_Blend( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) TT_Set_Var_Design( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) TT_Get_MM_Var( TT_Face face, FT_MM_Var* *master ); FT_LOCAL( FT_Error ) TT_Get_Var_Design( TT_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) TT_Set_Named_Instance( TT_Face face, FT_UInt instance_index ); FT_LOCAL( FT_Error ) tt_face_vary_cvt( TT_Face face, FT_Stream stream ); FT_LOCAL( FT_Error ) TT_Vary_Apply_Glyph_Deltas( TT_Face face, FT_UInt glyph_index, FT_Outline* outline, FT_Vector* unrounded, FT_UInt n_points ); FT_LOCAL( FT_Error ) tt_hadvance_adjust( TT_Face face, FT_UInt gindex, FT_Int *adelta ); FT_LOCAL( FT_Error ) tt_vadvance_adjust( TT_Face face, FT_UInt gindex, FT_Int *adelta ); FT_LOCAL( void ) tt_apply_mvar( TT_Face face ); FT_LOCAL( FT_Error ) tt_get_var_blend( TT_Face face, FT_UInt *num_coords, FT_Fixed* *coords, FT_Fixed* *normalizedcoords, FT_MM_Var* *mm_var ); FT_LOCAL( void ) tt_done_blend( TT_Face face ); #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ FT_END_HEADER #endif /* TTGXVAR_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttgxvar.h
C++
gpl-3.0
13,544
/**************************************************************************** * * ttinterp.c * * TrueType bytecode interpreter (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /* Greg Hitchcock from Microsoft has helped a lot in resolving unclear */ /* issues; many thanks! */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftcalc.h> #include <freetype/fttrigon.h> #include <freetype/ftsystem.h> #include <freetype/ftdriver.h> #include <freetype/ftmm.h> #include "ttinterp.h" #include "tterrors.h" #include "ttsubpix.h" #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include "ttgxvar.h" #endif #ifdef TT_USE_BYTECODE_INTERPRETER /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttinterp #define NO_SUBPIXEL_HINTING \ ( ((TT_Driver)FT_FACE_DRIVER( exc->face ))->interpreter_version == \ TT_INTERPRETER_VERSION_35 ) #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY #define SUBPIXEL_HINTING_INFINALITY \ ( ((TT_Driver)FT_FACE_DRIVER( exc->face ))->interpreter_version == \ TT_INTERPRETER_VERSION_38 ) #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL #define SUBPIXEL_HINTING_MINIMAL \ ( ((TT_Driver)FT_FACE_DRIVER( exc->face ))->interpreter_version == \ TT_INTERPRETER_VERSION_40 ) #endif #define PROJECT( v1, v2 ) \ exc->func_project( exc, \ SUB_LONG( (v1)->x, (v2)->x ), \ SUB_LONG( (v1)->y, (v2)->y ) ) #define DUALPROJ( v1, v2 ) \ exc->func_dualproj( exc, \ SUB_LONG( (v1)->x, (v2)->x ), \ SUB_LONG( (v1)->y, (v2)->y ) ) #define FAST_PROJECT( v ) \ exc->func_project( exc, (v)->x, (v)->y ) #define FAST_DUALPROJ( v ) \ exc->func_dualproj( exc, (v)->x, (v)->y ) /************************************************************************** * * Two simple bounds-checking macros. */ #define BOUNDS( x, n ) ( (FT_UInt)(x) >= (FT_UInt)(n) ) #define BOUNDSL( x, n ) ( (FT_ULong)(x) >= (FT_ULong)(n) ) #undef SUCCESS #define SUCCESS 0 #undef FAILURE #define FAILURE 1 /************************************************************************** * * CODERANGE FUNCTIONS * */ /************************************************************************** * * @Function: * TT_Goto_CodeRange * * @Description: * Switches to a new code range (updates the code related elements in * `exec', and `IP'). * * @Input: * range :: * The new execution code range. * * IP :: * The new IP in the new code range. * * @InOut: * exec :: * The target execution context. */ FT_LOCAL_DEF( void ) TT_Goto_CodeRange( TT_ExecContext exec, FT_Int range, FT_Long IP ) { TT_CodeRange* coderange; FT_ASSERT( range >= 1 && range <= 3 ); coderange = &exec->codeRangeTable[range - 1]; FT_ASSERT( coderange->base ); /* NOTE: Because the last instruction of a program may be a CALL */ /* which will return to the first byte *after* the code */ /* range, we test for IP <= Size instead of IP < Size. */ /* */ FT_ASSERT( IP <= coderange->size ); exec->code = coderange->base; exec->codeSize = coderange->size; exec->IP = IP; exec->curRange = range; } /************************************************************************** * * @Function: * TT_Set_CodeRange * * @Description: * Sets a code range. * * @Input: * range :: * The code range index. * * base :: * The new code base. * * length :: * The range size in bytes. * * @InOut: * exec :: * The target execution context. */ FT_LOCAL_DEF( void ) TT_Set_CodeRange( TT_ExecContext exec, FT_Int range, void* base, FT_Long length ) { FT_ASSERT( range >= 1 && range <= 3 ); exec->codeRangeTable[range - 1].base = (FT_Byte*)base; exec->codeRangeTable[range - 1].size = length; } /************************************************************************** * * @Function: * TT_Clear_CodeRange * * @Description: * Clears a code range. * * @Input: * range :: * The code range index. * * @InOut: * exec :: * The target execution context. */ FT_LOCAL_DEF( void ) TT_Clear_CodeRange( TT_ExecContext exec, FT_Int range ) { FT_ASSERT( range >= 1 && range <= 3 ); exec->codeRangeTable[range - 1].base = NULL; exec->codeRangeTable[range - 1].size = 0; } /************************************************************************** * * EXECUTION CONTEXT ROUTINES * */ /************************************************************************** * * @Function: * TT_Done_Context * * @Description: * Destroys a given context. * * @Input: * exec :: * A handle to the target execution context. * * memory :: * A handle to the parent memory object. * * @Note: * Only the glyph loader and debugger should call this function. */ FT_LOCAL_DEF( void ) TT_Done_Context( TT_ExecContext exec ) { FT_Memory memory = exec->memory; /* points zone */ exec->maxPoints = 0; exec->maxContours = 0; /* free stack */ FT_FREE( exec->stack ); exec->stackSize = 0; /* free glyf cvt working area */ FT_FREE( exec->glyfCvt ); exec->glyfCvtSize = 0; /* free glyf storage working area */ FT_FREE( exec->glyfStorage ); exec->glyfStoreSize = 0; /* free call stack */ FT_FREE( exec->callStack ); exec->callSize = 0; exec->callTop = 0; /* free glyph code range */ FT_FREE( exec->glyphIns ); exec->glyphSize = 0; exec->size = NULL; exec->face = NULL; FT_FREE( exec ); } /************************************************************************** * * @Function: * Update_Max * * @Description: * Checks the size of a buffer and reallocates it if necessary. * * @Input: * memory :: * A handle to the parent memory object. * * multiplier :: * The size in bytes of each element in the buffer. * * new_max :: * The new capacity (size) of the buffer. * * @InOut: * size :: * The address of the buffer's current size expressed * in elements. * * buff :: * The address of the buffer base pointer. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) Update_Max( FT_Memory memory, FT_ULong* size, FT_ULong multiplier, void* _pbuff, FT_ULong new_max ) { FT_Error error; void** pbuff = (void**)_pbuff; if ( *size < new_max ) { if ( FT_QREALLOC( *pbuff, *size * multiplier, new_max * multiplier ) ) return error; *size = new_max; } return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Load_Context * * @Description: * Prepare an execution context for glyph hinting. * * @Input: * face :: * A handle to the source face object. * * size :: * A handle to the source size object. * * @InOut: * exec :: * A handle to the target execution context. * * @Return: * FreeType error code. 0 means success. * * @Note: * Only the glyph loader and debugger should call this function. * * Note that not all members of `TT_ExecContext` get initialized. */ FT_LOCAL_DEF( FT_Error ) TT_Load_Context( TT_ExecContext exec, TT_Face face, TT_Size size ) { FT_Int i; FT_ULong tmp; TT_MaxProfile* maxp; FT_Error error; exec->face = face; maxp = &face->max_profile; exec->size = size; if ( size ) { exec->numFDefs = size->num_function_defs; exec->maxFDefs = size->max_function_defs; exec->numIDefs = size->num_instruction_defs; exec->maxIDefs = size->max_instruction_defs; exec->FDefs = size->function_defs; exec->IDefs = size->instruction_defs; exec->pointSize = size->point_size; exec->tt_metrics = size->ttmetrics; exec->metrics = *size->metrics; exec->maxFunc = size->max_func; exec->maxIns = size->max_ins; for ( i = 0; i < TT_MAX_CODE_RANGES; i++ ) exec->codeRangeTable[i] = size->codeRangeTable[i]; /* set graphics state */ exec->GS = size->GS; exec->cvtSize = size->cvt_size; exec->cvt = size->cvt; exec->storeSize = size->storage_size; exec->storage = size->storage; exec->twilight = size->twilight; /* In case of multi-threading it can happen that the old size object */ /* no longer exists, thus we must clear all glyph zone references. */ FT_ZERO( &exec->zp0 ); exec->zp1 = exec->zp0; exec->zp2 = exec->zp0; } /* XXX: We reserve a little more elements on the stack to deal safely */ /* with broken fonts like arialbs, courbs, timesbs, etc. */ tmp = (FT_ULong)exec->stackSize; error = Update_Max( exec->memory, &tmp, sizeof ( FT_F26Dot6 ), (void*)&exec->stack, maxp->maxStackElements + 32 ); exec->stackSize = (FT_Long)tmp; if ( error ) return error; tmp = (FT_ULong)exec->glyphSize; error = Update_Max( exec->memory, &tmp, sizeof ( FT_Byte ), (void*)&exec->glyphIns, maxp->maxSizeOfInstructions ); exec->glyphSize = (FT_UInt)tmp; if ( error ) return error; exec->pts.n_points = 0; exec->pts.n_contours = 0; exec->zp1 = exec->pts; exec->zp2 = exec->pts; exec->zp0 = exec->pts; exec->instruction_trap = FALSE; return FT_Err_Ok; } /************************************************************************** * * @Function: * TT_Save_Context * * @Description: * Saves the code ranges in a `size' object. * * @Input: * exec :: * A handle to the source execution context. * * @InOut: * size :: * A handle to the target size object. * * @Note: * Only the glyph loader and debugger should call this function. */ FT_LOCAL_DEF( void ) TT_Save_Context( TT_ExecContext exec, TT_Size size ) { FT_Int i; /* XXX: Will probably disappear soon with all the code range */ /* management, which is now rather obsolete. */ /* */ size->num_function_defs = exec->numFDefs; size->num_instruction_defs = exec->numIDefs; size->max_func = exec->maxFunc; size->max_ins = exec->maxIns; for ( i = 0; i < TT_MAX_CODE_RANGES; i++ ) size->codeRangeTable[i] = exec->codeRangeTable[i]; } /************************************************************************** * * @Function: * TT_Run_Context * * @Description: * Executes one or more instructions in the execution context. * * @Input: * exec :: * A handle to the target execution context. * * @Return: * TrueType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) TT_Run_Context( TT_ExecContext exec ) { TT_Goto_CodeRange( exec, tt_coderange_glyph, 0 ); exec->zp0 = exec->pts; exec->zp1 = exec->pts; exec->zp2 = exec->pts; exec->GS.gep0 = 1; exec->GS.gep1 = 1; exec->GS.gep2 = 1; exec->GS.projVector.x = 0x4000; exec->GS.projVector.y = 0x0000; exec->GS.freeVector = exec->GS.projVector; exec->GS.dualVector = exec->GS.projVector; exec->GS.round_state = 1; exec->GS.loop = 1; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY exec->iup_called = FALSE; #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL exec->iupx_called = FALSE; exec->iupy_called = FALSE; #endif /* some glyphs leave something on the stack. so we clean it */ /* before a new execution. */ exec->top = 0; exec->callTop = 0; return exec->face->interpreter( exec ); } /* The default value for `scan_control' is documented as FALSE in the */ /* TrueType specification. This is confusing since it implies a */ /* Boolean value. However, this is not the case, thus both the */ /* default values of our `scan_type' and `scan_control' fields (which */ /* the documentation's `scan_control' variable is split into) are */ /* zero. */ const TT_GraphicsState tt_default_graphics_state = { 0, 0, 0, { 0x4000, 0 }, { 0x4000, 0 }, { 0x4000, 0 }, 1, 64, 1, TRUE, 68, 0, 0, 9, 3, 0, FALSE, 0, 1, 1, 1 }; /* documentation is in ttinterp.h */ FT_EXPORT_DEF( TT_ExecContext ) TT_New_Context( TT_Driver driver ) { FT_Memory memory; FT_Error error; TT_ExecContext exec = NULL; if ( !driver ) goto Fail; memory = driver->root.root.memory; /* allocate object and zero everything inside */ if ( FT_NEW( exec ) ) goto Fail; /* create callStack here, other allocations delayed */ exec->memory = memory; exec->callSize = 32; if ( FT_QNEW_ARRAY( exec->callStack, exec->callSize ) ) FT_FREE( exec ); Fail: return exec; } /************************************************************************** * * Before an opcode is executed, the interpreter verifies that there are * enough arguments on the stack, with the help of the `Pop_Push_Count' * table. * * For each opcode, the first column gives the number of arguments that * are popped from the stack; the second one gives the number of those * that are pushed in result. * * Opcodes which have a varying number of parameters in the data stream * (NPUSHB, NPUSHW) are handled specially; they have a negative value in * the `opcode_length' table, and the value in `Pop_Push_Count' is set * to zero. * */ #undef PACK #define PACK( x, y ) ( ( x << 4 ) | y ) static const FT_Byte Pop_Push_Count[256] = { /* opcodes are gathered in groups of 16 */ /* please keep the spaces as they are */ /* 0x00 */ /* SVTCA[0] */ PACK( 0, 0 ), /* SVTCA[1] */ PACK( 0, 0 ), /* SPVTCA[0] */ PACK( 0, 0 ), /* SPVTCA[1] */ PACK( 0, 0 ), /* SFVTCA[0] */ PACK( 0, 0 ), /* SFVTCA[1] */ PACK( 0, 0 ), /* SPVTL[0] */ PACK( 2, 0 ), /* SPVTL[1] */ PACK( 2, 0 ), /* SFVTL[0] */ PACK( 2, 0 ), /* SFVTL[1] */ PACK( 2, 0 ), /* SPVFS */ PACK( 2, 0 ), /* SFVFS */ PACK( 2, 0 ), /* GPV */ PACK( 0, 2 ), /* GFV */ PACK( 0, 2 ), /* SFVTPV */ PACK( 0, 0 ), /* ISECT */ PACK( 5, 0 ), /* 0x10 */ /* SRP0 */ PACK( 1, 0 ), /* SRP1 */ PACK( 1, 0 ), /* SRP2 */ PACK( 1, 0 ), /* SZP0 */ PACK( 1, 0 ), /* SZP1 */ PACK( 1, 0 ), /* SZP2 */ PACK( 1, 0 ), /* SZPS */ PACK( 1, 0 ), /* SLOOP */ PACK( 1, 0 ), /* RTG */ PACK( 0, 0 ), /* RTHG */ PACK( 0, 0 ), /* SMD */ PACK( 1, 0 ), /* ELSE */ PACK( 0, 0 ), /* JMPR */ PACK( 1, 0 ), /* SCVTCI */ PACK( 1, 0 ), /* SSWCI */ PACK( 1, 0 ), /* SSW */ PACK( 1, 0 ), /* 0x20 */ /* DUP */ PACK( 1, 2 ), /* POP */ PACK( 1, 0 ), /* CLEAR */ PACK( 0, 0 ), /* SWAP */ PACK( 2, 2 ), /* DEPTH */ PACK( 0, 1 ), /* CINDEX */ PACK( 1, 1 ), /* MINDEX */ PACK( 1, 0 ), /* ALIGNPTS */ PACK( 2, 0 ), /* INS_$28 */ PACK( 0, 0 ), /* UTP */ PACK( 1, 0 ), /* LOOPCALL */ PACK( 2, 0 ), /* CALL */ PACK( 1, 0 ), /* FDEF */ PACK( 1, 0 ), /* ENDF */ PACK( 0, 0 ), /* MDAP[0] */ PACK( 1, 0 ), /* MDAP[1] */ PACK( 1, 0 ), /* 0x30 */ /* IUP[0] */ PACK( 0, 0 ), /* IUP[1] */ PACK( 0, 0 ), /* SHP[0] */ PACK( 0, 0 ), /* loops */ /* SHP[1] */ PACK( 0, 0 ), /* loops */ /* SHC[0] */ PACK( 1, 0 ), /* SHC[1] */ PACK( 1, 0 ), /* SHZ[0] */ PACK( 1, 0 ), /* SHZ[1] */ PACK( 1, 0 ), /* SHPIX */ PACK( 1, 0 ), /* loops */ /* IP */ PACK( 0, 0 ), /* loops */ /* MSIRP[0] */ PACK( 2, 0 ), /* MSIRP[1] */ PACK( 2, 0 ), /* ALIGNRP */ PACK( 0, 0 ), /* loops */ /* RTDG */ PACK( 0, 0 ), /* MIAP[0] */ PACK( 2, 0 ), /* MIAP[1] */ PACK( 2, 0 ), /* 0x40 */ /* NPUSHB */ PACK( 0, 0 ), /* NPUSHW */ PACK( 0, 0 ), /* WS */ PACK( 2, 0 ), /* RS */ PACK( 1, 1 ), /* WCVTP */ PACK( 2, 0 ), /* RCVT */ PACK( 1, 1 ), /* GC[0] */ PACK( 1, 1 ), /* GC[1] */ PACK( 1, 1 ), /* SCFS */ PACK( 2, 0 ), /* MD[0] */ PACK( 2, 1 ), /* MD[1] */ PACK( 2, 1 ), /* MPPEM */ PACK( 0, 1 ), /* MPS */ PACK( 0, 1 ), /* FLIPON */ PACK( 0, 0 ), /* FLIPOFF */ PACK( 0, 0 ), /* DEBUG */ PACK( 1, 0 ), /* 0x50 */ /* LT */ PACK( 2, 1 ), /* LTEQ */ PACK( 2, 1 ), /* GT */ PACK( 2, 1 ), /* GTEQ */ PACK( 2, 1 ), /* EQ */ PACK( 2, 1 ), /* NEQ */ PACK( 2, 1 ), /* ODD */ PACK( 1, 1 ), /* EVEN */ PACK( 1, 1 ), /* IF */ PACK( 1, 0 ), /* EIF */ PACK( 0, 0 ), /* AND */ PACK( 2, 1 ), /* OR */ PACK( 2, 1 ), /* NOT */ PACK( 1, 1 ), /* DELTAP1 */ PACK( 1, 0 ), /* SDB */ PACK( 1, 0 ), /* SDS */ PACK( 1, 0 ), /* 0x60 */ /* ADD */ PACK( 2, 1 ), /* SUB */ PACK( 2, 1 ), /* DIV */ PACK( 2, 1 ), /* MUL */ PACK( 2, 1 ), /* ABS */ PACK( 1, 1 ), /* NEG */ PACK( 1, 1 ), /* FLOOR */ PACK( 1, 1 ), /* CEILING */ PACK( 1, 1 ), /* ROUND[0] */ PACK( 1, 1 ), /* ROUND[1] */ PACK( 1, 1 ), /* ROUND[2] */ PACK( 1, 1 ), /* ROUND[3] */ PACK( 1, 1 ), /* NROUND[0] */ PACK( 1, 1 ), /* NROUND[1] */ PACK( 1, 1 ), /* NROUND[2] */ PACK( 1, 1 ), /* NROUND[3] */ PACK( 1, 1 ), /* 0x70 */ /* WCVTF */ PACK( 2, 0 ), /* DELTAP2 */ PACK( 1, 0 ), /* DELTAP3 */ PACK( 1, 0 ), /* DELTAC1 */ PACK( 1, 0 ), /* DELTAC2 */ PACK( 1, 0 ), /* DELTAC3 */ PACK( 1, 0 ), /* SROUND */ PACK( 1, 0 ), /* S45ROUND */ PACK( 1, 0 ), /* JROT */ PACK( 2, 0 ), /* JROF */ PACK( 2, 0 ), /* ROFF */ PACK( 0, 0 ), /* INS_$7B */ PACK( 0, 0 ), /* RUTG */ PACK( 0, 0 ), /* RDTG */ PACK( 0, 0 ), /* SANGW */ PACK( 1, 0 ), /* AA */ PACK( 1, 0 ), /* 0x80 */ /* FLIPPT */ PACK( 0, 0 ), /* loops */ /* FLIPRGON */ PACK( 2, 0 ), /* FLIPRGOFF */ PACK( 2, 0 ), /* INS_$83 */ PACK( 0, 0 ), /* INS_$84 */ PACK( 0, 0 ), /* SCANCTRL */ PACK( 1, 0 ), /* SDPVTL[0] */ PACK( 2, 0 ), /* SDPVTL[1] */ PACK( 2, 0 ), /* GETINFO */ PACK( 1, 1 ), /* IDEF */ PACK( 1, 0 ), /* ROLL */ PACK( 3, 3 ), /* MAX */ PACK( 2, 1 ), /* MIN */ PACK( 2, 1 ), /* SCANTYPE */ PACK( 1, 0 ), /* INSTCTRL */ PACK( 2, 0 ), /* INS_$8F */ PACK( 0, 0 ), /* 0x90 */ /* INS_$90 */ PACK( 0, 0 ), /* GETVAR */ PACK( 0, 0 ), /* will be handled specially */ /* GETDATA */ PACK( 0, 1 ), /* INS_$93 */ PACK( 0, 0 ), /* INS_$94 */ PACK( 0, 0 ), /* INS_$95 */ PACK( 0, 0 ), /* INS_$96 */ PACK( 0, 0 ), /* INS_$97 */ PACK( 0, 0 ), /* INS_$98 */ PACK( 0, 0 ), /* INS_$99 */ PACK( 0, 0 ), /* INS_$9A */ PACK( 0, 0 ), /* INS_$9B */ PACK( 0, 0 ), /* INS_$9C */ PACK( 0, 0 ), /* INS_$9D */ PACK( 0, 0 ), /* INS_$9E */ PACK( 0, 0 ), /* INS_$9F */ PACK( 0, 0 ), /* 0xA0 */ /* INS_$A0 */ PACK( 0, 0 ), /* INS_$A1 */ PACK( 0, 0 ), /* INS_$A2 */ PACK( 0, 0 ), /* INS_$A3 */ PACK( 0, 0 ), /* INS_$A4 */ PACK( 0, 0 ), /* INS_$A5 */ PACK( 0, 0 ), /* INS_$A6 */ PACK( 0, 0 ), /* INS_$A7 */ PACK( 0, 0 ), /* INS_$A8 */ PACK( 0, 0 ), /* INS_$A9 */ PACK( 0, 0 ), /* INS_$AA */ PACK( 0, 0 ), /* INS_$AB */ PACK( 0, 0 ), /* INS_$AC */ PACK( 0, 0 ), /* INS_$AD */ PACK( 0, 0 ), /* INS_$AE */ PACK( 0, 0 ), /* INS_$AF */ PACK( 0, 0 ), /* 0xB0 */ /* PUSHB[0] */ PACK( 0, 1 ), /* PUSHB[1] */ PACK( 0, 2 ), /* PUSHB[2] */ PACK( 0, 3 ), /* PUSHB[3] */ PACK( 0, 4 ), /* PUSHB[4] */ PACK( 0, 5 ), /* PUSHB[5] */ PACK( 0, 6 ), /* PUSHB[6] */ PACK( 0, 7 ), /* PUSHB[7] */ PACK( 0, 8 ), /* PUSHW[0] */ PACK( 0, 1 ), /* PUSHW[1] */ PACK( 0, 2 ), /* PUSHW[2] */ PACK( 0, 3 ), /* PUSHW[3] */ PACK( 0, 4 ), /* PUSHW[4] */ PACK( 0, 5 ), /* PUSHW[5] */ PACK( 0, 6 ), /* PUSHW[6] */ PACK( 0, 7 ), /* PUSHW[7] */ PACK( 0, 8 ), /* 0xC0 */ /* MDRP[00] */ PACK( 1, 0 ), /* MDRP[01] */ PACK( 1, 0 ), /* MDRP[02] */ PACK( 1, 0 ), /* MDRP[03] */ PACK( 1, 0 ), /* MDRP[04] */ PACK( 1, 0 ), /* MDRP[05] */ PACK( 1, 0 ), /* MDRP[06] */ PACK( 1, 0 ), /* MDRP[07] */ PACK( 1, 0 ), /* MDRP[08] */ PACK( 1, 0 ), /* MDRP[09] */ PACK( 1, 0 ), /* MDRP[10] */ PACK( 1, 0 ), /* MDRP[11] */ PACK( 1, 0 ), /* MDRP[12] */ PACK( 1, 0 ), /* MDRP[13] */ PACK( 1, 0 ), /* MDRP[14] */ PACK( 1, 0 ), /* MDRP[15] */ PACK( 1, 0 ), /* 0xD0 */ /* MDRP[16] */ PACK( 1, 0 ), /* MDRP[17] */ PACK( 1, 0 ), /* MDRP[18] */ PACK( 1, 0 ), /* MDRP[19] */ PACK( 1, 0 ), /* MDRP[20] */ PACK( 1, 0 ), /* MDRP[21] */ PACK( 1, 0 ), /* MDRP[22] */ PACK( 1, 0 ), /* MDRP[23] */ PACK( 1, 0 ), /* MDRP[24] */ PACK( 1, 0 ), /* MDRP[25] */ PACK( 1, 0 ), /* MDRP[26] */ PACK( 1, 0 ), /* MDRP[27] */ PACK( 1, 0 ), /* MDRP[28] */ PACK( 1, 0 ), /* MDRP[29] */ PACK( 1, 0 ), /* MDRP[30] */ PACK( 1, 0 ), /* MDRP[31] */ PACK( 1, 0 ), /* 0xE0 */ /* MIRP[00] */ PACK( 2, 0 ), /* MIRP[01] */ PACK( 2, 0 ), /* MIRP[02] */ PACK( 2, 0 ), /* MIRP[03] */ PACK( 2, 0 ), /* MIRP[04] */ PACK( 2, 0 ), /* MIRP[05] */ PACK( 2, 0 ), /* MIRP[06] */ PACK( 2, 0 ), /* MIRP[07] */ PACK( 2, 0 ), /* MIRP[08] */ PACK( 2, 0 ), /* MIRP[09] */ PACK( 2, 0 ), /* MIRP[10] */ PACK( 2, 0 ), /* MIRP[11] */ PACK( 2, 0 ), /* MIRP[12] */ PACK( 2, 0 ), /* MIRP[13] */ PACK( 2, 0 ), /* MIRP[14] */ PACK( 2, 0 ), /* MIRP[15] */ PACK( 2, 0 ), /* 0xF0 */ /* MIRP[16] */ PACK( 2, 0 ), /* MIRP[17] */ PACK( 2, 0 ), /* MIRP[18] */ PACK( 2, 0 ), /* MIRP[19] */ PACK( 2, 0 ), /* MIRP[20] */ PACK( 2, 0 ), /* MIRP[21] */ PACK( 2, 0 ), /* MIRP[22] */ PACK( 2, 0 ), /* MIRP[23] */ PACK( 2, 0 ), /* MIRP[24] */ PACK( 2, 0 ), /* MIRP[25] */ PACK( 2, 0 ), /* MIRP[26] */ PACK( 2, 0 ), /* MIRP[27] */ PACK( 2, 0 ), /* MIRP[28] */ PACK( 2, 0 ), /* MIRP[29] */ PACK( 2, 0 ), /* MIRP[30] */ PACK( 2, 0 ), /* MIRP[31] */ PACK( 2, 0 ) }; #ifdef FT_DEBUG_LEVEL_TRACE /* the first hex digit gives the length of the opcode name; the space */ /* after the digit is here just to increase readability of the source */ /* code */ static const char* const opcode_name[256] = { /* 0x00 */ "8 SVTCA[y]", "8 SVTCA[x]", "9 SPVTCA[y]", "9 SPVTCA[x]", "9 SFVTCA[y]", "9 SFVTCA[x]", "9 SPVTL[||]", "8 SPVTL[+]", "9 SFVTL[||]", "8 SFVTL[+]", "5 SPVFS", "5 SFVFS", "3 GPV", "3 GFV", "6 SFVTPV", "5 ISECT", /* 0x10 */ "4 SRP0", "4 SRP1", "4 SRP2", "4 SZP0", "4 SZP1", "4 SZP2", "4 SZPS", "5 SLOOP", "3 RTG", "4 RTHG", "3 SMD", "4 ELSE", "4 JMPR", "6 SCVTCI", "5 SSWCI", "3 SSW", /* 0x20 */ "3 DUP", "3 POP", "5 CLEAR", "4 SWAP", "5 DEPTH", "6 CINDEX", "6 MINDEX", "8 ALIGNPTS", "7 INS_$28", "3 UTP", "8 LOOPCALL", "4 CALL", "4 FDEF", "4 ENDF", "6 MDAP[]", "9 MDAP[rnd]", /* 0x30 */ "6 IUP[y]", "6 IUP[x]", "8 SHP[rp2]", "8 SHP[rp1]", "8 SHC[rp2]", "8 SHC[rp1]", "8 SHZ[rp2]", "8 SHZ[rp1]", "5 SHPIX", "2 IP", "7 MSIRP[]", "A MSIRP[rp0]", "7 ALIGNRP", "4 RTDG", "6 MIAP[]", "9 MIAP[rnd]", /* 0x40 */ "6 NPUSHB", "6 NPUSHW", "2 WS", "2 RS", "5 WCVTP", "4 RCVT", "8 GC[curr]", "8 GC[orig]", "4 SCFS", "8 MD[curr]", "8 MD[orig]", "5 MPPEM", "3 MPS", "6 FLIPON", "7 FLIPOFF", "5 DEBUG", /* 0x50 */ "2 LT", "4 LTEQ", "2 GT", "4 GTEQ", "2 EQ", "3 NEQ", "3 ODD", "4 EVEN", "2 IF", "3 EIF", "3 AND", "2 OR", "3 NOT", "7 DELTAP1", "3 SDB", "3 SDS", /* 0x60 */ "3 ADD", "3 SUB", "3 DIV", "3 MUL", "3 ABS", "3 NEG", "5 FLOOR", "7 CEILING", "8 ROUND[G]", "8 ROUND[B]", "8 ROUND[W]", "7 ROUND[]", "9 NROUND[G]", "9 NROUND[B]", "9 NROUND[W]", "8 NROUND[]", /* 0x70 */ "5 WCVTF", "7 DELTAP2", "7 DELTAP3", "7 DELTAC1", "7 DELTAC2", "7 DELTAC3", "6 SROUND", "8 S45ROUND", "4 JROT", "4 JROF", "4 ROFF", "7 INS_$7B", "4 RUTG", "4 RDTG", "5 SANGW", "2 AA", /* 0x80 */ "6 FLIPPT", "8 FLIPRGON", "9 FLIPRGOFF", "7 INS_$83", "7 INS_$84", "8 SCANCTRL", "A SDPVTL[||]", "9 SDPVTL[+]", "7 GETINFO", "4 IDEF", "4 ROLL", "3 MAX", "3 MIN", "8 SCANTYPE", "8 INSTCTRL", "7 INS_$8F", /* 0x90 */ "7 INS_$90", #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT "C GETVARIATION", "7 GETDATA", #else "7 INS_$91", "7 INS_$92", #endif "7 INS_$93", "7 INS_$94", "7 INS_$95", "7 INS_$96", "7 INS_$97", "7 INS_$98", "7 INS_$99", "7 INS_$9A", "7 INS_$9B", "7 INS_$9C", "7 INS_$9D", "7 INS_$9E", "7 INS_$9F", /* 0xA0 */ "7 INS_$A0", "7 INS_$A1", "7 INS_$A2", "7 INS_$A3", "7 INS_$A4", "7 INS_$A5", "7 INS_$A6", "7 INS_$A7", "7 INS_$A8", "7 INS_$A9", "7 INS_$AA", "7 INS_$AB", "7 INS_$AC", "7 INS_$AD", "7 INS_$AE", "7 INS_$AF", /* 0xB0 */ "8 PUSHB[0]", "8 PUSHB[1]", "8 PUSHB[2]", "8 PUSHB[3]", "8 PUSHB[4]", "8 PUSHB[5]", "8 PUSHB[6]", "8 PUSHB[7]", "8 PUSHW[0]", "8 PUSHW[1]", "8 PUSHW[2]", "8 PUSHW[3]", "8 PUSHW[4]", "8 PUSHW[5]", "8 PUSHW[6]", "8 PUSHW[7]", /* 0xC0 */ "7 MDRP[G]", "7 MDRP[B]", "7 MDRP[W]", "6 MDRP[]", "8 MDRP[rG]", "8 MDRP[rB]", "8 MDRP[rW]", "7 MDRP[r]", "8 MDRP[mG]", "8 MDRP[mB]", "8 MDRP[mW]", "7 MDRP[m]", "9 MDRP[mrG]", "9 MDRP[mrB]", "9 MDRP[mrW]", "8 MDRP[mr]", /* 0xD0 */ "8 MDRP[pG]", "8 MDRP[pB]", "8 MDRP[pW]", "7 MDRP[p]", "9 MDRP[prG]", "9 MDRP[prB]", "9 MDRP[prW]", "8 MDRP[pr]", "9 MDRP[pmG]", "9 MDRP[pmB]", "9 MDRP[pmW]", "8 MDRP[pm]", "A MDRP[pmrG]", "A MDRP[pmrB]", "A MDRP[pmrW]", "9 MDRP[pmr]", /* 0xE0 */ "7 MIRP[G]", "7 MIRP[B]", "7 MIRP[W]", "6 MIRP[]", "8 MIRP[rG]", "8 MIRP[rB]", "8 MIRP[rW]", "7 MIRP[r]", "8 MIRP[mG]", "8 MIRP[mB]", "8 MIRP[mW]", "7 MIRP[m]", "9 MIRP[mrG]", "9 MIRP[mrB]", "9 MIRP[mrW]", "8 MIRP[mr]", /* 0xF0 */ "8 MIRP[pG]", "8 MIRP[pB]", "8 MIRP[pW]", "7 MIRP[p]", "9 MIRP[prG]", "9 MIRP[prB]", "9 MIRP[prW]", "8 MIRP[pr]", "9 MIRP[pmG]", "9 MIRP[pmB]", "9 MIRP[pmW]", "8 MIRP[pm]", "A MIRP[pmrG]", "A MIRP[pmrB]", "A MIRP[pmrW]", "9 MIRP[pmr]" }; #endif /* FT_DEBUG_LEVEL_TRACE */ static const FT_Char opcode_length[256] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1,-2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 5, 7, 9, 11,13,15,17, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; #undef PACK #ifndef FT_CONFIG_OPTION_NO_ASSEMBLER #if defined( __arm__ ) && \ ( defined( __thumb2__ ) || !defined( __thumb__ ) ) #define TT_MulFix14 TT_MulFix14_arm static FT_Int32 TT_MulFix14_arm( FT_Int32 a, FT_Int b ) { FT_Int32 t, t2; #if defined( __CC_ARM ) || defined( __ARMCC__ ) __asm { smull t2, t, b, a /* (lo=t2,hi=t) = a*b */ mov a, t, asr #31 /* a = (hi >> 31) */ add a, a, #0x2000 /* a += 0x2000 */ adds t2, t2, a /* t2 += a */ adc t, t, #0 /* t += carry */ mov a, t2, lsr #14 /* a = t2 >> 14 */ orr a, a, t, lsl #18 /* a |= t << 18 */ } #elif defined( __GNUC__ ) __asm__ __volatile__ ( "smull %1, %2, %4, %3\n\t" /* (lo=%1,hi=%2) = a*b */ "mov %0, %2, asr #31\n\t" /* %0 = (hi >> 31) */ #if defined( __clang__ ) && defined( __thumb2__ ) "add.w %0, %0, #0x2000\n\t" /* %0 += 0x2000 */ #else "add %0, %0, #0x2000\n\t" /* %0 += 0x2000 */ #endif "adds %1, %1, %0\n\t" /* %1 += %0 */ "adc %2, %2, #0\n\t" /* %2 += carry */ "mov %0, %1, lsr #14\n\t" /* %0 = %1 >> 16 */ "orr %0, %0, %2, lsl #18\n\t" /* %0 |= %2 << 16 */ : "=r"(a), "=&r"(t2), "=&r"(t) : "r"(a), "r"(b) : "cc" ); #endif return a; } #endif /* __arm__ && ( __thumb2__ || !__thumb__ ) */ #endif /* !FT_CONFIG_OPTION_NO_ASSEMBLER */ #if defined( __GNUC__ ) && \ ( defined( __i386__ ) || defined( __x86_64__ ) ) #define TT_MulFix14 TT_MulFix14_long_long /* Temporarily disable the warning that C90 doesn't support `long long'. */ #if ( __GNUC__ * 100 + __GNUC_MINOR__ ) >= 406 #pragma GCC diagnostic push #endif #pragma GCC diagnostic ignored "-Wlong-long" /* This is declared `noinline' because inlining the function results */ /* in slower code. The `pure' attribute indicates that the result */ /* only depends on the parameters. */ static __attribute__(( noinline )) __attribute__(( pure )) FT_Int32 TT_MulFix14_long_long( FT_Int32 a, FT_Int b ) { long long ret = (long long)a * b; /* The following line assumes that right shifting of signed values */ /* will actually preserve the sign bit. The exact behaviour is */ /* undefined, but this is true on x86 and x86_64. */ long long tmp = ret >> 63; ret += 0x2000 + tmp; return (FT_Int32)( ret >> 14 ); } #if ( __GNUC__ * 100 + __GNUC_MINOR__ ) >= 406 #pragma GCC diagnostic pop #endif #endif /* __GNUC__ && ( __i386__ || __x86_64__ ) */ #ifndef TT_MulFix14 /* Compute (a*b)/2^14 with maximum accuracy and rounding. */ /* This is optimized to be faster than calling FT_MulFix() */ /* for platforms where sizeof(int) == 2. */ static FT_Int32 TT_MulFix14( FT_Int32 a, FT_Int b ) { FT_Int32 sign; FT_UInt32 ah, al, mid, lo, hi; sign = a ^ b; if ( a < 0 ) a = -a; if ( b < 0 ) b = -b; ah = (FT_UInt32)( ( a >> 16 ) & 0xFFFFU ); al = (FT_UInt32)( a & 0xFFFFU ); lo = al * b; mid = ah * b; hi = mid >> 16; mid = ( mid << 16 ) + ( 1 << 13 ); /* rounding */ lo += mid; if ( lo < mid ) hi += 1; mid = ( lo >> 14 ) | ( hi << 18 ); return sign >= 0 ? (FT_Int32)mid : -(FT_Int32)mid; } #endif /* !TT_MulFix14 */ #if defined( __GNUC__ ) && \ ( defined( __i386__ ) || \ defined( __x86_64__ ) || \ defined( __arm__ ) ) #define TT_DotFix14 TT_DotFix14_long_long #if ( __GNUC__ * 100 + __GNUC_MINOR__ ) >= 406 #pragma GCC diagnostic push #endif #pragma GCC diagnostic ignored "-Wlong-long" static __attribute__(( pure )) FT_Int32 TT_DotFix14_long_long( FT_Int32 ax, FT_Int32 ay, FT_Int bx, FT_Int by ) { /* Temporarily disable the warning that C90 doesn't support */ /* `long long'. */ long long temp1 = (long long)ax * bx; long long temp2 = (long long)ay * by; temp1 += temp2; temp2 = temp1 >> 63; temp1 += 0x2000 + temp2; return (FT_Int32)( temp1 >> 14 ); } #if ( __GNUC__ * 100 + __GNUC_MINOR__ ) >= 406 #pragma GCC diagnostic pop #endif #endif /* __GNUC__ && (__arm__ || __i386__ || __x86_64__) */ #ifndef TT_DotFix14 /* compute (ax*bx+ay*by)/2^14 with maximum accuracy and rounding */ static FT_Int32 TT_DotFix14( FT_Int32 ax, FT_Int32 ay, FT_Int bx, FT_Int by ) { FT_Int32 m, s, hi1, hi2, hi; FT_UInt32 l, lo1, lo2, lo; /* compute ax*bx as 64-bit value */ l = (FT_UInt32)( ( ax & 0xFFFFU ) * bx ); m = ( ax >> 16 ) * bx; lo1 = l + ( (FT_UInt32)m << 16 ); hi1 = ( m >> 16 ) + ( (FT_Int32)l >> 31 ) + ( lo1 < l ); /* compute ay*by as 64-bit value */ l = (FT_UInt32)( ( ay & 0xFFFFU ) * by ); m = ( ay >> 16 ) * by; lo2 = l + ( (FT_UInt32)m << 16 ); hi2 = ( m >> 16 ) + ( (FT_Int32)l >> 31 ) + ( lo2 < l ); /* add them */ lo = lo1 + lo2; hi = hi1 + hi2 + ( lo < lo1 ); /* divide the result by 2^14 with rounding */ s = hi >> 31; l = lo + (FT_UInt32)s; hi += s + ( l < lo ); lo = l; l = lo + 0x2000U; hi += ( l < lo ); return (FT_Int32)( ( (FT_UInt32)hi << 18 ) | ( l >> 14 ) ); } #endif /* TT_DotFix14 */ /************************************************************************** * * @Function: * Current_Ratio * * @Description: * Returns the current aspect ratio scaling factor depending on the * projection vector's state and device resolutions. * * @Return: * The aspect ratio in 16.16 format, always <= 1.0 . */ static FT_Long Current_Ratio( TT_ExecContext exc ) { if ( !exc->tt_metrics.ratio ) { if ( exc->GS.projVector.y == 0 ) exc->tt_metrics.ratio = exc->tt_metrics.x_ratio; else if ( exc->GS.projVector.x == 0 ) exc->tt_metrics.ratio = exc->tt_metrics.y_ratio; else { FT_F26Dot6 x, y; x = TT_MulFix14( exc->tt_metrics.x_ratio, exc->GS.projVector.x ); y = TT_MulFix14( exc->tt_metrics.y_ratio, exc->GS.projVector.y ); exc->tt_metrics.ratio = FT_Hypot( x, y ); } } return exc->tt_metrics.ratio; } FT_CALLBACK_DEF( FT_Long ) Current_Ppem( TT_ExecContext exc ) { return exc->tt_metrics.ppem; } FT_CALLBACK_DEF( FT_Long ) Current_Ppem_Stretched( TT_ExecContext exc ) { return FT_MulFix( exc->tt_metrics.ppem, Current_Ratio( exc ) ); } /************************************************************************** * * Functions related to the control value table (CVT). * */ FT_CALLBACK_DEF( FT_F26Dot6 ) Read_CVT( TT_ExecContext exc, FT_ULong idx ) { return exc->cvt[idx]; } FT_CALLBACK_DEF( FT_F26Dot6 ) Read_CVT_Stretched( TT_ExecContext exc, FT_ULong idx ) { return FT_MulFix( exc->cvt[idx], Current_Ratio( exc ) ); } static void Modify_CVT_Check( TT_ExecContext exc ) { /* TT_RunIns sets origCvt and restores cvt to origCvt when done. */ if ( exc->iniRange == tt_coderange_glyph && exc->cvt == exc->origCvt ) { exc->error = Update_Max( exc->memory, &exc->glyfCvtSize, sizeof ( FT_Long ), (void*)&exc->glyfCvt, exc->cvtSize ); if ( exc->error ) return; FT_ARRAY_COPY( exc->glyfCvt, exc->cvt, exc->glyfCvtSize ); exc->cvt = exc->glyfCvt; } } FT_CALLBACK_DEF( void ) Write_CVT( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ) { Modify_CVT_Check( exc ); if ( exc->error ) return; exc->cvt[idx] = value; } FT_CALLBACK_DEF( void ) Write_CVT_Stretched( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ) { Modify_CVT_Check( exc ); if ( exc->error ) return; exc->cvt[idx] = FT_DivFix( value, Current_Ratio( exc ) ); } FT_CALLBACK_DEF( void ) Move_CVT( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ) { Modify_CVT_Check( exc ); if ( exc->error ) return; exc->cvt[idx] = ADD_LONG( exc->cvt[idx], value ); } FT_CALLBACK_DEF( void ) Move_CVT_Stretched( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ) { Modify_CVT_Check( exc ); if ( exc->error ) return; exc->cvt[idx] = ADD_LONG( exc->cvt[idx], FT_DivFix( value, Current_Ratio( exc ) ) ); } /************************************************************************** * * @Function: * GetShortIns * * @Description: * Returns a short integer taken from the instruction stream at * address IP. * * @Return: * Short read at code[IP]. * * @Note: * This one could become a macro. */ static FT_Short GetShortIns( TT_ExecContext exc ) { /* Reading a byte stream so there is no endianness (DaveP) */ exc->IP += 2; return (FT_Short)( ( exc->code[exc->IP - 2] << 8 ) + exc->code[exc->IP - 1] ); } /************************************************************************** * * @Function: * Ins_Goto_CodeRange * * @Description: * Goes to a certain code range in the instruction stream. * * @Input: * aRange :: * The index of the code range. * * aIP :: * The new IP address in the code range. * * @Return: * SUCCESS or FAILURE. */ static FT_Bool Ins_Goto_CodeRange( TT_ExecContext exc, FT_Int aRange, FT_Long aIP ) { TT_CodeRange* range; if ( aRange < 1 || aRange > 3 ) { exc->error = FT_THROW( Bad_Argument ); return FAILURE; } range = &exc->codeRangeTable[aRange - 1]; if ( !range->base ) /* invalid coderange */ { exc->error = FT_THROW( Invalid_CodeRange ); return FAILURE; } /* NOTE: Because the last instruction of a program may be a CALL */ /* which will return to the first byte *after* the code */ /* range, we test for aIP <= Size, instead of aIP < Size. */ if ( aIP > range->size ) { exc->error = FT_THROW( Code_Overflow ); return FAILURE; } exc->code = range->base; exc->codeSize = range->size; exc->IP = aIP; exc->curRange = aRange; return SUCCESS; } /* * * Apple's TrueType specification at * * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM02/Chap2.html#order * * gives the following order of operations in instructions that move * points. * * - check single width cut-in (MIRP, MDRP) * * - check control value cut-in (MIRP, MIAP) * * - apply engine compensation (MIRP, MDRP) * * - round distance (MIRP, MDRP) or value (MIAP, MDAP) * * - check minimum distance (MIRP,MDRP) * * - move point (MIRP, MDRP, MIAP, MSIRP, MDAP) * * For rounding instructions, engine compensation happens before rounding. * */ /************************************************************************** * * @Function: * Direct_Move * * @Description: * Moves a point by a given distance along the freedom vector. The * point will be `touched'. * * @Input: * point :: * The index of the point to move. * * distance :: * The distance to apply. * * @InOut: * zone :: * The affected glyph zone. * * @Note: * See `ttinterp.h' for details on backward compatibility mode. * `Touches' the point. */ static void Direct_Move( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { FT_F26Dot6 v; v = exc->GS.freeVector.x; if ( v != 0 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && ( !exc->ignore_x_mode || ( exc->sph_tweak_flags & SPH_TWEAK_ALLOW_X_DMOVE ) ) ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, FT_MulDiv( distance, v, exc->F_dot_P ) ); else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* Exception to the post-IUP curfew: Allow the x component of */ /* diagonal moves, but only post-IUP. DejaVu tries to adjust */ /* diagonal stems like on `Z' and `z' post-IUP. */ if ( SUBPIXEL_HINTING_MINIMAL && !exc->backward_compatibility ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, FT_MulDiv( distance, v, exc->F_dot_P ) ); else #endif if ( NO_SUBPIXEL_HINTING ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, FT_MulDiv( distance, v, exc->F_dot_P ) ); zone->tags[point] |= FT_CURVE_TAG_TOUCH_X; } v = exc->GS.freeVector.y; if ( v != 0 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( !( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) ) #endif zone->cur[point].y = ADD_LONG( zone->cur[point].y, FT_MulDiv( distance, v, exc->F_dot_P ) ); zone->tags[point] |= FT_CURVE_TAG_TOUCH_Y; } } /************************************************************************** * * @Function: * Direct_Move_Orig * * @Description: * Moves the *original* position of a point by a given distance along * the freedom vector. Obviously, the point will not be `touched'. * * @Input: * point :: * The index of the point to move. * * distance :: * The distance to apply. * * @InOut: * zone :: * The affected glyph zone. */ static void Direct_Move_Orig( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { FT_F26Dot6 v; v = exc->GS.freeVector.x; if ( v != 0 ) zone->org[point].x = ADD_LONG( zone->org[point].x, FT_MulDiv( distance, v, exc->F_dot_P ) ); v = exc->GS.freeVector.y; if ( v != 0 ) zone->org[point].y = ADD_LONG( zone->org[point].y, FT_MulDiv( distance, v, exc->F_dot_P ) ); } /************************************************************************** * * Special versions of Direct_Move() * * The following versions are used whenever both vectors are both * along one of the coordinate unit vectors, i.e. in 90% of the cases. * See `ttinterp.h' for details on backward compatibility mode. * */ static void Direct_Move_X( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && !exc->ignore_x_mode ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, distance ); else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( SUBPIXEL_HINTING_MINIMAL && !exc->backward_compatibility ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, distance ); else #endif if ( NO_SUBPIXEL_HINTING ) zone->cur[point].x = ADD_LONG( zone->cur[point].x, distance ); zone->tags[point] |= FT_CURVE_TAG_TOUCH_X; } static void Direct_Move_Y( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { FT_UNUSED( exc ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( !( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) ) #endif zone->cur[point].y = ADD_LONG( zone->cur[point].y, distance ); zone->tags[point] |= FT_CURVE_TAG_TOUCH_Y; } /************************************************************************** * * Special versions of Direct_Move_Orig() * * The following versions are used whenever both vectors are both * along one of the coordinate unit vectors, i.e. in 90% of the cases. * */ static void Direct_Move_Orig_X( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { FT_UNUSED( exc ); zone->org[point].x = ADD_LONG( zone->org[point].x, distance ); } static void Direct_Move_Orig_Y( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ) { FT_UNUSED( exc ); zone->org[point].y = ADD_LONG( zone->org[point].y, distance ); } /************************************************************************** * * @Function: * Round_None * * @Description: * Does not round, but adds engine compensation. * * @Input: * distance :: * The distance (not) to round. * * color :: * The engine compensation color. * * @Return: * The compensated distance. */ static FT_F26Dot6 Round_None( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = ADD_LONG( distance, compensation ); if ( val < 0 ) val = 0; } else { val = SUB_LONG( distance, compensation ); if ( val > 0 ) val = 0; } return val; } /************************************************************************** * * @Function: * Round_To_Grid * * @Description: * Rounds value to grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. */ static FT_F26Dot6 Round_To_Grid( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = FT_PIX_ROUND_LONG( ADD_LONG( distance, compensation ) ); if ( val < 0 ) val = 0; } else { val = NEG_LONG( FT_PIX_ROUND_LONG( SUB_LONG( compensation, distance ) ) ); if ( val > 0 ) val = 0; } return val; } /************************************************************************** * * @Function: * Round_To_Half_Grid * * @Description: * Rounds value to half grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. */ static FT_F26Dot6 Round_To_Half_Grid( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = ADD_LONG( FT_PIX_FLOOR( ADD_LONG( distance, compensation ) ), 32 ); if ( val < 0 ) val = 32; } else { val = NEG_LONG( ADD_LONG( FT_PIX_FLOOR( SUB_LONG( compensation, distance ) ), 32 ) ); if ( val > 0 ) val = -32; } return val; } /************************************************************************** * * @Function: * Round_Down_To_Grid * * @Description: * Rounds value down to grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. */ static FT_F26Dot6 Round_Down_To_Grid( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = FT_PIX_FLOOR( ADD_LONG( distance, compensation ) ); if ( val < 0 ) val = 0; } else { val = NEG_LONG( FT_PIX_FLOOR( SUB_LONG( compensation, distance ) ) ); if ( val > 0 ) val = 0; } return val; } /************************************************************************** * * @Function: * Round_Up_To_Grid * * @Description: * Rounds value up to grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. */ static FT_F26Dot6 Round_Up_To_Grid( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = FT_PIX_CEIL_LONG( ADD_LONG( distance, compensation ) ); if ( val < 0 ) val = 0; } else { val = NEG_LONG( FT_PIX_CEIL_LONG( SUB_LONG( compensation, distance ) ) ); if ( val > 0 ) val = 0; } return val; } /************************************************************************** * * @Function: * Round_To_Double_Grid * * @Description: * Rounds value to double grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. */ static FT_F26Dot6 Round_To_Double_Grid( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = FT_PAD_ROUND_LONG( ADD_LONG( distance, compensation ), 32 ); if ( val < 0 ) val = 0; } else { val = NEG_LONG( FT_PAD_ROUND_LONG( SUB_LONG( compensation, distance ), 32 ) ); if ( val > 0 ) val = 0; } return val; } /************************************************************************** * * @Function: * Round_Super * * @Description: * Super-rounds value to grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. * * @Note: * The TrueType specification says very little about the relationship * between rounding and engine compensation. However, it seems from * the description of super round that we should add the compensation * before rounding. */ static FT_F26Dot6 Round_Super( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = ADD_LONG( distance, exc->threshold - exc->phase + compensation ) & -exc->period; val = ADD_LONG( val, exc->phase ); if ( val < 0 ) val = exc->phase; } else { val = NEG_LONG( SUB_LONG( exc->threshold - exc->phase + compensation, distance ) & -exc->period ); val = SUB_LONG( val, exc->phase ); if ( val > 0 ) val = -exc->phase; } return val; } /************************************************************************** * * @Function: * Round_Super_45 * * @Description: * Super-rounds value to grid after adding engine compensation. * * @Input: * distance :: * The distance to round. * * color :: * The engine compensation color. * * @Return: * Rounded distance. * * @Note: * There is a separate function for Round_Super_45() as we may need * greater precision. */ static FT_F26Dot6 Round_Super_45( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ) { FT_F26Dot6 compensation = exc->tt_metrics.compensations[color]; FT_F26Dot6 val; if ( distance >= 0 ) { val = ( ADD_LONG( distance, exc->threshold - exc->phase + compensation ) / exc->period ) * exc->period; val = ADD_LONG( val, exc->phase ); if ( val < 0 ) val = exc->phase; } else { val = NEG_LONG( ( SUB_LONG( exc->threshold - exc->phase + compensation, distance ) / exc->period ) * exc->period ); val = SUB_LONG( val, exc->phase ); if ( val > 0 ) val = -exc->phase; } return val; } /************************************************************************** * * @Function: * Compute_Round * * @Description: * Sets the rounding mode. * * @Input: * round_mode :: * The rounding mode to be used. */ static void Compute_Round( TT_ExecContext exc, FT_Byte round_mode ) { switch ( round_mode ) { case TT_Round_Off: exc->func_round = (TT_Round_Func)Round_None; break; case TT_Round_To_Grid: exc->func_round = (TT_Round_Func)Round_To_Grid; break; case TT_Round_Up_To_Grid: exc->func_round = (TT_Round_Func)Round_Up_To_Grid; break; case TT_Round_Down_To_Grid: exc->func_round = (TT_Round_Func)Round_Down_To_Grid; break; case TT_Round_To_Half_Grid: exc->func_round = (TT_Round_Func)Round_To_Half_Grid; break; case TT_Round_To_Double_Grid: exc->func_round = (TT_Round_Func)Round_To_Double_Grid; break; case TT_Round_Super: exc->func_round = (TT_Round_Func)Round_Super; break; case TT_Round_Super_45: exc->func_round = (TT_Round_Func)Round_Super_45; break; } } /************************************************************************** * * @Function: * SetSuperRound * * @Description: * Sets Super Round parameters. * * @Input: * GridPeriod :: * The grid period. * * selector :: * The SROUND opcode. */ static void SetSuperRound( TT_ExecContext exc, FT_F2Dot14 GridPeriod, FT_Long selector ) { switch ( (FT_Int)( selector & 0xC0 ) ) { case 0: exc->period = GridPeriod / 2; break; case 0x40: exc->period = GridPeriod; break; case 0x80: exc->period = GridPeriod * 2; break; /* This opcode is reserved, but... */ case 0xC0: exc->period = GridPeriod; break; } switch ( (FT_Int)( selector & 0x30 ) ) { case 0: exc->phase = 0; break; case 0x10: exc->phase = exc->period / 4; break; case 0x20: exc->phase = exc->period / 2; break; case 0x30: exc->phase = exc->period * 3 / 4; break; } if ( ( selector & 0x0F ) == 0 ) exc->threshold = exc->period - 1; else exc->threshold = ( (FT_Int)( selector & 0x0F ) - 4 ) * exc->period / 8; /* convert to F26Dot6 format */ exc->period >>= 8; exc->phase >>= 8; exc->threshold >>= 8; } /************************************************************************** * * @Function: * Project * * @Description: * Computes the projection of vector given by (v2-v1) along the * current projection vector. * * @Input: * v1 :: * First input vector. * v2 :: * Second input vector. * * @Return: * The distance in F26dot6 format. */ static FT_F26Dot6 Project( TT_ExecContext exc, FT_Pos dx, FT_Pos dy ) { return TT_DotFix14( dx, dy, exc->GS.projVector.x, exc->GS.projVector.y ); } /************************************************************************** * * @Function: * Dual_Project * * @Description: * Computes the projection of the vector given by (v2-v1) along the * current dual vector. * * @Input: * v1 :: * First input vector. * v2 :: * Second input vector. * * @Return: * The distance in F26dot6 format. */ static FT_F26Dot6 Dual_Project( TT_ExecContext exc, FT_Pos dx, FT_Pos dy ) { return TT_DotFix14( dx, dy, exc->GS.dualVector.x, exc->GS.dualVector.y ); } /************************************************************************** * * @Function: * Project_x * * @Description: * Computes the projection of the vector given by (v2-v1) along the * horizontal axis. * * @Input: * v1 :: * First input vector. * v2 :: * Second input vector. * * @Return: * The distance in F26dot6 format. */ static FT_F26Dot6 Project_x( TT_ExecContext exc, FT_Pos dx, FT_Pos dy ) { FT_UNUSED( exc ); FT_UNUSED( dy ); return dx; } /************************************************************************** * * @Function: * Project_y * * @Description: * Computes the projection of the vector given by (v2-v1) along the * vertical axis. * * @Input: * v1 :: * First input vector. * v2 :: * Second input vector. * * @Return: * The distance in F26dot6 format. */ static FT_F26Dot6 Project_y( TT_ExecContext exc, FT_Pos dx, FT_Pos dy ) { FT_UNUSED( exc ); FT_UNUSED( dx ); return dy; } /************************************************************************** * * @Function: * Compute_Funcs * * @Description: * Computes the projection and movement function pointers according * to the current graphics state. */ static void Compute_Funcs( TT_ExecContext exc ) { if ( exc->GS.freeVector.x == 0x4000 ) exc->F_dot_P = exc->GS.projVector.x; else if ( exc->GS.freeVector.y == 0x4000 ) exc->F_dot_P = exc->GS.projVector.y; else exc->F_dot_P = ( (FT_Long)exc->GS.projVector.x * exc->GS.freeVector.x + (FT_Long)exc->GS.projVector.y * exc->GS.freeVector.y ) >> 14; if ( exc->GS.projVector.x == 0x4000 ) exc->func_project = (TT_Project_Func)Project_x; else if ( exc->GS.projVector.y == 0x4000 ) exc->func_project = (TT_Project_Func)Project_y; else exc->func_project = (TT_Project_Func)Project; if ( exc->GS.dualVector.x == 0x4000 ) exc->func_dualproj = (TT_Project_Func)Project_x; else if ( exc->GS.dualVector.y == 0x4000 ) exc->func_dualproj = (TT_Project_Func)Project_y; else exc->func_dualproj = (TT_Project_Func)Dual_Project; exc->func_move = (TT_Move_Func)Direct_Move; exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig; if ( exc->F_dot_P == 0x4000L ) { if ( exc->GS.freeVector.x == 0x4000 ) { exc->func_move = (TT_Move_Func)Direct_Move_X; exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig_X; } else if ( exc->GS.freeVector.y == 0x4000 ) { exc->func_move = (TT_Move_Func)Direct_Move_Y; exc->func_move_orig = (TT_Move_Func)Direct_Move_Orig_Y; } } /* at small sizes, F_dot_P can become too small, resulting */ /* in overflows and `spikes' in a number of glyphs like `w'. */ if ( FT_ABS( exc->F_dot_P ) < 0x400L ) exc->F_dot_P = 0x4000L; /* Disable cached aspect ratio */ exc->tt_metrics.ratio = 0; } /************************************************************************** * * @Function: * Normalize * * @Description: * Norms a vector. * * @Input: * Vx :: * The horizontal input vector coordinate. * Vy :: * The vertical input vector coordinate. * * @Output: * R :: * The normed unit vector. * * @Return: * Returns FAILURE if a vector parameter is zero. * * @Note: * In case Vx and Vy are both zero, `Normalize' returns SUCCESS, and * R is undefined. */ static FT_Bool Normalize( FT_F26Dot6 Vx, FT_F26Dot6 Vy, FT_UnitVector* R ) { FT_Vector V; if ( Vx == 0 && Vy == 0 ) { /* XXX: UNDOCUMENTED! It seems that it is possible to try */ /* to normalize the vector (0,0). Return immediately. */ return SUCCESS; } V.x = Vx; V.y = Vy; FT_Vector_NormLen( &V ); R->x = (FT_F2Dot14)( V.x / 4 ); R->y = (FT_F2Dot14)( V.y / 4 ); return SUCCESS; } /************************************************************************** * * Here we start with the implementation of the various opcodes. * */ #define ARRAY_BOUND_ERROR \ do \ { \ exc->error = FT_THROW( Invalid_Reference ); \ return; \ } while (0) /************************************************************************** * * MPPEM[]: Measure Pixel Per EM * Opcode range: 0x4B * Stack: --> Euint16 */ static void Ins_MPPEM( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->func_cur_ppem( exc ); } /************************************************************************** * * MPS[]: Measure Point Size * Opcode range: 0x4C * Stack: --> Euint16 */ static void Ins_MPS( TT_ExecContext exc, FT_Long* args ) { if ( NO_SUBPIXEL_HINTING ) { /* Microsoft's GDI bytecode interpreter always returns value 12; */ /* we return the current PPEM value instead. */ args[0] = exc->func_cur_ppem( exc ); } else { /* A possible practical application of the MPS instruction is to */ /* implement optical scaling and similar features, which should be */ /* based on perceptual attributes, thus independent of the */ /* resolution. */ args[0] = exc->pointSize; } } /************************************************************************** * * DUP[]: DUPlicate the stack's top element * Opcode range: 0x20 * Stack: StkElt --> StkElt StkElt */ static void Ins_DUP( FT_Long* args ) { args[1] = args[0]; } /************************************************************************** * * POP[]: POP the stack's top element * Opcode range: 0x21 * Stack: StkElt --> */ static void Ins_POP( void ) { /* nothing to do */ } /************************************************************************** * * CLEAR[]: CLEAR the entire stack * Opcode range: 0x22 * Stack: StkElt... --> */ static void Ins_CLEAR( TT_ExecContext exc ) { exc->new_top = 0; } /************************************************************************** * * SWAP[]: SWAP the stack's top two elements * Opcode range: 0x23 * Stack: 2 * StkElt --> 2 * StkElt */ static void Ins_SWAP( FT_Long* args ) { FT_Long L; L = args[0]; args[0] = args[1]; args[1] = L; } /************************************************************************** * * DEPTH[]: return the stack DEPTH * Opcode range: 0x24 * Stack: --> uint32 */ static void Ins_DEPTH( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->top; } /************************************************************************** * * LT[]: Less Than * Opcode range: 0x50 * Stack: int32? int32? --> bool */ static void Ins_LT( FT_Long* args ) { args[0] = ( args[0] < args[1] ); } /************************************************************************** * * LTEQ[]: Less Than or EQual * Opcode range: 0x51 * Stack: int32? int32? --> bool */ static void Ins_LTEQ( FT_Long* args ) { args[0] = ( args[0] <= args[1] ); } /************************************************************************** * * GT[]: Greater Than * Opcode range: 0x52 * Stack: int32? int32? --> bool */ static void Ins_GT( FT_Long* args ) { args[0] = ( args[0] > args[1] ); } /************************************************************************** * * GTEQ[]: Greater Than or EQual * Opcode range: 0x53 * Stack: int32? int32? --> bool */ static void Ins_GTEQ( FT_Long* args ) { args[0] = ( args[0] >= args[1] ); } /************************************************************************** * * EQ[]: EQual * Opcode range: 0x54 * Stack: StkElt StkElt --> bool */ static void Ins_EQ( FT_Long* args ) { args[0] = ( args[0] == args[1] ); } /************************************************************************** * * NEQ[]: Not EQual * Opcode range: 0x55 * Stack: StkElt StkElt --> bool */ static void Ins_NEQ( FT_Long* args ) { args[0] = ( args[0] != args[1] ); } /************************************************************************** * * ODD[]: Is ODD * Opcode range: 0x56 * Stack: f26.6 --> bool */ static void Ins_ODD( TT_ExecContext exc, FT_Long* args ) { args[0] = ( ( exc->func_round( exc, args[0], 3 ) & 127 ) == 64 ); } /************************************************************************** * * EVEN[]: Is EVEN * Opcode range: 0x57 * Stack: f26.6 --> bool */ static void Ins_EVEN( TT_ExecContext exc, FT_Long* args ) { args[0] = ( ( exc->func_round( exc, args[0], 3 ) & 127 ) == 0 ); } /************************************************************************** * * AND[]: logical AND * Opcode range: 0x5A * Stack: uint32 uint32 --> uint32 */ static void Ins_AND( FT_Long* args ) { args[0] = ( args[0] && args[1] ); } /************************************************************************** * * OR[]: logical OR * Opcode range: 0x5B * Stack: uint32 uint32 --> uint32 */ static void Ins_OR( FT_Long* args ) { args[0] = ( args[0] || args[1] ); } /************************************************************************** * * NOT[]: logical NOT * Opcode range: 0x5C * Stack: StkElt --> uint32 */ static void Ins_NOT( FT_Long* args ) { args[0] = !args[0]; } /************************************************************************** * * ADD[]: ADD * Opcode range: 0x60 * Stack: f26.6 f26.6 --> f26.6 */ static void Ins_ADD( FT_Long* args ) { args[0] = ADD_LONG( args[0], args[1] ); } /************************************************************************** * * SUB[]: SUBtract * Opcode range: 0x61 * Stack: f26.6 f26.6 --> f26.6 */ static void Ins_SUB( FT_Long* args ) { args[0] = SUB_LONG( args[0], args[1] ); } /************************************************************************** * * DIV[]: DIVide * Opcode range: 0x62 * Stack: f26.6 f26.6 --> f26.6 */ static void Ins_DIV( TT_ExecContext exc, FT_Long* args ) { if ( args[1] == 0 ) exc->error = FT_THROW( Divide_By_Zero ); else args[0] = FT_MulDiv_No_Round( args[0], 64L, args[1] ); } /************************************************************************** * * MUL[]: MULtiply * Opcode range: 0x63 * Stack: f26.6 f26.6 --> f26.6 */ static void Ins_MUL( FT_Long* args ) { args[0] = FT_MulDiv( args[0], args[1], 64L ); } /************************************************************************** * * ABS[]: ABSolute value * Opcode range: 0x64 * Stack: f26.6 --> f26.6 */ static void Ins_ABS( FT_Long* args ) { if ( args[0] < 0 ) args[0] = NEG_LONG( args[0] ); } /************************************************************************** * * NEG[]: NEGate * Opcode range: 0x65 * Stack: f26.6 --> f26.6 */ static void Ins_NEG( FT_Long* args ) { args[0] = NEG_LONG( args[0] ); } /************************************************************************** * * FLOOR[]: FLOOR * Opcode range: 0x66 * Stack: f26.6 --> f26.6 */ static void Ins_FLOOR( FT_Long* args ) { args[0] = FT_PIX_FLOOR( args[0] ); } /************************************************************************** * * CEILING[]: CEILING * Opcode range: 0x67 * Stack: f26.6 --> f26.6 */ static void Ins_CEILING( FT_Long* args ) { args[0] = FT_PIX_CEIL_LONG( args[0] ); } /************************************************************************** * * RS[]: Read Store * Opcode range: 0x43 * Stack: uint32 --> uint32 */ static void Ins_RS( TT_ExecContext exc, FT_Long* args ) { FT_ULong I = (FT_ULong)args[0]; if ( BOUNDSL( I, exc->storeSize ) ) { if ( exc->pedantic_hinting ) ARRAY_BOUND_ERROR; else args[0] = 0; } else { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* subpixel hinting - avoid Typeman Dstroke and */ /* IStroke and Vacuform rounds */ if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && ( ( I == 24 && ( exc->face->sph_found_func_flags & ( SPH_FDEF_SPACING_1 | SPH_FDEF_SPACING_2 ) ) ) || ( I == 22 && ( exc->sph_in_func_flags & SPH_FDEF_TYPEMAN_STROKES ) ) || ( I == 8 && ( exc->face->sph_found_func_flags & SPH_FDEF_VACUFORM_ROUND_1 ) && exc->iup_called ) ) ) args[0] = 0; else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ args[0] = exc->storage[I]; } } /************************************************************************** * * WS[]: Write Store * Opcode range: 0x42 * Stack: uint32 uint32 --> */ static void Ins_WS( TT_ExecContext exc, FT_Long* args ) { FT_ULong I = (FT_ULong)args[0]; if ( BOUNDSL( I, exc->storeSize ) ) { if ( exc->pedantic_hinting ) ARRAY_BOUND_ERROR; } else { /* TT_RunIns sets origStorage and restores storage to origStorage */ /* when done. */ if ( exc->iniRange == tt_coderange_glyph && exc->storage == exc->origStorage ) { FT_ULong tmp = (FT_ULong)exc->glyfStoreSize; exc->error = Update_Max( exc->memory, &tmp, sizeof ( FT_Long ), (void*)&exc->glyfStorage, exc->storeSize ); exc->glyfStoreSize = (FT_UShort)tmp; if ( exc->error ) return; FT_ARRAY_COPY( exc->glyfStorage, exc->storage, exc->glyfStoreSize ); exc->storage = exc->glyfStorage; } exc->storage[I] = args[1]; } } /************************************************************************** * * WCVTP[]: Write CVT in Pixel units * Opcode range: 0x44 * Stack: f26.6 uint32 --> */ static void Ins_WCVTP( TT_ExecContext exc, FT_Long* args ) { FT_ULong I = (FT_ULong)args[0]; if ( BOUNDSL( I, exc->cvtSize ) ) { if ( exc->pedantic_hinting ) ARRAY_BOUND_ERROR; } else exc->func_write_cvt( exc, I, args[1] ); } /************************************************************************** * * WCVTF[]: Write CVT in Funits * Opcode range: 0x70 * Stack: uint32 uint32 --> */ static void Ins_WCVTF( TT_ExecContext exc, FT_Long* args ) { FT_ULong I = (FT_ULong)args[0]; if ( BOUNDSL( I, exc->cvtSize ) ) { if ( exc->pedantic_hinting ) ARRAY_BOUND_ERROR; } else exc->cvt[I] = FT_MulFix( args[1], exc->tt_metrics.scale ); } /************************************************************************** * * RCVT[]: Read CVT * Opcode range: 0x45 * Stack: uint32 --> f26.6 */ static void Ins_RCVT( TT_ExecContext exc, FT_Long* args ) { FT_ULong I = (FT_ULong)args[0]; if ( BOUNDSL( I, exc->cvtSize ) ) { if ( exc->pedantic_hinting ) ARRAY_BOUND_ERROR; else args[0] = 0; } else args[0] = exc->func_read_cvt( exc, I ); } /************************************************************************** * * AA[]: Adjust Angle * Opcode range: 0x7F * Stack: uint32 --> */ static void Ins_AA( void ) { /* intentionally no longer supported */ } /************************************************************************** * * DEBUG[]: DEBUG. Unsupported. * Opcode range: 0x4F * Stack: uint32 --> * * Note: The original instruction pops a value from the stack. */ static void Ins_DEBUG( TT_ExecContext exc ) { exc->error = FT_THROW( Debug_OpCode ); } /************************************************************************** * * ROUND[ab]: ROUND value * Opcode range: 0x68-0x6B * Stack: f26.6 --> f26.6 */ static void Ins_ROUND( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->func_round( exc, args[0], exc->opcode & 3 ); } /************************************************************************** * * NROUND[ab]: No ROUNDing of value * Opcode range: 0x6C-0x6F * Stack: f26.6 --> f26.6 */ static void Ins_NROUND( TT_ExecContext exc, FT_Long* args ) { args[0] = Round_None( exc, args[0], exc->opcode & 3 ); } /************************************************************************** * * MAX[]: MAXimum * Opcode range: 0x8B * Stack: int32? int32? --> int32 */ static void Ins_MAX( FT_Long* args ) { if ( args[1] > args[0] ) args[0] = args[1]; } /************************************************************************** * * MIN[]: MINimum * Opcode range: 0x8C * Stack: int32? int32? --> int32 */ static void Ins_MIN( FT_Long* args ) { if ( args[1] < args[0] ) args[0] = args[1]; } /************************************************************************** * * MINDEX[]: Move INDEXed element * Opcode range: 0x26 * Stack: int32? --> StkElt */ static void Ins_MINDEX( TT_ExecContext exc, FT_Long* args ) { FT_Long L, K; L = args[0]; if ( L <= 0 || L > exc->args ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); } else { K = exc->stack[exc->args - L]; FT_ARRAY_MOVE( &exc->stack[exc->args - L ], &exc->stack[exc->args - L + 1], ( L - 1 ) ); exc->stack[exc->args - 1] = K; } } /************************************************************************** * * CINDEX[]: Copy INDEXed element * Opcode range: 0x25 * Stack: int32 --> StkElt */ static void Ins_CINDEX( TT_ExecContext exc, FT_Long* args ) { FT_Long L; L = args[0]; if ( L <= 0 || L > exc->args ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); args[0] = 0; } else args[0] = exc->stack[exc->args - L]; } /************************************************************************** * * ROLL[]: ROLL top three elements * Opcode range: 0x8A * Stack: 3 * StkElt --> 3 * StkElt */ static void Ins_ROLL( FT_Long* args ) { FT_Long A, B, C; A = args[2]; B = args[1]; C = args[0]; args[2] = C; args[1] = A; args[0] = B; } /************************************************************************** * * MANAGING THE FLOW OF CONTROL * */ /************************************************************************** * * SLOOP[]: Set LOOP variable * Opcode range: 0x17 * Stack: int32? --> */ static void Ins_SLOOP( TT_ExecContext exc, FT_Long* args ) { if ( args[0] < 0 ) exc->error = FT_THROW( Bad_Argument ); else { /* we heuristically limit the number of loops to 16 bits */ exc->GS.loop = args[0] > 0xFFFFL ? 0xFFFFL : args[0]; } } static FT_Bool SkipCode( TT_ExecContext exc ) { exc->IP += exc->length; if ( exc->IP < exc->codeSize ) { exc->opcode = exc->code[exc->IP]; exc->length = opcode_length[exc->opcode]; if ( exc->length < 0 ) { if ( exc->IP + 1 >= exc->codeSize ) goto Fail_Overflow; exc->length = 2 - exc->length * exc->code[exc->IP + 1]; } if ( exc->IP + exc->length <= exc->codeSize ) return SUCCESS; } Fail_Overflow: exc->error = FT_THROW( Code_Overflow ); return FAILURE; } /************************************************************************** * * IF[]: IF test * Opcode range: 0x58 * Stack: StkElt --> */ static void Ins_IF( TT_ExecContext exc, FT_Long* args ) { FT_Int nIfs; FT_Bool Out; if ( args[0] != 0 ) return; nIfs = 1; Out = 0; do { if ( SkipCode( exc ) == FAILURE ) return; switch ( exc->opcode ) { case 0x58: /* IF */ nIfs++; break; case 0x1B: /* ELSE */ Out = FT_BOOL( nIfs == 1 ); break; case 0x59: /* EIF */ nIfs--; Out = FT_BOOL( nIfs == 0 ); break; } } while ( Out == 0 ); } /************************************************************************** * * ELSE[]: ELSE * Opcode range: 0x1B * Stack: --> */ static void Ins_ELSE( TT_ExecContext exc ) { FT_Int nIfs; nIfs = 1; do { if ( SkipCode( exc ) == FAILURE ) return; switch ( exc->opcode ) { case 0x58: /* IF */ nIfs++; break; case 0x59: /* EIF */ nIfs--; break; } } while ( nIfs != 0 ); } /************************************************************************** * * EIF[]: End IF * Opcode range: 0x59 * Stack: --> */ static void Ins_EIF( void ) { /* nothing to do */ } /************************************************************************** * * JMPR[]: JuMP Relative * Opcode range: 0x1C * Stack: int32 --> */ static void Ins_JMPR( TT_ExecContext exc, FT_Long* args ) { if ( args[0] == 0 && exc->args == 0 ) { exc->error = FT_THROW( Bad_Argument ); return; } exc->IP = ADD_LONG( exc->IP, args[0] ); if ( exc->IP < 0 || ( exc->callTop > 0 && exc->IP > exc->callStack[exc->callTop - 1].Def->end ) ) { exc->error = FT_THROW( Bad_Argument ); return; } exc->step_ins = FALSE; if ( args[0] < 0 ) { if ( ++exc->neg_jump_counter > exc->neg_jump_counter_max ) exc->error = FT_THROW( Execution_Too_Long ); } } /************************************************************************** * * JROT[]: Jump Relative On True * Opcode range: 0x78 * Stack: StkElt int32 --> */ static void Ins_JROT( TT_ExecContext exc, FT_Long* args ) { if ( args[1] != 0 ) Ins_JMPR( exc, args ); } /************************************************************************** * * JROF[]: Jump Relative On False * Opcode range: 0x79 * Stack: StkElt int32 --> */ static void Ins_JROF( TT_ExecContext exc, FT_Long* args ) { if ( args[1] == 0 ) Ins_JMPR( exc, args ); } /************************************************************************** * * DEFINING AND USING FUNCTIONS AND INSTRUCTIONS * */ /************************************************************************** * * FDEF[]: Function DEFinition * Opcode range: 0x2C * Stack: uint32 --> */ static void Ins_FDEF( TT_ExecContext exc, FT_Long* args ) { FT_ULong n; TT_DefRecord* rec; TT_DefRecord* limit; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* arguments to opcodes are skipped by `SKIP_Code' */ FT_Byte opcode_pattern[9][12] = { /* #0 inline delta function 1 */ { 0x4B, /* PPEM */ 0x53, /* GTEQ */ 0x23, /* SWAP */ 0x4B, /* PPEM */ 0x51, /* LTEQ */ 0x5A, /* AND */ 0x58, /* IF */ 0x38, /* SHPIX */ 0x1B, /* ELSE */ 0x21, /* POP */ 0x21, /* POP */ 0x59 /* EIF */ }, /* #1 inline delta function 2 */ { 0x4B, /* PPEM */ 0x54, /* EQ */ 0x58, /* IF */ 0x38, /* SHPIX */ 0x1B, /* ELSE */ 0x21, /* POP */ 0x21, /* POP */ 0x59 /* EIF */ }, /* #2 diagonal stroke function */ { 0x20, /* DUP */ 0x20, /* DUP */ 0xB0, /* PUSHB_1 */ /* 1 */ 0x60, /* ADD */ 0x46, /* GC_cur */ 0xB0, /* PUSHB_1 */ /* 64 */ 0x23, /* SWAP */ 0x42 /* WS */ }, /* #3 VacuFormRound function */ { 0x45, /* RCVT */ 0x23, /* SWAP */ 0x46, /* GC_cur */ 0x60, /* ADD */ 0x20, /* DUP */ 0xB0 /* PUSHB_1 */ /* 38 */ }, /* #4 TTFautohint bytecode (old) */ { 0x20, /* DUP */ 0x64, /* ABS */ 0xB0, /* PUSHB_1 */ /* 32 */ 0x60, /* ADD */ 0x66, /* FLOOR */ 0x23, /* SWAP */ 0xB0 /* PUSHB_1 */ }, /* #5 spacing function 1 */ { 0x01, /* SVTCA_x */ 0xB0, /* PUSHB_1 */ /* 24 */ 0x43, /* RS */ 0x58 /* IF */ }, /* #6 spacing function 2 */ { 0x01, /* SVTCA_x */ 0x18, /* RTG */ 0xB0, /* PUSHB_1 */ /* 24 */ 0x43, /* RS */ 0x58 /* IF */ }, /* #7 TypeMan Talk DiagEndCtrl function */ { 0x01, /* SVTCA_x */ 0x20, /* DUP */ 0xB0, /* PUSHB_1 */ /* 3 */ 0x25, /* CINDEX */ }, /* #8 TypeMan Talk Align */ { 0x06, /* SPVTL */ 0x7D, /* RDTG */ }, }; FT_UShort opcode_patterns = 9; FT_UShort opcode_pointer[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; FT_UShort opcode_size[9] = { 12, 8, 8, 6, 7, 4, 5, 4, 2 }; FT_UShort i; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /* FDEF is only allowed in `prep' or `fpgm' */ if ( exc->iniRange == tt_coderange_glyph ) { exc->error = FT_THROW( DEF_In_Glyf_Bytecode ); return; } /* some font programs are broken enough to redefine functions! */ /* We will then parse the current table. */ rec = exc->FDefs; limit = FT_OFFSET( rec, exc->numFDefs ); n = (FT_ULong)args[0]; for ( ; rec < limit; rec++ ) { if ( rec->opc == n ) break; } if ( rec == limit ) { /* check that there is enough room for new functions */ if ( exc->numFDefs >= exc->maxFDefs ) { exc->error = FT_THROW( Too_Many_Function_Defs ); return; } exc->numFDefs++; } /* Although FDEF takes unsigned 32-bit integer, */ /* func # must be within unsigned 16-bit integer */ if ( n > 0xFFFFU ) { exc->error = FT_THROW( Too_Many_Function_Defs ); return; } rec->range = exc->curRange; rec->opc = (FT_UInt16)n; rec->start = exc->IP + 1; rec->active = TRUE; rec->inline_delta = FALSE; rec->sph_fdef_flags = 0x0000; if ( n > exc->maxFunc ) exc->maxFunc = (FT_UInt16)n; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* We don't know for sure these are typeman functions, */ /* however they are only active when RS 22 is called */ if ( n >= 64 && n <= 66 ) rec->sph_fdef_flags |= SPH_FDEF_TYPEMAN_STROKES; #endif /* Now skip the whole function definition. */ /* We don't allow nested IDEFS & FDEFs. */ while ( SkipCode( exc ) == SUCCESS ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY ) { for ( i = 0; i < opcode_patterns; i++ ) { if ( opcode_pointer[i] < opcode_size[i] && exc->opcode == opcode_pattern[i][opcode_pointer[i]] ) { opcode_pointer[i] += 1; if ( opcode_pointer[i] == opcode_size[i] ) { FT_TRACE6(( "sph: Function %d, opcode ptrn: %ld, %s %s\n", i, n, exc->face->root.family_name, exc->face->root.style_name )); switch ( i ) { case 0: rec->sph_fdef_flags |= SPH_FDEF_INLINE_DELTA_1; exc->face->sph_found_func_flags |= SPH_FDEF_INLINE_DELTA_1; break; case 1: rec->sph_fdef_flags |= SPH_FDEF_INLINE_DELTA_2; exc->face->sph_found_func_flags |= SPH_FDEF_INLINE_DELTA_2; break; case 2: switch ( n ) { /* needs to be implemented still */ case 58: rec->sph_fdef_flags |= SPH_FDEF_DIAGONAL_STROKE; exc->face->sph_found_func_flags |= SPH_FDEF_DIAGONAL_STROKE; } break; case 3: switch ( n ) { case 0: rec->sph_fdef_flags |= SPH_FDEF_VACUFORM_ROUND_1; exc->face->sph_found_func_flags |= SPH_FDEF_VACUFORM_ROUND_1; } break; case 4: /* probably not necessary to detect anymore */ rec->sph_fdef_flags |= SPH_FDEF_TTFAUTOHINT_1; exc->face->sph_found_func_flags |= SPH_FDEF_TTFAUTOHINT_1; break; case 5: switch ( n ) { case 0: case 1: case 2: case 4: case 7: case 8: rec->sph_fdef_flags |= SPH_FDEF_SPACING_1; exc->face->sph_found_func_flags |= SPH_FDEF_SPACING_1; } break; case 6: switch ( n ) { case 0: case 1: case 2: case 4: case 7: case 8: rec->sph_fdef_flags |= SPH_FDEF_SPACING_2; exc->face->sph_found_func_flags |= SPH_FDEF_SPACING_2; } break; case 7: rec->sph_fdef_flags |= SPH_FDEF_TYPEMAN_DIAGENDCTRL; exc->face->sph_found_func_flags |= SPH_FDEF_TYPEMAN_DIAGENDCTRL; break; case 8: #if 0 rec->sph_fdef_flags |= SPH_FDEF_TYPEMAN_DIAGENDCTRL; exc->face->sph_found_func_flags |= SPH_FDEF_TYPEMAN_DIAGENDCTRL; #endif break; } opcode_pointer[i] = 0; } } else opcode_pointer[i] = 0; } /* Set sph_compatibility_mode only when deltas are detected */ exc->face->sph_compatibility_mode = ( ( exc->face->sph_found_func_flags & SPH_FDEF_INLINE_DELTA_1 ) | ( exc->face->sph_found_func_flags & SPH_FDEF_INLINE_DELTA_2 ) ); } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ switch ( exc->opcode ) { case 0x89: /* IDEF */ case 0x2C: /* FDEF */ exc->error = FT_THROW( Nested_DEFS ); return; case 0x2D: /* ENDF */ rec->end = exc->IP; return; } } } /************************************************************************** * * ENDF[]: END Function definition * Opcode range: 0x2D * Stack: --> */ static void Ins_ENDF( TT_ExecContext exc ) { TT_CallRec* pRec; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY exc->sph_in_func_flags = 0x0000; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ if ( exc->callTop <= 0 ) /* We encountered an ENDF without a call */ { exc->error = FT_THROW( ENDF_In_Exec_Stream ); return; } exc->callTop--; pRec = &exc->callStack[exc->callTop]; pRec->Cur_Count--; exc->step_ins = FALSE; if ( pRec->Cur_Count > 0 ) { exc->callTop++; exc->IP = pRec->Def->start; } else /* Loop through the current function */ Ins_Goto_CodeRange( exc, pRec->Caller_Range, pRec->Caller_IP ); /* Exit the current call frame. */ /* NOTE: If the last instruction of a program is a */ /* CALL or LOOPCALL, the return address is */ /* always out of the code range. This is a */ /* valid address, and it is why we do not test */ /* the result of Ins_Goto_CodeRange() here! */ } /************************************************************************** * * CALL[]: CALL function * Opcode range: 0x2B * Stack: uint32? --> */ static void Ins_CALL( TT_ExecContext exc, FT_Long* args ) { FT_ULong F; TT_CallRec* pCrec; TT_DefRecord* def; /* first of all, check the index */ F = (FT_ULong)args[0]; if ( BOUNDSL( F, exc->maxFunc + 1 ) ) goto Fail; if ( !exc->FDefs ) goto Fail; /* Except for some old Apple fonts, all functions in a TrueType */ /* font are defined in increasing order, starting from 0. This */ /* means that we normally have */ /* */ /* exc->maxFunc+1 == exc->numFDefs */ /* exc->FDefs[n].opc == n for n in 0..exc->maxFunc */ /* */ /* If this isn't true, we need to look up the function table. */ def = exc->FDefs + F; if ( exc->maxFunc + 1 != exc->numFDefs || def->opc != F ) { /* look up the FDefs table */ TT_DefRecord* limit; def = exc->FDefs; limit = def + exc->numFDefs; while ( def < limit && def->opc != F ) def++; if ( def == limit ) goto Fail; } /* check that the function is active */ if ( !def->active ) goto Fail; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && ( ( exc->iup_called && ( exc->sph_tweak_flags & SPH_TWEAK_NO_CALL_AFTER_IUP ) ) || ( def->sph_fdef_flags & SPH_FDEF_VACUFORM_ROUND_1 ) ) ) goto Fail; else exc->sph_in_func_flags = def->sph_fdef_flags; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /* check the call stack */ if ( exc->callTop >= exc->callSize ) { exc->error = FT_THROW( Stack_Overflow ); return; } pCrec = exc->callStack + exc->callTop; pCrec->Caller_Range = exc->curRange; pCrec->Caller_IP = exc->IP + 1; pCrec->Cur_Count = 1; pCrec->Def = def; exc->callTop++; Ins_Goto_CodeRange( exc, def->range, def->start ); exc->step_ins = FALSE; return; Fail: exc->error = FT_THROW( Invalid_Reference ); } /************************************************************************** * * LOOPCALL[]: LOOP and CALL function * Opcode range: 0x2A * Stack: uint32? Eint16? --> */ static void Ins_LOOPCALL( TT_ExecContext exc, FT_Long* args ) { FT_ULong F; TT_CallRec* pCrec; TT_DefRecord* def; /* first of all, check the index */ F = (FT_ULong)args[1]; if ( BOUNDSL( F, exc->maxFunc + 1 ) ) goto Fail; /* Except for some old Apple fonts, all functions in a TrueType */ /* font are defined in increasing order, starting from 0. This */ /* means that we normally have */ /* */ /* exc->maxFunc+1 == exc->numFDefs */ /* exc->FDefs[n].opc == n for n in 0..exc->maxFunc */ /* */ /* If this isn't true, we need to look up the function table. */ def = FT_OFFSET( exc->FDefs, F ); if ( exc->maxFunc + 1 != exc->numFDefs || def->opc != F ) { /* look up the FDefs table */ TT_DefRecord* limit; def = exc->FDefs; limit = FT_OFFSET( def, exc->numFDefs ); while ( def < limit && def->opc != F ) def++; if ( def == limit ) goto Fail; } /* check that the function is active */ if ( !def->active ) goto Fail; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && ( def->sph_fdef_flags & SPH_FDEF_VACUFORM_ROUND_1 ) ) goto Fail; else exc->sph_in_func_flags = def->sph_fdef_flags; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /* check stack */ if ( exc->callTop >= exc->callSize ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( args[0] > 0 ) { pCrec = exc->callStack + exc->callTop; pCrec->Caller_Range = exc->curRange; pCrec->Caller_IP = exc->IP + 1; pCrec->Cur_Count = (FT_Int)args[0]; pCrec->Def = def; exc->callTop++; Ins_Goto_CodeRange( exc, def->range, def->start ); exc->step_ins = FALSE; exc->loopcall_counter += (FT_ULong)args[0]; if ( exc->loopcall_counter > exc->loopcall_counter_max ) exc->error = FT_THROW( Execution_Too_Long ); } return; Fail: exc->error = FT_THROW( Invalid_Reference ); } /************************************************************************** * * IDEF[]: Instruction DEFinition * Opcode range: 0x89 * Stack: Eint8 --> */ static void Ins_IDEF( TT_ExecContext exc, FT_Long* args ) { TT_DefRecord* def; TT_DefRecord* limit; /* we enable IDEF only in `prep' or `fpgm' */ if ( exc->iniRange == tt_coderange_glyph ) { exc->error = FT_THROW( DEF_In_Glyf_Bytecode ); return; } /* First of all, look for the same function in our table */ def = exc->IDefs; limit = FT_OFFSET( def, exc->numIDefs ); for ( ; def < limit; def++ ) if ( def->opc == (FT_ULong)args[0] ) break; if ( def == limit ) { /* check that there is enough room for a new instruction */ if ( exc->numIDefs >= exc->maxIDefs ) { exc->error = FT_THROW( Too_Many_Instruction_Defs ); return; } exc->numIDefs++; } /* opcode must be unsigned 8-bit integer */ if ( 0 > args[0] || args[0] > 0x00FF ) { exc->error = FT_THROW( Too_Many_Instruction_Defs ); return; } def->opc = (FT_Byte)args[0]; def->start = exc->IP + 1; def->range = exc->curRange; def->active = TRUE; if ( (FT_ULong)args[0] > exc->maxIns ) exc->maxIns = (FT_Byte)args[0]; /* Now skip the whole function definition. */ /* We don't allow nested IDEFs & FDEFs. */ while ( SkipCode( exc ) == SUCCESS ) { switch ( exc->opcode ) { case 0x89: /* IDEF */ case 0x2C: /* FDEF */ exc->error = FT_THROW( Nested_DEFS ); return; case 0x2D: /* ENDF */ def->end = exc->IP; return; } } } /************************************************************************** * * PUSHING DATA ONTO THE INTERPRETER STACK * */ /************************************************************************** * * NPUSHB[]: PUSH N Bytes * Opcode range: 0x40 * Stack: --> uint32... */ static void Ins_NPUSHB( TT_ExecContext exc, FT_Long* args ) { FT_UShort L, K; L = (FT_UShort)exc->code[exc->IP + 1]; if ( BOUNDS( L, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( K = 1; K <= L; K++ ) args[K - 1] = exc->code[exc->IP + K + 1]; exc->new_top += L; } /************************************************************************** * * NPUSHW[]: PUSH N Words * Opcode range: 0x41 * Stack: --> int32... */ static void Ins_NPUSHW( TT_ExecContext exc, FT_Long* args ) { FT_UShort L, K; L = (FT_UShort)exc->code[exc->IP + 1]; if ( BOUNDS( L, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } exc->IP += 2; for ( K = 0; K < L; K++ ) args[K] = GetShortIns( exc ); exc->step_ins = FALSE; exc->new_top += L; } /************************************************************************** * * PUSHB[abc]: PUSH Bytes * Opcode range: 0xB0-0xB7 * Stack: --> uint32... */ static void Ins_PUSHB( TT_ExecContext exc, FT_Long* args ) { FT_UShort L, K; L = (FT_UShort)( exc->opcode - 0xB0 + 1 ); if ( BOUNDS( L, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( K = 1; K <= L; K++ ) args[K - 1] = exc->code[exc->IP + K]; } /************************************************************************** * * PUSHW[abc]: PUSH Words * Opcode range: 0xB8-0xBF * Stack: --> int32... */ static void Ins_PUSHW( TT_ExecContext exc, FT_Long* args ) { FT_UShort L, K; L = (FT_UShort)( exc->opcode - 0xB8 + 1 ); if ( BOUNDS( L, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } exc->IP++; for ( K = 0; K < L; K++ ) args[K] = GetShortIns( exc ); exc->step_ins = FALSE; } /************************************************************************** * * MANAGING THE GRAPHICS STATE * */ static FT_Bool Ins_SxVTL( TT_ExecContext exc, FT_UShort aIdx1, FT_UShort aIdx2, FT_UnitVector* Vec ) { FT_Long A, B, C; FT_Vector* p1; FT_Vector* p2; FT_Byte opcode = exc->opcode; if ( BOUNDS( aIdx1, exc->zp2.n_points ) || BOUNDS( aIdx2, exc->zp1.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return FAILURE; } p1 = exc->zp1.cur + aIdx2; p2 = exc->zp2.cur + aIdx1; A = SUB_LONG( p1->x, p2->x ); B = SUB_LONG( p1->y, p2->y ); /* If p1 == p2, SPvTL and SFvTL behave the same as */ /* SPvTCA[X] and SFvTCA[X], respectively. */ /* */ /* Confirmed by Greg Hitchcock. */ if ( A == 0 && B == 0 ) { A = 0x4000; opcode = 0; } if ( ( opcode & 1 ) != 0 ) { C = B; /* counter-clockwise rotation */ B = A; A = NEG_LONG( C ); } Normalize( A, B, Vec ); return SUCCESS; } /************************************************************************** * * SVTCA[a]: Set (F and P) Vectors to Coordinate Axis * Opcode range: 0x00-0x01 * Stack: --> * * SPvTCA[a]: Set PVector to Coordinate Axis * Opcode range: 0x02-0x03 * Stack: --> * * SFvTCA[a]: Set FVector to Coordinate Axis * Opcode range: 0x04-0x05 * Stack: --> */ static void Ins_SxyTCA( TT_ExecContext exc ) { FT_Short AA, BB; FT_Byte opcode = exc->opcode; AA = (FT_Short)( ( opcode & 1 ) << 14 ); BB = (FT_Short)( AA ^ 0x4000 ); if ( opcode < 4 ) { exc->GS.projVector.x = AA; exc->GS.projVector.y = BB; exc->GS.dualVector.x = AA; exc->GS.dualVector.y = BB; } if ( ( opcode & 2 ) == 0 ) { exc->GS.freeVector.x = AA; exc->GS.freeVector.y = BB; } Compute_Funcs( exc ); } /************************************************************************** * * SPvTL[a]: Set PVector To Line * Opcode range: 0x06-0x07 * Stack: uint32 uint32 --> */ static void Ins_SPVTL( TT_ExecContext exc, FT_Long* args ) { if ( Ins_SxVTL( exc, (FT_UShort)args[1], (FT_UShort)args[0], &exc->GS.projVector ) == SUCCESS ) { exc->GS.dualVector = exc->GS.projVector; Compute_Funcs( exc ); } } /************************************************************************** * * SFvTL[a]: Set FVector To Line * Opcode range: 0x08-0x09 * Stack: uint32 uint32 --> */ static void Ins_SFVTL( TT_ExecContext exc, FT_Long* args ) { if ( Ins_SxVTL( exc, (FT_UShort)args[1], (FT_UShort)args[0], &exc->GS.freeVector ) == SUCCESS ) { Compute_Funcs( exc ); } } /************************************************************************** * * SFvTPv[]: Set FVector To PVector * Opcode range: 0x0E * Stack: --> */ static void Ins_SFVTPV( TT_ExecContext exc ) { exc->GS.freeVector = exc->GS.projVector; Compute_Funcs( exc ); } /************************************************************************** * * SPvFS[]: Set PVector From Stack * Opcode range: 0x0A * Stack: f2.14 f2.14 --> */ static void Ins_SPVFS( TT_ExecContext exc, FT_Long* args ) { FT_Short S; FT_Long X, Y; /* Only use low 16bits, then sign extend */ S = (FT_Short)args[1]; Y = (FT_Long)S; S = (FT_Short)args[0]; X = (FT_Long)S; Normalize( X, Y, &exc->GS.projVector ); exc->GS.dualVector = exc->GS.projVector; Compute_Funcs( exc ); } /************************************************************************** * * SFvFS[]: Set FVector From Stack * Opcode range: 0x0B * Stack: f2.14 f2.14 --> */ static void Ins_SFVFS( TT_ExecContext exc, FT_Long* args ) { FT_Short S; FT_Long X, Y; /* Only use low 16bits, then sign extend */ S = (FT_Short)args[1]; Y = (FT_Long)S; S = (FT_Short)args[0]; X = S; Normalize( X, Y, &exc->GS.freeVector ); Compute_Funcs( exc ); } /************************************************************************** * * GPv[]: Get Projection Vector * Opcode range: 0x0C * Stack: ef2.14 --> ef2.14 */ static void Ins_GPV( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->GS.projVector.x; args[1] = exc->GS.projVector.y; } /************************************************************************** * * GFv[]: Get Freedom Vector * Opcode range: 0x0D * Stack: ef2.14 --> ef2.14 */ static void Ins_GFV( TT_ExecContext exc, FT_Long* args ) { args[0] = exc->GS.freeVector.x; args[1] = exc->GS.freeVector.y; } /************************************************************************** * * SRP0[]: Set Reference Point 0 * Opcode range: 0x10 * Stack: uint32 --> */ static void Ins_SRP0( TT_ExecContext exc, FT_Long* args ) { exc->GS.rp0 = (FT_UShort)args[0]; } /************************************************************************** * * SRP1[]: Set Reference Point 1 * Opcode range: 0x11 * Stack: uint32 --> */ static void Ins_SRP1( TT_ExecContext exc, FT_Long* args ) { exc->GS.rp1 = (FT_UShort)args[0]; } /************************************************************************** * * SRP2[]: Set Reference Point 2 * Opcode range: 0x12 * Stack: uint32 --> */ static void Ins_SRP2( TT_ExecContext exc, FT_Long* args ) { exc->GS.rp2 = (FT_UShort)args[0]; } /************************************************************************** * * SMD[]: Set Minimum Distance * Opcode range: 0x1A * Stack: f26.6 --> */ static void Ins_SMD( TT_ExecContext exc, FT_Long* args ) { exc->GS.minimum_distance = args[0]; } /************************************************************************** * * SCVTCI[]: Set Control Value Table Cut In * Opcode range: 0x1D * Stack: f26.6 --> */ static void Ins_SCVTCI( TT_ExecContext exc, FT_Long* args ) { exc->GS.control_value_cutin = (FT_F26Dot6)args[0]; } /************************************************************************** * * SSWCI[]: Set Single Width Cut In * Opcode range: 0x1E * Stack: f26.6 --> */ static void Ins_SSWCI( TT_ExecContext exc, FT_Long* args ) { exc->GS.single_width_cutin = (FT_F26Dot6)args[0]; } /************************************************************************** * * SSW[]: Set Single Width * Opcode range: 0x1F * Stack: int32? --> */ static void Ins_SSW( TT_ExecContext exc, FT_Long* args ) { exc->GS.single_width_value = FT_MulFix( args[0], exc->tt_metrics.scale ); } /************************************************************************** * * FLIPON[]: Set auto-FLIP to ON * Opcode range: 0x4D * Stack: --> */ static void Ins_FLIPON( TT_ExecContext exc ) { exc->GS.auto_flip = TRUE; } /************************************************************************** * * FLIPOFF[]: Set auto-FLIP to OFF * Opcode range: 0x4E * Stack: --> */ static void Ins_FLIPOFF( TT_ExecContext exc ) { exc->GS.auto_flip = FALSE; } /************************************************************************** * * SANGW[]: Set ANGle Weight * Opcode range: 0x7E * Stack: uint32 --> */ static void Ins_SANGW( void ) { /* instruction not supported anymore */ } /************************************************************************** * * SDB[]: Set Delta Base * Opcode range: 0x5E * Stack: uint32 --> */ static void Ins_SDB( TT_ExecContext exc, FT_Long* args ) { exc->GS.delta_base = (FT_UShort)args[0]; } /************************************************************************** * * SDS[]: Set Delta Shift * Opcode range: 0x5F * Stack: uint32 --> */ static void Ins_SDS( TT_ExecContext exc, FT_Long* args ) { if ( (FT_ULong)args[0] > 6UL ) exc->error = FT_THROW( Bad_Argument ); else exc->GS.delta_shift = (FT_UShort)args[0]; } /************************************************************************** * * RTHG[]: Round To Half Grid * Opcode range: 0x19 * Stack: --> */ static void Ins_RTHG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_To_Half_Grid; exc->func_round = (TT_Round_Func)Round_To_Half_Grid; } /************************************************************************** * * RTG[]: Round To Grid * Opcode range: 0x18 * Stack: --> */ static void Ins_RTG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_To_Grid; exc->func_round = (TT_Round_Func)Round_To_Grid; } /************************************************************************** * RTDG[]: Round To Double Grid * Opcode range: 0x3D * Stack: --> */ static void Ins_RTDG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_To_Double_Grid; exc->func_round = (TT_Round_Func)Round_To_Double_Grid; } /************************************************************************** * RUTG[]: Round Up To Grid * Opcode range: 0x7C * Stack: --> */ static void Ins_RUTG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_Up_To_Grid; exc->func_round = (TT_Round_Func)Round_Up_To_Grid; } /************************************************************************** * * RDTG[]: Round Down To Grid * Opcode range: 0x7D * Stack: --> */ static void Ins_RDTG( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_Down_To_Grid; exc->func_round = (TT_Round_Func)Round_Down_To_Grid; } /************************************************************************** * * ROFF[]: Round OFF * Opcode range: 0x7A * Stack: --> */ static void Ins_ROFF( TT_ExecContext exc ) { exc->GS.round_state = TT_Round_Off; exc->func_round = (TT_Round_Func)Round_None; } /************************************************************************** * * SROUND[]: Super ROUND * Opcode range: 0x76 * Stack: Eint8 --> */ static void Ins_SROUND( TT_ExecContext exc, FT_Long* args ) { SetSuperRound( exc, 0x4000, args[0] ); exc->GS.round_state = TT_Round_Super; exc->func_round = (TT_Round_Func)Round_Super; } /************************************************************************** * * S45ROUND[]: Super ROUND 45 degrees * Opcode range: 0x77 * Stack: uint32 --> */ static void Ins_S45ROUND( TT_ExecContext exc, FT_Long* args ) { SetSuperRound( exc, 0x2D41, args[0] ); exc->GS.round_state = TT_Round_Super_45; exc->func_round = (TT_Round_Func)Round_Super_45; } /************************************************************************** * * GC[a]: Get Coordinate projected onto * Opcode range: 0x46-0x47 * Stack: uint32 --> f26.6 * * XXX: UNDOCUMENTED: Measures from the original glyph must be taken * along the dual projection vector! */ static void Ins_GC( TT_ExecContext exc, FT_Long* args ) { FT_ULong L; FT_F26Dot6 R; L = (FT_ULong)args[0]; if ( BOUNDSL( L, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); R = 0; } else { if ( exc->opcode & 1 ) R = FAST_DUALPROJ( &exc->zp2.org[L] ); else R = FAST_PROJECT( &exc->zp2.cur[L] ); } args[0] = R; } /************************************************************************** * * SCFS[]: Set Coordinate From Stack * Opcode range: 0x48 * Stack: f26.6 uint32 --> * * Formula: * * OA := OA + ( value - OA.p )/( f.p ) * f */ static void Ins_SCFS( TT_ExecContext exc, FT_Long* args ) { FT_Long K; FT_UShort L; L = (FT_UShort)args[0]; if ( BOUNDS( L, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } K = FAST_PROJECT( &exc->zp2.cur[L] ); exc->func_move( exc, &exc->zp2, L, SUB_LONG( args[1], K ) ); /* UNDOCUMENTED! The MS rasterizer does that with */ /* twilight points (confirmed by Greg Hitchcock) */ if ( exc->GS.gep2 == 0 ) exc->zp2.org[L] = exc->zp2.cur[L]; } /************************************************************************** * * MD[a]: Measure Distance * Opcode range: 0x49-0x4A * Stack: uint32 uint32 --> f26.6 * * XXX: UNDOCUMENTED: Measure taken in the original glyph must be along * the dual projection vector. * * XXX: UNDOCUMENTED: Flag attributes are inverted! * 0 => measure distance in original outline * 1 => measure distance in grid-fitted outline * * XXX: UNDOCUMENTED: `zp0 - zp1', and not `zp2 - zp1! */ static void Ins_MD( TT_ExecContext exc, FT_Long* args ) { FT_UShort K, L; FT_F26Dot6 D; K = (FT_UShort)args[1]; L = (FT_UShort)args[0]; if ( BOUNDS( L, exc->zp0.n_points ) || BOUNDS( K, exc->zp1.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); D = 0; } else { if ( exc->opcode & 1 ) D = PROJECT( exc->zp0.cur + L, exc->zp1.cur + K ); else { /* XXX: UNDOCUMENTED: twilight zone special case */ if ( exc->GS.gep0 == 0 || exc->GS.gep1 == 0 ) { FT_Vector* vec1 = exc->zp0.org + L; FT_Vector* vec2 = exc->zp1.org + K; D = DUALPROJ( vec1, vec2 ); } else { FT_Vector* vec1 = exc->zp0.orus + L; FT_Vector* vec2 = exc->zp1.orus + K; if ( exc->metrics.x_scale == exc->metrics.y_scale ) { /* this should be faster */ D = DUALPROJ( vec1, vec2 ); D = FT_MulFix( D, exc->metrics.x_scale ); } else { FT_Vector vec; vec.x = FT_MulFix( vec1->x - vec2->x, exc->metrics.x_scale ); vec.y = FT_MulFix( vec1->y - vec2->y, exc->metrics.y_scale ); D = FAST_DUALPROJ( &vec ); } } } } #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* Disable Type 2 Vacuform Rounds - e.g. Arial Narrow */ if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && ( D < 0 ? NEG_LONG( D ) : D ) == 64 ) D += 1; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ args[0] = D; } /************************************************************************** * * SDPvTL[a]: Set Dual PVector to Line * Opcode range: 0x86-0x87 * Stack: uint32 uint32 --> */ static void Ins_SDPVTL( TT_ExecContext exc, FT_Long* args ) { FT_Long A, B, C; FT_UShort p1, p2; /* was FT_Int in pas type ERROR */ FT_Byte opcode = exc->opcode; p1 = (FT_UShort)args[1]; p2 = (FT_UShort)args[0]; if ( BOUNDS( p2, exc->zp1.n_points ) || BOUNDS( p1, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } { FT_Vector* v1 = exc->zp1.org + p2; FT_Vector* v2 = exc->zp2.org + p1; A = SUB_LONG( v1->x, v2->x ); B = SUB_LONG( v1->y, v2->y ); /* If v1 == v2, SDPvTL behaves the same as */ /* SVTCA[X], respectively. */ /* */ /* Confirmed by Greg Hitchcock. */ if ( A == 0 && B == 0 ) { A = 0x4000; opcode = 0; } } if ( ( opcode & 1 ) != 0 ) { C = B; /* counter-clockwise rotation */ B = A; A = NEG_LONG( C ); } Normalize( A, B, &exc->GS.dualVector ); { FT_Vector* v1 = exc->zp1.cur + p2; FT_Vector* v2 = exc->zp2.cur + p1; A = SUB_LONG( v1->x, v2->x ); B = SUB_LONG( v1->y, v2->y ); if ( A == 0 && B == 0 ) { A = 0x4000; opcode = 0; } } if ( ( opcode & 1 ) != 0 ) { C = B; /* counter-clockwise rotation */ B = A; A = NEG_LONG( C ); } Normalize( A, B, &exc->GS.projVector ); Compute_Funcs( exc ); } /************************************************************************** * * SZP0[]: Set Zone Pointer 0 * Opcode range: 0x13 * Stack: uint32 --> */ static void Ins_SZP0( TT_ExecContext exc, FT_Long* args ) { switch ( (FT_Int)args[0] ) { case 0: exc->zp0 = exc->twilight; break; case 1: exc->zp0 = exc->pts; break; default: if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } exc->GS.gep0 = (FT_UShort)args[0]; } /************************************************************************** * * SZP1[]: Set Zone Pointer 1 * Opcode range: 0x14 * Stack: uint32 --> */ static void Ins_SZP1( TT_ExecContext exc, FT_Long* args ) { switch ( (FT_Int)args[0] ) { case 0: exc->zp1 = exc->twilight; break; case 1: exc->zp1 = exc->pts; break; default: if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } exc->GS.gep1 = (FT_UShort)args[0]; } /************************************************************************** * * SZP2[]: Set Zone Pointer 2 * Opcode range: 0x15 * Stack: uint32 --> */ static void Ins_SZP2( TT_ExecContext exc, FT_Long* args ) { switch ( (FT_Int)args[0] ) { case 0: exc->zp2 = exc->twilight; break; case 1: exc->zp2 = exc->pts; break; default: if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } exc->GS.gep2 = (FT_UShort)args[0]; } /************************************************************************** * * SZPS[]: Set Zone PointerS * Opcode range: 0x16 * Stack: uint32 --> */ static void Ins_SZPS( TT_ExecContext exc, FT_Long* args ) { switch ( (FT_Int)args[0] ) { case 0: exc->zp0 = exc->twilight; break; case 1: exc->zp0 = exc->pts; break; default: if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } exc->zp1 = exc->zp0; exc->zp2 = exc->zp0; exc->GS.gep0 = (FT_UShort)args[0]; exc->GS.gep1 = (FT_UShort)args[0]; exc->GS.gep2 = (FT_UShort)args[0]; } /************************************************************************** * * INSTCTRL[]: INSTruction ConTRoL * Opcode range: 0x8E * Stack: int32 int32 --> */ static void Ins_INSTCTRL( TT_ExecContext exc, FT_Long* args ) { FT_ULong K, L, Kf; K = (FT_ULong)args[1]; L = (FT_ULong)args[0]; /* selector values cannot be `OR'ed; */ /* they are indices starting with index 1, not flags */ if ( K < 1 || K > 3 ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } /* convert index to flag value */ Kf = 1 << ( K - 1 ); if ( L != 0 ) { /* arguments to selectors look like flag values */ if ( L != Kf ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } } /* INSTCTRL should only be used in the CVT program */ if ( exc->iniRange == tt_coderange_cvt ) { exc->GS.instruct_control &= ~(FT_Byte)Kf; exc->GS.instruct_control |= (FT_Byte)L; } /* except to change the subpixel flags temporarily */ else if ( exc->iniRange == tt_coderange_glyph && K == 3 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* INSTCTRL modifying flag 3 also has an effect */ /* outside of the CVT program */ if ( SUBPIXEL_HINTING_INFINALITY ) exc->ignore_x_mode = !FT_BOOL( L == 4 ); #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* Native ClearType fonts sign a waiver that turns off all backward */ /* compatibility hacks and lets them program points to the grid like */ /* it's 1996. They might sign a waiver for just one glyph, though. */ if ( SUBPIXEL_HINTING_MINIMAL ) exc->backward_compatibility = !FT_BOOL( L == 4 ); #endif } else if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); } /************************************************************************** * * SCANCTRL[]: SCAN ConTRoL * Opcode range: 0x85 * Stack: uint32? --> */ static void Ins_SCANCTRL( TT_ExecContext exc, FT_Long* args ) { FT_Int A; /* Get Threshold */ A = (FT_Int)( args[0] & 0xFF ); if ( A == 0xFF ) { exc->GS.scan_control = TRUE; return; } else if ( A == 0 ) { exc->GS.scan_control = FALSE; return; } if ( ( args[0] & 0x100 ) != 0 && exc->tt_metrics.ppem <= A ) exc->GS.scan_control = TRUE; if ( ( args[0] & 0x200 ) != 0 && exc->tt_metrics.rotated ) exc->GS.scan_control = TRUE; if ( ( args[0] & 0x400 ) != 0 && exc->tt_metrics.stretched ) exc->GS.scan_control = TRUE; if ( ( args[0] & 0x800 ) != 0 && exc->tt_metrics.ppem > A ) exc->GS.scan_control = FALSE; if ( ( args[0] & 0x1000 ) != 0 && exc->tt_metrics.rotated ) exc->GS.scan_control = FALSE; if ( ( args[0] & 0x2000 ) != 0 && exc->tt_metrics.stretched ) exc->GS.scan_control = FALSE; } /************************************************************************** * * SCANTYPE[]: SCAN TYPE * Opcode range: 0x8D * Stack: uint16 --> */ static void Ins_SCANTYPE( TT_ExecContext exc, FT_Long* args ) { if ( args[0] >= 0 ) exc->GS.scan_type = (FT_Int)args[0] & 0xFFFF; } /************************************************************************** * * MANAGING OUTLINES * */ /************************************************************************** * * FLIPPT[]: FLIP PoinT * Opcode range: 0x80 * Stack: uint32... --> */ static void Ins_FLIPPT( TT_ExecContext exc ) { FT_UShort point; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* See `ttinterp.h' for details on backward compatibility mode. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) goto Fail; #endif if ( exc->top < exc->GS.loop ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Too_Few_Arguments ); goto Fail; } while ( exc->GS.loop > 0 ) { exc->args--; point = (FT_UShort)exc->stack[exc->args]; if ( BOUNDS( point, exc->pts.n_points ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } } else exc->pts.tags[point] ^= FT_CURVE_TAG_ON; exc->GS.loop--; } Fail: exc->GS.loop = 1; exc->new_top = exc->args; } /************************************************************************** * * FLIPRGON[]: FLIP RanGe ON * Opcode range: 0x81 * Stack: uint32 uint32 --> */ static void Ins_FLIPRGON( TT_ExecContext exc, FT_Long* args ) { FT_UShort I, K, L; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* See `ttinterp.h' for details on backward compatibility mode. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) return; #endif K = (FT_UShort)args[1]; L = (FT_UShort)args[0]; if ( BOUNDS( K, exc->pts.n_points ) || BOUNDS( L, exc->pts.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } for ( I = L; I <= K; I++ ) exc->pts.tags[I] |= FT_CURVE_TAG_ON; } /************************************************************************** * * FLIPRGOFF: FLIP RanGe OFF * Opcode range: 0x82 * Stack: uint32 uint32 --> */ static void Ins_FLIPRGOFF( TT_ExecContext exc, FT_Long* args ) { FT_UShort I, K, L; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* See `ttinterp.h' for details on backward compatibility mode. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) return; #endif K = (FT_UShort)args[1]; L = (FT_UShort)args[0]; if ( BOUNDS( K, exc->pts.n_points ) || BOUNDS( L, exc->pts.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } for ( I = L; I <= K; I++ ) exc->pts.tags[I] &= ~FT_CURVE_TAG_ON; } static FT_Bool Compute_Point_Displacement( TT_ExecContext exc, FT_F26Dot6* x, FT_F26Dot6* y, TT_GlyphZone zone, FT_UShort* refp ) { TT_GlyphZoneRec zp; FT_UShort p; FT_F26Dot6 d; if ( exc->opcode & 1 ) { zp = exc->zp0; p = exc->GS.rp1; } else { zp = exc->zp1; p = exc->GS.rp2; } if ( BOUNDS( p, zp.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); *refp = 0; return FAILURE; } *zone = zp; *refp = p; d = PROJECT( zp.cur + p, zp.org + p ); *x = FT_MulDiv( d, (FT_Long)exc->GS.freeVector.x, exc->F_dot_P ); *y = FT_MulDiv( d, (FT_Long)exc->GS.freeVector.y, exc->F_dot_P ); return SUCCESS; } /* See `ttinterp.h' for details on backward compatibility mode. */ static void Move_Zp2_Point( TT_ExecContext exc, FT_UShort point, FT_F26Dot6 dx, FT_F26Dot6 dy, FT_Bool touch ) { if ( exc->GS.freeVector.x != 0 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( !( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility ) ) #endif exc->zp2.cur[point].x = ADD_LONG( exc->zp2.cur[point].x, dx ); if ( touch ) exc->zp2.tags[point] |= FT_CURVE_TAG_TOUCH_X; } if ( exc->GS.freeVector.y != 0 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( !( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility && exc->iupx_called && exc->iupy_called ) ) #endif exc->zp2.cur[point].y = ADD_LONG( exc->zp2.cur[point].y, dy ); if ( touch ) exc->zp2.tags[point] |= FT_CURVE_TAG_TOUCH_Y; } } /************************************************************************** * * SHP[a]: SHift Point by the last point * Opcode range: 0x32-0x33 * Stack: uint32... --> */ static void Ins_SHP( TT_ExecContext exc ) { TT_GlyphZoneRec zp; FT_UShort refp; FT_F26Dot6 dx, dy; FT_UShort point; if ( exc->top < exc->GS.loop ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } if ( Compute_Point_Displacement( exc, &dx, &dy, &zp, &refp ) ) return; while ( exc->GS.loop > 0 ) { exc->args--; point = (FT_UShort)exc->stack[exc->args]; if ( BOUNDS( point, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } } else #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* doesn't follow Cleartype spec but produces better result */ if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode ) Move_Zp2_Point( exc, point, 0, dy, TRUE ); else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ Move_Zp2_Point( exc, point, dx, dy, TRUE ); exc->GS.loop--; } Fail: exc->GS.loop = 1; exc->new_top = exc->args; } /************************************************************************** * * SHC[a]: SHift Contour * Opcode range: 0x34-35 * Stack: uint32 --> * * UNDOCUMENTED: According to Greg Hitchcock, there is one (virtual) * contour in the twilight zone, namely contour number * zero which includes all points of it. */ static void Ins_SHC( TT_ExecContext exc, FT_Long* args ) { TT_GlyphZoneRec zp; FT_UShort refp; FT_F26Dot6 dx, dy; FT_Short contour, bounds; FT_UShort start, limit, i; contour = (FT_Short)args[0]; bounds = ( exc->GS.gep2 == 0 ) ? 1 : exc->zp2.n_contours; if ( BOUNDS( contour, bounds ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } if ( Compute_Point_Displacement( exc, &dx, &dy, &zp, &refp ) ) return; if ( contour == 0 ) start = 0; else start = (FT_UShort)( exc->zp2.contours[contour - 1] + 1 - exc->zp2.first_point ); /* we use the number of points if in the twilight zone */ if ( exc->GS.gep2 == 0 ) limit = exc->zp2.n_points; else limit = (FT_UShort)( exc->zp2.contours[contour] - exc->zp2.first_point + 1 ); for ( i = start; i < limit; i++ ) { if ( zp.cur != exc->zp2.cur || refp != i ) Move_Zp2_Point( exc, i, dx, dy, TRUE ); } } /************************************************************************** * * SHZ[a]: SHift Zone * Opcode range: 0x36-37 * Stack: uint32 --> */ static void Ins_SHZ( TT_ExecContext exc, FT_Long* args ) { TT_GlyphZoneRec zp; FT_UShort refp; FT_F26Dot6 dx, dy; FT_UShort limit, i; if ( BOUNDS( args[0], 2 ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } if ( Compute_Point_Displacement( exc, &dx, &dy, &zp, &refp ) ) return; /* XXX: UNDOCUMENTED! SHZ doesn't move the phantom points. */ /* Twilight zone has no real contours, so use `n_points'. */ /* Normal zone's `n_points' includes phantoms, so must */ /* use end of last contour. */ if ( exc->GS.gep2 == 0 ) limit = (FT_UShort)exc->zp2.n_points; else if ( exc->GS.gep2 == 1 && exc->zp2.n_contours > 0 ) limit = (FT_UShort)( exc->zp2.contours[exc->zp2.n_contours - 1] + 1 ); else limit = 0; /* XXX: UNDOCUMENTED! SHZ doesn't touch the points */ for ( i = 0; i < limit; i++ ) { if ( zp.cur != exc->zp2.cur || refp != i ) Move_Zp2_Point( exc, i, dx, dy, FALSE ); } } /************************************************************************** * * SHPIX[]: SHift points by a PIXel amount * Opcode range: 0x38 * Stack: f26.6 uint32... --> */ static void Ins_SHPIX( TT_ExecContext exc, FT_Long* args ) { FT_F26Dot6 dx, dy; FT_UShort point; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL FT_Bool in_twilight = FT_BOOL( exc->GS.gep0 == 0 || exc->GS.gep1 == 0 || exc->GS.gep2 == 0 ); #endif if ( exc->top < exc->GS.loop + 1 ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } dx = TT_MulFix14( args[0], exc->GS.freeVector.x ); dy = TT_MulFix14( args[0], exc->GS.freeVector.y ); while ( exc->GS.loop > 0 ) { exc->args--; point = (FT_UShort)exc->stack[exc->args]; if ( BOUNDS( point, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } } else #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode ) { FT_Int B1, B2; /* If not using ignore_x_mode rendering, allow ZP2 move. */ /* If inline deltas aren't allowed, skip ZP2 move. */ /* If using ignore_x_mode rendering, allow ZP2 point move if: */ /* - freedom vector is y and sph_compatibility_mode is off */ /* - the glyph is composite and the move is in the Y direction */ /* - the glyph is specifically set to allow SHPIX moves */ /* - the move is on a previously Y-touched point */ /* save point for later comparison */ B1 = exc->zp2.cur[point].y; if ( exc->face->sph_compatibility_mode ) { if ( exc->sph_tweak_flags & SPH_TWEAK_ROUND_NONPIXEL_Y_MOVES ) dy = FT_PIX_ROUND( B1 + dy ) - B1; /* skip post-iup deltas */ if ( exc->iup_called && ( ( exc->sph_in_func_flags & SPH_FDEF_INLINE_DELTA_1 ) || ( exc->sph_in_func_flags & SPH_FDEF_INLINE_DELTA_2 ) ) ) goto Skip; if ( !( exc->sph_tweak_flags & SPH_TWEAK_ALWAYS_SKIP_DELTAP ) && ( ( exc->is_composite && exc->GS.freeVector.y != 0 ) || ( exc->zp2.tags[point] & FT_CURVE_TAG_TOUCH_Y ) || ( exc->sph_tweak_flags & SPH_TWEAK_DO_SHPIX ) ) ) Move_Zp2_Point( exc, point, 0, dy, TRUE ); /* save new point */ if ( exc->GS.freeVector.y != 0 ) { B2 = exc->zp2.cur[point].y; /* reverse any disallowed moves */ if ( ( B1 & 63 ) == 0 && ( B2 & 63 ) != 0 && B1 != B2 ) Move_Zp2_Point( exc, point, 0, NEG_LONG( dy ), TRUE ); } } else if ( exc->GS.freeVector.y != 0 ) { Move_Zp2_Point( exc, point, dx, dy, TRUE ); /* save new point */ B2 = exc->zp2.cur[point].y; /* reverse any disallowed moves */ if ( ( exc->sph_tweak_flags & SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES ) && ( B1 & 63 ) != 0 && ( B2 & 63 ) != 0 && B1 != B2 ) Move_Zp2_Point( exc, point, NEG_LONG( dx ), NEG_LONG( dy ), TRUE ); } else if ( exc->sph_in_func_flags & SPH_FDEF_TYPEMAN_DIAGENDCTRL ) Move_Zp2_Point( exc, point, dx, dy, TRUE ); } else #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility ) { /* Special case: allow SHPIX to move points in the twilight zone. */ /* Otherwise, treat SHPIX the same as DELTAP. Unbreaks various */ /* fonts such as older versions of Rokkitt and DTL Argo T Light */ /* that would glitch severely after calling ALIGNRP after a */ /* blocked SHPIX. */ if ( in_twilight || ( !( exc->iupx_called && exc->iupy_called ) && ( ( exc->is_composite && exc->GS.freeVector.y != 0 ) || ( exc->zp2.tags[point] & FT_CURVE_TAG_TOUCH_Y ) ) ) ) Move_Zp2_Point( exc, point, 0, dy, TRUE ); } else #endif Move_Zp2_Point( exc, point, dx, dy, TRUE ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY Skip: #endif exc->GS.loop--; } Fail: exc->GS.loop = 1; exc->new_top = exc->args; } /************************************************************************** * * MSIRP[a]: Move Stack Indirect Relative Position * Opcode range: 0x3A-0x3B * Stack: f26.6 uint32 --> */ static void Ins_MSIRP( TT_ExecContext exc, FT_Long* args ) { FT_UShort point = 0; FT_F26Dot6 distance; point = (FT_UShort)args[0]; if ( BOUNDS( point, exc->zp1.n_points ) || BOUNDS( exc->GS.rp0, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } /* UNDOCUMENTED! The MS rasterizer does that with */ /* twilight points (confirmed by Greg Hitchcock) */ if ( exc->GS.gep1 == 0 ) { exc->zp1.org[point] = exc->zp0.org[exc->GS.rp0]; exc->func_move_orig( exc, &exc->zp1, point, args[1] ); exc->zp1.cur[point] = exc->zp1.org[point]; } distance = PROJECT( exc->zp1.cur + point, exc->zp0.cur + exc->GS.rp0 ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* subpixel hinting - make MSIRP respect CVT cut-in; */ if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 ) { FT_F26Dot6 control_value_cutin = exc->GS.control_value_cutin; FT_F26Dot6 delta; if ( !( exc->sph_tweak_flags & SPH_TWEAK_NORMAL_ROUND ) ) control_value_cutin = 0; delta = SUB_LONG( distance, args[1] ); if ( delta < 0 ) delta = NEG_LONG( delta ); if ( delta >= control_value_cutin ) distance = args[1]; } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ exc->func_move( exc, &exc->zp1, point, SUB_LONG( args[1], distance ) ); exc->GS.rp1 = exc->GS.rp0; exc->GS.rp2 = point; if ( ( exc->opcode & 1 ) != 0 ) exc->GS.rp0 = point; } /************************************************************************** * * MDAP[a]: Move Direct Absolute Point * Opcode range: 0x2E-0x2F * Stack: uint32 --> */ static void Ins_MDAP( TT_ExecContext exc, FT_Long* args ) { FT_UShort point; FT_F26Dot6 cur_dist; FT_F26Dot6 distance; point = (FT_UShort)args[0]; if ( BOUNDS( point, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } if ( ( exc->opcode & 1 ) != 0 ) { cur_dist = FAST_PROJECT( &exc->zp0.cur[point] ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 ) distance = SUB_LONG( Round_None( exc, cur_dist, 3 ), cur_dist ); else #endif distance = SUB_LONG( exc->func_round( exc, cur_dist, 3 ), cur_dist ); } else distance = 0; exc->func_move( exc, &exc->zp0, point, distance ); exc->GS.rp0 = point; exc->GS.rp1 = point; } /************************************************************************** * * MIAP[a]: Move Indirect Absolute Point * Opcode range: 0x3E-0x3F * Stack: uint32 uint32 --> */ static void Ins_MIAP( TT_ExecContext exc, FT_Long* args ) { FT_ULong cvtEntry; FT_UShort point; FT_F26Dot6 distance; FT_F26Dot6 org_dist; cvtEntry = (FT_ULong)args[1]; point = (FT_UShort)args[0]; if ( BOUNDS( point, exc->zp0.n_points ) || BOUNDSL( cvtEntry, exc->cvtSize ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } /* UNDOCUMENTED! */ /* */ /* The behaviour of an MIAP instruction is quite different when used */ /* in the twilight zone. */ /* */ /* First, no control value cut-in test is performed as it would fail */ /* anyway. Second, the original point, i.e. (org_x,org_y) of */ /* zp0.point, is set to the absolute, unrounded distance found in the */ /* CVT. */ /* */ /* This is used in the CVT programs of the Microsoft fonts Arial, */ /* Times, etc., in order to re-adjust some key font heights. It */ /* allows the use of the IP instruction in the twilight zone, which */ /* otherwise would be invalid according to the specification. */ /* */ /* We implement it with a special sequence for the twilight zone. */ /* This is a bad hack, but it seems to work. */ /* */ /* Confirmed by Greg Hitchcock. */ distance = exc->func_read_cvt( exc, cvtEntry ); if ( exc->GS.gep0 == 0 ) /* If in twilight zone */ { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* Only adjust if not in sph_compatibility_mode or ignore_x_mode. */ /* Determined via experimentation and may be incorrect... */ if ( !( SUBPIXEL_HINTING_INFINALITY && ( exc->ignore_x_mode && exc->face->sph_compatibility_mode ) ) ) #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ exc->zp0.org[point].x = TT_MulFix14( distance, exc->GS.freeVector.x ); exc->zp0.org[point].y = TT_MulFix14( distance, exc->GS.freeVector.y ); exc->zp0.cur[point] = exc->zp0.org[point]; } #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && ( exc->sph_tweak_flags & SPH_TWEAK_MIAP_HACK ) && distance > 0 && exc->GS.freeVector.y != 0 ) distance = 0; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ org_dist = FAST_PROJECT( &exc->zp0.cur[point] ); if ( ( exc->opcode & 1 ) != 0 ) /* rounding and control cut-in flag */ { FT_F26Dot6 control_value_cutin = exc->GS.control_value_cutin; FT_F26Dot6 delta; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 && exc->GS.freeVector.y == 0 && !( exc->sph_tweak_flags & SPH_TWEAK_NORMAL_ROUND ) ) control_value_cutin = 0; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ delta = SUB_LONG( distance, org_dist ); if ( delta < 0 ) delta = NEG_LONG( delta ); if ( delta > control_value_cutin ) distance = org_dist; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 ) distance = Round_None( exc, distance, 3 ); else #endif distance = exc->func_round( exc, distance, 3 ); } exc->func_move( exc, &exc->zp0, point, SUB_LONG( distance, org_dist ) ); Fail: exc->GS.rp0 = point; exc->GS.rp1 = point; } /************************************************************************** * * MDRP[abcde]: Move Direct Relative Point * Opcode range: 0xC0-0xDF * Stack: uint32 --> */ static void Ins_MDRP( TT_ExecContext exc, FT_Long* args ) { FT_UShort point = 0; FT_F26Dot6 org_dist, distance; point = (FT_UShort)args[0]; if ( BOUNDS( point, exc->zp1.n_points ) || BOUNDS( exc->GS.rp0, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } /* XXX: Is there some undocumented feature while in the */ /* twilight zone? */ /* XXX: UNDOCUMENTED: twilight zone special case */ if ( exc->GS.gep0 == 0 || exc->GS.gep1 == 0 ) { FT_Vector* vec1 = &exc->zp1.org[point]; FT_Vector* vec2 = &exc->zp0.org[exc->GS.rp0]; org_dist = DUALPROJ( vec1, vec2 ); } else { FT_Vector* vec1 = &exc->zp1.orus[point]; FT_Vector* vec2 = &exc->zp0.orus[exc->GS.rp0]; if ( exc->metrics.x_scale == exc->metrics.y_scale ) { /* this should be faster */ org_dist = DUALPROJ( vec1, vec2 ); org_dist = FT_MulFix( org_dist, exc->metrics.x_scale ); } else { FT_Vector vec; vec.x = FT_MulFix( SUB_LONG( vec1->x, vec2->x ), exc->metrics.x_scale ); vec.y = FT_MulFix( SUB_LONG( vec1->y, vec2->y ), exc->metrics.y_scale ); org_dist = FAST_DUALPROJ( &vec ); } } /* single width cut-in test */ /* |org_dist - single_width_value| < single_width_cutin */ if ( exc->GS.single_width_cutin > 0 && org_dist < exc->GS.single_width_value + exc->GS.single_width_cutin && org_dist > exc->GS.single_width_value - exc->GS.single_width_cutin ) { if ( org_dist >= 0 ) org_dist = exc->GS.single_width_value; else org_dist = -exc->GS.single_width_value; } /* round flag */ if ( ( exc->opcode & 4 ) != 0 ) { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 ) distance = Round_None( exc, org_dist, exc->opcode & 3 ); else #endif distance = exc->func_round( exc, org_dist, exc->opcode & 3 ); } else distance = Round_None( exc, org_dist, exc->opcode & 3 ); /* minimum distance flag */ if ( ( exc->opcode & 8 ) != 0 ) { FT_F26Dot6 minimum_distance = exc->GS.minimum_distance; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 && !( exc->sph_tweak_flags & SPH_TWEAK_NORMAL_ROUND ) ) minimum_distance = 0; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ if ( org_dist >= 0 ) { if ( distance < minimum_distance ) distance = minimum_distance; } else { if ( distance > NEG_LONG( minimum_distance ) ) distance = NEG_LONG( minimum_distance ); } } /* now move the point */ org_dist = PROJECT( exc->zp1.cur + point, exc->zp0.cur + exc->GS.rp0 ); exc->func_move( exc, &exc->zp1, point, SUB_LONG( distance, org_dist ) ); Fail: exc->GS.rp1 = exc->GS.rp0; exc->GS.rp2 = point; if ( ( exc->opcode & 16 ) != 0 ) exc->GS.rp0 = point; } /************************************************************************** * * MIRP[abcde]: Move Indirect Relative Point * Opcode range: 0xE0-0xFF * Stack: int32? uint32 --> */ static void Ins_MIRP( TT_ExecContext exc, FT_Long* args ) { FT_UShort point; FT_ULong cvtEntry; FT_F26Dot6 cvt_dist, distance, cur_dist, org_dist; FT_F26Dot6 delta; point = (FT_UShort)args[0]; cvtEntry = (FT_ULong)( ADD_LONG( args[1], 1 ) ); /* XXX: UNDOCUMENTED! cvt[-1] = 0 always */ if ( BOUNDS( point, exc->zp1.n_points ) || BOUNDSL( cvtEntry, exc->cvtSize + 1 ) || BOUNDS( exc->GS.rp0, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } if ( !cvtEntry ) cvt_dist = 0; else cvt_dist = exc->func_read_cvt( exc, cvtEntry - 1 ); /* single width test */ delta = SUB_LONG( cvt_dist, exc->GS.single_width_value ); if ( delta < 0 ) delta = NEG_LONG( delta ); if ( delta < exc->GS.single_width_cutin ) { if ( cvt_dist >= 0 ) cvt_dist = exc->GS.single_width_value; else cvt_dist = -exc->GS.single_width_value; } /* UNDOCUMENTED! The MS rasterizer does that with */ /* twilight points (confirmed by Greg Hitchcock) */ if ( exc->GS.gep1 == 0 ) { exc->zp1.org[point].x = ADD_LONG( exc->zp0.org[exc->GS.rp0].x, TT_MulFix14( cvt_dist, exc->GS.freeVector.x ) ); exc->zp1.org[point].y = ADD_LONG( exc->zp0.org[exc->GS.rp0].y, TT_MulFix14( cvt_dist, exc->GS.freeVector.y ) ); exc->zp1.cur[point] = exc->zp1.org[point]; } org_dist = DUALPROJ( &exc->zp1.org[point], &exc->zp0.org[exc->GS.rp0] ); cur_dist = PROJECT ( &exc->zp1.cur[point], &exc->zp0.cur[exc->GS.rp0] ); /* auto-flip test */ if ( exc->GS.auto_flip ) { if ( ( org_dist ^ cvt_dist ) < 0 ) cvt_dist = NEG_LONG( cvt_dist ); } /* control value cut-in and round */ if ( ( exc->opcode & 4 ) != 0 ) { /* XXX: UNDOCUMENTED! Only perform cut-in test when both points */ /* refer to the same zone. */ if ( exc->GS.gep0 == exc->GS.gep1 ) { FT_F26Dot6 control_value_cutin = exc->GS.control_value_cutin; /* XXX: According to Greg Hitchcock, the following wording is */ /* the right one: */ /* */ /* When the absolute difference between the value in */ /* the table [CVT] and the measurement directly from */ /* the outline is _greater_ than the cut_in value, the */ /* outline measurement is used. */ /* */ /* This is from `instgly.doc'. The description in */ /* `ttinst2.doc', version 1.66, is thus incorrect since */ /* it implies `>=' instead of `>'. */ delta = SUB_LONG( cvt_dist, org_dist ); if ( delta < 0 ) delta = NEG_LONG( delta ); if ( delta > control_value_cutin ) cvt_dist = org_dist; } distance = exc->func_round( exc, cvt_dist, exc->opcode & 3 ); } else { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* do cvt cut-in always in MIRP for sph */ if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.gep0 == exc->GS.gep1 ) { FT_F26Dot6 control_value_cutin = exc->GS.control_value_cutin; if ( exc->GS.freeVector.x != 0 && !( exc->sph_tweak_flags & SPH_TWEAK_NORMAL_ROUND ) ) control_value_cutin = 0; if ( exc->GS.freeVector.y != 0 && ( exc->sph_tweak_flags & SPH_TWEAK_TIMES_NEW_ROMAN_HACK ) ) { if ( cur_dist < -64 ) cvt_dist -= 16; else if ( cur_dist > 64 && cur_dist < 84 ) cvt_dist += 32; } delta = SUB_LONG( cvt_dist, org_dist ); if ( delta < 0 ) delta = NEG_LONG( delta ); if ( delta > control_value_cutin ) cvt_dist = org_dist; } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ distance = Round_None( exc, cvt_dist, exc->opcode & 3 ); } /* minimum distance test */ if ( ( exc->opcode & 8 ) != 0 ) { FT_F26Dot6 minimum_distance = exc->GS.minimum_distance; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.x != 0 && !( exc->sph_tweak_flags & SPH_TWEAK_NORMAL_ROUND ) ) minimum_distance = 0; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ if ( org_dist >= 0 ) { if ( distance < minimum_distance ) distance = minimum_distance; } else { if ( distance > NEG_LONG( minimum_distance ) ) distance = NEG_LONG( minimum_distance ); } } #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->GS.freeVector.y != 0 ) { FT_Int B1, B2; B1 = exc->zp1.cur[point].y; /* Round moves if necessary */ if ( exc->sph_tweak_flags & SPH_TWEAK_ROUND_NONPIXEL_Y_MOVES ) distance = FT_PIX_ROUND( B1 + distance - cur_dist ) - B1 + cur_dist; if ( ( exc->opcode & 16 ) == 0 && ( exc->opcode & 8 ) == 0 && ( exc->sph_tweak_flags & SPH_TWEAK_COURIER_NEW_2_HACK ) ) distance += 64; exc->func_move( exc, &exc->zp1, point, SUB_LONG( distance, cur_dist ) ); B2 = exc->zp1.cur[point].y; /* Reverse move if necessary */ if ( ( exc->face->sph_compatibility_mode && ( B1 & 63 ) == 0 && ( B2 & 63 ) != 0 ) || ( ( exc->sph_tweak_flags & SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES ) && ( B1 & 63 ) != 0 && ( B2 & 63 ) != 0 ) ) exc->func_move( exc, &exc->zp1, point, SUB_LONG( cur_dist, distance ) ); } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ exc->func_move( exc, &exc->zp1, point, SUB_LONG( distance, cur_dist ) ); Fail: exc->GS.rp1 = exc->GS.rp0; if ( ( exc->opcode & 16 ) != 0 ) exc->GS.rp0 = point; exc->GS.rp2 = point; } /************************************************************************** * * ALIGNRP[]: ALIGN Relative Point * Opcode range: 0x3C * Stack: uint32 uint32... --> */ static void Ins_ALIGNRP( TT_ExecContext exc ) { FT_UShort point; FT_F26Dot6 distance; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->iup_called && ( exc->sph_tweak_flags & SPH_TWEAK_NO_ALIGNRP_AFTER_IUP ) ) { exc->error = FT_THROW( Invalid_Reference ); goto Fail; } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ if ( exc->top < exc->GS.loop || BOUNDS( exc->GS.rp0, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } while ( exc->GS.loop > 0 ) { exc->args--; point = (FT_UShort)exc->stack[exc->args]; if ( BOUNDS( point, exc->zp1.n_points ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } } else { distance = PROJECT( exc->zp1.cur + point, exc->zp0.cur + exc->GS.rp0 ); exc->func_move( exc, &exc->zp1, point, NEG_LONG( distance ) ); } exc->GS.loop--; } Fail: exc->GS.loop = 1; exc->new_top = exc->args; } /************************************************************************** * * ISECT[]: moves point to InterSECTion * Opcode range: 0x0F * Stack: 5 * uint32 --> */ static void Ins_ISECT( TT_ExecContext exc, FT_Long* args ) { FT_UShort point, a0, a1, b0, b1; FT_F26Dot6 discriminant, dotproduct; FT_F26Dot6 dx, dy, dax, day, dbx, dby; FT_F26Dot6 val; FT_Vector R; point = (FT_UShort)args[0]; a0 = (FT_UShort)args[1]; a1 = (FT_UShort)args[2]; b0 = (FT_UShort)args[3]; b1 = (FT_UShort)args[4]; if ( BOUNDS( b0, exc->zp0.n_points ) || BOUNDS( b1, exc->zp0.n_points ) || BOUNDS( a0, exc->zp1.n_points ) || BOUNDS( a1, exc->zp1.n_points ) || BOUNDS( point, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } /* Cramer's rule */ dbx = SUB_LONG( exc->zp0.cur[b1].x, exc->zp0.cur[b0].x ); dby = SUB_LONG( exc->zp0.cur[b1].y, exc->zp0.cur[b0].y ); dax = SUB_LONG( exc->zp1.cur[a1].x, exc->zp1.cur[a0].x ); day = SUB_LONG( exc->zp1.cur[a1].y, exc->zp1.cur[a0].y ); dx = SUB_LONG( exc->zp0.cur[b0].x, exc->zp1.cur[a0].x ); dy = SUB_LONG( exc->zp0.cur[b0].y, exc->zp1.cur[a0].y ); discriminant = ADD_LONG( FT_MulDiv( dax, NEG_LONG( dby ), 0x40 ), FT_MulDiv( day, dbx, 0x40 ) ); dotproduct = ADD_LONG( FT_MulDiv( dax, dbx, 0x40 ), FT_MulDiv( day, dby, 0x40 ) ); /* The discriminant above is actually a cross product of vectors */ /* da and db. Together with the dot product, they can be used as */ /* surrogates for sine and cosine of the angle between the vectors. */ /* Indeed, */ /* dotproduct = |da||db|cos(angle) */ /* discriminant = |da||db|sin(angle) . */ /* We use these equations to reject grazing intersections by */ /* thresholding abs(tan(angle)) at 1/19, corresponding to 3 degrees. */ if ( MUL_LONG( 19, FT_ABS( discriminant ) ) > FT_ABS( dotproduct ) ) { val = ADD_LONG( FT_MulDiv( dx, NEG_LONG( dby ), 0x40 ), FT_MulDiv( dy, dbx, 0x40 ) ); R.x = FT_MulDiv( val, dax, discriminant ); R.y = FT_MulDiv( val, day, discriminant ); /* XXX: Block in backward_compatibility and/or post-IUP? */ exc->zp2.cur[point].x = ADD_LONG( exc->zp1.cur[a0].x, R.x ); exc->zp2.cur[point].y = ADD_LONG( exc->zp1.cur[a0].y, R.y ); } else { /* else, take the middle of the middles of A and B */ /* XXX: Block in backward_compatibility and/or post-IUP? */ exc->zp2.cur[point].x = ADD_LONG( ADD_LONG( exc->zp1.cur[a0].x, exc->zp1.cur[a1].x ), ADD_LONG( exc->zp0.cur[b0].x, exc->zp0.cur[b1].x ) ) / 4; exc->zp2.cur[point].y = ADD_LONG( ADD_LONG( exc->zp1.cur[a0].y, exc->zp1.cur[a1].y ), ADD_LONG( exc->zp0.cur[b0].y, exc->zp0.cur[b1].y ) ) / 4; } exc->zp2.tags[point] |= FT_CURVE_TAG_TOUCH_BOTH; } /************************************************************************** * * ALIGNPTS[]: ALIGN PoinTS * Opcode range: 0x27 * Stack: uint32 uint32 --> */ static void Ins_ALIGNPTS( TT_ExecContext exc, FT_Long* args ) { FT_UShort p1, p2; FT_F26Dot6 distance; p1 = (FT_UShort)args[0]; p2 = (FT_UShort)args[1]; if ( BOUNDS( p1, exc->zp1.n_points ) || BOUNDS( p2, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } distance = PROJECT( exc->zp0.cur + p2, exc->zp1.cur + p1 ) / 2; exc->func_move( exc, &exc->zp1, p1, distance ); exc->func_move( exc, &exc->zp0, p2, NEG_LONG( distance ) ); } /************************************************************************** * * IP[]: Interpolate Point * Opcode range: 0x39 * Stack: uint32... --> */ /* SOMETIMES, DUMBER CODE IS BETTER CODE */ static void Ins_IP( TT_ExecContext exc ) { FT_F26Dot6 old_range, cur_range; FT_Vector* orus_base; FT_Vector* cur_base; FT_Int twilight; if ( exc->top < exc->GS.loop ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } /* * We need to deal in a special way with the twilight zone. * Otherwise, by definition, the value of exc->twilight.orus[n] is (0,0), * for every n. */ twilight = ( exc->GS.gep0 == 0 || exc->GS.gep1 == 0 || exc->GS.gep2 == 0 ); if ( BOUNDS( exc->GS.rp1, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); goto Fail; } if ( twilight ) orus_base = &exc->zp0.org[exc->GS.rp1]; else orus_base = &exc->zp0.orus[exc->GS.rp1]; cur_base = &exc->zp0.cur[exc->GS.rp1]; /* XXX: There are some glyphs in some braindead but popular */ /* fonts out there (e.g. [aeu]grave in monotype.ttf) */ /* calling IP[] with bad values of rp[12]. */ /* Do something sane when this odd thing happens. */ if ( BOUNDS( exc->GS.rp1, exc->zp0.n_points ) || BOUNDS( exc->GS.rp2, exc->zp1.n_points ) ) { old_range = 0; cur_range = 0; } else { if ( twilight ) old_range = DUALPROJ( &exc->zp1.org[exc->GS.rp2], orus_base ); else if ( exc->metrics.x_scale == exc->metrics.y_scale ) old_range = DUALPROJ( &exc->zp1.orus[exc->GS.rp2], orus_base ); else { FT_Vector vec; vec.x = FT_MulFix( SUB_LONG( exc->zp1.orus[exc->GS.rp2].x, orus_base->x ), exc->metrics.x_scale ); vec.y = FT_MulFix( SUB_LONG( exc->zp1.orus[exc->GS.rp2].y, orus_base->y ), exc->metrics.y_scale ); old_range = FAST_DUALPROJ( &vec ); } cur_range = PROJECT( &exc->zp1.cur[exc->GS.rp2], cur_base ); } for ( ; exc->GS.loop > 0; exc->GS.loop-- ) { FT_UInt point = (FT_UInt)exc->stack[--exc->args]; FT_F26Dot6 org_dist, cur_dist, new_dist; /* check point bounds */ if ( BOUNDS( point, exc->zp2.n_points ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } continue; } if ( twilight ) org_dist = DUALPROJ( &exc->zp2.org[point], orus_base ); else if ( exc->metrics.x_scale == exc->metrics.y_scale ) org_dist = DUALPROJ( &exc->zp2.orus[point], orus_base ); else { FT_Vector vec; vec.x = FT_MulFix( SUB_LONG( exc->zp2.orus[point].x, orus_base->x ), exc->metrics.x_scale ); vec.y = FT_MulFix( SUB_LONG( exc->zp2.orus[point].y, orus_base->y ), exc->metrics.y_scale ); org_dist = FAST_DUALPROJ( &vec ); } cur_dist = PROJECT( &exc->zp2.cur[point], cur_base ); if ( org_dist ) { if ( old_range ) new_dist = FT_MulDiv( org_dist, cur_range, old_range ); else { /* This is the same as what MS does for the invalid case: */ /* */ /* delta = (Original_Pt - Original_RP1) - */ /* (Current_Pt - Current_RP1) ; */ /* */ /* In FreeType speak: */ /* */ /* delta = org_dist - cur_dist . */ /* */ /* We move `point' by `new_dist - cur_dist' after leaving */ /* this block, thus we have */ /* */ /* new_dist - cur_dist = delta , */ /* new_dist - cur_dist = org_dist - cur_dist , */ /* new_dist = org_dist . */ new_dist = org_dist; } } else new_dist = 0; exc->func_move( exc, &exc->zp2, (FT_UShort)point, SUB_LONG( new_dist, cur_dist ) ); } Fail: exc->GS.loop = 1; exc->new_top = exc->args; } /************************************************************************** * * UTP[a]: UnTouch Point * Opcode range: 0x29 * Stack: uint32 --> */ static void Ins_UTP( TT_ExecContext exc, FT_Long* args ) { FT_UShort point; FT_Byte mask; point = (FT_UShort)args[0]; if ( BOUNDS( point, exc->zp0.n_points ) ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); return; } mask = 0xFF; if ( exc->GS.freeVector.x != 0 ) mask &= ~FT_CURVE_TAG_TOUCH_X; if ( exc->GS.freeVector.y != 0 ) mask &= ~FT_CURVE_TAG_TOUCH_Y; exc->zp0.tags[point] &= mask; } /* Local variables for Ins_IUP: */ typedef struct IUP_WorkerRec_ { FT_Vector* orgs; /* original and current coordinate */ FT_Vector* curs; /* arrays */ FT_Vector* orus; FT_UInt max_points; } IUP_WorkerRec, *IUP_Worker; static void _iup_worker_shift( IUP_Worker worker, FT_UInt p1, FT_UInt p2, FT_UInt p ) { FT_UInt i; FT_F26Dot6 dx; dx = SUB_LONG( worker->curs[p].x, worker->orgs[p].x ); if ( dx != 0 ) { for ( i = p1; i < p; i++ ) worker->curs[i].x = ADD_LONG( worker->curs[i].x, dx ); for ( i = p + 1; i <= p2; i++ ) worker->curs[i].x = ADD_LONG( worker->curs[i].x, dx ); } } static void _iup_worker_interpolate( IUP_Worker worker, FT_UInt p1, FT_UInt p2, FT_UInt ref1, FT_UInt ref2 ) { FT_UInt i; FT_F26Dot6 orus1, orus2, org1, org2, cur1, cur2, delta1, delta2; if ( p1 > p2 ) return; if ( BOUNDS( ref1, worker->max_points ) || BOUNDS( ref2, worker->max_points ) ) return; orus1 = worker->orus[ref1].x; orus2 = worker->orus[ref2].x; if ( orus1 > orus2 ) { FT_F26Dot6 tmp_o; FT_UInt tmp_r; tmp_o = orus1; orus1 = orus2; orus2 = tmp_o; tmp_r = ref1; ref1 = ref2; ref2 = tmp_r; } org1 = worker->orgs[ref1].x; org2 = worker->orgs[ref2].x; cur1 = worker->curs[ref1].x; cur2 = worker->curs[ref2].x; delta1 = SUB_LONG( cur1, org1 ); delta2 = SUB_LONG( cur2, org2 ); if ( cur1 == cur2 || orus1 == orus2 ) { /* trivial snap or shift of untouched points */ for ( i = p1; i <= p2; i++ ) { FT_F26Dot6 x = worker->orgs[i].x; if ( x <= org1 ) x = ADD_LONG( x, delta1 ); else if ( x >= org2 ) x = ADD_LONG( x, delta2 ); else x = cur1; worker->curs[i].x = x; } } else { FT_Fixed scale = 0; FT_Bool scale_valid = 0; /* interpolation */ for ( i = p1; i <= p2; i++ ) { FT_F26Dot6 x = worker->orgs[i].x; if ( x <= org1 ) x = ADD_LONG( x, delta1 ); else if ( x >= org2 ) x = ADD_LONG( x, delta2 ); else { if ( !scale_valid ) { scale_valid = 1; scale = FT_DivFix( SUB_LONG( cur2, cur1 ), SUB_LONG( orus2, orus1 ) ); } x = ADD_LONG( cur1, FT_MulFix( SUB_LONG( worker->orus[i].x, orus1 ), scale ) ); } worker->curs[i].x = x; } } } /************************************************************************** * * IUP[a]: Interpolate Untouched Points * Opcode range: 0x30-0x31 * Stack: --> */ static void Ins_IUP( TT_ExecContext exc ) { IUP_WorkerRec V; FT_Byte mask; FT_UInt first_point; /* first point of contour */ FT_UInt end_point; /* end point (last+1) of contour */ FT_UInt first_touched; /* first touched point in contour */ FT_UInt cur_touched; /* current touched point in contour */ FT_UInt point; /* current point */ FT_Short contour; /* current contour */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* See `ttinterp.h' for details on backward compatibility mode. */ /* Allow IUP until it has been called on both axes. Immediately */ /* return on subsequent ones. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility ) { if ( exc->iupx_called && exc->iupy_called ) return; if ( exc->opcode & 1 ) exc->iupx_called = TRUE; else exc->iupy_called = TRUE; } #endif /* ignore empty outlines */ if ( exc->pts.n_contours == 0 ) return; if ( exc->opcode & 1 ) { mask = FT_CURVE_TAG_TOUCH_X; V.orgs = exc->pts.org; V.curs = exc->pts.cur; V.orus = exc->pts.orus; } else { mask = FT_CURVE_TAG_TOUCH_Y; V.orgs = (FT_Vector*)( (FT_Pos*)exc->pts.org + 1 ); V.curs = (FT_Vector*)( (FT_Pos*)exc->pts.cur + 1 ); V.orus = (FT_Vector*)( (FT_Pos*)exc->pts.orus + 1 ); } V.max_points = exc->pts.n_points; contour = 0; point = 0; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode ) { exc->iup_called = TRUE; if ( exc->sph_tweak_flags & SPH_TWEAK_SKIP_IUP ) return; } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ do { end_point = exc->pts.contours[contour] - exc->pts.first_point; first_point = point; if ( BOUNDS( end_point, exc->pts.n_points ) ) end_point = exc->pts.n_points - 1; while ( point <= end_point && ( exc->pts.tags[point] & mask ) == 0 ) point++; if ( point <= end_point ) { first_touched = point; cur_touched = point; point++; while ( point <= end_point ) { if ( ( exc->pts.tags[point] & mask ) != 0 ) { _iup_worker_interpolate( &V, cur_touched + 1, point - 1, cur_touched, point ); cur_touched = point; } point++; } if ( cur_touched == first_touched ) _iup_worker_shift( &V, first_point, end_point, cur_touched ); else { _iup_worker_interpolate( &V, (FT_UShort)( cur_touched + 1 ), end_point, cur_touched, first_touched ); if ( first_touched > 0 ) _iup_worker_interpolate( &V, first_point, first_touched - 1, cur_touched, first_touched ); } } contour++; } while ( contour < exc->pts.n_contours ); } /************************************************************************** * * DELTAPn[]: DELTA exceptions P1, P2, P3 * Opcode range: 0x5D,0x71,0x72 * Stack: uint32 (2 * uint32)... --> */ static void Ins_DELTAP( TT_ExecContext exc, FT_Long* args ) { FT_ULong nump, k; FT_UShort A; FT_ULong C, P; FT_Long B; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->ignore_x_mode && exc->iup_called && ( exc->sph_tweak_flags & SPH_TWEAK_NO_DELTAP_AFTER_IUP ) ) goto Fail; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ P = (FT_ULong)exc->func_cur_ppem( exc ); nump = (FT_ULong)args[0]; /* some points theoretically may occur more than once, thus UShort isn't enough */ for ( k = 1; k <= nump; k++ ) { if ( exc->args < 2 ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Too_Few_Arguments ); exc->args = 0; goto Fail; } exc->args -= 2; A = (FT_UShort)exc->stack[exc->args + 1]; B = exc->stack[exc->args]; /* XXX: Because some popular fonts contain some invalid DeltaP */ /* instructions, we simply ignore them when the stacked */ /* point reference is off limit, rather than returning an */ /* error. As a delta instruction doesn't change a glyph */ /* in great ways, this shouldn't be a problem. */ if ( !BOUNDS( A, exc->zp0.n_points ) ) { C = ( (FT_ULong)B & 0xF0 ) >> 4; switch ( exc->opcode ) { case 0x5D: break; case 0x71: C += 16; break; case 0x72: C += 32; break; } C += exc->GS.delta_base; if ( P == C ) { B = ( (FT_ULong)B & 0xF ) - 8; if ( B >= 0 ) B++; B *= 1L << ( 6 - exc->GS.delta_shift ); #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY ) { /* * Allow delta move if * * - not using ignore_x_mode rendering, * - glyph is specifically set to allow it, or * - glyph is composite and freedom vector is not in subpixel * direction. */ if ( !exc->ignore_x_mode || ( exc->sph_tweak_flags & SPH_TWEAK_ALWAYS_DO_DELTAP ) || ( exc->is_composite && exc->GS.freeVector.y != 0 ) ) exc->func_move( exc, &exc->zp0, A, B ); /* Otherwise, apply subpixel hinting and compatibility mode */ /* rules, always skipping deltas in subpixel direction. */ else if ( exc->ignore_x_mode && exc->GS.freeVector.y != 0 ) { FT_UShort B1, B2; /* save the y value of the point now; compare after move */ B1 = (FT_UShort)exc->zp0.cur[A].y; /* Standard subpixel hinting: Allow y move for y-touched */ /* points. This messes up DejaVu ... */ if ( !exc->face->sph_compatibility_mode && ( exc->zp0.tags[A] & FT_CURVE_TAG_TOUCH_Y ) ) exc->func_move( exc, &exc->zp0, A, B ); /* compatibility mode */ else if ( exc->face->sph_compatibility_mode && !( exc->sph_tweak_flags & SPH_TWEAK_ALWAYS_SKIP_DELTAP ) ) { if ( exc->sph_tweak_flags & SPH_TWEAK_ROUND_NONPIXEL_Y_MOVES ) B = FT_PIX_ROUND( B1 + B ) - B1; /* Allow delta move if using sph_compatibility_mode, */ /* IUP has not been called, and point is touched on Y. */ if ( !exc->iup_called && ( exc->zp0.tags[A] & FT_CURVE_TAG_TOUCH_Y ) ) exc->func_move( exc, &exc->zp0, A, B ); } B2 = (FT_UShort)exc->zp0.cur[A].y; /* Reverse this move if it results in a disallowed move */ if ( exc->GS.freeVector.y != 0 && ( ( exc->face->sph_compatibility_mode && ( B1 & 63 ) == 0 && ( B2 & 63 ) != 0 ) || ( ( exc->sph_tweak_flags & SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES_DELTAP ) && ( B1 & 63 ) != 0 && ( B2 & 63 ) != 0 ) ) ) exc->func_move( exc, &exc->zp0, A, NEG_LONG( B ) ); } } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ { #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* See `ttinterp.h' for details on backward compatibility */ /* mode. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->backward_compatibility ) { if ( !( exc->iupx_called && exc->iupy_called ) && ( ( exc->is_composite && exc->GS.freeVector.y != 0 ) || ( exc->zp0.tags[A] & FT_CURVE_TAG_TOUCH_Y ) ) ) exc->func_move( exc, &exc->zp0, A, B ); } else #endif exc->func_move( exc, &exc->zp0, A, B ); } } } else if ( exc->pedantic_hinting ) exc->error = FT_THROW( Invalid_Reference ); } Fail: exc->new_top = exc->args; } /************************************************************************** * * DELTACn[]: DELTA exceptions C1, C2, C3 * Opcode range: 0x73,0x74,0x75 * Stack: uint32 (2 * uint32)... --> */ static void Ins_DELTAC( TT_ExecContext exc, FT_Long* args ) { FT_ULong nump, k; FT_ULong A, C, P; FT_Long B; P = (FT_ULong)exc->func_cur_ppem( exc ); nump = (FT_ULong)args[0]; for ( k = 1; k <= nump; k++ ) { if ( exc->args < 2 ) { if ( exc->pedantic_hinting ) exc->error = FT_THROW( Too_Few_Arguments ); exc->args = 0; goto Fail; } exc->args -= 2; A = (FT_ULong)exc->stack[exc->args + 1]; B = exc->stack[exc->args]; if ( BOUNDSL( A, exc->cvtSize ) ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Invalid_Reference ); return; } } else { C = ( (FT_ULong)B & 0xF0 ) >> 4; switch ( exc->opcode ) { case 0x73: break; case 0x74: C += 16; break; case 0x75: C += 32; break; } C += exc->GS.delta_base; if ( P == C ) { B = ( (FT_ULong)B & 0xF ) - 8; if ( B >= 0 ) B++; B *= 1L << ( 6 - exc->GS.delta_shift ); exc->func_move_cvt( exc, A, B ); } } } Fail: exc->new_top = exc->args; } /************************************************************************** * * MISC. INSTRUCTIONS * */ /************************************************************************** * * GETINFO[]: GET INFOrmation * Opcode range: 0x88 * Stack: uint32 --> uint32 * * XXX: UNDOCUMENTED: Selector bits higher than 9 are currently (May * 2015) not documented in the OpenType specification. * * Selector bit 11 is incorrectly described as bit 8, while the * real meaning of bit 8 (vertical LCD subpixels) stays * undocumented. The same mistake can be found in Greg Hitchcock's * whitepaper. */ static void Ins_GETINFO( TT_ExecContext exc, FT_Long* args ) { FT_Long K; TT_Driver driver = (TT_Driver)FT_FACE_DRIVER( exc->face ); K = 0; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /********************************* * RASTERIZER VERSION * Selector Bit: 0 * Return Bit(s): 0-7 */ if ( SUBPIXEL_HINTING_INFINALITY && ( args[0] & 1 ) != 0 && exc->subpixel_hinting ) { if ( exc->ignore_x_mode ) { /* if in ClearType backward compatibility mode, */ /* we sometimes change the TrueType version dynamically */ K = exc->rasterizer_version; FT_TRACE6(( "Setting rasterizer version %d\n", exc->rasterizer_version )); } else K = TT_INTERPRETER_VERSION_38; } else #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ if ( ( args[0] & 1 ) != 0 ) K = driver->interpreter_version; /********************************* * GLYPH ROTATED * Selector Bit: 1 * Return Bit(s): 8 */ if ( ( args[0] & 2 ) != 0 && exc->tt_metrics.rotated ) K |= 1 << 8; /********************************* * GLYPH STRETCHED * Selector Bit: 2 * Return Bit(s): 9 */ if ( ( args[0] & 4 ) != 0 && exc->tt_metrics.stretched ) K |= 1 << 9; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /********************************* * VARIATION GLYPH * Selector Bit: 3 * Return Bit(s): 10 * * XXX: UNDOCUMENTED! */ if ( (args[0] & 8 ) != 0 && exc->face->blend ) K |= 1 << 10; #endif /********************************* * BI-LEVEL HINTING AND * GRAYSCALE RENDERING * Selector Bit: 5 * Return Bit(s): 12 */ if ( ( args[0] & 32 ) != 0 && exc->grayscale ) K |= 1 << 12; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* Toggle the following flags only outside of monochrome mode. */ /* Otherwise, instructions may behave weirdly and rendering results */ /* may differ between v35 and v40 mode, e.g., in `Times New Roman */ /* Bold Italic'. */ if ( SUBPIXEL_HINTING_MINIMAL && exc->subpixel_hinting_lean ) { /********************************* * HINTING FOR SUBPIXEL * Selector Bit: 6 * Return Bit(s): 13 * * v40 does subpixel hinting by default. */ if ( ( args[0] & 64 ) != 0 ) K |= 1 << 13; /********************************* * VERTICAL LCD SUBPIXELS? * Selector Bit: 8 * Return Bit(s): 15 */ if ( ( args[0] & 256 ) != 0 && exc->vertical_lcd_lean ) K |= 1 << 15; /********************************* * SUBPIXEL POSITIONED? * Selector Bit: 10 * Return Bit(s): 17 * * XXX: FreeType supports it, dependent on what client does? */ if ( ( args[0] & 1024 ) != 0 ) K |= 1 << 17; /********************************* * SYMMETRICAL SMOOTHING * Selector Bit: 11 * Return Bit(s): 18 * * The only smoothing method FreeType supports unless someone sets * FT_LOAD_TARGET_MONO. */ if ( ( args[0] & 2048 ) != 0 && exc->subpixel_hinting_lean ) K |= 1 << 18; /********************************* * CLEARTYPE HINTING AND * GRAYSCALE RENDERING * Selector Bit: 12 * Return Bit(s): 19 * * Grayscale rendering is what FreeType does anyway unless someone * sets FT_LOAD_TARGET_MONO or FT_LOAD_TARGET_LCD(_V) */ if ( ( args[0] & 4096 ) != 0 && exc->grayscale_cleartype ) K |= 1 << 19; } #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY && exc->rasterizer_version >= TT_INTERPRETER_VERSION_35 ) { if ( exc->rasterizer_version >= 37 ) { /********************************* * HINTING FOR SUBPIXEL * Selector Bit: 6 * Return Bit(s): 13 */ if ( ( args[0] & 64 ) != 0 && exc->subpixel_hinting ) K |= 1 << 13; /********************************* * COMPATIBLE WIDTHS ENABLED * Selector Bit: 7 * Return Bit(s): 14 * * Functionality still needs to be added */ if ( ( args[0] & 128 ) != 0 && exc->compatible_widths ) K |= 1 << 14; /********************************* * VERTICAL LCD SUBPIXELS? * Selector Bit: 8 * Return Bit(s): 15 * * Functionality still needs to be added */ if ( ( args[0] & 256 ) != 0 && exc->vertical_lcd ) K |= 1 << 15; /********************************* * HINTING FOR BGR? * Selector Bit: 9 * Return Bit(s): 16 * * Functionality still needs to be added */ if ( ( args[0] & 512 ) != 0 && exc->bgr ) K |= 1 << 16; if ( exc->rasterizer_version >= 38 ) { /********************************* * SUBPIXEL POSITIONED? * Selector Bit: 10 * Return Bit(s): 17 * * Functionality still needs to be added */ if ( ( args[0] & 1024 ) != 0 && exc->subpixel_positioned ) K |= 1 << 17; /********************************* * SYMMETRICAL SMOOTHING * Selector Bit: 11 * Return Bit(s): 18 * * Functionality still needs to be added */ if ( ( args[0] & 2048 ) != 0 && exc->symmetrical_smoothing ) K |= 1 << 18; /********************************* * GRAY CLEARTYPE * Selector Bit: 12 * Return Bit(s): 19 * * Functionality still needs to be added */ if ( ( args[0] & 4096 ) != 0 && exc->gray_cleartype ) K |= 1 << 19; } } } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ args[0] = K; } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /************************************************************************** * * GETVARIATION[]: get normalized variation (blend) coordinates * Opcode range: 0x91 * Stack: --> f2.14... * * XXX: UNDOCUMENTED! There is no official documentation from Apple for * this bytecode instruction. Active only if a font has GX * variation axes. */ static void Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } } /************************************************************************** * * GETDATA[]: no idea what this is good for * Opcode range: 0x92 * Stack: --> 17 * * XXX: UNDOCUMENTED! There is no documentation from Apple for this * very weird bytecode instruction. */ static void Ins_GETDATA( FT_Long* args ) { args[0] = 17; } #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ static void Ins_UNKNOWN( TT_ExecContext exc ) { TT_DefRecord* def = exc->IDefs; TT_DefRecord* limit = FT_OFFSET( def, exc->numIDefs ); for ( ; def < limit; def++ ) { if ( (FT_Byte)def->opc == exc->opcode && def->active ) { TT_CallRec* call; if ( exc->callTop >= exc->callSize ) { exc->error = FT_THROW( Stack_Overflow ); return; } call = exc->callStack + exc->callTop++; call->Caller_Range = exc->curRange; call->Caller_IP = exc->IP + 1; call->Cur_Count = 1; call->Def = def; Ins_Goto_CodeRange( exc, def->range, def->start ); exc->step_ins = FALSE; return; } } exc->error = FT_THROW( Invalid_Opcode ); } /************************************************************************** * * RUN * * This function executes a run of opcodes. It will exit in the * following cases: * * - Errors (in which case it returns FALSE). * * - Reaching the end of the main code range (returns TRUE). * Reaching the end of a code range within a function call is an * error. * * - After executing one single opcode, if the flag `Instruction_Trap' * is set to TRUE (returns TRUE). * * On exit with TRUE, test IP < CodeSize to know whether it comes from * an instruction trap or a normal termination. * * * Note: The documented DEBUG opcode pops a value from the stack. This * behaviour is unsupported; here a DEBUG opcode is always an * error. * * * THIS IS THE INTERPRETER'S MAIN LOOP. * */ /* documentation is in ttinterp.h */ FT_EXPORT_DEF( FT_Error ) TT_RunIns( TT_ExecContext exc ) { FT_ULong ins_counter = 0; /* executed instructions counter */ FT_ULong num_twilight_points; FT_UShort i; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY FT_Byte opcode_pattern[1][2] = { /* #8 TypeMan Talk Align */ { 0x06, /* SPVTL */ 0x7D, /* RDTG */ }, }; FT_UShort opcode_patterns = 1; FT_UShort opcode_pointer[1] = { 0 }; FT_UShort opcode_size[1] = { 1 }; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /* We restrict the number of twilight points to a reasonable, */ /* heuristic value to avoid slow execution of malformed bytecode. */ num_twilight_points = FT_MAX( 30, 2 * ( exc->pts.n_points + exc->cvtSize ) ); if ( exc->twilight.n_points > num_twilight_points ) { if ( num_twilight_points > 0xFFFFU ) num_twilight_points = 0xFFFFU; FT_TRACE5(( "TT_RunIns: Resetting number of twilight points\n" )); FT_TRACE5(( " from %d to the more reasonable value %ld\n", exc->twilight.n_points, num_twilight_points )); exc->twilight.n_points = (FT_UShort)num_twilight_points; } /* Set up loop detectors. We restrict the number of LOOPCALL loops */ /* and the number of JMPR, JROT, and JROF calls with a negative */ /* argument to values that depend on various parameters like the */ /* size of the CVT table or the number of points in the current */ /* glyph (if applicable). */ /* */ /* The idea is that in real-world bytecode you either iterate over */ /* all CVT entries (in the `prep' table), or over all points (or */ /* contours, in the `glyf' table) of a glyph, and such iterations */ /* don't happen very often. */ exc->loopcall_counter = 0; exc->neg_jump_counter = 0; /* The maximum values are heuristic. */ if ( exc->pts.n_points ) exc->loopcall_counter_max = FT_MAX( 50, 10 * exc->pts.n_points ) + FT_MAX( 50, exc->cvtSize / 10 ); else exc->loopcall_counter_max = 300 + 22 * exc->cvtSize; /* as a protection against an unreasonable number of CVT entries */ /* we assume at most 100 control values per glyph for the counter */ if ( exc->loopcall_counter_max > 100 * (FT_ULong)exc->face->root.num_glyphs ) exc->loopcall_counter_max = 100 * (FT_ULong)exc->face->root.num_glyphs; FT_TRACE5(( "TT_RunIns: Limiting total number of loops in LOOPCALL" " to %ld\n", exc->loopcall_counter_max )); exc->neg_jump_counter_max = exc->loopcall_counter_max; FT_TRACE5(( "TT_RunIns: Limiting total number of backward jumps" " to %ld\n", exc->neg_jump_counter_max )); /* set PPEM and CVT functions */ exc->tt_metrics.ratio = 0; if ( exc->metrics.x_ppem != exc->metrics.y_ppem ) { /* non-square pixels, use the stretched routines */ exc->func_cur_ppem = Current_Ppem_Stretched; exc->func_read_cvt = Read_CVT_Stretched; exc->func_write_cvt = Write_CVT_Stretched; exc->func_move_cvt = Move_CVT_Stretched; } else { /* square pixels, use normal routines */ exc->func_cur_ppem = Current_Ppem; exc->func_read_cvt = Read_CVT; exc->func_write_cvt = Write_CVT; exc->func_move_cvt = Move_CVT; } exc->origCvt = exc->cvt; exc->origStorage = exc->storage; exc->iniRange = exc->curRange; Compute_Funcs( exc ); Compute_Round( exc, (FT_Byte)exc->GS.round_state ); do { exc->opcode = exc->code[exc->IP]; #ifdef FT_DEBUG_LEVEL_TRACE if ( ft_trace_levels[trace_ttinterp] >= 6 ) { FT_Long cnt = FT_MIN( 8, exc->top ); FT_Long n; /* if tracing level is 7, show current code position */ /* and the first few stack elements also */ FT_TRACE6(( " " )); FT_TRACE7(( "%06ld ", exc->IP )); FT_TRACE6(( "%s", opcode_name[exc->opcode] + 2 )); FT_TRACE7(( "%*s", *opcode_name[exc->opcode] == 'A' ? 2 : 12 - ( *opcode_name[exc->opcode] - '0' ), "#" )); for ( n = 1; n <= cnt; n++ ) FT_TRACE7(( " %ld", exc->stack[exc->top - n] )); FT_TRACE6(( "\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ if ( ( exc->length = opcode_length[exc->opcode] ) < 0 ) { if ( exc->IP + 1 >= exc->codeSize ) goto LErrorCodeOverflow_; exc->length = 2 - exc->length * exc->code[exc->IP + 1]; } if ( exc->IP + exc->length > exc->codeSize ) goto LErrorCodeOverflow_; /* First, let's check for empty stack and overflow */ exc->args = exc->top - ( Pop_Push_Count[exc->opcode] >> 4 ); /* `args' is the top of the stack once arguments have been popped. */ /* One can also interpret it as the index of the last argument. */ if ( exc->args < 0 ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Too_Few_Arguments ); goto LErrorLabel_; } /* push zeroes onto the stack */ for ( i = 0; i < Pop_Push_Count[exc->opcode] >> 4; i++ ) exc->stack[i] = 0; exc->args = 0; } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( exc->opcode == 0x91 ) { /* this is very special: GETVARIATION returns */ /* a variable number of arguments */ /* it is the job of the application to `activate' GX handling, */ /* this is, calling any of the GX API functions on the current */ /* font to select a variation instance */ if ( exc->face->blend ) exc->new_top = exc->args + exc->face->blend->num_axis; } else #endif exc->new_top = exc->args + ( Pop_Push_Count[exc->opcode] & 15 ); /* `new_top' is the new top of the stack, after the instruction's */ /* execution. `top' will be set to `new_top' after the `switch' */ /* statement. */ if ( exc->new_top > exc->stackSize ) { exc->error = FT_THROW( Stack_Overflow ); goto LErrorLabel_; } exc->step_ins = TRUE; exc->error = FT_Err_Ok; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY ) { for ( i = 0; i < opcode_patterns; i++ ) { if ( opcode_pointer[i] < opcode_size[i] && exc->opcode == opcode_pattern[i][opcode_pointer[i]] ) { opcode_pointer[i] += 1; if ( opcode_pointer[i] == opcode_size[i] ) { FT_TRACE6(( "sph: opcode ptrn: %d, %s %s\n", i, exc->face->root.family_name, exc->face->root.style_name )); switch ( i ) { case 0: break; } opcode_pointer[i] = 0; } } else opcode_pointer[i] = 0; } } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ { FT_Long* args = exc->stack + exc->args; FT_Byte opcode = exc->opcode; switch ( opcode ) { case 0x00: /* SVTCA y */ case 0x01: /* SVTCA x */ case 0x02: /* SPvTCA y */ case 0x03: /* SPvTCA x */ case 0x04: /* SFvTCA y */ case 0x05: /* SFvTCA x */ Ins_SxyTCA( exc ); break; case 0x06: /* SPvTL // */ case 0x07: /* SPvTL + */ Ins_SPVTL( exc, args ); break; case 0x08: /* SFvTL // */ case 0x09: /* SFvTL + */ Ins_SFVTL( exc, args ); break; case 0x0A: /* SPvFS */ Ins_SPVFS( exc, args ); break; case 0x0B: /* SFvFS */ Ins_SFVFS( exc, args ); break; case 0x0C: /* GPv */ Ins_GPV( exc, args ); break; case 0x0D: /* GFv */ Ins_GFV( exc, args ); break; case 0x0E: /* SFvTPv */ Ins_SFVTPV( exc ); break; case 0x0F: /* ISECT */ Ins_ISECT( exc, args ); break; case 0x10: /* SRP0 */ Ins_SRP0( exc, args ); break; case 0x11: /* SRP1 */ Ins_SRP1( exc, args ); break; case 0x12: /* SRP2 */ Ins_SRP2( exc, args ); break; case 0x13: /* SZP0 */ Ins_SZP0( exc, args ); break; case 0x14: /* SZP1 */ Ins_SZP1( exc, args ); break; case 0x15: /* SZP2 */ Ins_SZP2( exc, args ); break; case 0x16: /* SZPS */ Ins_SZPS( exc, args ); break; case 0x17: /* SLOOP */ Ins_SLOOP( exc, args ); break; case 0x18: /* RTG */ Ins_RTG( exc ); break; case 0x19: /* RTHG */ Ins_RTHG( exc ); break; case 0x1A: /* SMD */ Ins_SMD( exc, args ); break; case 0x1B: /* ELSE */ Ins_ELSE( exc ); break; case 0x1C: /* JMPR */ Ins_JMPR( exc, args ); break; case 0x1D: /* SCVTCI */ Ins_SCVTCI( exc, args ); break; case 0x1E: /* SSWCI */ Ins_SSWCI( exc, args ); break; case 0x1F: /* SSW */ Ins_SSW( exc, args ); break; case 0x20: /* DUP */ Ins_DUP( args ); break; case 0x21: /* POP */ Ins_POP(); break; case 0x22: /* CLEAR */ Ins_CLEAR( exc ); break; case 0x23: /* SWAP */ Ins_SWAP( args ); break; case 0x24: /* DEPTH */ Ins_DEPTH( exc, args ); break; case 0x25: /* CINDEX */ Ins_CINDEX( exc, args ); break; case 0x26: /* MINDEX */ Ins_MINDEX( exc, args ); break; case 0x27: /* ALIGNPTS */ Ins_ALIGNPTS( exc, args ); break; case 0x28: /* RAW */ Ins_UNKNOWN( exc ); break; case 0x29: /* UTP */ Ins_UTP( exc, args ); break; case 0x2A: /* LOOPCALL */ Ins_LOOPCALL( exc, args ); break; case 0x2B: /* CALL */ Ins_CALL( exc, args ); break; case 0x2C: /* FDEF */ Ins_FDEF( exc, args ); break; case 0x2D: /* ENDF */ Ins_ENDF( exc ); break; case 0x2E: /* MDAP */ case 0x2F: /* MDAP */ Ins_MDAP( exc, args ); break; case 0x30: /* IUP */ case 0x31: /* IUP */ Ins_IUP( exc ); break; case 0x32: /* SHP */ case 0x33: /* SHP */ Ins_SHP( exc ); break; case 0x34: /* SHC */ case 0x35: /* SHC */ Ins_SHC( exc, args ); break; case 0x36: /* SHZ */ case 0x37: /* SHZ */ Ins_SHZ( exc, args ); break; case 0x38: /* SHPIX */ Ins_SHPIX( exc, args ); break; case 0x39: /* IP */ Ins_IP( exc ); break; case 0x3A: /* MSIRP */ case 0x3B: /* MSIRP */ Ins_MSIRP( exc, args ); break; case 0x3C: /* AlignRP */ Ins_ALIGNRP( exc ); break; case 0x3D: /* RTDG */ Ins_RTDG( exc ); break; case 0x3E: /* MIAP */ case 0x3F: /* MIAP */ Ins_MIAP( exc, args ); break; case 0x40: /* NPUSHB */ Ins_NPUSHB( exc, args ); break; case 0x41: /* NPUSHW */ Ins_NPUSHW( exc, args ); break; case 0x42: /* WS */ Ins_WS( exc, args ); break; case 0x43: /* RS */ Ins_RS( exc, args ); break; case 0x44: /* WCVTP */ Ins_WCVTP( exc, args ); break; case 0x45: /* RCVT */ Ins_RCVT( exc, args ); break; case 0x46: /* GC */ case 0x47: /* GC */ Ins_GC( exc, args ); break; case 0x48: /* SCFS */ Ins_SCFS( exc, args ); break; case 0x49: /* MD */ case 0x4A: /* MD */ Ins_MD( exc, args ); break; case 0x4B: /* MPPEM */ Ins_MPPEM( exc, args ); break; case 0x4C: /* MPS */ Ins_MPS( exc, args ); break; case 0x4D: /* FLIPON */ Ins_FLIPON( exc ); break; case 0x4E: /* FLIPOFF */ Ins_FLIPOFF( exc ); break; case 0x4F: /* DEBUG */ Ins_DEBUG( exc ); break; case 0x50: /* LT */ Ins_LT( args ); break; case 0x51: /* LTEQ */ Ins_LTEQ( args ); break; case 0x52: /* GT */ Ins_GT( args ); break; case 0x53: /* GTEQ */ Ins_GTEQ( args ); break; case 0x54: /* EQ */ Ins_EQ( args ); break; case 0x55: /* NEQ */ Ins_NEQ( args ); break; case 0x56: /* ODD */ Ins_ODD( exc, args ); break; case 0x57: /* EVEN */ Ins_EVEN( exc, args ); break; case 0x58: /* IF */ Ins_IF( exc, args ); break; case 0x59: /* EIF */ Ins_EIF(); break; case 0x5A: /* AND */ Ins_AND( args ); break; case 0x5B: /* OR */ Ins_OR( args ); break; case 0x5C: /* NOT */ Ins_NOT( args ); break; case 0x5D: /* DELTAP1 */ Ins_DELTAP( exc, args ); break; case 0x5E: /* SDB */ Ins_SDB( exc, args ); break; case 0x5F: /* SDS */ Ins_SDS( exc, args ); break; case 0x60: /* ADD */ Ins_ADD( args ); break; case 0x61: /* SUB */ Ins_SUB( args ); break; case 0x62: /* DIV */ Ins_DIV( exc, args ); break; case 0x63: /* MUL */ Ins_MUL( args ); break; case 0x64: /* ABS */ Ins_ABS( args ); break; case 0x65: /* NEG */ Ins_NEG( args ); break; case 0x66: /* FLOOR */ Ins_FLOOR( args ); break; case 0x67: /* CEILING */ Ins_CEILING( args ); break; case 0x68: /* ROUND */ case 0x69: /* ROUND */ case 0x6A: /* ROUND */ case 0x6B: /* ROUND */ Ins_ROUND( exc, args ); break; case 0x6C: /* NROUND */ case 0x6D: /* NROUND */ case 0x6E: /* NRRUND */ case 0x6F: /* NROUND */ Ins_NROUND( exc, args ); break; case 0x70: /* WCVTF */ Ins_WCVTF( exc, args ); break; case 0x71: /* DELTAP2 */ case 0x72: /* DELTAP3 */ Ins_DELTAP( exc, args ); break; case 0x73: /* DELTAC0 */ case 0x74: /* DELTAC1 */ case 0x75: /* DELTAC2 */ Ins_DELTAC( exc, args ); break; case 0x76: /* SROUND */ Ins_SROUND( exc, args ); break; case 0x77: /* S45Round */ Ins_S45ROUND( exc, args ); break; case 0x78: /* JROT */ Ins_JROT( exc, args ); break; case 0x79: /* JROF */ Ins_JROF( exc, args ); break; case 0x7A: /* ROFF */ Ins_ROFF( exc ); break; case 0x7B: /* ???? */ Ins_UNKNOWN( exc ); break; case 0x7C: /* RUTG */ Ins_RUTG( exc ); break; case 0x7D: /* RDTG */ Ins_RDTG( exc ); break; case 0x7E: /* SANGW */ Ins_SANGW(); break; case 0x7F: /* AA */ Ins_AA(); break; case 0x80: /* FLIPPT */ Ins_FLIPPT( exc ); break; case 0x81: /* FLIPRGON */ Ins_FLIPRGON( exc, args ); break; case 0x82: /* FLIPRGOFF */ Ins_FLIPRGOFF( exc, args ); break; case 0x83: /* UNKNOWN */ case 0x84: /* UNKNOWN */ Ins_UNKNOWN( exc ); break; case 0x85: /* SCANCTRL */ Ins_SCANCTRL( exc, args ); break; case 0x86: /* SDPvTL */ case 0x87: /* SDPvTL */ Ins_SDPVTL( exc, args ); break; case 0x88: /* GETINFO */ Ins_GETINFO( exc, args ); break; case 0x89: /* IDEF */ Ins_IDEF( exc, args ); break; case 0x8A: /* ROLL */ Ins_ROLL( args ); break; case 0x8B: /* MAX */ Ins_MAX( args ); break; case 0x8C: /* MIN */ Ins_MIN( args ); break; case 0x8D: /* SCANTYPE */ Ins_SCANTYPE( exc, args ); break; case 0x8E: /* INSTCTRL */ Ins_INSTCTRL( exc, args ); break; case 0x8F: /* ADJUST */ case 0x90: /* ADJUST */ Ins_UNKNOWN( exc ); break; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT case 0x91: /* it is the job of the application to `activate' GX handling, */ /* this is, calling any of the GX API functions on the current */ /* font to select a variation instance */ if ( exc->face->blend ) Ins_GETVARIATION( exc, args ); else Ins_UNKNOWN( exc ); break; case 0x92: /* there is at least one MS font (LaoUI.ttf version 5.01) that */ /* uses IDEFs for 0x91 and 0x92; for this reason we activate */ /* GETDATA for GX fonts only, similar to GETVARIATION */ if ( exc->face->blend ) Ins_GETDATA( args ); else Ins_UNKNOWN( exc ); break; #endif default: if ( opcode >= 0xE0 ) Ins_MIRP( exc, args ); else if ( opcode >= 0xC0 ) Ins_MDRP( exc, args ); else if ( opcode >= 0xB8 ) Ins_PUSHW( exc, args ); else if ( opcode >= 0xB0 ) Ins_PUSHB( exc, args ); else Ins_UNKNOWN( exc ); } } if ( exc->error ) { switch ( exc->error ) { /* looking for redefined instructions */ case FT_ERR( Invalid_Opcode ): { TT_DefRecord* def = exc->IDefs; TT_DefRecord* limit = FT_OFFSET( def, exc->numIDefs ); for ( ; def < limit; def++ ) { if ( def->active && exc->opcode == (FT_Byte)def->opc ) { TT_CallRec* callrec; if ( exc->callTop >= exc->callSize ) { exc->error = FT_THROW( Invalid_Reference ); goto LErrorLabel_; } callrec = &exc->callStack[exc->callTop]; callrec->Caller_Range = exc->curRange; callrec->Caller_IP = exc->IP + 1; callrec->Cur_Count = 1; callrec->Def = def; if ( Ins_Goto_CodeRange( exc, def->range, def->start ) == FAILURE ) goto LErrorLabel_; goto LSuiteLabel_; } } } exc->error = FT_THROW( Invalid_Opcode ); goto LErrorLabel_; #if 0 break; /* Unreachable code warning suppression. */ /* Leave to remind in case a later change the editor */ /* to consider break; */ #endif default: goto LErrorLabel_; #if 0 break; #endif } } exc->top = exc->new_top; if ( exc->step_ins ) exc->IP += exc->length; /* increment instruction counter and check if we didn't */ /* run this program for too long (e.g. infinite loops). */ if ( ++ins_counter > TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES ) { exc->error = FT_THROW( Execution_Too_Long ); goto LErrorLabel_; } LSuiteLabel_: if ( exc->IP >= exc->codeSize ) { if ( exc->callTop > 0 ) { exc->error = FT_THROW( Code_Overflow ); goto LErrorLabel_; } else goto LNo_Error_; } } while ( !exc->instruction_trap ); LNo_Error_: FT_TRACE4(( " %ld instruction%s executed\n", ins_counter, ins_counter == 1 ? "" : "s" )); exc->cvt = exc->origCvt; exc->storage = exc->origStorage; return FT_Err_Ok; LErrorCodeOverflow_: exc->error = FT_THROW( Code_Overflow ); LErrorLabel_: if ( exc->error && !exc->instruction_trap ) FT_TRACE1(( " The interpreter returned error 0x%x\n", exc->error )); exc->cvt = exc->origCvt; exc->storage = exc->origStorage; return exc->error; } #else /* !TT_USE_BYTECODE_INTERPRETER */ /* ANSI C doesn't like empty source files */ typedef int _tt_interp_dummy; #endif /* !TT_USE_BYTECODE_INTERPRETER */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttinterp.c
C++
gpl-3.0
222,576
/**************************************************************************** * * ttinterp.h * * TrueType bytecode interpreter (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTINTERP_H_ #define TTINTERP_H_ #include "ttobjs.h" FT_BEGIN_HEADER /************************************************************************** * * Rounding mode constants. */ #define TT_Round_Off 5 #define TT_Round_To_Half_Grid 0 #define TT_Round_To_Grid 1 #define TT_Round_To_Double_Grid 2 #define TT_Round_Up_To_Grid 4 #define TT_Round_Down_To_Grid 3 #define TT_Round_Super 6 #define TT_Round_Super_45 7 /************************************************************************** * * Function types used by the interpreter, depending on various modes * (e.g. the rounding mode, whether to render a vertical or horizontal * line etc). * */ /* Rounding function */ typedef FT_F26Dot6 (*TT_Round_Func)( TT_ExecContext exc, FT_F26Dot6 distance, FT_Int color ); /* Point displacement along the freedom vector routine */ typedef void (*TT_Move_Func)( TT_ExecContext exc, TT_GlyphZone zone, FT_UShort point, FT_F26Dot6 distance ); /* Distance projection along one of the projection vectors */ typedef FT_F26Dot6 (*TT_Project_Func)( TT_ExecContext exc, FT_Pos dx, FT_Pos dy ); /* getting current ppem. Take care of non-square pixels if necessary */ typedef FT_Long (*TT_Cur_Ppem_Func)( TT_ExecContext exc ); /* reading a cvt value. Take care of non-square pixels if necessary */ typedef FT_F26Dot6 (*TT_Get_CVT_Func)( TT_ExecContext exc, FT_ULong idx ); /* setting or moving a cvt value. Take care of non-square pixels */ /* if necessary */ typedef void (*TT_Set_CVT_Func)( TT_ExecContext exc, FT_ULong idx, FT_F26Dot6 value ); /************************************************************************** * * This structure defines a call record, used to manage function calls. */ typedef struct TT_CallRec_ { FT_Int Caller_Range; FT_Long Caller_IP; FT_Long Cur_Count; TT_DefRecord *Def; /* either FDEF or IDEF */ } TT_CallRec, *TT_CallStack; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /************************************************************************** * * These structures define rules used to tweak subpixel hinting for * various fonts. "", 0, "", NULL value indicates to match any value. */ #define SPH_MAX_NAME_SIZE 32 #define SPH_MAX_CLASS_MEMBERS 100 typedef struct SPH_TweakRule_ { const char family[SPH_MAX_NAME_SIZE]; const FT_UInt ppem; const char style[SPH_MAX_NAME_SIZE]; const FT_ULong glyph; } SPH_TweakRule; typedef struct SPH_ScaleRule_ { const char family[SPH_MAX_NAME_SIZE]; const FT_UInt ppem; const char style[SPH_MAX_NAME_SIZE]; const FT_ULong glyph; const FT_ULong scale; } SPH_ScaleRule; typedef struct SPH_Font_Class_ { const char name[SPH_MAX_NAME_SIZE]; const char member[SPH_MAX_CLASS_MEMBERS][SPH_MAX_NAME_SIZE]; } SPH_Font_Class; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /************************************************************************** * * The main structure for the interpreter which collects all necessary * variables and states. * * Members that are initialized by `TT_Load_Context` are marked with '!'. * Members that are initialized by `TT_Run_Context` are marked with '@'. */ typedef struct TT_ExecContextRec_ { TT_Face face; /* ! */ TT_Size size; /* ! */ FT_Memory memory; /* instructions state */ FT_Error error; /* last execution error */ FT_Long top; /* @ top of exec. stack */ FT_Long stackSize; /* ! size of exec. stack */ FT_Long* stack; /* ! current exec. stack */ FT_Long args; FT_Long new_top; /* new top after exec. */ TT_GlyphZoneRec zp0, /* @! zone records */ zp1, /* @! */ zp2, /* @! */ pts, /* ! */ twilight; /* ! */ FT_Long pointSize; /* ! in 26.6 format */ FT_Size_Metrics metrics; /* ! */ TT_Size_Metrics tt_metrics; /* ! size metrics */ TT_GraphicsState GS; /* !@ current graphics state */ FT_Int iniRange; /* initial code range number */ FT_Int curRange; /* current code range number */ FT_Byte* code; /* current code range */ FT_Long IP; /* current instruction pointer */ FT_Long codeSize; /* size of current range */ FT_Byte opcode; /* current opcode */ FT_Int length; /* length of current opcode */ FT_Bool step_ins; /* true if the interpreter must */ /* increment IP after ins. exec */ FT_ULong cvtSize; /* ! */ FT_Long* cvt; /* ! */ FT_ULong glyfCvtSize; FT_Long* glyfCvt; /* cvt working copy for glyph */ FT_Long* origCvt; FT_UInt glyphSize; /* ! glyph instructions buffer size */ FT_Byte* glyphIns; /* ! glyph instructions buffer */ FT_UInt numFDefs; /* ! number of function defs */ FT_UInt maxFDefs; /* ! maximum number of function defs */ TT_DefArray FDefs; /* table of FDefs entries */ FT_UInt numIDefs; /* ! number of instruction defs */ FT_UInt maxIDefs; /* ! maximum number of ins defs */ TT_DefArray IDefs; /* table of IDefs entries */ FT_UInt maxFunc; /* ! maximum function index */ FT_UInt maxIns; /* ! maximum instruction index */ FT_Int callTop, /* @ top of call stack during execution */ callSize; /* size of call stack */ TT_CallStack callStack; /* call stack */ FT_UShort maxPoints; /* capacity of this context's `pts' */ FT_Short maxContours; /* record, expressed in points and */ /* contours. */ TT_CodeRangeTable codeRangeTable; /* ! table of valid code ranges */ /* useful for the debugger */ FT_UShort storeSize; /* ! size of current storage */ FT_Long* storage; /* ! storage area */ FT_UShort glyfStoreSize; FT_Long* glyfStorage; /* storage working copy for glyph */ FT_Long* origStorage; FT_F26Dot6 period; /* values used for the */ FT_F26Dot6 phase; /* `SuperRounding' */ FT_F26Dot6 threshold; FT_Bool instruction_trap; /* ! If `True', the interpreter */ /* exits after each instruction */ TT_GraphicsState default_GS; /* graphics state resulting from */ /* the prep program */ FT_Bool is_composite; /* true if the glyph is composite */ FT_Bool pedantic_hinting; /* true if pedantic interpretation */ /* latest interpreter additions */ FT_Long F_dot_P; /* dot product of freedom and projection */ /* vectors */ TT_Round_Func func_round; /* current rounding function */ TT_Project_Func func_project, /* current projection function */ func_dualproj, /* current dual proj. function */ func_freeProj; /* current freedom proj. func */ TT_Move_Func func_move; /* current point move function */ TT_Move_Func func_move_orig; /* move original position function */ TT_Cur_Ppem_Func func_cur_ppem; /* get current proj. ppem value */ TT_Get_CVT_Func func_read_cvt; /* read a cvt entry */ TT_Set_CVT_Func func_write_cvt; /* write a cvt entry (in pixels) */ TT_Set_CVT_Func func_move_cvt; /* incr a cvt entry (in pixels) */ FT_Bool grayscale; /* bi-level hinting and */ /* grayscale rendering */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* * FreeType supports ClearType-like hinting of TrueType fonts through * the version 40 interpreter. This is achieved through several hacks * in the base (v35) interpreter, as detailed below. * * ClearType is an umbrella term for several rendering techniques * employed by Microsoft's various GUI and rendering toolkit * implementations, most importantly: subpixel rendering for using the * RGB subpixels of LCDs to approximately triple the perceived * resolution on the x-axis and subpixel hinting for positioning stems * on subpixel borders. TrueType programming is explicit, i.e., fonts * must be programmed to take advantage of ClearType's possibilities. * * When ClearType was introduced, it seemed unlikely that all fonts * would be reprogrammed, so Microsoft decided to implement a backward * compatibility mode. It employs several simple to complicated * assumptions and tricks, many of them font-dependent, that modify the * interpretation of the bytecode contained in these fonts to retrofit * them into a ClearType-y look. The quality of the results varies. * Most (web)fonts that were released since then have come to rely on * these hacks to render correctly, even some of Microsoft's flagship * fonts (e.g., Calibri, Cambria, Segoe UI). * * FreeType's minimal subpixel hinting code (interpreter version 40) * employs a small list of font-agnostic hacks loosely based on the * public information available on Microsoft's compatibility mode[2]. * The focus is on modern (web)fonts rather than legacy fonts that were * made for monochrome rendering. It will not match ClearType rendering * exactly. Unlike the `Infinality' code (interpreter version 38) that * came before, it will not try to toggle hacks for specific fonts for * performance and complexity reasons. It will fall back to version 35 * behavior for tricky fonts[1] or when monochrome rendering is * requested. * * Major hacks * * - Any point movement on the x axis is ignored (cf. `Direct_Move' and * `Direct_Move_X'). This has the smallest code footprint and single * biggest effect. The ClearType way to increase resolution is * supersampling the x axis, the FreeType way is ignoring instructions * on the x axis, which gives the same result in the majority of * cases. * * - Points are not moved post-IUP (neither on the x nor on the y axis), * except the x component of diagonal moves post-IUP (cf. * `Direct_Move', `Direct_Move_Y', `Move_Zp2_Point'). Post-IUP * changes are commonly used to `fix' pixel patterns which has little * use outside monochrome rendering. * * - SHPIX and DELTAP don't execute unless moving a composite on the * y axis or moving a previously y touched point. SHPIX additionally * denies movement on the x axis (cf. `Ins_SHPIX' and `Ins_DELTAP'). * Both instructions are commonly used to `fix' pixel patterns for * monochrome or Windows's GDI rendering but make little sense for * FreeType rendering. Both can distort the outline. See [2] for * details. * * - The hdmx table and modifications to phantom points are ignored. * Bearings and advance widths remain unchanged (except rounding them * outside the interpreter!), cf. `compute_glyph_metrics' and * `TT_Hint_Glyph'. Letting non-native-ClearType fonts modify spacing * might mess up spacing. * * Minor hacks * * - FLIPRGON, FLIPRGOFF, and FLIPPT don't execute post-IUP. This * prevents dents in e.g. Arial-Regular's `D' and `G' glyphs at * various sizes. * * (Post-IUP is the state after both IUP[x] and IUP[y] have been * executed.) * * The best results are achieved for fonts that were from the outset * designed with ClearType in mind, meaning they leave the x axis mostly * alone and don't mess with the `final' outline to produce more * pleasing pixel patterns. The harder the designer tried to produce * very specific patterns (`superhinting') for pre-ClearType-displays, * the worse the results. * * Microsoft defines a way to turn off backward compatibility and * interpret instructions as before (called `native ClearType')[2][3]. * The font designer then regains full control and is responsible for * making the font work correctly with ClearType without any * hand-holding by the interpreter or rasterizer[4]. The v40 * interpreter assumes backward compatibility by default, which can be * turned off the same way by executing the following in the control * program (cf. `Ins_INSTCTRL'). * * #PUSH 4,3 * INSTCTRL[] * * [1] Tricky fonts as FreeType defines them rely on the bytecode * interpreter to display correctly. Hacks can interfere with them, * so they get treated like native ClearType fonts (v40 with * backward compatibility turned off). Cf. `TT_RunIns'. * * [2] Proposed by Microsoft's Greg Hitchcock in * https://www.microsoft.com/typography/cleartype/truetypecleartype.aspx * * [3] Beat Stamm describes it in more detail: * http://rastertragedy.com/RTRCh4.htm#Sec12. * * [4] The list of `native ClearType' fonts is small at the time of this * writing; I found the following on a Windows 10 Update 1511 * installation: Constantia, Corbel, Sitka, Malgun Gothic, Microsoft * JhengHei (Bold and UI Bold), Microsoft YaHei (Bold and UI Bold), * SimSun, NSimSun, and Yu Gothic. * */ /* Using v40 implies subpixel hinting, unless FT_RENDER_MODE_MONO has been * requested. Used to detect interpreter */ /* version switches. `_lean' to differentiate from the Infinality */ /* `subpixel_hinting', which is managed differently. */ FT_Bool subpixel_hinting_lean; /* Long side of a LCD subpixel is vertical (e.g., screen is rotated). */ /* `_lean' to differentiate from the Infinality `vertical_lcd', which */ /* is managed differently. */ FT_Bool vertical_lcd_lean; /* Default to backward compatibility mode in v40 interpreter. If */ /* this is false, it implies the interpreter is in v35 or in native */ /* ClearType mode. */ FT_Bool backward_compatibility; /* Useful for detecting and denying post-IUP trickery that is usually */ /* used to fix pixel patterns (`superhinting'). */ FT_Bool iupx_called; FT_Bool iupy_called; /* ClearType hinting and grayscale rendering, as used by Universal */ /* Windows Platform apps (Windows 8 and above). Like the standard */ /* colorful ClearType mode, it utilizes a vastly increased virtual */ /* resolution on the x axis. Different from bi-level hinting and */ /* grayscale rendering, the old mode from Win9x days that roughly */ /* adheres to the physical pixel grid on both axes. */ FT_Bool grayscale_cleartype; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY TT_Round_Func func_round_sphn; /* subpixel rounding function */ FT_Bool subpixel_hinting; /* Using subpixel hinting? */ FT_Bool ignore_x_mode; /* Standard rendering mode for */ /* subpixel hinting. On if gray */ /* or subpixel hinting is on. */ /* The following 6 aren't fully implemented but here for MS rasterizer */ /* compatibility. */ FT_Bool compatible_widths; /* compatible widths? */ FT_Bool symmetrical_smoothing; /* symmetrical_smoothing? */ FT_Bool bgr; /* bgr instead of rgb? */ FT_Bool vertical_lcd; /* long side of LCD subpixel */ /* rectangles is horizontal */ FT_Bool subpixel_positioned; /* subpixel positioned */ /* (DirectWrite ClearType)? */ FT_Bool gray_cleartype; /* ClearType hinting but */ /* grayscale rendering */ FT_Int rasterizer_version; /* MS rasterizer version */ FT_Bool iup_called; /* IUP called for glyph? */ FT_ULong sph_tweak_flags; /* flags to control */ /* hint tweaks */ FT_ULong sph_in_func_flags; /* flags to indicate if in */ /* special functions */ #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ /* We maintain two counters (in addition to the instruction counter) */ /* that act as loop detectors for LOOPCALL and jump opcodes with */ /* negative arguments. */ FT_ULong loopcall_counter; FT_ULong loopcall_counter_max; FT_ULong neg_jump_counter; FT_ULong neg_jump_counter_max; } TT_ExecContextRec; extern const TT_GraphicsState tt_default_graphics_state; #ifdef TT_USE_BYTECODE_INTERPRETER FT_LOCAL( void ) TT_Goto_CodeRange( TT_ExecContext exec, FT_Int range, FT_Long IP ); FT_LOCAL( void ) TT_Set_CodeRange( TT_ExecContext exec, FT_Int range, void* base, FT_Long length ); FT_LOCAL( void ) TT_Clear_CodeRange( TT_ExecContext exec, FT_Int range ); FT_LOCAL( FT_Error ) Update_Max( FT_Memory memory, FT_ULong* size, FT_ULong multiplier, void* _pbuff, FT_ULong new_max ); #endif /* TT_USE_BYTECODE_INTERPRETER */ /************************************************************************** * * @Function: * TT_New_Context * * @Description: * Create a `TT_ExecContext`. Note that there is now an execution * context per `TT_Size` that is not shared among faces. * * @Input: * driver :: * A handle to the driver, used for memory allocation. * * @Return: * A handle to a new empty execution context. * * @Note: * Only the glyph loader and debugger should call this function. * (And right now only the glyph loader uses it.) */ FT_EXPORT( TT_ExecContext ) TT_New_Context( TT_Driver driver ); #ifdef TT_USE_BYTECODE_INTERPRETER FT_LOCAL( void ) TT_Done_Context( TT_ExecContext exec ); FT_LOCAL( FT_Error ) TT_Load_Context( TT_ExecContext exec, TT_Face face, TT_Size size ); FT_LOCAL( void ) TT_Save_Context( TT_ExecContext exec, TT_Size ins ); FT_LOCAL( FT_Error ) TT_Run_Context( TT_ExecContext exec ); #endif /* TT_USE_BYTECODE_INTERPRETER */ /************************************************************************** * * @Function: * TT_RunIns * * @Description: * Executes one or more instruction in the execution context. This * is the main function of the TrueType opcode interpreter. * * @Input: * exec :: * A handle to the target execution context. * * @Return: * FreeType error code. 0 means success. * * @Note: * Only the object manager and debugger should call this function. * * This function is publicly exported because it is directly * invoked by the TrueType debugger. */ FT_EXPORT( FT_Error ) TT_RunIns( TT_ExecContext exec ); FT_END_HEADER #endif /* TTINTERP_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttinterp.h
C++
gpl-3.0
21,871
/**************************************************************************** * * ttobjs.c * * Objects manager (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/tttags.h> #include <freetype/internal/sfnt.h> #include <freetype/ftdriver.h> #include "ttgload.h" #include "ttpload.h" #include "tterrors.h" #ifdef TT_USE_BYTECODE_INTERPRETER #include "ttinterp.h" #endif #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include "ttgxvar.h" #endif /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttobjs #ifdef TT_USE_BYTECODE_INTERPRETER /************************************************************************** * * GLYPH ZONE FUNCTIONS * */ /************************************************************************** * * @Function: * tt_glyphzone_done * * @Description: * Deallocate a glyph zone. * * @Input: * zone :: * A pointer to the target glyph zone. */ FT_LOCAL_DEF( void ) tt_glyphzone_done( TT_GlyphZone zone ) { FT_Memory memory = zone->memory; if ( memory ) { FT_FREE( zone->contours ); FT_FREE( zone->tags ); FT_FREE( zone->cur ); FT_FREE( zone->org ); FT_FREE( zone->orus ); zone->max_points = zone->n_points = 0; zone->max_contours = zone->n_contours = 0; zone->memory = NULL; } } /************************************************************************** * * @Function: * tt_glyphzone_new * * @Description: * Allocate a new glyph zone. * * @Input: * memory :: * A handle to the current memory object. * * maxPoints :: * The capacity of glyph zone in points. * * maxContours :: * The capacity of glyph zone in contours. * * @Output: * zone :: * A pointer to the target glyph zone record. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_glyphzone_new( FT_Memory memory, FT_UShort maxPoints, FT_Short maxContours, TT_GlyphZone zone ) { FT_Error error; FT_ZERO( zone ); zone->memory = memory; if ( FT_NEW_ARRAY( zone->org, maxPoints ) || FT_NEW_ARRAY( zone->cur, maxPoints ) || FT_NEW_ARRAY( zone->orus, maxPoints ) || FT_NEW_ARRAY( zone->tags, maxPoints ) || FT_NEW_ARRAY( zone->contours, maxContours ) ) { tt_glyphzone_done( zone ); } else { zone->max_points = maxPoints; zone->max_contours = maxContours; } return error; } /* * Fonts embedded in PDFs are made unique by prepending randomization * prefixes to their names: as defined in Section 5.5.3, 'Font Subsets', * of the PDF Reference, they consist of 6 uppercase letters followed by * the `+` sign. For safety, we do not skip prefixes violating this rule. */ static const FT_String* tt_skip_pdffont_random_tag( const FT_String* name ) { unsigned int i; if ( ft_strlen( name ) < 8 || name[6] != '+' ) return name; for ( i = 0; i < 6; i++ ) if ( !ft_isupper( name[i] ) ) return name; FT_TRACE7(( "name without randomization tag: %s\n", name + 7 )); return name + 7; } /* Compare the face with a list of well-known `tricky' fonts. */ /* This list shall be expanded as we find more of them. */ static FT_Bool tt_check_trickyness_family( const FT_String* name ) { #define TRICK_NAMES_MAX_CHARACTERS 19 #define TRICK_NAMES_COUNT 20 static const char trick_names[TRICK_NAMES_COUNT] [TRICK_NAMES_MAX_CHARACTERS + 1] = { /* PostScript names are given in brackets if they differ from the family name. The version numbers, together with the copyright or release year data, are taken from fonts available to the developers. Note that later versions of the fonts might be no longer tricky; for example, `MingLiU' version 7.00 (file `mingliu.ttc' from Windows 7) is an ordinary TTC with non-tricky subfonts. */ "cpop", /* dftt-p7.ttf; version 1.00, 1992 [DLJGyShoMedium] */ "DFGirl-W6-WIN-BF", /* dftt-h6.ttf; version 1.00, 1993 */ "DFGothic-EB", /* DynaLab Inc. 1992-1995 */ "DFGyoSho-Lt", /* DynaLab Inc. 1992-1995 */ "DFHei", /* DynaLab Inc. 1992-1995 [DFHei-Bd-WIN-HK-BF] */ /* covers "DFHei-Md-HK-BF", maybe DynaLab Inc. */ "DFHSGothic-W5", /* DynaLab Inc. 1992-1995 */ "DFHSMincho-W3", /* DynaLab Inc. 1992-1995 */ "DFHSMincho-W7", /* DynaLab Inc. 1992-1995 */ "DFKaiSho-SB", /* dfkaisb.ttf */ "DFKaiShu", /* covers "DFKaiShu-Md-HK-BF", maybe DynaLab Inc. */ "DFKai-SB", /* kaiu.ttf; version 3.00, 1998 [DFKaiShu-SB-Estd-BF] */ "DFMing", /* DynaLab Inc. 1992-1995 [DFMing-Md-WIN-HK-BF] */ /* covers "DFMing-Bd-HK-BF", maybe DynaLab Inc. */ "DLC", /* dftt-m7.ttf; version 1.00, 1993 [DLCMingBold] */ /* dftt-f5.ttf; version 1.00, 1993 [DLCFongSung] */ /* covers following */ /* "DLCHayMedium", dftt-b5.ttf; version 1.00, 1993 */ /* "DLCHayBold", dftt-b7.ttf; version 1.00, 1993 */ /* "DLCKaiMedium", dftt-k5.ttf; version 1.00, 1992 */ /* "DLCLiShu", dftt-l5.ttf; version 1.00, 1992 */ /* "DLCRoundBold", dftt-r7.ttf; version 1.00, 1993 */ "HuaTianKaiTi?", /* htkt2.ttf */ "HuaTianSongTi?", /* htst3.ttf */ "Ming(for ISO10646)", /* hkscsiic.ttf; version 0.12, 2007 [Ming] */ /* iicore.ttf; version 0.07, 2007 [Ming] */ "MingLiU", /* mingliu.ttf */ /* mingliu.ttc; version 3.21, 2001 */ "MingMedium", /* dftt-m5.ttf; version 1.00, 1993 [DLCMingMedium] */ "PMingLiU", /* mingliu.ttc; version 3.21, 2001 */ "MingLi43", /* mingli.ttf; version 1.00, 1992 */ }; int nn; const FT_String* name_without_tag; name_without_tag = tt_skip_pdffont_random_tag( name ); for ( nn = 0; nn < TRICK_NAMES_COUNT; nn++ ) if ( ft_strstr( name_without_tag, trick_names[nn] ) ) return TRUE; return FALSE; } /* XXX: This function should be in the `sfnt' module. */ /* Some PDF generators clear the checksums in the TrueType header table. */ /* For example, Quartz ContextPDF clears all entries, or Bullzip PDF */ /* Printer clears the entries for subsetted subtables. We thus have to */ /* recalculate the checksums where necessary. */ static FT_UInt32 tt_synth_sfnt_checksum( FT_Stream stream, FT_ULong length ) { FT_Error error; FT_UInt32 checksum = 0; FT_UInt i; if ( FT_FRAME_ENTER( length ) ) return 0; for ( ; length > 3; length -= 4 ) checksum += (FT_UInt32)FT_GET_ULONG(); for ( i = 3; length > 0; length--, i-- ) checksum += (FT_UInt32)FT_GET_BYTE() << ( i * 8 ); FT_FRAME_EXIT(); return checksum; } /* XXX: This function should be in the `sfnt' module. */ static FT_ULong tt_get_sfnt_checksum( TT_Face face, FT_UShort i ) { #if 0 /* if we believe the written value, use following part. */ if ( face->dir_tables[i].CheckSum ) return face->dir_tables[i].CheckSum; #endif if ( !face->goto_table ) return 0; if ( face->goto_table( face, face->dir_tables[i].Tag, face->root.stream, NULL ) ) return 0; return (FT_ULong)tt_synth_sfnt_checksum( face->root.stream, face->dir_tables[i].Length ); } typedef struct tt_sfnt_id_rec_ { FT_ULong CheckSum; FT_ULong Length; } tt_sfnt_id_rec; static FT_Bool tt_check_trickyness_sfnt_ids( TT_Face face ) { #define TRICK_SFNT_IDS_PER_FACE 3 #define TRICK_SFNT_IDS_NUM_FACES 31 static const tt_sfnt_id_rec sfnt_id[TRICK_SFNT_IDS_NUM_FACES] [TRICK_SFNT_IDS_PER_FACE] = { #define TRICK_SFNT_ID_cvt 0 #define TRICK_SFNT_ID_fpgm 1 #define TRICK_SFNT_ID_prep 2 { /* MingLiU 1995 */ { 0x05BCF058UL, 0x000002E4UL }, /* cvt */ { 0x28233BF1UL, 0x000087C4UL }, /* fpgm */ { 0xA344A1EAUL, 0x000001E1UL } /* prep */ }, { /* MingLiU 1996- */ { 0x05BCF058UL, 0x000002E4UL }, /* cvt */ { 0x28233BF1UL, 0x000087C4UL }, /* fpgm */ { 0xA344A1EBUL, 0x000001E1UL } /* prep */ }, { /* DFGothic-EB */ { 0x12C3EBB2UL, 0x00000350UL }, /* cvt */ { 0xB680EE64UL, 0x000087A7UL }, /* fpgm */ { 0xCE939563UL, 0x00000758UL } /* prep */ }, { /* DFGyoSho-Lt */ { 0x11E5EAD4UL, 0x00000350UL }, /* cvt */ { 0xCE5956E9UL, 0x0000BC85UL }, /* fpgm */ { 0x8272F416UL, 0x00000045UL } /* prep */ }, { /* DFHei-Md-HK-BF */ { 0x1257EB46UL, 0x00000350UL }, /* cvt */ { 0xF699D160UL, 0x0000715FUL }, /* fpgm */ { 0xD222F568UL, 0x000003BCUL } /* prep */ }, { /* DFHSGothic-W5 */ { 0x1262EB4EUL, 0x00000350UL }, /* cvt */ { 0xE86A5D64UL, 0x00007940UL }, /* fpgm */ { 0x7850F729UL, 0x000005FFUL } /* prep */ }, { /* DFHSMincho-W3 */ { 0x122DEB0AUL, 0x00000350UL }, /* cvt */ { 0x3D16328AUL, 0x0000859BUL }, /* fpgm */ { 0xA93FC33BUL, 0x000002CBUL } /* prep */ }, { /* DFHSMincho-W7 */ { 0x125FEB26UL, 0x00000350UL }, /* cvt */ { 0xA5ACC982UL, 0x00007EE1UL }, /* fpgm */ { 0x90999196UL, 0x0000041FUL } /* prep */ }, { /* DFKaiShu */ { 0x11E5EAD4UL, 0x00000350UL }, /* cvt */ { 0x5A30CA3BUL, 0x00009063UL }, /* fpgm */ { 0x13A42602UL, 0x0000007EUL } /* prep */ }, { /* DFKaiShu, variant */ { 0x11E5EAD4UL, 0x00000350UL }, /* cvt */ { 0xA6E78C01UL, 0x00008998UL }, /* fpgm */ { 0x13A42602UL, 0x0000007EUL } /* prep */ }, { /* DFKaiShu-Md-HK-BF */ { 0x11E5EAD4UL, 0x00000360UL }, /* cvt */ { 0x9DB282B2UL, 0x0000C06EUL }, /* fpgm */ { 0x53E6D7CAUL, 0x00000082UL } /* prep */ }, { /* DFMing-Bd-HK-BF */ { 0x1243EB18UL, 0x00000350UL }, /* cvt */ { 0xBA0A8C30UL, 0x000074ADUL }, /* fpgm */ { 0xF3D83409UL, 0x0000037BUL } /* prep */ }, { /* DLCLiShu */ { 0x07DCF546UL, 0x00000308UL }, /* cvt */ { 0x40FE7C90UL, 0x00008E2AUL }, /* fpgm */ { 0x608174B5UL, 0x0000007AUL } /* prep */ }, { /* DLCHayBold */ { 0xEB891238UL, 0x00000308UL }, /* cvt */ { 0xD2E4DCD4UL, 0x0000676FUL }, /* fpgm */ { 0x8EA5F293UL, 0x000003B8UL } /* prep */ }, { /* HuaTianKaiTi */ { 0xFFFBFFFCUL, 0x00000008UL }, /* cvt */ { 0x9C9E48B8UL, 0x0000BEA2UL }, /* fpgm */ { 0x70020112UL, 0x00000008UL } /* prep */ }, { /* HuaTianSongTi */ { 0xFFFBFFFCUL, 0x00000008UL }, /* cvt */ { 0x0A5A0483UL, 0x00017C39UL }, /* fpgm */ { 0x70020112UL, 0x00000008UL } /* prep */ }, { /* NEC fadpop7.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x40C92555UL, 0x000000E5UL }, /* fpgm */ { 0xA39B58E3UL, 0x0000117CUL } /* prep */ }, { /* NEC fadrei5.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x33C41652UL, 0x000000E5UL }, /* fpgm */ { 0x26D6C52AUL, 0x00000F6AUL } /* prep */ }, { /* NEC fangot7.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x6DB1651DUL, 0x0000019DUL }, /* fpgm */ { 0x6C6E4B03UL, 0x00002492UL } /* prep */ }, { /* NEC fangyo5.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x40C92555UL, 0x000000E5UL }, /* fpgm */ { 0xDE51FAD0UL, 0x0000117CUL } /* prep */ }, { /* NEC fankyo5.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x85E47664UL, 0x000000E5UL }, /* fpgm */ { 0xA6C62831UL, 0x00001CAAUL } /* prep */ }, { /* NEC fanrgo5.ttf */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x2D891CFDUL, 0x0000019DUL }, /* fpgm */ { 0xA0604633UL, 0x00001DE8UL } /* prep */ }, { /* NEC fangot5.ttc */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x40AA774CUL, 0x000001CBUL }, /* fpgm */ { 0x9B5CAA96UL, 0x00001F9AUL } /* prep */ }, { /* NEC fanmin3.ttc */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x0D3DE9CBUL, 0x00000141UL }, /* fpgm */ { 0xD4127766UL, 0x00002280UL } /* prep */ }, { /* NEC FA-Gothic, 1996 */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x4A692698UL, 0x000001F0UL }, /* fpgm */ { 0x340D4346UL, 0x00001FCAUL } /* prep */ }, { /* NEC FA-Minchou, 1996 */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0xCD34C604UL, 0x00000166UL }, /* fpgm */ { 0x6CF31046UL, 0x000022B0UL } /* prep */ }, { /* NEC FA-RoundGothicB, 1996 */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0x5DA75315UL, 0x0000019DUL }, /* fpgm */ { 0x40745A5FUL, 0x000022E0UL } /* prep */ }, { /* NEC FA-RoundGothicM, 1996 */ { 0x00000000UL, 0x00000000UL }, /* cvt */ { 0xF055FC48UL, 0x000001C2UL }, /* fpgm */ { 0x3900DED3UL, 0x00001E18UL } /* prep */ }, { /* MINGLI.TTF, 1992 */ { 0x00170003UL, 0x00000060UL }, /* cvt */ { 0xDBB4306EUL, 0x000058AAUL }, /* fpgm */ { 0xD643482AUL, 0x00000035UL } /* prep */ }, { /* DFHei-Bd-WIN-HK-BF, issue #1087 */ { 0x1269EB58UL, 0x00000350UL }, /* cvt */ { 0x5CD5957AUL, 0x00006A4EUL }, /* fpgm */ { 0xF758323AUL, 0x00000380UL } /* prep */ }, { /* DFMing-Md-WIN-HK-BF, issue #1087 */ { 0x122FEB0BUL, 0x00000350UL }, /* cvt */ { 0x7F10919AUL, 0x000070A9UL }, /* fpgm */ { 0x7CD7E7B7UL, 0x0000025CUL } /* prep */ } }; FT_ULong checksum; int num_matched_ids[TRICK_SFNT_IDS_NUM_FACES]; FT_Bool has_cvt, has_fpgm, has_prep; FT_UShort i; int j, k; FT_MEM_SET( num_matched_ids, 0, sizeof ( int ) * TRICK_SFNT_IDS_NUM_FACES ); has_cvt = FALSE; has_fpgm = FALSE; has_prep = FALSE; for ( i = 0; i < face->num_tables; i++ ) { checksum = 0; switch( face->dir_tables[i].Tag ) { case TTAG_cvt: k = TRICK_SFNT_ID_cvt; has_cvt = TRUE; break; case TTAG_fpgm: k = TRICK_SFNT_ID_fpgm; has_fpgm = TRUE; break; case TTAG_prep: k = TRICK_SFNT_ID_prep; has_prep = TRUE; break; default: continue; } for ( j = 0; j < TRICK_SFNT_IDS_NUM_FACES; j++ ) if ( face->dir_tables[i].Length == sfnt_id[j][k].Length ) { if ( !checksum ) checksum = tt_get_sfnt_checksum( face, i ); if ( sfnt_id[j][k].CheckSum == checksum ) num_matched_ids[j]++; if ( num_matched_ids[j] == TRICK_SFNT_IDS_PER_FACE ) return TRUE; } } for ( j = 0; j < TRICK_SFNT_IDS_NUM_FACES; j++ ) { if ( !has_cvt && !sfnt_id[j][TRICK_SFNT_ID_cvt].Length ) num_matched_ids[j]++; if ( !has_fpgm && !sfnt_id[j][TRICK_SFNT_ID_fpgm].Length ) num_matched_ids[j]++; if ( !has_prep && !sfnt_id[j][TRICK_SFNT_ID_prep].Length ) num_matched_ids[j]++; if ( num_matched_ids[j] == TRICK_SFNT_IDS_PER_FACE ) return TRUE; } return FALSE; } static FT_Bool tt_check_trickyness( FT_Face face ) { if ( !face ) return FALSE; /* For first, check the face name for quick check. */ if ( face->family_name && tt_check_trickyness_family( face->family_name ) ) { FT_TRACE3(( "found as a tricky font" " by its family name: %s\n", face->family_name )); return TRUE; } /* Type42 fonts may lack `name' tables, we thus try to identify */ /* tricky fonts by checking the checksums of Type42-persistent */ /* sfnt tables (`cvt', `fpgm', and `prep'). */ if ( tt_check_trickyness_sfnt_ids( (TT_Face)face ) ) { FT_TRACE3(( "found as a tricky font" " by its cvt/fpgm/prep table checksum\n" )); return TRUE; } return FALSE; } #endif /* TT_USE_BYTECODE_INTERPRETER */ /* Check whether `.notdef' is the only glyph in the `loca' table. */ static FT_Bool tt_check_single_notdef( FT_Face ttface ) { FT_Bool result = FALSE; TT_Face face = (TT_Face)ttface; FT_UInt asize; FT_ULong i; FT_ULong glyph_index = 0; FT_UInt count = 0; for( i = 0; i < face->num_locations; i++ ) { tt_face_get_location( face, i, &asize ); if ( asize > 0 ) { count += 1; if ( count > 1 ) break; glyph_index = i; } } /* Only have a single outline. */ if ( count == 1 ) { if ( glyph_index == 0 ) result = TRUE; else { /* FIXME: Need to test glyphname == .notdef ? */ FT_Error error; char buf[8]; error = FT_Get_Glyph_Name( ttface, glyph_index, buf, 8 ); if ( !error && buf[0] == '.' && !ft_strncmp( buf, ".notdef", 8 ) ) result = TRUE; } } return result; } /************************************************************************** * * @Function: * tt_face_init * * @Description: * Initialize a given TrueType face object. * * @Input: * stream :: * The source font stream. * * face_index :: * The index of the TrueType font, if we are opening a * collection, in bits 0-15. The numbered instance * index~+~1 of a GX (sub)font, if applicable, in bits * 16-30. * * num_params :: * Number of additional generic parameters. Ignored. * * params :: * Additional generic parameters. Ignored. * * @InOut: * face :: * The newly built face object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_init( FT_Stream stream, FT_Face ttface, /* TT_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { FT_Error error; FT_Library library; SFNT_Service sfnt; TT_Face face = (TT_Face)ttface; FT_TRACE2(( "TTF driver\n" )); library = ttface->driver->root.library; sfnt = (SFNT_Service)FT_Get_Module_Interface( library, "sfnt" ); if ( !sfnt ) { FT_ERROR(( "tt_face_init: cannot access `sfnt' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } /* create input stream from resource */ if ( FT_STREAM_SEEK( 0 ) ) goto Exit; /* check that we have a valid TrueType file */ FT_TRACE2(( " " )); error = sfnt->init_face( stream, face, face_index, num_params, params ); /* Stream may have changed. */ stream = face->root.stream; if ( error ) goto Exit; /* We must also be able to accept Mac/GX fonts, as well as OT ones. */ /* The 0x00020000 tag is completely undocumented; some fonts from */ /* Arphic made for Chinese Windows 3.1 have this. */ if ( face->format_tag != 0x00010000L && /* MS fonts */ face->format_tag != 0x00020000L && /* CJK fonts for Win 3.1 */ face->format_tag != TTAG_true && /* Mac fonts */ face->format_tag != TTAG_0xA5kbd && /* `Keyboard.dfont' (legacy Mac OS X) */ face->format_tag != TTAG_0xA5lst ) /* `LastResort.dfont' (legacy Mac OS X) */ { FT_TRACE2(( " not a TTF font\n" )); goto Bad_Format; } #ifdef TT_USE_BYTECODE_INTERPRETER ttface->face_flags |= FT_FACE_FLAG_HINTER; #endif /* If we are performing a simple font format check, exit immediately. */ if ( face_index < 0 ) return FT_Err_Ok; /* Load font directory */ error = sfnt->load_face( stream, face, face_index, num_params, params ); if ( error ) goto Exit; #ifdef TT_USE_BYTECODE_INTERPRETER if ( tt_check_trickyness( ttface ) ) ttface->face_flags |= FT_FACE_FLAG_TRICKY; #endif error = tt_face_load_hdmx( face, stream ); if ( error ) goto Exit; if ( FT_IS_SCALABLE( ttface ) || FT_HAS_SBIX( ttface ) ) { #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( !ttface->internal->incremental_interface ) #endif { error = tt_face_load_loca( face, stream ); /* having a (non-zero) `glyf' table without */ /* a `loca' table is not valid */ if ( face->glyf_len && FT_ERR_EQ( error, Table_Missing ) ) goto Exit; if ( error ) goto Exit; } /* `fpgm', `cvt', and `prep' are optional */ error = tt_face_load_cvt( face, stream ); if ( error && FT_ERR_NEQ( error, Table_Missing ) ) goto Exit; error = tt_face_load_fpgm( face, stream ); if ( error && FT_ERR_NEQ( error, Table_Missing ) ) goto Exit; error = tt_face_load_prep( face, stream ); if ( error && FT_ERR_NEQ( error, Table_Missing ) ) goto Exit; /* Check the scalable flag based on `loca'. */ #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( !ttface->internal->incremental_interface ) #endif { if ( ttface->num_fixed_sizes && face->glyph_locations && tt_check_single_notdef( ttface ) ) { FT_TRACE5(( "tt_face_init:" " Only the `.notdef' glyph has an outline.\n" )); FT_TRACE5(( " " " Resetting scalable flag to FALSE.\n" )); ttface->face_flags &= ~FT_FACE_FLAG_SCALABLE; } } } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT { FT_UInt instance_index = (FT_UInt)face_index >> 16; if ( FT_HAS_MULTIPLE_MASTERS( ttface ) && instance_index > 0 ) { error = TT_Set_Named_Instance( face, instance_index ); if ( error ) goto Exit; tt_apply_mvar( face ); } } #endif /* TT_CONFIG_OPTION_GX_VAR_SUPPORT */ /* initialize standard glyph loading routines */ TT_Init_Glyph_Loading( face ); Exit: return error; Bad_Format: error = FT_THROW( Unknown_File_Format ); goto Exit; } /************************************************************************** * * @Function: * tt_face_done * * @Description: * Finalize a given face object. * * @Input: * face :: * A pointer to the face object to destroy. */ FT_LOCAL_DEF( void ) tt_face_done( FT_Face ttface ) /* TT_Face */ { TT_Face face = (TT_Face)ttface; FT_Memory memory; FT_Stream stream; SFNT_Service sfnt; if ( !face ) return; memory = ttface->memory; stream = ttface->stream; sfnt = (SFNT_Service)face->sfnt; /* for `extended TrueType formats' (i.e. compressed versions) */ if ( face->extra.finalizer ) face->extra.finalizer( face->extra.data ); if ( sfnt ) sfnt->done_face( face ); /* freeing the locations table */ tt_face_done_loca( face ); tt_face_free_hdmx( face ); /* freeing the CVT */ FT_FREE( face->cvt ); face->cvt_size = 0; /* freeing the programs */ FT_FRAME_RELEASE( face->font_program ); FT_FRAME_RELEASE( face->cvt_program ); face->font_program_size = 0; face->cvt_program_size = 0; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT tt_done_blend( face ); face->blend = NULL; #endif } /************************************************************************** * * SIZE FUNCTIONS * */ #ifdef TT_USE_BYTECODE_INTERPRETER /************************************************************************** * * @Function: * tt_size_run_fpgm * * @Description: * Run the font program. * * @Input: * size :: * A handle to the size object. * * pedantic :: * Set if bytecode execution should be pedantic. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_size_run_fpgm( TT_Size size, FT_Bool pedantic ) { TT_Face face = (TT_Face)size->root.face; TT_ExecContext exec; FT_Error error; exec = size->context; error = TT_Load_Context( exec, face, size ); if ( error ) return error; exec->callTop = 0; exec->top = 0; exec->period = 64; exec->phase = 0; exec->threshold = 0; exec->instruction_trap = FALSE; exec->F_dot_P = 0x4000L; exec->pedantic_hinting = pedantic; { FT_Size_Metrics* size_metrics = &exec->metrics; TT_Size_Metrics* tt_metrics = &exec->tt_metrics; size_metrics->x_ppem = 0; size_metrics->y_ppem = 0; size_metrics->x_scale = 0; size_metrics->y_scale = 0; tt_metrics->ppem = 0; tt_metrics->scale = 0; tt_metrics->ratio = 0x10000L; } /* allow font program execution */ TT_Set_CodeRange( exec, tt_coderange_font, face->font_program, (FT_Long)face->font_program_size ); /* disable CVT and glyph programs coderange */ TT_Clear_CodeRange( exec, tt_coderange_cvt ); TT_Clear_CodeRange( exec, tt_coderange_glyph ); if ( face->font_program_size > 0 ) { TT_Goto_CodeRange( exec, tt_coderange_font, 0 ); FT_TRACE4(( "Executing `fpgm' table.\n" )); error = face->interpreter( exec ); #ifdef FT_DEBUG_LEVEL_TRACE if ( error ) FT_TRACE4(( " interpretation failed with error code 0x%x\n", error )); #endif } else error = FT_Err_Ok; size->bytecode_ready = error; if ( !error ) TT_Save_Context( exec, size ); return error; } /************************************************************************** * * @Function: * tt_size_run_prep * * @Description: * Run the control value program. * * @Input: * size :: * A handle to the size object. * * pedantic :: * Set if bytecode execution should be pedantic. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_size_run_prep( TT_Size size, FT_Bool pedantic ) { TT_Face face = (TT_Face)size->root.face; TT_ExecContext exec; FT_Error error; FT_UInt i; /* unscaled CVT values are already stored in 26.6 format */ FT_Fixed scale = size->ttmetrics.scale >> 6; /* Scale the cvt values to the new ppem. */ /* By default, we use the y ppem value for scaling. */ FT_TRACE6(( "CVT values:\n" )); for ( i = 0; i < size->cvt_size; i++ ) { size->cvt[i] = FT_MulFix( face->cvt[i], scale ); FT_TRACE6(( " %3d: %f (%f)\n", i, face->cvt[i] / 64.0, size->cvt[i] / 64.0 )); } FT_TRACE6(( "\n" )); exec = size->context; error = TT_Load_Context( exec, face, size ); if ( error ) return error; exec->callTop = 0; exec->top = 0; exec->instruction_trap = FALSE; exec->pedantic_hinting = pedantic; TT_Set_CodeRange( exec, tt_coderange_cvt, face->cvt_program, (FT_Long)face->cvt_program_size ); TT_Clear_CodeRange( exec, tt_coderange_glyph ); if ( face->cvt_program_size > 0 ) { TT_Goto_CodeRange( exec, tt_coderange_cvt, 0 ); FT_TRACE4(( "Executing `prep' table.\n" )); error = face->interpreter( exec ); #ifdef FT_DEBUG_LEVEL_TRACE if ( error ) FT_TRACE4(( " interpretation failed with error code 0x%x\n", error )); #endif } else error = FT_Err_Ok; size->cvt_ready = error; /* UNDOCUMENTED! The MS rasterizer doesn't allow the following */ /* graphics state variables to be modified by the CVT program. */ exec->GS.dualVector.x = 0x4000; exec->GS.dualVector.y = 0; exec->GS.projVector.x = 0x4000; exec->GS.projVector.y = 0x0; exec->GS.freeVector.x = 0x4000; exec->GS.freeVector.y = 0x0; exec->GS.rp0 = 0; exec->GS.rp1 = 0; exec->GS.rp2 = 0; exec->GS.gep0 = 1; exec->GS.gep1 = 1; exec->GS.gep2 = 1; exec->GS.loop = 1; /* save as default graphics state */ size->GS = exec->GS; TT_Save_Context( exec, size ); return error; } static void tt_size_done_bytecode( FT_Size ftsize ) { TT_Size size = (TT_Size)ftsize; TT_Face face = (TT_Face)ftsize->face; FT_Memory memory = face->root.memory; if ( size->context ) { TT_Done_Context( size->context ); size->context = NULL; } FT_FREE( size->cvt ); size->cvt_size = 0; /* free storage area */ FT_FREE( size->storage ); size->storage_size = 0; /* twilight zone */ tt_glyphzone_done( &size->twilight ); FT_FREE( size->function_defs ); FT_FREE( size->instruction_defs ); size->num_function_defs = 0; size->max_function_defs = 0; size->num_instruction_defs = 0; size->max_instruction_defs = 0; size->max_func = 0; size->max_ins = 0; size->bytecode_ready = -1; size->cvt_ready = -1; } /* Initialize bytecode-related fields in the size object. */ /* We do this only if bytecode interpretation is really needed. */ static FT_Error tt_size_init_bytecode( FT_Size ftsize, FT_Bool pedantic ) { FT_Error error; TT_Size size = (TT_Size)ftsize; TT_Face face = (TT_Face)ftsize->face; FT_Memory memory = face->root.memory; FT_UShort n_twilight; TT_MaxProfile* maxp = &face->max_profile; /* clean up bytecode related data */ FT_FREE( size->function_defs ); FT_FREE( size->instruction_defs ); FT_FREE( size->cvt ); FT_FREE( size->storage ); if ( size->context ) TT_Done_Context( size->context ); tt_glyphzone_done( &size->twilight ); size->bytecode_ready = -1; size->cvt_ready = -1; size->context = TT_New_Context( (TT_Driver)face->root.driver ); size->max_function_defs = maxp->maxFunctionDefs; size->max_instruction_defs = maxp->maxInstructionDefs; size->num_function_defs = 0; size->num_instruction_defs = 0; size->max_func = 0; size->max_ins = 0; size->cvt_size = face->cvt_size; size->storage_size = maxp->maxStorage; /* Set default metrics */ { TT_Size_Metrics* tt_metrics = &size->ttmetrics; tt_metrics->rotated = FALSE; tt_metrics->stretched = FALSE; /* Set default engine compensation. Value 3 is not described */ /* in the OpenType specification (as of Mai 2019), but Greg */ /* says that MS handles it the same as `gray'. */ /* */ /* The Apple specification says that the compensation for */ /* `gray' is always zero. FreeType doesn't do any */ /* compensation at all. */ tt_metrics->compensations[0] = 0; /* gray */ tt_metrics->compensations[1] = 0; /* black */ tt_metrics->compensations[2] = 0; /* white */ tt_metrics->compensations[3] = 0; /* zero */ } /* allocate function defs, instruction defs, cvt, and storage area */ if ( FT_NEW_ARRAY( size->function_defs, size->max_function_defs ) || FT_NEW_ARRAY( size->instruction_defs, size->max_instruction_defs ) || FT_NEW_ARRAY( size->cvt, size->cvt_size ) || FT_NEW_ARRAY( size->storage, size->storage_size ) ) goto Exit; /* reserve twilight zone */ n_twilight = maxp->maxTwilightPoints; /* there are 4 phantom points (do we need this?) */ n_twilight += 4; error = tt_glyphzone_new( memory, n_twilight, 0, &size->twilight ); if ( error ) goto Exit; size->twilight.n_points = n_twilight; size->GS = tt_default_graphics_state; /* set `face->interpreter' according to the debug hook present */ { FT_Library library = face->root.driver->root.library; face->interpreter = (TT_Interpreter) library->debug_hooks[FT_DEBUG_HOOK_TRUETYPE]; if ( !face->interpreter ) face->interpreter = (TT_Interpreter)TT_RunIns; } /* Fine, now run the font program! */ /* In case of an error while executing `fpgm', we intentionally don't */ /* clean up immediately – bugs in the `fpgm' are so fundamental that */ /* all following hinting calls should fail. Additionally, `fpgm' is */ /* to be executed just once; calling it again is completely useless */ /* and might even lead to extremely slow behaviour if it is malformed */ /* (containing an infinite loop, for example). */ error = tt_size_run_fpgm( size, pedantic ); return error; Exit: if ( error ) tt_size_done_bytecode( ftsize ); return error; } FT_LOCAL_DEF( FT_Error ) tt_size_ready_bytecode( TT_Size size, FT_Bool pedantic ) { FT_Error error = FT_Err_Ok; if ( size->bytecode_ready < 0 ) error = tt_size_init_bytecode( (FT_Size)size, pedantic ); else error = size->bytecode_ready; if ( error ) goto Exit; /* rescale CVT when needed */ if ( size->cvt_ready < 0 ) { FT_UShort i; /* all twilight points are originally zero */ for ( i = 0; i < size->twilight.n_points; i++ ) { size->twilight.org[i].x = 0; size->twilight.org[i].y = 0; size->twilight.cur[i].x = 0; size->twilight.cur[i].y = 0; } /* clear storage area */ for ( i = 0; i < size->storage_size; i++ ) size->storage[i] = 0; size->GS = tt_default_graphics_state; error = tt_size_run_prep( size, pedantic ); } else error = size->cvt_ready; Exit: return error; } #endif /* TT_USE_BYTECODE_INTERPRETER */ /************************************************************************** * * @Function: * tt_size_init * * @Description: * Initialize a new TrueType size object. * * @InOut: * size :: * A handle to the size object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_size_init( FT_Size ttsize ) /* TT_Size */ { TT_Size size = (TT_Size)ttsize; FT_Error error = FT_Err_Ok; #ifdef TT_USE_BYTECODE_INTERPRETER size->bytecode_ready = -1; size->cvt_ready = -1; #endif size->ttmetrics.valid = FALSE; size->strike_index = 0xFFFFFFFFUL; return error; } /************************************************************************** * * @Function: * tt_size_done * * @Description: * The TrueType size object finalizer. * * @Input: * size :: * A handle to the target size object. */ FT_LOCAL_DEF( void ) tt_size_done( FT_Size ttsize ) /* TT_Size */ { TT_Size size = (TT_Size)ttsize; #ifdef TT_USE_BYTECODE_INTERPRETER tt_size_done_bytecode( ttsize ); #endif size->ttmetrics.valid = FALSE; } /************************************************************************** * * @Function: * tt_size_reset * * @Description: * Reset a TrueType size when resolutions and character dimensions * have been changed. * * @Input: * size :: * A handle to the target size object. * * only_height :: * Only recompute ascender, descender, and height; * this flag is used for variation fonts where * `tt_size_reset' is used as an iterator function. */ FT_LOCAL_DEF( FT_Error ) tt_size_reset( TT_Size size, FT_Bool only_height ) { TT_Face face; FT_Size_Metrics* size_metrics; face = (TT_Face)size->root.face; /* nothing to do for CFF2 */ if ( face->is_cff2 ) return FT_Err_Ok; size->ttmetrics.valid = FALSE; size_metrics = &size->hinted_metrics; /* copy the result from base layer */ *size_metrics = size->root.metrics; if ( size_metrics->x_ppem < 1 || size_metrics->y_ppem < 1 ) return FT_THROW( Invalid_PPem ); /* This bit flag, if set, indicates that the ppems must be */ /* rounded to integers. Nearly all TrueType fonts have this bit */ /* set, as hinting won't work really well otherwise. */ /* */ if ( face->header.Flags & 8 ) { /* the TT spec always asks for ROUND, not FLOOR or CEIL */ size_metrics->ascender = FT_PIX_ROUND( FT_MulFix( face->root.ascender, size_metrics->y_scale ) ); size_metrics->descender = FT_PIX_ROUND( FT_MulFix( face->root.descender, size_metrics->y_scale ) ); size_metrics->height = FT_PIX_ROUND( FT_MulFix( face->root.height, size_metrics->y_scale ) ); } size->ttmetrics.valid = TRUE; if ( only_height ) { /* we must not recompute the scaling values here since */ /* `tt_size_reset' was already called (with only_height = 0) */ return FT_Err_Ok; } if ( face->header.Flags & 8 ) { /* base scaling values on integer ppem values, */ /* as mandated by the TrueType specification */ size_metrics->x_scale = FT_DivFix( size_metrics->x_ppem << 6, face->root.units_per_EM ); size_metrics->y_scale = FT_DivFix( size_metrics->y_ppem << 6, face->root.units_per_EM ); size_metrics->max_advance = FT_PIX_ROUND( FT_MulFix( face->root.max_advance_width, size_metrics->x_scale ) ); } /* compute new transformation */ if ( size_metrics->x_ppem >= size_metrics->y_ppem ) { size->ttmetrics.scale = size_metrics->x_scale; size->ttmetrics.ppem = size_metrics->x_ppem; size->ttmetrics.x_ratio = 0x10000L; size->ttmetrics.y_ratio = FT_DivFix( size_metrics->y_ppem, size_metrics->x_ppem ); } else { size->ttmetrics.scale = size_metrics->y_scale; size->ttmetrics.ppem = size_metrics->y_ppem; size->ttmetrics.x_ratio = FT_DivFix( size_metrics->x_ppem, size_metrics->y_ppem ); size->ttmetrics.y_ratio = 0x10000L; } size->widthp = tt_face_get_device_metrics( face, size_metrics->x_ppem, 0 ); size->metrics = size_metrics; #ifdef TT_USE_BYTECODE_INTERPRETER size->cvt_ready = -1; #endif /* TT_USE_BYTECODE_INTERPRETER */ return FT_Err_Ok; } /************************************************************************** * * @Function: * tt_driver_init * * @Description: * Initialize a given TrueType driver object. * * @Input: * driver :: * A handle to the target driver object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_driver_init( FT_Module ttdriver ) /* TT_Driver */ { #ifdef TT_USE_BYTECODE_INTERPRETER TT_Driver driver = (TT_Driver)ttdriver; driver->interpreter_version = TT_INTERPRETER_VERSION_35; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY driver->interpreter_version = TT_INTERPRETER_VERSION_38; #endif #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL driver->interpreter_version = TT_INTERPRETER_VERSION_40; #endif #else /* !TT_USE_BYTECODE_INTERPRETER */ FT_UNUSED( ttdriver ); #endif /* !TT_USE_BYTECODE_INTERPRETER */ return FT_Err_Ok; } /************************************************************************** * * @Function: * tt_driver_done * * @Description: * Finalize a given TrueType driver. * * @Input: * driver :: * A handle to the target TrueType driver. */ FT_LOCAL_DEF( void ) tt_driver_done( FT_Module ttdriver ) /* TT_Driver */ { FT_UNUSED( ttdriver ); } /************************************************************************** * * @Function: * tt_slot_init * * @Description: * Initialize a new slot object. * * @InOut: * slot :: * A handle to the slot object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_slot_init( FT_GlyphSlot slot ) { return FT_GlyphLoader_CreateExtra( slot->internal->loader ); } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttobjs.c
C++
gpl-3.0
43,077
/**************************************************************************** * * ttobjs.h * * Objects manager (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTOBJS_H_ #define TTOBJS_H_ #include <freetype/internal/ftobjs.h> #include <freetype/internal/tttypes.h> FT_BEGIN_HEADER /************************************************************************** * * @Type: * TT_Driver * * @Description: * A handle to a TrueType driver object. */ typedef struct TT_DriverRec_* TT_Driver; /************************************************************************** * * @Type: * TT_GlyphSlot * * @Description: * A handle to a TrueType glyph slot object. * * @Note: * This is a direct typedef of FT_GlyphSlot, as there is nothing * specific about the TrueType glyph slot. */ typedef FT_GlyphSlot TT_GlyphSlot; /************************************************************************** * * @Struct: * TT_GraphicsState * * @Description: * The TrueType graphics state used during bytecode interpretation. */ typedef struct TT_GraphicsState_ { FT_UShort rp0; FT_UShort rp1; FT_UShort rp2; FT_UnitVector dualVector; FT_UnitVector projVector; FT_UnitVector freeVector; FT_Long loop; FT_F26Dot6 minimum_distance; FT_Int round_state; FT_Bool auto_flip; FT_F26Dot6 control_value_cutin; FT_F26Dot6 single_width_cutin; FT_F26Dot6 single_width_value; FT_UShort delta_base; FT_UShort delta_shift; FT_Byte instruct_control; /* According to Greg Hitchcock from Microsoft, the `scan_control' */ /* variable as documented in the TrueType specification is a 32-bit */ /* integer; the high-word part holds the SCANTYPE value, the low-word */ /* part the SCANCTRL value. We separate it into two fields. */ FT_Bool scan_control; FT_Int scan_type; FT_UShort gep0; FT_UShort gep1; FT_UShort gep2; } TT_GraphicsState; #ifdef TT_USE_BYTECODE_INTERPRETER FT_LOCAL( void ) tt_glyphzone_done( TT_GlyphZone zone ); FT_LOCAL( FT_Error ) tt_glyphzone_new( FT_Memory memory, FT_UShort maxPoints, FT_Short maxContours, TT_GlyphZone zone ); #endif /* TT_USE_BYTECODE_INTERPRETER */ /************************************************************************** * * EXECUTION SUBTABLES * * These sub-tables relate to instruction execution. * */ #define TT_MAX_CODE_RANGES 3 /************************************************************************** * * There can only be 3 active code ranges at once: * - the Font Program * - the CVT Program * - a glyph's instructions set */ typedef enum TT_CodeRange_Tag_ { tt_coderange_none = 0, tt_coderange_font, tt_coderange_cvt, tt_coderange_glyph } TT_CodeRange_Tag; typedef struct TT_CodeRange_ { FT_Byte* base; FT_Long size; } TT_CodeRange; typedef TT_CodeRange TT_CodeRangeTable[TT_MAX_CODE_RANGES]; /************************************************************************** * * Defines a function/instruction definition record. */ typedef struct TT_DefRecord_ { FT_Int range; /* in which code range is it located? */ FT_Long start; /* where does it start? */ FT_Long end; /* where does it end? */ FT_UInt opc; /* function #, or instruction code */ FT_Bool active; /* is it active? */ FT_Bool inline_delta; /* is function that defines inline delta? */ FT_ULong sph_fdef_flags; /* flags to identify special functions */ } TT_DefRecord, *TT_DefArray; /************************************************************************** * * Subglyph transformation record. */ typedef struct TT_Transform_ { FT_Fixed xx, xy; /* transformation matrix coefficients */ FT_Fixed yx, yy; FT_F26Dot6 ox, oy; /* offsets */ } TT_Transform; /************************************************************************** * * A note regarding non-squared pixels: * * (This text will probably go into some docs at some time; for now, it * is kept here to explain some definitions in the TT_Size_Metrics * record). * * The CVT is a one-dimensional array containing values that control * certain important characteristics in a font, like the height of all * capitals, all lowercase letter, default spacing or stem width/height. * * These values are found in FUnits in the font file, and must be scaled * to pixel coordinates before being used by the CVT and glyph programs. * Unfortunately, when using distinct x and y resolutions (or distinct x * and y pointsizes), there are two possible scalings. * * A first try was to implement a `lazy' scheme where all values were * scaled when first used. However, while some values are always used * in the same direction, some others are used under many different * circumstances and orientations. * * I have found a simpler way to do the same, and it even seems to work * in most of the cases: * * - All CVT values are scaled to the maximum ppem size. * * - When performing a read or write in the CVT, a ratio factor is used * to perform adequate scaling. Example: * * x_ppem = 14 * y_ppem = 10 * * We choose ppem = x_ppem = 14 as the CVT scaling size. All cvt * entries are scaled to it. * * x_ratio = 1.0 * y_ratio = y_ppem/ppem (< 1.0) * * We compute the current ratio like: * * - If projVector is horizontal, * ratio = x_ratio = 1.0 * * - if projVector is vertical, * ratio = y_ratio * * - else, * ratio = sqrt( (proj.x * x_ratio) ^ 2 + (proj.y * y_ratio) ^ 2 ) * * Reading a cvt value returns * ratio * cvt[index] * * Writing a cvt value in pixels: * cvt[index] / ratio * * The current ppem is simply * ratio * ppem * */ /************************************************************************** * * Metrics used by the TrueType size and context objects. */ typedef struct TT_Size_Metrics_ { /* for non-square pixels */ FT_Long x_ratio; FT_Long y_ratio; FT_UShort ppem; /* maximum ppem size */ FT_Long ratio; /* current ratio */ FT_Fixed scale; FT_F26Dot6 compensations[4]; /* device-specific compensations */ FT_Bool valid; FT_Bool rotated; /* `is the glyph rotated?'-flag */ FT_Bool stretched; /* `is the glyph stretched?'-flag */ } TT_Size_Metrics; /************************************************************************** * * TrueType size class. */ typedef struct TT_SizeRec_ { FT_SizeRec root; /* we have our own copy of metrics so that we can modify */ /* it without affecting auto-hinting (when used) */ FT_Size_Metrics* metrics; /* for the current rendering mode */ FT_Size_Metrics hinted_metrics; /* for the hinted rendering mode */ TT_Size_Metrics ttmetrics; FT_Byte* widthp; /* glyph widths from the hdmx table */ FT_ULong strike_index; /* 0xFFFFFFFF to indicate invalid */ #ifdef TT_USE_BYTECODE_INTERPRETER FT_Long point_size; /* for the `MPS' bytecode instruction */ FT_UInt num_function_defs; /* number of function definitions */ FT_UInt max_function_defs; TT_DefArray function_defs; /* table of function definitions */ FT_UInt num_instruction_defs; /* number of ins. definitions */ FT_UInt max_instruction_defs; TT_DefArray instruction_defs; /* table of ins. definitions */ FT_UInt max_func; FT_UInt max_ins; TT_CodeRangeTable codeRangeTable; TT_GraphicsState GS; FT_ULong cvt_size; /* the scaled control value table */ FT_Long* cvt; FT_UShort storage_size; /* The storage area is now part of */ FT_Long* storage; /* the instance */ TT_GlyphZoneRec twilight; /* The instance's twilight zone */ TT_ExecContext context; /* if negative, `fpgm' (resp. `prep'), wasn't executed yet; */ /* otherwise it is the returned error code */ FT_Error bytecode_ready; FT_Error cvt_ready; #endif /* TT_USE_BYTECODE_INTERPRETER */ } TT_SizeRec; /************************************************************************** * * TrueType driver class. */ typedef struct TT_DriverRec_ { FT_DriverRec root; TT_GlyphZoneRec zone; /* glyph loader points zone */ FT_UInt interpreter_version; } TT_DriverRec; /* Note: All of the functions below (except tt_size_reset()) are used */ /* as function pointers in a FT_Driver_ClassRec. Therefore their */ /* parameters are of types FT_Face, FT_Size, etc., rather than TT_Face, */ /* TT_Size, etc., so that the compiler can confirm that the types and */ /* number of parameters are correct. In all cases the FT_xxx types are */ /* cast to their TT_xxx counterparts inside the functions since FreeType */ /* will always use the TT driver to create them. */ /************************************************************************** * * Face functions */ FT_LOCAL( FT_Error ) tt_face_init( FT_Stream stream, FT_Face ttface, /* TT_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ); FT_LOCAL( void ) tt_face_done( FT_Face ttface ); /* TT_Face */ /************************************************************************** * * Size functions */ FT_LOCAL( FT_Error ) tt_size_init( FT_Size ttsize ); /* TT_Size */ FT_LOCAL( void ) tt_size_done( FT_Size ttsize ); /* TT_Size */ #ifdef TT_USE_BYTECODE_INTERPRETER FT_LOCAL( FT_Error ) tt_size_run_fpgm( TT_Size size, FT_Bool pedantic ); FT_LOCAL( FT_Error ) tt_size_run_prep( TT_Size size, FT_Bool pedantic ); FT_LOCAL( FT_Error ) tt_size_ready_bytecode( TT_Size size, FT_Bool pedantic ); #endif /* TT_USE_BYTECODE_INTERPRETER */ FT_LOCAL( FT_Error ) tt_size_reset( TT_Size size, FT_Bool only_height ); /************************************************************************** * * Driver functions */ FT_LOCAL( FT_Error ) tt_driver_init( FT_Module ttdriver ); /* TT_Driver */ FT_LOCAL( void ) tt_driver_done( FT_Module ttdriver ); /* TT_Driver */ /************************************************************************** * * Slot functions */ FT_LOCAL( FT_Error ) tt_slot_init( FT_GlyphSlot slot ); /* auxiliary */ #define IS_HINTED( flags ) ( ( flags & FT_LOAD_NO_HINTING ) == 0 ) FT_END_HEADER #endif /* TTOBJS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttobjs.h
C++
gpl-3.0
12,050
/**************************************************************************** * * ttpload.c * * TrueType-specific tables loader (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftobjs.h> #include <freetype/internal/ftstream.h> #include <freetype/tttags.h> #include "ttpload.h" #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include "ttgxvar.h" #endif #include "tterrors.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT ttpload /************************************************************************** * * @Function: * tt_face_load_loca * * @Description: * Load the locations table. * * @InOut: * face :: * A handle to the target face object. * * @Input: * stream :: * The input stream. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_load_loca( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_len; FT_Int shift; /* we need the size of the `glyf' table for malformed `loca' tables */ error = face->goto_table( face, TTAG_glyf, stream, &face->glyf_len ); /* it is possible that a font doesn't have a glyf table at all */ /* or its size is zero */ if ( FT_ERR_EQ( error, Table_Missing ) ) { face->glyf_len = 0; face->glyf_offset = 0; } else if ( error ) goto Exit; else { #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( face->root.internal->incremental_interface ) face->glyf_offset = 0; else #endif face->glyf_offset = FT_STREAM_POS(); } FT_TRACE2(( "Locations " )); error = face->goto_table( face, TTAG_loca, stream, &table_len ); if ( error ) { error = FT_THROW( Locations_Missing ); goto Exit; } shift = face->header.Index_To_Loc_Format != 0 ? 2 : 1; if ( table_len > 0x10000UL << shift ) { FT_TRACE2(( "table too large\n" )); table_len = 0x10000UL << shift; } face->num_locations = table_len >> shift; if ( face->num_locations != (FT_ULong)face->root.num_glyphs + 1 ) { FT_TRACE2(( "glyph count mismatch! loca: %ld, maxp: %ld\n", face->num_locations - 1, face->root.num_glyphs )); /* we only handle the case where `maxp' gives a larger value */ if ( face->num_locations < (FT_ULong)face->root.num_glyphs + 1 ) { FT_ULong new_loca_len = ( (FT_ULong)face->root.num_glyphs + 1 ) << shift; TT_Table entry = face->dir_tables; TT_Table limit = entry + face->num_tables; FT_Long pos = (FT_Long)FT_STREAM_POS(); FT_Long dist = 0x7FFFFFFFL; FT_Bool found = 0; /* compute the distance to next table in font file */ for ( ; entry < limit; entry++ ) { FT_Long diff = (FT_Long)entry->Offset - pos; if ( diff > 0 && diff < dist ) { dist = diff; found = 1; } } if ( !found ) { /* `loca' is the last table */ dist = (FT_Long)stream->size - pos; } if ( new_loca_len <= (FT_ULong)dist ) { face->num_locations = (FT_ULong)face->root.num_glyphs + 1; table_len = new_loca_len; FT_TRACE2(( "adjusting num_locations to %ld\n", face->num_locations )); } else { face->root.num_glyphs = face->num_locations ? (FT_Long)face->num_locations - 1 : 0; FT_TRACE2(( "adjusting num_glyphs to %ld\n", face->root.num_glyphs )); } } } /* * Extract the frame. We don't need to decompress it since * we are able to parse it directly. */ if ( FT_FRAME_EXTRACT( table_len, face->glyph_locations ) ) goto Exit; FT_TRACE2(( "loaded\n" )); Exit: return error; } FT_LOCAL_DEF( FT_ULong ) tt_face_get_location( TT_Face face, FT_UInt gindex, FT_UInt *asize ) { FT_ULong pos1, pos2; FT_Byte* p; FT_Byte* p_limit; pos1 = pos2 = 0; if ( gindex < face->num_locations ) { if ( face->header.Index_To_Loc_Format != 0 ) { p = face->glyph_locations + gindex * 4; p_limit = face->glyph_locations + face->num_locations * 4; pos1 = FT_NEXT_ULONG( p ); pos2 = pos1; if ( p + 4 <= p_limit ) pos2 = FT_NEXT_ULONG( p ); } else { p = face->glyph_locations + gindex * 2; p_limit = face->glyph_locations + face->num_locations * 2; pos1 = FT_NEXT_USHORT( p ); pos2 = pos1; if ( p + 2 <= p_limit ) pos2 = FT_NEXT_USHORT( p ); pos1 <<= 1; pos2 <<= 1; } } /* Check broken location data. */ if ( pos1 > face->glyf_len ) { FT_TRACE1(( "tt_face_get_location:" " too large offset (0x%08lx) found for glyph index %d,\n", pos1, gindex )); FT_TRACE1(( " " " exceeding the end of `glyf' table (0x%08lx)\n", face->glyf_len )); *asize = 0; return 0; } if ( pos2 > face->glyf_len ) { /* We try to sanitize the last `loca' entry. */ if ( gindex == face->num_locations - 2 ) { FT_TRACE1(( "tt_face_get_location:" " too large size (%ld bytes) found for glyph index %d,\n", pos2 - pos1, gindex )); FT_TRACE1(( " " " truncating at the end of `glyf' table to %ld bytes\n", face->glyf_len - pos1 )); pos2 = face->glyf_len; } else { FT_TRACE1(( "tt_face_get_location:" " too large offset (0x%08lx) found for glyph index %d,\n", pos2, gindex + 1 )); FT_TRACE1(( " " " exceeding the end of `glyf' table (0x%08lx)\n", face->glyf_len )); *asize = 0; return 0; } } /* The `loca' table must be ordered; it refers to the length of */ /* an entry as the difference between the current and the next */ /* position. However, there do exist (malformed) fonts which */ /* don't obey this rule, so we are only able to provide an */ /* upper bound for the size. */ /* */ /* We get (intentionally) a wrong, non-zero result in case the */ /* `glyf' table is missing. */ if ( pos2 >= pos1 ) *asize = (FT_UInt)( pos2 - pos1 ); else *asize = (FT_UInt)( face->glyf_len - pos1 ); return pos1; } FT_LOCAL_DEF( void ) tt_face_done_loca( TT_Face face ) { FT_Stream stream = face->root.stream; FT_FRAME_RELEASE( face->glyph_locations ); face->num_locations = 0; } /************************************************************************** * * @Function: * tt_face_load_cvt * * @Description: * Load the control value table into a face object. * * @InOut: * face :: * A handle to the target face object. * * @Input: * stream :: * A handle to the input stream. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_load_cvt( TT_Face face, FT_Stream stream ) { #ifdef TT_USE_BYTECODE_INTERPRETER FT_Error error; FT_Memory memory = stream->memory; FT_ULong table_len; FT_TRACE2(( "CVT " )); error = face->goto_table( face, TTAG_cvt, stream, &table_len ); if ( error ) { FT_TRACE2(( "is missing\n" )); face->cvt_size = 0; face->cvt = NULL; error = FT_Err_Ok; goto Exit; } face->cvt_size = table_len / 2; if ( FT_QNEW_ARRAY( face->cvt, face->cvt_size ) ) goto Exit; if ( FT_FRAME_ENTER( face->cvt_size * 2L ) ) goto Exit; { FT_Int32* cur = face->cvt; FT_Int32* limit = cur + face->cvt_size; for ( ; cur < limit; cur++ ) *cur = FT_GET_SHORT() * 64; } FT_FRAME_EXIT(); FT_TRACE2(( "loaded\n" )); #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( face->doblend ) error = tt_face_vary_cvt( face, stream ); #endif Exit: return error; #else /* !TT_USE_BYTECODE_INTERPRETER */ FT_UNUSED( face ); FT_UNUSED( stream ); return FT_Err_Ok; #endif } /************************************************************************** * * @Function: * tt_face_load_fpgm * * @Description: * Load the font program. * * @InOut: * face :: * A handle to the target face object. * * @Input: * stream :: * A handle to the input stream. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_load_fpgm( TT_Face face, FT_Stream stream ) { #ifdef TT_USE_BYTECODE_INTERPRETER FT_Error error; FT_ULong table_len; FT_TRACE2(( "Font program " )); /* The font program is optional */ error = face->goto_table( face, TTAG_fpgm, stream, &table_len ); if ( error ) { face->font_program = NULL; face->font_program_size = 0; error = FT_Err_Ok; FT_TRACE2(( "is missing\n" )); } else { face->font_program_size = table_len; if ( FT_FRAME_EXTRACT( table_len, face->font_program ) ) goto Exit; FT_TRACE2(( "loaded, %12ld bytes\n", face->font_program_size )); } Exit: return error; #else /* !TT_USE_BYTECODE_INTERPRETER */ FT_UNUSED( face ); FT_UNUSED( stream ); return FT_Err_Ok; #endif } /************************************************************************** * * @Function: * tt_face_load_prep * * @Description: * Load the cvt program. * * @InOut: * face :: * A handle to the target face object. * * @Input: * stream :: * A handle to the input stream. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_load_prep( TT_Face face, FT_Stream stream ) { #ifdef TT_USE_BYTECODE_INTERPRETER FT_Error error; FT_ULong table_len; FT_TRACE2(( "Prep program " )); error = face->goto_table( face, TTAG_prep, stream, &table_len ); if ( error ) { face->cvt_program = NULL; face->cvt_program_size = 0; error = FT_Err_Ok; FT_TRACE2(( "is missing\n" )); } else { face->cvt_program_size = table_len; if ( FT_FRAME_EXTRACT( table_len, face->cvt_program ) ) goto Exit; FT_TRACE2(( "loaded, %12ld bytes\n", face->cvt_program_size )); } Exit: return error; #else /* !TT_USE_BYTECODE_INTERPRETER */ FT_UNUSED( face ); FT_UNUSED( stream ); return FT_Err_Ok; #endif } FT_COMPARE_DEF( int ) compare_ppem( const void* a, const void* b ) { return **(FT_Byte**)a - **(FT_Byte**)b; } /************************************************************************** * * @Function: * tt_face_load_hdmx * * @Description: * Load the `hdmx' table into the face object. * * @Input: * face :: * A handle to the target face object. * * stream :: * A handle to the input stream. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) tt_face_load_hdmx( TT_Face face, FT_Stream stream ) { FT_Error error; FT_Memory memory = stream->memory; FT_UInt nn, num_records; FT_ULong table_size, record_size; FT_Byte* p; FT_Byte* limit; /* this table is optional */ error = face->goto_table( face, TTAG_hdmx, stream, &table_size ); if ( error || table_size < 8 ) return FT_Err_Ok; if ( FT_FRAME_EXTRACT( table_size, face->hdmx_table ) ) goto Exit; p = face->hdmx_table; limit = p + table_size; /* Given that `hdmx' tables are losing its importance (for example, */ /* variation fonts introduced in OpenType 1.8 must not have this */ /* table) we no longer test for a correct `version' field. */ p += 2; num_records = FT_NEXT_USHORT( p ); record_size = FT_NEXT_ULONG( p ); /* There are at least two fonts, HANNOM-A and HANNOM-B version */ /* 2.0 (2005), which get this wrong: The upper two bytes of */ /* the size value are set to 0xFF instead of 0x00. We catch */ /* and fix this. */ if ( record_size >= 0xFFFF0000UL ) record_size &= 0xFFFFU; FT_TRACE2(( "Hdmx " )); /* The limit for `num_records' is a heuristic value. */ if ( num_records > 255 || num_records == 0 ) { FT_TRACE2(( "with unreasonable %u records rejected\n", num_records )); goto Fail; } /* Out-of-spec tables are rejected. The record size must be */ /* equal to the number of glyphs + 2 + 32-bit padding. */ if ( (FT_Long)record_size != ( ( face->root.num_glyphs + 2 + 3 ) & ~3 ) ) { FT_TRACE2(( "with record size off by %ld bytes rejected\n", (FT_Long)record_size - ( ( face->root.num_glyphs + 2 + 3 ) & ~3 ) )); goto Fail; } if ( FT_QNEW_ARRAY( face->hdmx_records, num_records ) ) goto Fail; for ( nn = 0; nn < num_records; nn++ ) { if ( p + record_size > limit ) break; face->hdmx_records[nn] = p; p += record_size; } /* The records must be already sorted by ppem but it does not */ /* hurt to make sure so that the binary search works later. */ ft_qsort( face->hdmx_records, nn, sizeof ( FT_Byte* ), compare_ppem ); face->hdmx_record_count = nn; face->hdmx_table_size = table_size; face->hdmx_record_size = record_size; FT_TRACE2(( "%ux%lu loaded\n", num_records, record_size )); Exit: return error; Fail: FT_FRAME_RELEASE( face->hdmx_table ); face->hdmx_table_size = 0; goto Exit; } FT_LOCAL_DEF( void ) tt_face_free_hdmx( TT_Face face ) { FT_Stream stream = face->root.stream; FT_Memory memory = stream->memory; FT_FREE( face->hdmx_records ); FT_FRAME_RELEASE( face->hdmx_table ); } /************************************************************************** * * Return the advance width table for a given pixel size if it is found * in the font's `hdmx' table (if any). The records must be sorted for * the binary search to work properly. */ FT_LOCAL_DEF( FT_Byte* ) tt_face_get_device_metrics( TT_Face face, FT_UInt ppem, FT_UInt gindex ) { FT_UInt min = 0; FT_UInt max = face->hdmx_record_count; FT_UInt mid; FT_Byte* result = NULL; while ( min < max ) { mid = ( min + max ) >> 1; if ( face->hdmx_records[mid][0] > ppem ) max = mid; else if ( face->hdmx_records[mid][0] < ppem ) min = mid + 1; else { result = face->hdmx_records[mid] + 2 + gindex; break; } } return result; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttpload.c
C++
gpl-3.0
16,462
/**************************************************************************** * * ttpload.h * * TrueType-specific tables loader (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTPLOAD_H_ #define TTPLOAD_H_ #include <freetype/internal/tttypes.h> FT_BEGIN_HEADER FT_LOCAL( FT_Error ) tt_face_load_loca( TT_Face face, FT_Stream stream ); FT_LOCAL( FT_ULong ) tt_face_get_location( TT_Face face, FT_UInt gindex, FT_UInt *asize ); FT_LOCAL( void ) tt_face_done_loca( TT_Face face ); FT_LOCAL( FT_Error ) tt_face_load_cvt( TT_Face face, FT_Stream stream ); FT_LOCAL( FT_Error ) tt_face_load_fpgm( TT_Face face, FT_Stream stream ); FT_LOCAL( FT_Error ) tt_face_load_prep( TT_Face face, FT_Stream stream ); FT_LOCAL( FT_Error ) tt_face_load_hdmx( TT_Face face, FT_Stream stream ); FT_LOCAL( void ) tt_face_free_hdmx( TT_Face face ); FT_LOCAL( FT_Byte* ) tt_face_get_device_metrics( TT_Face face, FT_UInt ppem, FT_UInt gindex ); FT_END_HEADER #endif /* TTPLOAD_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttpload.h
C++
gpl-3.0
1,658
/**************************************************************************** * * ttsubpix.c * * TrueType Subpixel Hinting. * * Copyright (C) 2010-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftcalc.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/sfnt.h> #include <freetype/tttags.h> #include <freetype/ftoutln.h> #include <freetype/ftdriver.h> #include "ttsubpix.h" #if defined( TT_USE_BYTECODE_INTERPRETER ) && \ defined( TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY ) /************************************************************************** * * These rules affect how the TT Interpreter does hinting, with the * goal of doing subpixel hinting by (in general) ignoring x moves. * Some of these rules are fixes that go above and beyond the * stated techniques in the MS whitepaper on Cleartype, due to * artifacts in many glyphs. So, these rules make some glyphs render * better than they do in the MS rasterizer. * * "" string or 0 int/char indicates to apply to all glyphs. * "-" used as dummy placeholders, but any non-matching string works. * * Some of this could arguably be implemented in fontconfig, however: * * - Fontconfig can't set things on a glyph-by-glyph basis. * - The tweaks that happen here are very low-level, from an average * user's point of view and are best implemented in the hinter. * * The goal is to make the subpixel hinting techniques as generalized * as possible across all fonts to prevent the need for extra rules such * as these. * * The rule structure is designed so that entirely new rules can easily * be added when a new compatibility feature is discovered. * * The rule structures could also use some enhancement to handle ranges. * * ****************** WORK IN PROGRESS ******************* */ /* These are `classes' of fonts that can be grouped together and used in */ /* rules below. A blank entry "" is required at the end of these! */ #define FAMILY_CLASS_RULES_SIZE 7 static const SPH_Font_Class FAMILY_CLASS_Rules [FAMILY_CLASS_RULES_SIZE] = { { "MS Legacy Fonts", { "Aharoni", "Andale Mono", "Andalus", "Angsana New", "AngsanaUPC", "Arabic Transparent", "Arial Black", "Arial Narrow", "Arial Unicode MS", "Arial", "Batang", "Browallia New", "BrowalliaUPC", "Comic Sans MS", "Cordia New", "CordiaUPC", "Courier New", "DFKai-SB", "David Transparent", "David", "DilleniaUPC", "Estrangelo Edessa", "EucrosiaUPC", "FangSong_GB2312", "Fixed Miriam Transparent", "FrankRuehl", "Franklin Gothic Medium", "FreesiaUPC", "Garamond", "Gautami", "Georgia", "Gulim", "Impact", "IrisUPC", "JasmineUPC", "KaiTi_GB2312", "KodchiangUPC", "Latha", "Levenim MT", "LilyUPC", "Lucida Console", "Lucida Sans Unicode", "MS Gothic", "MS Mincho", "MV Boli", "Mangal", "Marlett", "Microsoft Sans Serif", "Mingliu", "Miriam Fixed", "Miriam Transparent", "Miriam", "Narkisim", "Palatino Linotype", "Raavi", "Rod Transparent", "Rod", "Shruti", "SimHei", "Simplified Arabic Fixed", "Simplified Arabic", "Simsun", "Sylfaen", "Symbol", "Tahoma", "Times New Roman", "Traditional Arabic", "Trebuchet MS", "Tunga", "Verdana", "Webdings", "Wingdings", "", }, }, { "Core MS Legacy Fonts", { "Arial Black", "Arial Narrow", "Arial Unicode MS", "Arial", "Comic Sans MS", "Courier New", "Garamond", "Georgia", "Impact", "Lucida Console", "Lucida Sans Unicode", "Microsoft Sans Serif", "Palatino Linotype", "Tahoma", "Times New Roman", "Trebuchet MS", "Verdana", "", }, }, { "Apple Legacy Fonts", { "Geneva", "Times", "Monaco", "Century", "Chalkboard", "Lobster", "Century Gothic", "Optima", "Lucida Grande", "Gill Sans", "Baskerville", "Helvetica", "Helvetica Neue", "", }, }, { "Legacy Sans Fonts", { "Andale Mono", "Arial Unicode MS", "Arial", "Century Gothic", "Comic Sans MS", "Franklin Gothic Medium", "Geneva", "Lucida Console", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans Typewriter", "Microsoft Sans Serif", "Monaco", "Tahoma", "Trebuchet MS", "Verdana", "", }, }, { "Misc Legacy Fonts", { "Dark Courier", "", }, }, { "Verdana Clones", { "DejaVu Sans", "Bitstream Vera Sans", "", }, }, { "Verdana and Clones", { "DejaVu Sans", "Bitstream Vera Sans", "Verdana", "", }, }, }; /* Define this to force natural (i.e. not bitmap-compatible) widths. */ /* The default leans strongly towards natural widths except for a few */ /* legacy fonts where a selective combination produces nicer results. */ /* #define FORCE_NATURAL_WIDTHS */ /* Define `classes' of styles that can be grouped together and used in */ /* rules below. A blank entry "" is required at the end of these! */ #define STYLE_CLASS_RULES_SIZE 5 static const SPH_Font_Class STYLE_CLASS_Rules [STYLE_CLASS_RULES_SIZE] = { { "Regular Class", { "Regular", "Book", "Medium", "Roman", "Normal", "", }, }, { "Regular/Italic Class", { "Regular", "Book", "Medium", "Italic", "Oblique", "Roman", "Normal", "", }, }, { "Bold/BoldItalic Class", { "Bold", "Bold Italic", "Black", "", }, }, { "Bold/Italic/BoldItalic Class", { "Bold", "Bold Italic", "Black", "Italic", "Oblique", "", }, }, { "Regular/Bold Class", { "Regular", "Book", "Medium", "Normal", "Roman", "Bold", "Black", "", }, }, }; /* Force special legacy fixes for fonts. */ #define COMPATIBILITY_MODE_RULES_SIZE 1 static const SPH_TweakRule COMPATIBILITY_MODE_Rules [COMPATIBILITY_MODE_RULES_SIZE] = { { "Verdana Clones", 0, "", 0 }, }; /* Don't do subpixel (ignore_x_mode) hinting; do normal hinting. */ #define PIXEL_HINTING_RULES_SIZE 2 static const SPH_TweakRule PIXEL_HINTING_Rules [PIXEL_HINTING_RULES_SIZE] = { /* these characters are almost always safe */ { "Courier New", 12, "Italic", 'z' }, { "Courier New", 11, "Italic", 'z' }, }; /* Subpixel hinting ignores SHPIX rules on X. Force SHPIX for these. */ #define DO_SHPIX_RULES_SIZE 1 static const SPH_TweakRule DO_SHPIX_Rules [DO_SHPIX_RULES_SIZE] = { { "-", 0, "", 0 }, }; /* Skip Y moves that start with a point that is not on a Y pixel */ /* boundary and don't move that point to a Y pixel boundary. */ #define SKIP_NONPIXEL_Y_MOVES_RULES_SIZE 4 static const SPH_TweakRule SKIP_NONPIXEL_Y_MOVES_Rules [SKIP_NONPIXEL_Y_MOVES_RULES_SIZE] = { /* fix vwxyz thinness */ { "Consolas", 0, "", 0 }, /* Fix thin middle stems */ { "Core MS Legacy Fonts", 0, "Regular", 0 }, /* Cyrillic small letter I */ { "Legacy Sans Fonts", 0, "", 0 }, /* Fix artifacts with some Regular & Bold */ { "Verdana Clones", 0, "", 0 }, }; #define SKIP_NONPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE 1 static const SPH_TweakRule SKIP_NONPIXEL_Y_MOVES_Rules_Exceptions [SKIP_NONPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE] = { /* Fixes < and > */ { "Courier New", 0, "Regular", 0 }, }; /* Skip Y moves that start with a point that is not on a Y pixel */ /* boundary and don't move that point to a Y pixel boundary. */ #define SKIP_NONPIXEL_Y_MOVES_DELTAP_RULES_SIZE 2 static const SPH_TweakRule SKIP_NONPIXEL_Y_MOVES_DELTAP_Rules [SKIP_NONPIXEL_Y_MOVES_DELTAP_RULES_SIZE] = { /* Maintain thickness of diagonal in 'N' */ { "Times New Roman", 0, "Regular/Bold Class", 'N' }, { "Georgia", 0, "Regular/Bold Class", 'N' }, }; /* Skip Y moves that move a point off a Y pixel boundary. */ #define SKIP_OFFPIXEL_Y_MOVES_RULES_SIZE 1 static const SPH_TweakRule SKIP_OFFPIXEL_Y_MOVES_Rules [SKIP_OFFPIXEL_Y_MOVES_RULES_SIZE] = { { "-", 0, "", 0 }, }; #define SKIP_OFFPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE 1 static const SPH_TweakRule SKIP_OFFPIXEL_Y_MOVES_Rules_Exceptions [SKIP_OFFPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE] = { { "-", 0, "", 0 }, }; /* Round moves that don't move a point to a Y pixel boundary. */ #define ROUND_NONPIXEL_Y_MOVES_RULES_SIZE 2 static const SPH_TweakRule ROUND_NONPIXEL_Y_MOVES_Rules [ROUND_NONPIXEL_Y_MOVES_RULES_SIZE] = { /* Droid font instructions don't snap Y to pixels */ { "Droid Sans", 0, "Regular/Italic Class", 0 }, { "Droid Sans Mono", 0, "", 0 }, }; #define ROUND_NONPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE 1 static const SPH_TweakRule ROUND_NONPIXEL_Y_MOVES_Rules_Exceptions [ROUND_NONPIXEL_Y_MOVES_RULES_EXCEPTIONS_SIZE] = { { "-", 0, "", 0 }, }; /* Allow a Direct_Move along X freedom vector if matched. */ #define ALLOW_X_DMOVE_RULES_SIZE 1 static const SPH_TweakRule ALLOW_X_DMOVE_Rules [ALLOW_X_DMOVE_RULES_SIZE] = { /* Fixes vanishing diagonal in 4 */ { "Verdana", 0, "Regular", '4' }, }; /* Return MS rasterizer version 35 if matched. */ #define RASTERIZER_35_RULES_SIZE 8 static const SPH_TweakRule RASTERIZER_35_Rules [RASTERIZER_35_RULES_SIZE] = { /* This seems to be the only way to make these look good */ { "Times New Roman", 0, "Regular", 'i' }, { "Times New Roman", 0, "Regular", 'j' }, { "Times New Roman", 0, "Regular", 'm' }, { "Times New Roman", 0, "Regular", 'r' }, { "Times New Roman", 0, "Regular", 'a' }, { "Times New Roman", 0, "Regular", 'n' }, { "Times New Roman", 0, "Regular", 'p' }, { "Times", 0, "", 0 }, }; /* Don't round to the subpixel grid. Round to pixel grid. */ #define NORMAL_ROUND_RULES_SIZE 1 static const SPH_TweakRule NORMAL_ROUND_Rules [NORMAL_ROUND_RULES_SIZE] = { /* Fix serif thickness for certain ppems */ /* Can probably be generalized somehow */ { "Courier New", 0, "", 0 }, }; /* Skip IUP instructions if matched. */ #define SKIP_IUP_RULES_SIZE 1 static const SPH_TweakRule SKIP_IUP_Rules [SKIP_IUP_RULES_SIZE] = { { "Arial", 13, "Regular", 'a' }, }; /* Skip MIAP Twilight hack if matched. */ #define MIAP_HACK_RULES_SIZE 1 static const SPH_TweakRule MIAP_HACK_Rules [MIAP_HACK_RULES_SIZE] = { { "Geneva", 12, "", 0 }, }; /* Skip DELTAP instructions if matched. */ #define ALWAYS_SKIP_DELTAP_RULES_SIZE 23 static const SPH_TweakRule ALWAYS_SKIP_DELTAP_Rules [ALWAYS_SKIP_DELTAP_RULES_SIZE] = { { "Georgia", 0, "Regular", 'k' }, /* fix various problems with e in different versions */ { "Trebuchet MS", 14, "Regular", 'e' }, { "Trebuchet MS", 13, "Regular", 'e' }, { "Trebuchet MS", 15, "Regular", 'e' }, { "Trebuchet MS", 0, "Italic", 'v' }, { "Trebuchet MS", 0, "Italic", 'w' }, { "Trebuchet MS", 0, "Regular", 'Y' }, { "Arial", 11, "Regular", 's' }, /* prevent problems with '3' and others */ { "Verdana", 10, "Regular", 0 }, { "Verdana", 9, "Regular", 0 }, /* Cyrillic small letter short I */ { "Legacy Sans Fonts", 0, "", 0x438 }, { "Legacy Sans Fonts", 0, "", 0x439 }, { "Arial", 10, "Regular", '6' }, { "Arial", 0, "Bold/BoldItalic Class", 'a' }, /* Make horizontal stems consistent with the rest */ { "Arial", 24, "Bold", 'a' }, { "Arial", 25, "Bold", 'a' }, { "Arial", 24, "Bold", 's' }, { "Arial", 25, "Bold", 's' }, { "Arial", 34, "Bold", 's' }, { "Arial", 35, "Bold", 's' }, { "Arial", 36, "Bold", 's' }, { "Arial", 25, "Regular", 's' }, { "Arial", 26, "Regular", 's' }, }; /* Always do DELTAP instructions if matched. */ #define ALWAYS_DO_DELTAP_RULES_SIZE 1 static const SPH_TweakRule ALWAYS_DO_DELTAP_Rules [ALWAYS_DO_DELTAP_RULES_SIZE] = { { "-", 0, "", 0 }, }; /* Don't allow ALIGNRP after IUP. */ #define NO_ALIGNRP_AFTER_IUP_RULES_SIZE 1 static const SPH_TweakRule NO_ALIGNRP_AFTER_IUP_Rules [NO_ALIGNRP_AFTER_IUP_RULES_SIZE] = { /* Prevent creation of dents in outline */ { "-", 0, "", 0 }, }; /* Don't allow DELTAP after IUP. */ #define NO_DELTAP_AFTER_IUP_RULES_SIZE 1 static const SPH_TweakRule NO_DELTAP_AFTER_IUP_Rules [NO_DELTAP_AFTER_IUP_RULES_SIZE] = { { "-", 0, "", 0 }, }; /* Don't allow CALL after IUP. */ #define NO_CALL_AFTER_IUP_RULES_SIZE 1 static const SPH_TweakRule NO_CALL_AFTER_IUP_Rules [NO_CALL_AFTER_IUP_RULES_SIZE] = { /* Prevent creation of dents in outline */ { "-", 0, "", 0 }, }; /* De-embolden these glyphs slightly. */ #define DEEMBOLDEN_RULES_SIZE 9 static const SPH_TweakRule DEEMBOLDEN_Rules [DEEMBOLDEN_RULES_SIZE] = { { "Courier New", 0, "Bold", 'A' }, { "Courier New", 0, "Bold", 'W' }, { "Courier New", 0, "Bold", 'w' }, { "Courier New", 0, "Bold", 'M' }, { "Courier New", 0, "Bold", 'X' }, { "Courier New", 0, "Bold", 'K' }, { "Courier New", 0, "Bold", 'x' }, { "Courier New", 0, "Bold", 'z' }, { "Courier New", 0, "Bold", 'v' }, }; /* Embolden these glyphs slightly. */ #define EMBOLDEN_RULES_SIZE 2 static const SPH_TweakRule EMBOLDEN_Rules [EMBOLDEN_RULES_SIZE] = { { "Courier New", 0, "Regular", 0 }, { "Courier New", 0, "Italic", 0 }, }; /* This is a CVT hack that makes thick horizontal stems on 2, 5, 7 */ /* similar to Windows XP. */ #define TIMES_NEW_ROMAN_HACK_RULES_SIZE 12 static const SPH_TweakRule TIMES_NEW_ROMAN_HACK_Rules [TIMES_NEW_ROMAN_HACK_RULES_SIZE] = { { "Times New Roman", 16, "Italic", '2' }, { "Times New Roman", 16, "Italic", '5' }, { "Times New Roman", 16, "Italic", '7' }, { "Times New Roman", 16, "Regular", '2' }, { "Times New Roman", 16, "Regular", '5' }, { "Times New Roman", 16, "Regular", '7' }, { "Times New Roman", 17, "Italic", '2' }, { "Times New Roman", 17, "Italic", '5' }, { "Times New Roman", 17, "Italic", '7' }, { "Times New Roman", 17, "Regular", '2' }, { "Times New Roman", 17, "Regular", '5' }, { "Times New Roman", 17, "Regular", '7' }, }; /* This fudges distance on 2 to get rid of the vanishing stem issue. */ /* A real solution to this is certainly welcome. */ #define COURIER_NEW_2_HACK_RULES_SIZE 15 static const SPH_TweakRule COURIER_NEW_2_HACK_Rules [COURIER_NEW_2_HACK_RULES_SIZE] = { { "Courier New", 10, "Regular", '2' }, { "Courier New", 11, "Regular", '2' }, { "Courier New", 12, "Regular", '2' }, { "Courier New", 13, "Regular", '2' }, { "Courier New", 14, "Regular", '2' }, { "Courier New", 15, "Regular", '2' }, { "Courier New", 16, "Regular", '2' }, { "Courier New", 17, "Regular", '2' }, { "Courier New", 18, "Regular", '2' }, { "Courier New", 19, "Regular", '2' }, { "Courier New", 20, "Regular", '2' }, { "Courier New", 21, "Regular", '2' }, { "Courier New", 22, "Regular", '2' }, { "Courier New", 23, "Regular", '2' }, { "Courier New", 24, "Regular", '2' }, }; #ifndef FORCE_NATURAL_WIDTHS /* Use compatible widths with these glyphs. Compatible widths is always */ /* on when doing B/W TrueType instructing, but is used selectively here, */ /* typically on glyphs with 3 or more vertical stems. */ #define COMPATIBLE_WIDTHS_RULES_SIZE 38 static const SPH_TweakRule COMPATIBLE_WIDTHS_Rules [COMPATIBLE_WIDTHS_RULES_SIZE] = { { "Arial Unicode MS", 12, "Regular Class", 'm' }, { "Arial Unicode MS", 14, "Regular Class", 'm' }, /* Cyrillic small letter sha */ { "Arial", 10, "Regular Class", 0x448 }, { "Arial", 11, "Regular Class", 'm' }, { "Arial", 12, "Regular Class", 'm' }, /* Cyrillic small letter sha */ { "Arial", 12, "Regular Class", 0x448 }, { "Arial", 13, "Regular Class", 0x448 }, { "Arial", 14, "Regular Class", 'm' }, /* Cyrillic small letter sha */ { "Arial", 14, "Regular Class", 0x448 }, { "Arial", 15, "Regular Class", 0x448 }, { "Arial", 17, "Regular Class", 'm' }, { "DejaVu Sans", 15, "Regular Class", 0 }, { "Microsoft Sans Serif", 11, "Regular Class", 0 }, { "Microsoft Sans Serif", 12, "Regular Class", 0 }, { "Segoe UI", 11, "Regular Class", 0 }, { "Monaco", 0, "Regular Class", 0 }, { "Segoe UI", 12, "Regular Class", 'm' }, { "Segoe UI", 14, "Regular Class", 'm' }, { "Tahoma", 11, "Regular Class", 0 }, { "Times New Roman", 16, "Regular Class", 'c' }, { "Times New Roman", 16, "Regular Class", 'm' }, { "Times New Roman", 16, "Regular Class", 'o' }, { "Times New Roman", 16, "Regular Class", 'w' }, { "Trebuchet MS", 11, "Regular Class", 0 }, { "Trebuchet MS", 12, "Regular Class", 0 }, { "Trebuchet MS", 14, "Regular Class", 0 }, { "Trebuchet MS", 15, "Regular Class", 0 }, { "Ubuntu", 12, "Regular Class", 'm' }, /* Cyrillic small letter sha */ { "Verdana", 10, "Regular Class", 0x448 }, { "Verdana", 11, "Regular Class", 0x448 }, { "Verdana and Clones", 12, "Regular Class", 'i' }, { "Verdana and Clones", 12, "Regular Class", 'j' }, { "Verdana and Clones", 12, "Regular Class", 'l' }, { "Verdana and Clones", 12, "Regular Class", 'm' }, { "Verdana and Clones", 13, "Regular Class", 'i' }, { "Verdana and Clones", 13, "Regular Class", 'j' }, { "Verdana and Clones", 13, "Regular Class", 'l' }, { "Verdana and Clones", 14, "Regular Class", 'm' }, }; /* Scaling slightly in the x-direction prior to hinting results in */ /* more visually pleasing glyphs in certain cases. */ /* This sometimes needs to be coordinated with compatible width rules. */ /* A value of 1000 corresponds to a scaled value of 1.0. */ #define X_SCALING_RULES_SIZE 50 static const SPH_ScaleRule X_SCALING_Rules[X_SCALING_RULES_SIZE] = { { "DejaVu Sans", 12, "Regular Class", 'm', 950 }, { "Verdana and Clones", 12, "Regular Class", 'a', 1100 }, { "Verdana and Clones", 13, "Regular Class", 'a', 1050 }, { "Arial", 11, "Regular Class", 'm', 975 }, { "Arial", 12, "Regular Class", 'm', 1050 }, /* Cyrillic small letter el */ { "Arial", 13, "Regular Class", 0x43B, 950 }, { "Arial", 13, "Regular Class", 'o', 950 }, { "Arial", 13, "Regular Class", 'e', 950 }, { "Arial", 14, "Regular Class", 'm', 950 }, /* Cyrillic small letter el */ { "Arial", 15, "Regular Class", 0x43B, 925 }, { "Bitstream Vera Sans", 10, "Regular/Italic Class", 0, 1100 }, { "Bitstream Vera Sans", 12, "Regular/Italic Class", 0, 1050 }, { "Bitstream Vera Sans", 16, "Regular Class", 0, 1050 }, { "Bitstream Vera Sans", 9, "Regular/Italic Class", 0, 1050 }, { "DejaVu Sans", 12, "Regular Class", 'l', 975 }, { "DejaVu Sans", 12, "Regular Class", 'i', 975 }, { "DejaVu Sans", 12, "Regular Class", 'j', 975 }, { "DejaVu Sans", 13, "Regular Class", 'l', 950 }, { "DejaVu Sans", 13, "Regular Class", 'i', 950 }, { "DejaVu Sans", 13, "Regular Class", 'j', 950 }, { "DejaVu Sans", 10, "Regular/Italic Class", 0, 1100 }, { "DejaVu Sans", 12, "Regular/Italic Class", 0, 1050 }, { "Georgia", 10, "", 0, 1050 }, { "Georgia", 11, "", 0, 1100 }, { "Georgia", 12, "", 0, 1025 }, { "Georgia", 13, "", 0, 1050 }, { "Georgia", 16, "", 0, 1050 }, { "Georgia", 17, "", 0, 1030 }, { "Liberation Sans", 12, "Regular Class", 'm', 1100 }, { "Lucida Grande", 11, "Regular Class", 'm', 1100 }, { "Microsoft Sans Serif", 11, "Regular Class", 'm', 950 }, { "Microsoft Sans Serif", 12, "Regular Class", 'm', 1050 }, { "Segoe UI", 12, "Regular Class", 'H', 1050 }, { "Segoe UI", 12, "Regular Class", 'm', 1050 }, { "Segoe UI", 14, "Regular Class", 'm', 1050 }, { "Tahoma", 11, "Regular Class", 'i', 975 }, { "Tahoma", 11, "Regular Class", 'l', 975 }, { "Tahoma", 11, "Regular Class", 'j', 900 }, { "Tahoma", 11, "Regular Class", 'm', 918 }, { "Verdana", 10, "Regular/Italic Class", 0, 1100 }, { "Verdana", 12, "Regular Class", 'm', 975 }, { "Verdana", 12, "Regular/Italic Class", 0, 1050 }, { "Verdana", 13, "Regular/Italic Class", 'i', 950 }, { "Verdana", 13, "Regular/Italic Class", 'j', 950 }, { "Verdana", 13, "Regular/Italic Class", 'l', 950 }, { "Verdana", 16, "Regular Class", 0, 1050 }, { "Verdana", 9, "Regular/Italic Class", 0, 1050 }, { "Times New Roman", 16, "Regular Class", 'm', 918 }, { "Trebuchet MS", 11, "Regular Class", 'm', 800 }, { "Trebuchet MS", 12, "Regular Class", 'm', 800 }, }; #else #define COMPATIBLE_WIDTHS_RULES_SIZE 1 static const SPH_TweakRule COMPATIBLE_WIDTHS_Rules [COMPATIBLE_WIDTHS_RULES_SIZE] = { { "-", 0, "", 0 }, }; #define X_SCALING_RULES_SIZE 1 static const SPH_ScaleRule X_SCALING_Rules [X_SCALING_RULES_SIZE] = { { "-", 0, "", 0, 1000 }, }; #endif /* FORCE_NATURAL_WIDTHS */ static FT_Bool is_member_of_family_class( const FT_String* detected_font_name, const FT_String* rule_font_name ) { FT_UInt i, j; /* Does font name match rule family? */ if ( ft_strcmp( detected_font_name, rule_font_name ) == 0 ) return TRUE; /* Is font name a wildcard ""? */ if ( ft_strcmp( rule_font_name, "" ) == 0 ) return TRUE; /* Is font name contained in a class list? */ for ( i = 0; i < FAMILY_CLASS_RULES_SIZE; i++ ) { if ( ft_strcmp( FAMILY_CLASS_Rules[i].name, rule_font_name ) == 0 ) { for ( j = 0; j < SPH_MAX_CLASS_MEMBERS; j++ ) { if ( ft_strcmp( FAMILY_CLASS_Rules[i].member[j], "" ) == 0 ) continue; if ( ft_strcmp( FAMILY_CLASS_Rules[i].member[j], detected_font_name ) == 0 ) return TRUE; } } } return FALSE; } static FT_Bool is_member_of_style_class( const FT_String* detected_font_style, const FT_String* rule_font_style ) { FT_UInt i, j; /* Does font style match rule style? */ if ( ft_strcmp( detected_font_style, rule_font_style ) == 0 ) return TRUE; /* Is font style a wildcard ""? */ if ( ft_strcmp( rule_font_style, "" ) == 0 ) return TRUE; /* Is font style contained in a class list? */ for ( i = 0; i < STYLE_CLASS_RULES_SIZE; i++ ) { if ( ft_strcmp( STYLE_CLASS_Rules[i].name, rule_font_style ) == 0 ) { for ( j = 0; j < SPH_MAX_CLASS_MEMBERS; j++ ) { if ( ft_strcmp( STYLE_CLASS_Rules[i].member[j], "" ) == 0 ) continue; if ( ft_strcmp( STYLE_CLASS_Rules[i].member[j], detected_font_style ) == 0 ) return TRUE; } } } return FALSE; } FT_LOCAL_DEF( FT_Bool ) sph_test_tweak( TT_Face face, const FT_String* family, FT_UInt ppem, const FT_String* style, FT_UInt glyph_index, const SPH_TweakRule* rule, FT_UInt num_rules ) { FT_UInt i; /* rule checks may be able to be optimized further */ for ( i = 0; i < num_rules; i++ ) { if ( family && ( is_member_of_family_class ( family, rule[i].family ) ) ) if ( rule[i].ppem == 0 || rule[i].ppem == ppem ) if ( style && is_member_of_style_class ( style, rule[i].style ) ) if ( rule[i].glyph == 0 || FT_Get_Char_Index( (FT_Face)face, rule[i].glyph ) == glyph_index ) return TRUE; } return FALSE; } static FT_UInt scale_test_tweak( TT_Face face, const FT_String* family, FT_UInt ppem, const FT_String* style, FT_UInt glyph_index, const SPH_ScaleRule* rule, FT_UInt num_rules ) { FT_UInt i; /* rule checks may be able to be optimized further */ for ( i = 0; i < num_rules; i++ ) { if ( family && ( is_member_of_family_class ( family, rule[i].family ) ) ) if ( rule[i].ppem == 0 || rule[i].ppem == ppem ) if ( style && is_member_of_style_class( style, rule[i].style ) ) if ( rule[i].glyph == 0 || FT_Get_Char_Index( (FT_Face)face, rule[i].glyph ) == glyph_index ) return rule[i].scale; } return 1000; } FT_LOCAL_DEF( FT_UInt ) sph_test_tweak_x_scaling( TT_Face face, const FT_String* family, FT_UInt ppem, const FT_String* style, FT_UInt glyph_index ) { return scale_test_tweak( face, family, ppem, style, glyph_index, X_SCALING_Rules, X_SCALING_RULES_SIZE ); } #define TWEAK_RULES( x ) \ if ( sph_test_tweak( face, family, ppem, style, glyph_index, \ x##_Rules, x##_RULES_SIZE ) ) \ loader->exec->sph_tweak_flags |= SPH_TWEAK_##x #define TWEAK_RULES_EXCEPTIONS( x ) \ if ( sph_test_tweak( face, family, ppem, style, glyph_index, \ x##_Rules_Exceptions, x##_RULES_EXCEPTIONS_SIZE ) ) \ loader->exec->sph_tweak_flags &= ~SPH_TWEAK_##x FT_LOCAL_DEF( void ) sph_set_tweaks( TT_Loader loader, FT_UInt glyph_index ) { TT_Face face = loader->face; FT_String* family = face->root.family_name; FT_UInt ppem = loader->size->metrics->x_ppem; FT_String* style = face->root.style_name; /* don't apply rules if style isn't set */ if ( !face->root.style_name ) return; #ifdef SPH_DEBUG_MORE_VERBOSE printf( "%s,%d,%s,%c=%d ", family, ppem, style, glyph_index, glyph_index ); #endif TWEAK_RULES( PIXEL_HINTING ); if ( loader->exec->sph_tweak_flags & SPH_TWEAK_PIXEL_HINTING ) { loader->exec->ignore_x_mode = FALSE; return; } TWEAK_RULES( ALLOW_X_DMOVE ); TWEAK_RULES( ALWAYS_DO_DELTAP ); TWEAK_RULES( ALWAYS_SKIP_DELTAP ); TWEAK_RULES( DEEMBOLDEN ); TWEAK_RULES( DO_SHPIX ); TWEAK_RULES( EMBOLDEN ); TWEAK_RULES( MIAP_HACK ); TWEAK_RULES( NORMAL_ROUND ); TWEAK_RULES( NO_ALIGNRP_AFTER_IUP ); TWEAK_RULES( NO_CALL_AFTER_IUP ); TWEAK_RULES( NO_DELTAP_AFTER_IUP ); TWEAK_RULES( RASTERIZER_35 ); TWEAK_RULES( SKIP_IUP ); TWEAK_RULES( SKIP_OFFPIXEL_Y_MOVES ); TWEAK_RULES_EXCEPTIONS( SKIP_OFFPIXEL_Y_MOVES ); TWEAK_RULES( SKIP_NONPIXEL_Y_MOVES_DELTAP ); TWEAK_RULES( SKIP_NONPIXEL_Y_MOVES ); TWEAK_RULES_EXCEPTIONS( SKIP_NONPIXEL_Y_MOVES ); TWEAK_RULES( ROUND_NONPIXEL_Y_MOVES ); TWEAK_RULES_EXCEPTIONS( ROUND_NONPIXEL_Y_MOVES ); if ( loader->exec->sph_tweak_flags & SPH_TWEAK_RASTERIZER_35 ) { if ( loader->exec->rasterizer_version != TT_INTERPRETER_VERSION_35 ) { loader->exec->rasterizer_version = TT_INTERPRETER_VERSION_35; loader->exec->size->cvt_ready = -1; tt_size_ready_bytecode( loader->exec->size, FT_BOOL( loader->load_flags & FT_LOAD_PEDANTIC ) ); } else loader->exec->rasterizer_version = TT_INTERPRETER_VERSION_35; } else { if ( loader->exec->rasterizer_version != SPH_OPTION_SET_RASTERIZER_VERSION ) { loader->exec->rasterizer_version = SPH_OPTION_SET_RASTERIZER_VERSION; loader->exec->size->cvt_ready = -1; tt_size_ready_bytecode( loader->exec->size, FT_BOOL( loader->load_flags & FT_LOAD_PEDANTIC ) ); } else loader->exec->rasterizer_version = SPH_OPTION_SET_RASTERIZER_VERSION; } if ( IS_HINTED( loader->load_flags ) ) { TWEAK_RULES( TIMES_NEW_ROMAN_HACK ); TWEAK_RULES( COURIER_NEW_2_HACK ); } if ( sph_test_tweak( face, family, ppem, style, glyph_index, COMPATIBILITY_MODE_Rules, COMPATIBILITY_MODE_RULES_SIZE ) ) loader->exec->face->sph_compatibility_mode = TRUE; if ( IS_HINTED( loader->load_flags ) ) { if ( sph_test_tweak( face, family, ppem, style, glyph_index, COMPATIBLE_WIDTHS_Rules, COMPATIBLE_WIDTHS_RULES_SIZE ) ) loader->exec->compatible_widths |= TRUE; } } #else /* !(TT_USE_BYTECODE_INTERPRETER && */ /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY) */ /* ANSI C doesn't like empty source files */ typedef int _tt_subpix_dummy; #endif /* !(TT_USE_BYTECODE_INTERPRETER && */ /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY) */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttsubpix.c
C++
gpl-3.0
32,091
/**************************************************************************** * * ttsubpix.h * * TrueType Subpixel Hinting. * * Copyright (C) 2010-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTSUBPIX_H_ #define TTSUBPIX_H_ #include "ttobjs.h" #include "ttinterp.h" FT_BEGIN_HEADER #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /************************************************************************** * * ID flags to identify special functions at FDEF and runtime. * */ #define SPH_FDEF_INLINE_DELTA_1 0x0000001 #define SPH_FDEF_INLINE_DELTA_2 0x0000002 #define SPH_FDEF_DIAGONAL_STROKE 0x0000004 #define SPH_FDEF_VACUFORM_ROUND_1 0x0000008 #define SPH_FDEF_TTFAUTOHINT_1 0x0000010 #define SPH_FDEF_SPACING_1 0x0000020 #define SPH_FDEF_SPACING_2 0x0000040 #define SPH_FDEF_TYPEMAN_STROKES 0x0000080 #define SPH_FDEF_TYPEMAN_DIAGENDCTRL 0x0000100 /************************************************************************** * * Tweak flags that are set for each glyph by the below rules. * */ #define SPH_TWEAK_ALLOW_X_DMOVE 0x0000001UL #define SPH_TWEAK_ALWAYS_DO_DELTAP 0x0000002UL #define SPH_TWEAK_ALWAYS_SKIP_DELTAP 0x0000004UL #define SPH_TWEAK_COURIER_NEW_2_HACK 0x0000008UL #define SPH_TWEAK_DEEMBOLDEN 0x0000010UL #define SPH_TWEAK_DO_SHPIX 0x0000020UL #define SPH_TWEAK_EMBOLDEN 0x0000040UL #define SPH_TWEAK_MIAP_HACK 0x0000080UL #define SPH_TWEAK_NORMAL_ROUND 0x0000100UL #define SPH_TWEAK_NO_ALIGNRP_AFTER_IUP 0x0000200UL #define SPH_TWEAK_NO_CALL_AFTER_IUP 0x0000400UL #define SPH_TWEAK_NO_DELTAP_AFTER_IUP 0x0000800UL #define SPH_TWEAK_PIXEL_HINTING 0x0001000UL #define SPH_TWEAK_RASTERIZER_35 0x0002000UL #define SPH_TWEAK_ROUND_NONPIXEL_Y_MOVES 0x0004000UL #define SPH_TWEAK_SKIP_IUP 0x0008000UL #define SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES 0x0010000UL #define SPH_TWEAK_SKIP_OFFPIXEL_Y_MOVES 0x0020000UL #define SPH_TWEAK_TIMES_NEW_ROMAN_HACK 0x0040000UL #define SPH_TWEAK_SKIP_NONPIXEL_Y_MOVES_DELTAP 0x0080000UL FT_LOCAL( FT_Bool ) sph_test_tweak( TT_Face face, const FT_String* family, FT_UInt ppem, const FT_String* style, FT_UInt glyph_index, const SPH_TweakRule* rule, FT_UInt num_rules ); FT_LOCAL( FT_UInt ) sph_test_tweak_x_scaling( TT_Face face, const FT_String* family, FT_UInt ppem, const FT_String* style, FT_UInt glyph_index ); FT_LOCAL( void ) sph_set_tweaks( TT_Loader loader, FT_UInt glyph_index ); /* These macros are defined absent a method for setting them */ #define SPH_OPTION_BITMAP_WIDTHS FALSE #define SPH_OPTION_SET_SUBPIXEL TRUE #define SPH_OPTION_SET_GRAYSCALE FALSE #define SPH_OPTION_SET_COMPATIBLE_WIDTHS FALSE #define SPH_OPTION_SET_RASTERIZER_VERSION 38 #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ FT_END_HEADER #endif /* TTSUBPIX_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/truetype/ttsubpix.h
C++
gpl-3.0
3,848
# # FreeType 2 Type1 module definition # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += TYPE1_DRIVER define TYPE1_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, t1_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)type1 $(ECHO_DRIVER_DESC)Postscript font files with extension *.pfa or *.pfb$(ECHO_DRIVER_DONE) endef # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/module.mk
mk
gpl-3.0
677
# # FreeType 2 Type1 driver configuration rules # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # Type1 driver directory # T1_DIR := $(SRC_DIR)/type1 # compilation flags for the driver # T1_COMPILE := $(CC) $(ANSIFLAGS) \ $I$(subst /,$(COMPILER_SEP),$(T1_DIR)) \ $(INCLUDE_FLAGS) \ $(FT_CFLAGS) # Type1 driver sources (i.e., C files) # T1_DRV_SRC := $(T1_DIR)/t1parse.c \ $(T1_DIR)/t1load.c \ $(T1_DIR)/t1driver.c \ $(T1_DIR)/t1afm.c \ $(T1_DIR)/t1gload.c \ $(T1_DIR)/t1objs.c # Type1 driver headers # T1_DRV_H := $(T1_DRV_SRC:%.c=%.h) \ $(T1_DIR)/t1tokens.h \ $(T1_DIR)/t1errors.h # Type1 driver object(s) # # T1_DRV_OBJ_M is used during `multi' builds # T1_DRV_OBJ_S is used during `single' builds # T1_DRV_OBJ_M := $(T1_DRV_SRC:$(T1_DIR)/%.c=$(OBJ_DIR)/%.$O) T1_DRV_OBJ_S := $(OBJ_DIR)/type1.$O # Type1 driver source file for single build # T1_DRV_SRC_S := $(T1_DIR)/type1.c # Type1 driver - single object # $(T1_DRV_OBJ_S): $(T1_DRV_SRC_S) $(T1_DRV_SRC) $(FREETYPE_H) $(T1_DRV_H) $(T1_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(T1_DRV_SRC_S)) # Type1 driver - multiple objects # $(OBJ_DIR)/%.$O: $(T1_DIR)/%.c $(FREETYPE_H) $(T1_DRV_H) $(T1_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(T1_DRV_OBJ_S) DRV_OBJS_M += $(T1_DRV_OBJ_M) # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/rules.mk
mk
gpl-3.0
1,861
/**************************************************************************** * * t1afm.c * * AFM support for Type 1 fonts (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "t1afm.h" #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/psaux.h> #include "t1errors.h" #ifndef T1_CONFIG_OPTION_NO_AFM /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1afm FT_LOCAL_DEF( void ) T1_Done_Metrics( FT_Memory memory, AFM_FontInfo fi ) { FT_FREE( fi->KernPairs ); fi->NumKernPair = 0; FT_FREE( fi->TrackKerns ); fi->NumTrackKern = 0; FT_FREE( fi ); } /* read a glyph name and return the equivalent glyph index */ static FT_Int t1_get_index( const char* name, FT_Offset len, void* user_data ) { T1_Font type1 = (T1_Font)user_data; FT_Int n; /* PS string/name length must be < 16-bit */ if ( len > 0xFFFFU ) return 0; for ( n = 0; n < type1->num_glyphs; n++ ) { char* gname = (char*)type1->glyph_names[n]; if ( gname && gname[0] == name[0] && ft_strlen( gname ) == len && ft_strncmp( gname, name, len ) == 0 ) return n; } return 0; } #undef KERN_INDEX #define KERN_INDEX( g1, g2 ) ( ( (FT_ULong)(g1) << 16 ) | (g2) ) /* compare two kerning pairs */ FT_COMPARE_DEF( int ) compare_kern_pairs( const void* a, const void* b ) { AFM_KernPair pair1 = (AFM_KernPair)a; AFM_KernPair pair2 = (AFM_KernPair)b; FT_ULong index1 = KERN_INDEX( pair1->index1, pair1->index2 ); FT_ULong index2 = KERN_INDEX( pair2->index1, pair2->index2 ); if ( index1 > index2 ) return 1; else if ( index1 < index2 ) return -1; else return 0; } /* parse a PFM file -- for now, only read the kerning pairs */ static FT_Error T1_Read_PFM( FT_Face t1_face, FT_Stream stream, AFM_FontInfo fi ) { FT_Error error = FT_Err_Ok; FT_Memory memory = stream->memory; FT_Byte* start; FT_Byte* limit; FT_Byte* p; AFM_KernPair kp; FT_Int width_table_length; FT_CharMap oldcharmap; FT_CharMap charmap; FT_Int n; start = (FT_Byte*)stream->cursor; limit = (FT_Byte*)stream->limit; /* Figure out how long the width table is. */ /* This info is a little-endian short at offset 99. */ p = start + 99; if ( p + 2 > limit ) { error = FT_THROW( Unknown_File_Format ); goto Exit; } width_table_length = FT_PEEK_USHORT_LE( p ); p += 18 + width_table_length; if ( p + 0x12 > limit || FT_PEEK_USHORT_LE( p ) < 0x12 ) /* extension table is probably optional */ goto Exit; /* Kerning offset is 14 bytes from start of extensions table. */ p += 14; p = start + FT_PEEK_ULONG_LE( p ); if ( p == start ) /* zero offset means no table */ goto Exit; if ( p + 2 > limit ) { error = FT_THROW( Unknown_File_Format ); goto Exit; } fi->NumKernPair = FT_PEEK_USHORT_LE( p ); p += 2; if ( p + 4 * fi->NumKernPair > limit ) { error = FT_THROW( Unknown_File_Format ); goto Exit; } /* Actually, kerning pairs are simply optional! */ if ( fi->NumKernPair == 0 ) goto Exit; /* allocate the pairs */ if ( FT_QNEW_ARRAY( fi->KernPairs, fi->NumKernPair ) ) goto Exit; /* now, read each kern pair */ kp = fi->KernPairs; limit = p + 4 * fi->NumKernPair; /* PFM kerning data are stored by encoding rather than glyph index, */ /* so find the PostScript charmap of this font and install it */ /* temporarily. If we find no PostScript charmap, then just use */ /* the default and hope it is the right one. */ oldcharmap = t1_face->charmap; charmap = NULL; for ( n = 0; n < t1_face->num_charmaps; n++ ) { charmap = t1_face->charmaps[n]; /* check against PostScript pseudo platform */ if ( charmap->platform_id == 7 ) { error = FT_Set_Charmap( t1_face, charmap ); if ( error ) goto Exit; break; } } /* Kerning info is stored as: */ /* */ /* encoding of first glyph (1 byte) */ /* encoding of second glyph (1 byte) */ /* offset (little-endian short) */ for ( ; p < limit; p += 4 ) { kp->index1 = FT_Get_Char_Index( t1_face, p[0] ); kp->index2 = FT_Get_Char_Index( t1_face, p[1] ); kp->x = (FT_Int)FT_PEEK_SHORT_LE(p + 2); kp->y = 0; kp++; } if ( oldcharmap ) error = FT_Set_Charmap( t1_face, oldcharmap ); if ( error ) goto Exit; /* now, sort the kern pairs according to their glyph indices */ ft_qsort( fi->KernPairs, fi->NumKernPair, sizeof ( AFM_KernPairRec ), compare_kern_pairs ); Exit: if ( error ) { FT_FREE( fi->KernPairs ); fi->NumKernPair = 0; } return error; } /* parse a metrics file -- either AFM or PFM depending on what */ /* it turns out to be */ FT_LOCAL_DEF( FT_Error ) T1_Read_Metrics( FT_Face t1_face, FT_Stream stream ) { PSAux_Service psaux; FT_Memory memory = stream->memory; AFM_ParserRec parser; AFM_FontInfo fi = NULL; FT_Error error = FT_ERR( Unknown_File_Format ); T1_Face face = (T1_Face)t1_face; T1_Font t1_font = &face->type1; if ( face->afm_data ) { FT_TRACE1(( "T1_Read_Metrics:" " Freeing previously attached metrics data.\n" )); T1_Done_Metrics( memory, (AFM_FontInfo)face->afm_data ); face->afm_data = NULL; } if ( FT_NEW( fi ) || FT_FRAME_ENTER( stream->size ) ) goto Exit; fi->FontBBox = t1_font->font_bbox; fi->Ascender = t1_font->font_bbox.yMax; fi->Descender = t1_font->font_bbox.yMin; psaux = (PSAux_Service)face->psaux; if ( psaux->afm_parser_funcs ) { error = psaux->afm_parser_funcs->init( &parser, stream->memory, stream->cursor, stream->limit ); if ( !error ) { parser.FontInfo = fi; parser.get_index = t1_get_index; parser.user_data = t1_font; error = psaux->afm_parser_funcs->parse( &parser ); psaux->afm_parser_funcs->done( &parser ); } } if ( FT_ERR_EQ( error, Unknown_File_Format ) ) { FT_Byte* start = stream->cursor; /* MS Windows allows versions up to 0x3FF without complaining */ if ( stream->size > 6 && start[1] < 4 && FT_PEEK_ULONG_LE( start + 2 ) == stream->size ) error = T1_Read_PFM( t1_face, stream, fi ); } if ( !error ) { t1_font->font_bbox = fi->FontBBox; t1_face->bbox.xMin = fi->FontBBox.xMin >> 16; t1_face->bbox.yMin = fi->FontBBox.yMin >> 16; /* no `U' suffix here to 0xFFFF! */ t1_face->bbox.xMax = ( fi->FontBBox.xMax + 0xFFFF ) >> 16; t1_face->bbox.yMax = ( fi->FontBBox.yMax + 0xFFFF ) >> 16; /* no `U' suffix here to 0x8000! */ t1_face->ascender = (FT_Short)( ( fi->Ascender + 0x8000 ) >> 16 ); t1_face->descender = (FT_Short)( ( fi->Descender + 0x8000 ) >> 16 ); if ( fi->NumKernPair ) { t1_face->face_flags |= FT_FACE_FLAG_KERNING; face->afm_data = fi; fi = NULL; } } FT_FRAME_EXIT(); Exit: if ( fi ) T1_Done_Metrics( memory, fi ); return error; } /* find the kerning for a given glyph pair */ FT_LOCAL_DEF( void ) T1_Get_Kerning( AFM_FontInfo fi, FT_UInt glyph1, FT_UInt glyph2, FT_Vector* kerning ) { AFM_KernPair min, mid, max; FT_ULong idx = KERN_INDEX( glyph1, glyph2 ); /* simple binary search */ min = fi->KernPairs; max = min + fi->NumKernPair - 1; while ( min <= max ) { FT_ULong midi; mid = min + ( max - min ) / 2; midi = KERN_INDEX( mid->index1, mid->index2 ); if ( midi == idx ) { kerning->x = mid->x; kerning->y = mid->y; return; } if ( midi < idx ) min = mid + 1; else max = mid - 1; } kerning->x = 0; kerning->y = 0; } FT_LOCAL_DEF( FT_Error ) T1_Get_Track_Kerning( FT_Face face, FT_Fixed ptsize, FT_Int degree, FT_Fixed* kerning ) { AFM_FontInfo fi = (AFM_FontInfo)( (T1_Face)face )->afm_data; FT_UInt i; if ( !fi ) return FT_THROW( Invalid_Argument ); for ( i = 0; i < fi->NumTrackKern; i++ ) { AFM_TrackKern tk = fi->TrackKerns + i; if ( tk->degree != degree ) continue; if ( ptsize < tk->min_ptsize ) *kerning = tk->min_kern; else if ( ptsize > tk->max_ptsize ) *kerning = tk->max_kern; else { *kerning = FT_MulDiv( ptsize - tk->min_ptsize, tk->max_kern - tk->min_kern, tk->max_ptsize - tk->min_ptsize ) + tk->min_kern; } } return FT_Err_Ok; } #else /* T1_CONFIG_OPTION_NO_AFM */ /* ANSI C doesn't like empty source files */ typedef int _t1_afm_dummy; #endif /* T1_CONFIG_OPTION_NO_AFM */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1afm.c
C++
gpl-3.0
10,614
/**************************************************************************** * * t1afm.h * * AFM support for Type 1 fonts (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1AFM_H_ #define T1AFM_H_ #include "t1objs.h" #include <freetype/internal/t1types.h> FT_BEGIN_HEADER FT_LOCAL( FT_Error ) T1_Read_Metrics( FT_Face face, FT_Stream stream ); FT_LOCAL( void ) T1_Done_Metrics( FT_Memory memory, AFM_FontInfo fi ); FT_LOCAL( void ) T1_Get_Kerning( AFM_FontInfo fi, FT_UInt glyph1, FT_UInt glyph2, FT_Vector* kerning ); FT_LOCAL( FT_Error ) T1_Get_Track_Kerning( FT_Face face, FT_Fixed ptsize, FT_Int degree, FT_Fixed* kerning ); FT_END_HEADER #endif /* T1AFM_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1afm.h
C++
gpl-3.0
1,285
/**************************************************************************** * * t1driver.c * * Type 1 driver interface (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "t1driver.h" #include "t1gload.h" #include "t1load.h" #include "t1errors.h" #ifndef T1_CONFIG_OPTION_NO_AFM #include "t1afm.h" #endif #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/fthash.h> #include <freetype/internal/ftpsprop.h> #include <freetype/ftdriver.h> #include <freetype/internal/services/svmm.h> #include <freetype/internal/services/svgldict.h> #include <freetype/internal/services/svfntfmt.h> #include <freetype/internal/services/svpostnm.h> #include <freetype/internal/services/svpscmap.h> #include <freetype/internal/services/svpsinfo.h> #include <freetype/internal/services/svprop.h> #include <freetype/internal/services/svkern.h> /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1driver /* * GLYPH DICT SERVICE * */ static FT_Error t1_get_glyph_name( T1_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ) { FT_STRCPYN( buffer, face->type1.glyph_names[glyph_index], buffer_max ); return FT_Err_Ok; } static FT_UInt t1_get_name_index( T1_Face face, const FT_String* glyph_name ) { FT_Int i; for ( i = 0; i < face->type1.num_glyphs; i++ ) { FT_String* gname = face->type1.glyph_names[i]; if ( !ft_strcmp( glyph_name, gname ) ) return (FT_UInt)i; } return 0; } static const FT_Service_GlyphDictRec t1_service_glyph_dict = { (FT_GlyphDict_GetNameFunc) t1_get_glyph_name, /* get_name */ (FT_GlyphDict_NameIndexFunc)t1_get_name_index /* name_index */ }; /* * POSTSCRIPT NAME SERVICE * */ static const char* t1_get_ps_name( T1_Face face ) { return (const char*) face->type1.font_name; } static const FT_Service_PsFontNameRec t1_service_ps_name = { (FT_PsName_GetFunc)t1_get_ps_name /* get_ps_font_name */ }; /* * MULTIPLE MASTERS SERVICE * */ #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT static const FT_Service_MultiMastersRec t1_service_multi_masters = { (FT_Get_MM_Func) T1_Get_Multi_Master, /* get_mm */ (FT_Set_MM_Design_Func) T1_Set_MM_Design, /* set_mm_design */ (FT_Set_MM_Blend_Func) T1_Set_MM_Blend, /* set_mm_blend */ (FT_Get_MM_Blend_Func) T1_Get_MM_Blend, /* get_mm_blend */ (FT_Get_MM_Var_Func) T1_Get_MM_Var, /* get_mm_var */ (FT_Set_Var_Design_Func) T1_Set_Var_Design, /* set_var_design */ (FT_Get_Var_Design_Func) T1_Get_Var_Design, /* get_var_design */ (FT_Set_Instance_Func) T1_Reset_MM_Blend, /* set_instance */ (FT_Set_MM_WeightVector_Func)T1_Set_MM_WeightVector, /* set_mm_weightvector */ (FT_Get_MM_WeightVector_Func)T1_Get_MM_WeightVector, /* get_mm_weightvector */ (FT_Get_Var_Blend_Func) NULL, /* get_var_blend */ (FT_Done_Blend_Func) T1_Done_Blend /* done_blend */ }; #endif /* * POSTSCRIPT INFO SERVICE * */ static FT_Error t1_ps_get_font_info( FT_Face face, PS_FontInfoRec* afont_info ) { *afont_info = ((T1_Face)face)->type1.font_info; return FT_Err_Ok; } static FT_Error t1_ps_get_font_extra( FT_Face face, PS_FontExtraRec* afont_extra ) { *afont_extra = ((T1_Face)face)->type1.font_extra; return FT_Err_Ok; } static FT_Int t1_ps_has_glyph_names( FT_Face face ) { FT_UNUSED( face ); return 1; } static FT_Error t1_ps_get_font_private( FT_Face face, PS_PrivateRec* afont_private ) { *afont_private = ((T1_Face)face)->type1.private_dict; return FT_Err_Ok; } static FT_Long t1_ps_get_font_value( FT_Face face, PS_Dict_Keys key, FT_UInt idx, void *value, FT_Long value_len_ ) { FT_ULong retval = 0; /* always >= 1 if valid */ FT_ULong value_len = value_len_ < 0 ? 0 : (FT_ULong)value_len_; T1_Face t1face = (T1_Face)face; T1_Font type1 = &t1face->type1; switch ( key ) { case PS_DICT_FONT_TYPE: retval = sizeof ( type1->font_type ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->font_type; break; case PS_DICT_FONT_MATRIX: if ( idx < sizeof ( type1->font_matrix ) / sizeof ( type1->font_matrix.xx ) ) { FT_Fixed val = 0; retval = sizeof ( val ); if ( value && value_len >= retval ) { switch ( idx ) { case 0: val = type1->font_matrix.xx; break; case 1: val = type1->font_matrix.xy; break; case 2: val = type1->font_matrix.yx; break; case 3: val = type1->font_matrix.yy; break; } *((FT_Fixed *)value) = val; } } break; case PS_DICT_FONT_BBOX: if ( idx < sizeof ( type1->font_bbox ) / sizeof ( type1->font_bbox.xMin ) ) { FT_Fixed val = 0; retval = sizeof ( val ); if ( value && value_len >= retval ) { switch ( idx ) { case 0: val = type1->font_bbox.xMin; break; case 1: val = type1->font_bbox.yMin; break; case 2: val = type1->font_bbox.xMax; break; case 3: val = type1->font_bbox.yMax; break; } *((FT_Fixed *)value) = val; } } break; case PS_DICT_PAINT_TYPE: retval = sizeof ( type1->paint_type ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->paint_type; break; case PS_DICT_FONT_NAME: if ( type1->font_name ) { retval = ft_strlen( type1->font_name ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_name ), retval ); } break; case PS_DICT_UNIQUE_ID: retval = sizeof ( type1->private_dict.unique_id ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->private_dict.unique_id; break; case PS_DICT_NUM_CHAR_STRINGS: retval = sizeof ( type1->num_glyphs ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->num_glyphs; break; case PS_DICT_CHAR_STRING_KEY: if ( idx < (FT_UInt)type1->num_glyphs ) { retval = ft_strlen( type1->glyph_names[idx] ) + 1; if ( value && value_len >= retval ) { ft_memcpy( value, (void *)( type1->glyph_names[idx] ), retval ); ((FT_Char *)value)[retval - 1] = (FT_Char)'\0'; } } break; case PS_DICT_CHAR_STRING: if ( idx < (FT_UInt)type1->num_glyphs ) { retval = type1->charstrings_len[idx] + 1; if ( value && value_len >= retval ) { ft_memcpy( value, (void *)( type1->charstrings[idx] ), retval - 1 ); ((FT_Char *)value)[retval - 1] = (FT_Char)'\0'; } } break; case PS_DICT_ENCODING_TYPE: retval = sizeof ( type1->encoding_type ); if ( value && value_len >= retval ) *((T1_EncodingType *)value) = type1->encoding_type; break; case PS_DICT_ENCODING_ENTRY: if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY && idx < (FT_UInt)type1->encoding.num_chars ) { retval = ft_strlen( type1->encoding.char_name[idx] ) + 1; if ( value && value_len >= retval ) { ft_memcpy( value, (void *)( type1->encoding.char_name[idx] ), retval - 1 ); ((FT_Char *)value)[retval - 1] = (FT_Char)'\0'; } } break; case PS_DICT_NUM_SUBRS: retval = sizeof ( type1->num_subrs ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->num_subrs; break; case PS_DICT_SUBR: { FT_Bool ok = 0; if ( type1->subrs_hash ) { /* convert subr index to array index */ size_t* val = ft_hash_num_lookup( (FT_Int)idx, type1->subrs_hash ); if ( val ) { idx = *val; ok = 1; } } else { if ( idx < (FT_UInt)type1->num_subrs ) ok = 1; } if ( ok && type1->subrs ) { retval = type1->subrs_len[idx] + 1; if ( value && value_len >= retval ) { ft_memcpy( value, (void *)( type1->subrs[idx] ), retval - 1 ); ((FT_Char *)value)[retval - 1] = (FT_Char)'\0'; } } } break; case PS_DICT_STD_HW: retval = sizeof ( type1->private_dict.standard_width[0] ); if ( value && value_len >= retval ) *((FT_UShort *)value) = type1->private_dict.standard_width[0]; break; case PS_DICT_STD_VW: retval = sizeof ( type1->private_dict.standard_height[0] ); if ( value && value_len >= retval ) *((FT_UShort *)value) = type1->private_dict.standard_height[0]; break; case PS_DICT_NUM_BLUE_VALUES: retval = sizeof ( type1->private_dict.num_blue_values ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_blue_values; break; case PS_DICT_BLUE_VALUE: if ( idx < type1->private_dict.num_blue_values ) { retval = sizeof ( type1->private_dict.blue_values[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.blue_values[idx]; } break; case PS_DICT_BLUE_SCALE: retval = sizeof ( type1->private_dict.blue_scale ); if ( value && value_len >= retval ) *((FT_Fixed *)value) = type1->private_dict.blue_scale; break; case PS_DICT_BLUE_FUZZ: retval = sizeof ( type1->private_dict.blue_fuzz ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->private_dict.blue_fuzz; break; case PS_DICT_BLUE_SHIFT: retval = sizeof ( type1->private_dict.blue_shift ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->private_dict.blue_shift; break; case PS_DICT_NUM_OTHER_BLUES: retval = sizeof ( type1->private_dict.num_other_blues ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_other_blues; break; case PS_DICT_OTHER_BLUE: if ( idx < type1->private_dict.num_other_blues ) { retval = sizeof ( type1->private_dict.other_blues[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.other_blues[idx]; } break; case PS_DICT_NUM_FAMILY_BLUES: retval = sizeof ( type1->private_dict.num_family_blues ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_family_blues; break; case PS_DICT_FAMILY_BLUE: if ( idx < type1->private_dict.num_family_blues ) { retval = sizeof ( type1->private_dict.family_blues[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.family_blues[idx]; } break; case PS_DICT_NUM_FAMILY_OTHER_BLUES: retval = sizeof ( type1->private_dict.num_family_other_blues ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_family_other_blues; break; case PS_DICT_FAMILY_OTHER_BLUE: if ( idx < type1->private_dict.num_family_other_blues ) { retval = sizeof ( type1->private_dict.family_other_blues[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.family_other_blues[idx]; } break; case PS_DICT_NUM_STEM_SNAP_H: retval = sizeof ( type1->private_dict.num_snap_widths ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_snap_widths; break; case PS_DICT_STEM_SNAP_H: if ( idx < type1->private_dict.num_snap_widths ) { retval = sizeof ( type1->private_dict.snap_widths[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.snap_widths[idx]; } break; case PS_DICT_NUM_STEM_SNAP_V: retval = sizeof ( type1->private_dict.num_snap_heights ); if ( value && value_len >= retval ) *((FT_Byte *)value) = type1->private_dict.num_snap_heights; break; case PS_DICT_STEM_SNAP_V: if ( idx < type1->private_dict.num_snap_heights ) { retval = sizeof ( type1->private_dict.snap_heights[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.snap_heights[idx]; } break; case PS_DICT_RND_STEM_UP: retval = sizeof ( type1->private_dict.round_stem_up ); if ( value && value_len >= retval ) *((FT_Bool *)value) = type1->private_dict.round_stem_up; break; case PS_DICT_FORCE_BOLD: retval = sizeof ( type1->private_dict.force_bold ); if ( value && value_len >= retval ) *((FT_Bool *)value) = type1->private_dict.force_bold; break; case PS_DICT_MIN_FEATURE: if ( idx < sizeof ( type1->private_dict.min_feature ) / sizeof ( type1->private_dict.min_feature[0] ) ) { retval = sizeof ( type1->private_dict.min_feature[idx] ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->private_dict.min_feature[idx]; } break; case PS_DICT_LEN_IV: retval = sizeof ( type1->private_dict.lenIV ); if ( value && value_len >= retval ) *((FT_Int *)value) = type1->private_dict.lenIV; break; case PS_DICT_PASSWORD: retval = sizeof ( type1->private_dict.password ); if ( value && value_len >= retval ) *((FT_Long *)value) = type1->private_dict.password; break; case PS_DICT_LANGUAGE_GROUP: retval = sizeof ( type1->private_dict.language_group ); if ( value && value_len >= retval ) *((FT_Long *)value) = type1->private_dict.language_group; break; case PS_DICT_IS_FIXED_PITCH: retval = sizeof ( type1->font_info.is_fixed_pitch ); if ( value && value_len >= retval ) *((FT_Bool *)value) = type1->font_info.is_fixed_pitch; break; case PS_DICT_UNDERLINE_POSITION: retval = sizeof ( type1->font_info.underline_position ); if ( value && value_len >= retval ) *((FT_Short *)value) = type1->font_info.underline_position; break; case PS_DICT_UNDERLINE_THICKNESS: retval = sizeof ( type1->font_info.underline_thickness ); if ( value && value_len >= retval ) *((FT_UShort *)value) = type1->font_info.underline_thickness; break; case PS_DICT_FS_TYPE: retval = sizeof ( type1->font_extra.fs_type ); if ( value && value_len >= retval ) *((FT_UShort *)value) = type1->font_extra.fs_type; break; case PS_DICT_VERSION: if ( type1->font_info.version ) { retval = ft_strlen( type1->font_info.version ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_info.version ), retval ); } break; case PS_DICT_NOTICE: if ( type1->font_info.notice ) { retval = ft_strlen( type1->font_info.notice ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_info.notice ), retval ); } break; case PS_DICT_FULL_NAME: if ( type1->font_info.full_name ) { retval = ft_strlen( type1->font_info.full_name ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_info.full_name ), retval ); } break; case PS_DICT_FAMILY_NAME: if ( type1->font_info.family_name ) { retval = ft_strlen( type1->font_info.family_name ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_info.family_name ), retval ); } break; case PS_DICT_WEIGHT: if ( type1->font_info.weight ) { retval = ft_strlen( type1->font_info.weight ) + 1; if ( value && value_len >= retval ) ft_memcpy( value, (void *)( type1->font_info.weight ), retval ); } break; case PS_DICT_ITALIC_ANGLE: retval = sizeof ( type1->font_info.italic_angle ); if ( value && value_len >= retval ) *((FT_Long *)value) = type1->font_info.italic_angle; break; } return retval == 0 ? -1 : (FT_Long)retval; } static const FT_Service_PsInfoRec t1_service_ps_info = { (PS_GetFontInfoFunc) t1_ps_get_font_info, /* ps_get_font_info */ (PS_GetFontExtraFunc) t1_ps_get_font_extra, /* ps_get_font_extra */ (PS_HasGlyphNamesFunc) t1_ps_has_glyph_names, /* ps_has_glyph_names */ (PS_GetFontPrivateFunc)t1_ps_get_font_private, /* ps_get_font_private */ (PS_GetFontValueFunc) t1_ps_get_font_value, /* ps_get_font_value */ }; #ifndef T1_CONFIG_OPTION_NO_AFM static const FT_Service_KerningRec t1_service_kerning = { T1_Get_Track_Kerning, /* get_track */ }; #endif /* * PROPERTY SERVICE * */ FT_DEFINE_SERVICE_PROPERTIESREC( t1_service_properties, (FT_Properties_SetFunc)ps_property_set, /* set_property */ (FT_Properties_GetFunc)ps_property_get ) /* get_property */ /* * SERVICE LIST * */ static const FT_ServiceDescRec t1_services[] = { { FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &t1_service_ps_name }, { FT_SERVICE_ID_GLYPH_DICT, &t1_service_glyph_dict }, { FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_TYPE_1 }, { FT_SERVICE_ID_POSTSCRIPT_INFO, &t1_service_ps_info }, { FT_SERVICE_ID_PROPERTIES, &t1_service_properties }, #ifndef T1_CONFIG_OPTION_NO_AFM { FT_SERVICE_ID_KERNING, &t1_service_kerning }, #endif #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT { FT_SERVICE_ID_MULTI_MASTERS, &t1_service_multi_masters }, #endif { NULL, NULL } }; FT_CALLBACK_DEF( FT_Module_Interface ) Get_Interface( FT_Module module, const FT_String* t1_interface ) { FT_UNUSED( module ); return ft_service_list_lookup( t1_services, t1_interface ); } #ifndef T1_CONFIG_OPTION_NO_AFM /************************************************************************** * * @Function: * Get_Kerning * * @Description: * A driver method used to return the kerning vector between two * glyphs of the same face. * * @Input: * face :: * A handle to the source face object. * * left_glyph :: * The index of the left glyph in the kern pair. * * right_glyph :: * The index of the right glyph in the kern pair. * * @Output: * kerning :: * The kerning vector. This is in font units for * scalable formats, and in pixels for fixed-sizes * formats. * * @Return: * FreeType error code. 0 means success. * * @Note: * Only horizontal layouts (left-to-right & right-to-left) are * supported by this function. Other layouts, or more sophisticated * kernings are out of scope of this method (the basic driver * interface is meant to be simple). * * They can be implemented by format-specific interfaces. */ static FT_Error Get_Kerning( FT_Face t1face, /* T1_Face */ FT_UInt left_glyph, FT_UInt right_glyph, FT_Vector* kerning ) { T1_Face face = (T1_Face)t1face; kerning->x = 0; kerning->y = 0; if ( face->afm_data ) T1_Get_Kerning( (AFM_FontInfo)face->afm_data, left_glyph, right_glyph, kerning ); return FT_Err_Ok; } #endif /* T1_CONFIG_OPTION_NO_AFM */ FT_CALLBACK_TABLE_DEF const FT_Driver_ClassRec t1_driver_class = { { FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_SCALABLE | FT_MODULE_DRIVER_HAS_HINTER, sizeof ( PS_DriverRec ), "type1", 0x10000L, 0x20000L, NULL, /* module-specific interface */ T1_Driver_Init, /* FT_Module_Constructor module_init */ T1_Driver_Done, /* FT_Module_Destructor module_done */ Get_Interface, /* FT_Module_Requester get_interface */ }, sizeof ( T1_FaceRec ), sizeof ( T1_SizeRec ), sizeof ( T1_GlyphSlotRec ), T1_Face_Init, /* FT_Face_InitFunc init_face */ T1_Face_Done, /* FT_Face_DoneFunc done_face */ T1_Size_Init, /* FT_Size_InitFunc init_size */ T1_Size_Done, /* FT_Size_DoneFunc done_size */ T1_GlyphSlot_Init, /* FT_Slot_InitFunc init_slot */ T1_GlyphSlot_Done, /* FT_Slot_DoneFunc done_slot */ T1_Load_Glyph, /* FT_Slot_LoadFunc load_glyph */ #ifdef T1_CONFIG_OPTION_NO_AFM NULL, /* FT_Face_GetKerningFunc get_kerning */ NULL, /* FT_Face_AttachFunc attach_file */ #else Get_Kerning, /* FT_Face_GetKerningFunc get_kerning */ T1_Read_Metrics, /* FT_Face_AttachFunc attach_file */ #endif T1_Get_Advances, /* FT_Face_GetAdvancesFunc get_advances */ T1_Size_Request, /* FT_Size_RequestFunc request_size */ NULL /* FT_Size_SelectFunc select_size */ }; /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1driver.c
C++
gpl-3.0
23,138
/**************************************************************************** * * t1driver.h * * High-level Type 1 driver interface (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1DRIVER_H_ #define T1DRIVER_H_ #include <freetype/internal/ftdrv.h> FT_BEGIN_HEADER FT_EXPORT_VAR( const FT_Driver_ClassRec ) t1_driver_class; FT_END_HEADER #endif /* T1DRIVER_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1driver.h
C++
gpl-3.0
769
/**************************************************************************** * * t1errors.h * * Type 1 error codes (specification only). * * Copyright (C) 2001-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This file is used to define the Type 1 error enumeration constants. * */ #ifndef T1ERRORS_H_ #define T1ERRORS_H_ #include <freetype/ftmoderr.h> #undef FTERRORS_H_ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX T1_Err_ #define FT_ERR_BASE FT_Mod_Err_Type1 #include <freetype/fterrors.h> #endif /* T1ERRORS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1errors.h
C++
gpl-3.0
969
/**************************************************************************** * * t1gload.c * * Type 1 Glyph Loader (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "t1gload.h" #include <freetype/internal/ftcalc.h> #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/ftoutln.h> #include <freetype/internal/psaux.h> #include <freetype/internal/cfftypes.h> #include <freetype/ftdriver.h> #include "t1errors.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1gload static FT_Error T1_Parse_Glyph_And_Get_Char_String( T1_Decoder decoder, FT_UInt glyph_index, FT_Data* char_string, FT_Bool* force_scaling ) { T1_Face face = (T1_Face)decoder->builder.face; T1_Font type1 = &face->type1; FT_Error error = FT_Err_Ok; PSAux_Service psaux = (PSAux_Service)face->psaux; const T1_Decoder_Funcs decoder_funcs = psaux->t1_decoder_funcs; PS_Decoder psdecoder; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Incremental_InterfaceRec *inc = face->root.internal->incremental_interface; #endif #ifdef T1_CONFIG_OPTION_OLD_ENGINE PS_Driver driver = (PS_Driver)FT_FACE_DRIVER( face ); #endif decoder->font_matrix = type1->font_matrix; decoder->font_offset = type1->font_offset; #ifdef FT_CONFIG_OPTION_INCREMENTAL /* For incremental fonts get the character data using the */ /* callback function. */ if ( inc ) error = inc->funcs->get_glyph_data( inc->object, glyph_index, char_string ); else #endif /* FT_CONFIG_OPTION_INCREMENTAL */ /* For ordinary fonts get the character data stored in the face record. */ { char_string->pointer = type1->charstrings[glyph_index]; char_string->length = type1->charstrings_len[glyph_index]; } if ( !error ) { /* choose which renderer to use */ #ifdef T1_CONFIG_OPTION_OLD_ENGINE if ( driver->hinting_engine == FT_HINTING_FREETYPE || decoder->builder.metrics_only ) error = decoder_funcs->parse_charstrings_old( decoder, (FT_Byte*)char_string->pointer, (FT_UInt)char_string->length ); #else if ( decoder->builder.metrics_only ) error = decoder_funcs->parse_metrics( decoder, (FT_Byte*)char_string->pointer, (FT_UInt)char_string->length ); #endif else { CFF_SubFontRec subfont; psaux->ps_decoder_init( &psdecoder, decoder, TRUE ); psaux->t1_make_subfont( FT_FACE( face ), &face->type1.private_dict, &subfont ); psdecoder.current_subfont = &subfont; error = decoder_funcs->parse_charstrings( &psdecoder, (FT_Byte*)char_string->pointer, (FT_ULong)char_string->length ); /* Adobe's engine uses 16.16 numbers everywhere; */ /* as a consequence, glyphs larger than 2000ppem get rejected */ if ( FT_ERR_EQ( error, Glyph_Too_Big ) ) { /* this time, we retry unhinted and scale up the glyph later on */ /* (the engine uses and sets the hardcoded value 0x10000 / 64 = */ /* 0x400 for both `x_scale' and `y_scale' in this case) */ ((T1_GlyphSlot)decoder->builder.glyph)->hint = FALSE; *force_scaling = TRUE; error = decoder_funcs->parse_charstrings( &psdecoder, (FT_Byte*)char_string->pointer, (FT_ULong)char_string->length ); } } } #ifdef FT_CONFIG_OPTION_INCREMENTAL /* Incremental fonts can optionally override the metrics. */ if ( !error && inc && inc->funcs->get_glyph_metrics ) { FT_Incremental_MetricsRec metrics; metrics.bearing_x = FIXED_TO_INT( decoder->builder.left_bearing.x ); metrics.bearing_y = 0; metrics.advance = FIXED_TO_INT( decoder->builder.advance.x ); metrics.advance_v = FIXED_TO_INT( decoder->builder.advance.y ); error = inc->funcs->get_glyph_metrics( inc->object, glyph_index, FALSE, &metrics ); decoder->builder.left_bearing.x = INT_TO_FIXED( metrics.bearing_x ); decoder->builder.advance.x = INT_TO_FIXED( metrics.advance ); decoder->builder.advance.y = INT_TO_FIXED( metrics.advance_v ); } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ return error; } FT_CALLBACK_DEF( FT_Error ) T1_Parse_Glyph( T1_Decoder decoder, FT_UInt glyph_index ) { FT_Data glyph_data; FT_Bool force_scaling = FALSE; FT_Error error = T1_Parse_Glyph_And_Get_Char_String( decoder, glyph_index, &glyph_data, &force_scaling ); #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( !error ) { T1_Face face = (T1_Face)decoder->builder.face; if ( face->root.internal->incremental_interface ) face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &glyph_data ); } #endif /* FT_CONFIG_OPTION_INCREMENTAL */ return error; } /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /********** *********/ /********** COMPUTE THE MAXIMUM ADVANCE WIDTH *********/ /********** *********/ /********** The following code is in charge of computing *********/ /********** the maximum advance width of the font. It *********/ /********** quickly processes each glyph charstring to *********/ /********** extract the value from either a `sbw' or `seac' *********/ /********** operator. *********/ /********** *********/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ FT_LOCAL_DEF( FT_Error ) T1_Compute_Max_Advance( T1_Face face, FT_Pos* max_advance ) { FT_Error error; T1_DecoderRec decoder; FT_Int glyph_index; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) ); *max_advance = 0; /* initialize load decoder */ error = psaux->t1_decoder_funcs->init( &decoder, (FT_Face)face, 0, /* size */ 0, /* glyph slot */ (FT_Byte**)type1->glyph_names, face->blend, 0, FT_RENDER_MODE_NORMAL, T1_Parse_Glyph ); if ( error ) return error; decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.subrs_hash = type1->subrs_hash; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; *max_advance = 0; FT_TRACE6(( "T1_Compute_Max_Advance:\n" )); /* for each glyph, parse the glyph charstring and extract */ /* the advance width */ for ( glyph_index = 0; glyph_index < type1->num_glyphs; glyph_index++ ) { /* now get load the unscaled outline */ (void)T1_Parse_Glyph( &decoder, (FT_UInt)glyph_index ); if ( glyph_index == 0 || decoder.builder.advance.x > *max_advance ) *max_advance = decoder.builder.advance.x; /* ignore the error if one occurred - skip to next glyph */ } FT_TRACE6(( "T1_Compute_Max_Advance: max advance: %f\n", *max_advance / 65536.0 )); psaux->t1_decoder_funcs->done( &decoder ); return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Get_Advances( FT_Face t1face, /* T1_Face */ FT_UInt first, FT_UInt count, FT_Int32 load_flags, FT_Fixed* advances ) { T1_Face face = (T1_Face)t1face; T1_DecoderRec decoder; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_UInt nn; FT_Error error; FT_TRACE5(( "T1_Get_Advances:\n" )); if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { for ( nn = 0; nn < count; nn++ ) { advances[nn] = 0; FT_TRACE5(( " idx %d: advance height 0 font units\n", first + nn )); } return FT_Err_Ok; } error = psaux->t1_decoder_funcs->init( &decoder, (FT_Face)face, 0, /* size */ 0, /* glyph slot */ (FT_Byte**)type1->glyph_names, face->blend, 0, FT_RENDER_MODE_NORMAL, T1_Parse_Glyph ); if ( error ) return error; decoder.builder.metrics_only = 1; decoder.builder.load_points = 0; decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.subrs_hash = type1->subrs_hash; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; for ( nn = 0; nn < count; nn++ ) { error = T1_Parse_Glyph( &decoder, first + nn ); if ( !error ) advances[nn] = FIXED_TO_INT( decoder.builder.advance.x ); else advances[nn] = 0; FT_TRACE5(( " idx %d: advance width %ld font unit%s\n", first + nn, advances[nn], advances[nn] == 1 ? "" : "s" )); } return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Load_Glyph( FT_GlyphSlot t1glyph, /* T1_GlyphSlot */ FT_Size t1size, /* T1_Size */ FT_UInt glyph_index, FT_Int32 load_flags ) { T1_GlyphSlot glyph = (T1_GlyphSlot)t1glyph; FT_Error error; T1_DecoderRec decoder; T1_Face face = (T1_Face)t1glyph->face; FT_Bool hinting; FT_Bool scaled; FT_Bool force_scaling = FALSE; T1_Font type1 = &face->type1; PSAux_Service psaux = (PSAux_Service)face->psaux; const T1_Decoder_Funcs decoder_funcs = psaux->t1_decoder_funcs; FT_Matrix font_matrix; FT_Vector font_offset; FT_Data glyph_data; FT_Bool must_finish_decoder = FALSE; #ifdef FT_CONFIG_OPTION_INCREMENTAL FT_Bool glyph_data_loaded = 0; #endif #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_index >= (FT_UInt)face->root.num_glyphs && !face->root.internal->incremental_interface ) #else if ( glyph_index >= (FT_UInt)face->root.num_glyphs ) #endif /* FT_CONFIG_OPTION_INCREMENTAL */ { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_TRACE1(( "T1_Load_Glyph: glyph index %d\n", glyph_index )); FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) ); if ( load_flags & FT_LOAD_NO_RECURSE ) load_flags |= FT_LOAD_NO_SCALE | FT_LOAD_NO_HINTING; if ( t1size ) { glyph->x_scale = t1size->metrics.x_scale; glyph->y_scale = t1size->metrics.y_scale; } else { glyph->x_scale = 0x10000L; glyph->y_scale = 0x10000L; } t1glyph->outline.n_points = 0; t1glyph->outline.n_contours = 0; hinting = FT_BOOL( !( load_flags & FT_LOAD_NO_SCALE ) && !( load_flags & FT_LOAD_NO_HINTING ) ); scaled = FT_BOOL( !( load_flags & FT_LOAD_NO_SCALE ) ); glyph->hint = hinting; glyph->scaled = scaled; t1glyph->format = FT_GLYPH_FORMAT_OUTLINE; error = decoder_funcs->init( &decoder, t1glyph->face, t1size, t1glyph, (FT_Byte**)type1->glyph_names, face->blend, hinting, FT_LOAD_TARGET_MODE( load_flags ), T1_Parse_Glyph ); if ( error ) goto Exit; must_finish_decoder = TRUE; decoder.builder.no_recurse = FT_BOOL( load_flags & FT_LOAD_NO_RECURSE ); decoder.num_subrs = type1->num_subrs; decoder.subrs = type1->subrs; decoder.subrs_len = type1->subrs_len; decoder.subrs_hash = type1->subrs_hash; decoder.buildchar = face->buildchar; decoder.len_buildchar = face->len_buildchar; /* now load the unscaled outline */ error = T1_Parse_Glyph_And_Get_Char_String( &decoder, glyph_index, &glyph_data, &force_scaling ); if ( error ) goto Exit; #ifdef FT_CONFIG_OPTION_INCREMENTAL glyph_data_loaded = 1; #endif hinting = glyph->hint; font_matrix = decoder.font_matrix; font_offset = decoder.font_offset; /* save new glyph tables */ decoder_funcs->done( &decoder ); must_finish_decoder = FALSE; /* now, set the metrics -- this is rather simple, as */ /* the left side bearing is the xMin, and the top side */ /* bearing the yMax */ if ( !error ) { t1glyph->outline.flags &= FT_OUTLINE_OWNER; t1glyph->outline.flags |= FT_OUTLINE_REVERSE_FILL; /* for composite glyphs, return only left side bearing and */ /* advance width */ if ( load_flags & FT_LOAD_NO_RECURSE ) { FT_Slot_Internal internal = t1glyph->internal; t1glyph->metrics.horiBearingX = FIXED_TO_INT( decoder.builder.left_bearing.x ); t1glyph->metrics.horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); internal->glyph_matrix = font_matrix; internal->glyph_delta = font_offset; internal->glyph_transformed = 1; } else { FT_BBox cbox; FT_Glyph_Metrics* metrics = &t1glyph->metrics; /* copy the _unscaled_ advance width */ metrics->horiAdvance = FIXED_TO_INT( decoder.builder.advance.x ); t1glyph->linearHoriAdvance = FIXED_TO_INT( decoder.builder.advance.x ); t1glyph->internal->glyph_transformed = 0; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* make up vertical ones */ metrics->vertAdvance = ( face->type1.font_bbox.yMax - face->type1.font_bbox.yMin ) >> 16; t1glyph->linearVertAdvance = metrics->vertAdvance; } else { metrics->vertAdvance = FIXED_TO_INT( decoder.builder.advance.y ); t1glyph->linearVertAdvance = FIXED_TO_INT( decoder.builder.advance.y ); } t1glyph->format = FT_GLYPH_FORMAT_OUTLINE; if ( t1size && t1size->metrics.y_ppem < 24 ) t1glyph->outline.flags |= FT_OUTLINE_HIGH_PRECISION; #if 1 /* apply the font matrix, if any */ if ( font_matrix.xx != 0x10000L || font_matrix.yy != 0x10000L || font_matrix.xy != 0 || font_matrix.yx != 0 ) { FT_Outline_Transform( &t1glyph->outline, &font_matrix ); metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, font_matrix.xx ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, font_matrix.yy ); } if ( font_offset.x || font_offset.y ) { FT_Outline_Translate( &t1glyph->outline, font_offset.x, font_offset.y ); metrics->horiAdvance += font_offset.x; metrics->vertAdvance += font_offset.y; } #endif if ( ( load_flags & FT_LOAD_NO_SCALE ) == 0 || force_scaling ) { /* scale the outline and the metrics */ FT_Int n; FT_Outline* cur = decoder.builder.base; FT_Vector* vec = cur->points; FT_Fixed x_scale = glyph->x_scale; FT_Fixed y_scale = glyph->y_scale; /* First of all, scale the points, if we are not hinting */ if ( !hinting || !decoder.builder.hints_funcs ) for ( n = cur->n_points; n > 0; n--, vec++ ) { vec->x = FT_MulFix( vec->x, x_scale ); vec->y = FT_MulFix( vec->y, y_scale ); } /* Then scale the metrics */ metrics->horiAdvance = FT_MulFix( metrics->horiAdvance, x_scale ); metrics->vertAdvance = FT_MulFix( metrics->vertAdvance, y_scale ); } /* compute the other metrics */ FT_Outline_Get_CBox( &t1glyph->outline, &cbox ); metrics->width = cbox.xMax - cbox.xMin; metrics->height = cbox.yMax - cbox.yMin; metrics->horiBearingX = cbox.xMin; metrics->horiBearingY = cbox.yMax; if ( load_flags & FT_LOAD_VERTICAL_LAYOUT ) { /* make up vertical ones */ ft_synthesize_vertical_metrics( metrics, metrics->vertAdvance ); } } /* Set control data to the glyph charstrings. Note that this is */ /* _not_ zero-terminated. */ t1glyph->control_data = (FT_Byte*)glyph_data.pointer; t1glyph->control_len = glyph_data.length; } Exit: #ifdef FT_CONFIG_OPTION_INCREMENTAL if ( glyph_data_loaded && face->root.internal->incremental_interface ) { face->root.internal->incremental_interface->funcs->free_glyph_data( face->root.internal->incremental_interface->object, &glyph_data ); /* Set the control data to null - it is no longer available if */ /* loaded incrementally. */ t1glyph->control_data = NULL; t1glyph->control_len = 0; } #endif if ( must_finish_decoder ) decoder_funcs->done( &decoder ); return error; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1gload.c
C++
gpl-3.0
20,361
/**************************************************************************** * * t1gload.h * * Type 1 Glyph Loader (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1GLOAD_H_ #define T1GLOAD_H_ #include "t1objs.h" FT_BEGIN_HEADER FT_LOCAL( FT_Error ) T1_Compute_Max_Advance( T1_Face face, FT_Pos* max_advance ); FT_LOCAL( FT_Error ) T1_Get_Advances( FT_Face face, FT_UInt first, FT_UInt count, FT_Int32 load_flags, FT_Fixed* advances ); FT_LOCAL( FT_Error ) T1_Load_Glyph( FT_GlyphSlot glyph, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ); FT_END_HEADER #endif /* T1GLOAD_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1gload.h
C++
gpl-3.0
1,193
/**************************************************************************** * * t1load.c * * Type 1 font loader (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This is the new and improved Type 1 data loader for FreeType 2. The * old loader has several problems: it is slow, complex, difficult to * maintain, and contains incredible hacks to make it accept some * ill-formed Type 1 fonts without hiccup-ing. Moreover, about 5% of * the Type 1 fonts on my machine still aren't loaded correctly by it. * * This version is much simpler, much faster and also easier to read and * maintain by a great order of magnitude. The idea behind it is to * _not_ try to read the Type 1 token stream with a state machine (i.e. * a Postscript-like interpreter) but rather to perform simple pattern * matching. * * Indeed, nearly all data definitions follow a simple pattern like * * ... /Field <data> ... * * where <data> can be a number, a boolean, a string, or an array of * numbers. There are a few exceptions, namely the encoding, font name, * charstrings, and subrs; they are handled with a special pattern * matching routine. * * All other common cases are handled very simply. The matching rules * are defined in the file `t1tokens.h' through the use of several * macros calls PARSE_XXX. This file is included twice here; the first * time to generate parsing callback functions, the second time to * generate a table of keywords (with pointers to the associated * callback functions). * * The function `parse_dict' simply scans *linearly* a given dictionary * (either the top-level or private one) and calls the appropriate * callback when it encounters an immediate keyword. * * This is by far the fastest way one can find to parse and read all * data. * * This led to tremendous code size reduction. Note that later, the * glyph loader will also be _greatly_ simplified, and the automatic * hinter will replace the clumsy `t1hinter'. * */ #include <ft2build.h> #include <freetype/internal/ftdebug.h> #include FT_CONFIG_CONFIG_H #include <freetype/ftmm.h> #include <freetype/internal/t1types.h> #include <freetype/internal/ftcalc.h> #include <freetype/internal/fthash.h> #include "t1load.h" #include "t1errors.h" #ifdef FT_CONFIG_OPTION_INCREMENTAL #define IS_INCREMENTAL FT_BOOL( face->root.internal->incremental_interface ) #else #define IS_INCREMENTAL 0 #endif /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1load #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** MULTIPLE MASTERS SUPPORT *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static FT_Error t1_allocate_blend( T1_Face face, FT_UInt num_designs, FT_UInt num_axis ) { PS_Blend blend; FT_Memory memory = face->root.memory; FT_Error error = FT_Err_Ok; blend = face->blend; if ( !blend ) { if ( FT_NEW( blend ) ) goto Exit; blend->num_default_design_vector = 0; blend->weight_vector = NULL; blend->default_weight_vector = NULL; blend->design_pos[0] = NULL; face->blend = blend; } /* allocate design data if needed */ if ( num_designs > 0 ) { if ( blend->num_designs == 0 ) { FT_UInt nn; /* allocate the blend `private' and `font_info' dictionaries */ if ( FT_NEW_ARRAY( blend->font_infos[1], num_designs ) || FT_NEW_ARRAY( blend->privates [1], num_designs ) || FT_NEW_ARRAY( blend->bboxes [1], num_designs ) ) goto Exit; blend->font_infos[0] = &face->type1.font_info; blend->privates [0] = &face->type1.private_dict; blend->bboxes [0] = &face->type1.font_bbox; for ( nn = 2; nn <= num_designs; nn++ ) { blend->font_infos[nn] = blend->font_infos[nn - 1] + 1; blend->privates [nn] = blend->privates [nn - 1] + 1; blend->bboxes [nn] = blend->bboxes [nn - 1] + 1; } blend->num_designs = num_designs; } else if ( blend->num_designs != num_designs ) goto Fail; } /* allocate axis data if needed */ if ( num_axis > 0 ) { if ( blend->num_axis != 0 && blend->num_axis != num_axis ) goto Fail; blend->num_axis = num_axis; } Exit: return error; Fail: error = FT_THROW( Invalid_File_Format ); goto Exit; } FT_LOCAL_DEF( FT_Error ) T1_Get_Multi_Master( T1_Face face, FT_Multi_Master* master ) { PS_Blend blend = face->blend; FT_UInt n; FT_Error error; error = FT_THROW( Invalid_Argument ); if ( blend ) { master->num_axis = blend->num_axis; master->num_designs = blend->num_designs; for ( n = 0; n < blend->num_axis; n++ ) { FT_MM_Axis* axis = master->axis + n; PS_DesignMap map = blend->design_map + n; axis->name = blend->axis_names[n]; axis->minimum = map->design_points[0]; axis->maximum = map->design_points[map->num_points - 1]; } error = FT_Err_Ok; } return error; } /************************************************************************** * * Given a normalized (blend) coordinate, figure out the design * coordinate appropriate for that value. */ static FT_Fixed mm_axis_unmap( PS_DesignMap axismap, FT_Fixed ncv ) { int j; if ( ncv <= axismap->blend_points[0] ) return INT_TO_FIXED( axismap->design_points[0] ); for ( j = 1; j < axismap->num_points; j++ ) { if ( ncv <= axismap->blend_points[j] ) return INT_TO_FIXED( axismap->design_points[j - 1] ) + ( axismap->design_points[j] - axismap->design_points[j - 1] ) * FT_DivFix( ncv - axismap->blend_points[j - 1], axismap->blend_points[j] - axismap->blend_points[j - 1] ); } return INT_TO_FIXED( axismap->design_points[axismap->num_points - 1] ); } /************************************************************************** * * Given a vector of weights, one for each design, figure out the * normalized axis coordinates which gave rise to those weights. */ static void mm_weights_unmap( FT_Fixed* weights, FT_Fixed* axiscoords, FT_UInt axis_count ) { FT_ASSERT( axis_count <= T1_MAX_MM_AXIS ); if ( axis_count == 1 ) axiscoords[0] = weights[1]; else if ( axis_count == 2 ) { axiscoords[0] = weights[3] + weights[1]; axiscoords[1] = weights[3] + weights[2]; } else if ( axis_count == 3 ) { axiscoords[0] = weights[7] + weights[5] + weights[3] + weights[1]; axiscoords[1] = weights[7] + weights[6] + weights[3] + weights[2]; axiscoords[2] = weights[7] + weights[6] + weights[5] + weights[4]; } else { axiscoords[0] = weights[15] + weights[13] + weights[11] + weights[9] + weights[7] + weights[5] + weights[3] + weights[1]; axiscoords[1] = weights[15] + weights[14] + weights[11] + weights[10] + weights[7] + weights[6] + weights[3] + weights[2]; axiscoords[2] = weights[15] + weights[14] + weights[13] + weights[12] + weights[7] + weights[6] + weights[5] + weights[4]; axiscoords[3] = weights[15] + weights[14] + weights[13] + weights[12] + weights[11] + weights[10] + weights[9] + weights[8]; } } /************************************************************************** * * Just a wrapper around T1_Get_Multi_Master to support the different * arguments needed by the GX var distortable fonts. */ FT_LOCAL_DEF( FT_Error ) T1_Get_MM_Var( T1_Face face, FT_MM_Var* *master ) { FT_Memory memory = face->root.memory; FT_MM_Var *mmvar = NULL; FT_Multi_Master mmaster; FT_Error error; FT_UInt i; FT_Fixed axiscoords[T1_MAX_MM_AXIS]; PS_Blend blend = face->blend; FT_UShort* axis_flags; FT_Offset mmvar_size; FT_Offset axis_flags_size; FT_Offset axis_size; error = T1_Get_Multi_Master( face, &mmaster ); if ( error ) goto Exit; /* the various `*_size' variables, which we also use as */ /* offsets into the `mmvar' array, must be multiples of the */ /* pointer size (except the last one); without such an */ /* alignment there might be runtime errors due to */ /* misaligned addresses */ #undef ALIGN_SIZE #define ALIGN_SIZE( n ) \ ( ( (n) + sizeof (void*) - 1 ) & ~( sizeof (void*) - 1 ) ) mmvar_size = ALIGN_SIZE( sizeof ( FT_MM_Var ) ); axis_flags_size = ALIGN_SIZE( mmaster.num_axis * sizeof ( FT_UShort ) ); axis_size = mmaster.num_axis * sizeof ( FT_Var_Axis ); if ( FT_ALLOC( mmvar, mmvar_size + axis_flags_size + axis_size ) ) goto Exit; mmvar->num_axis = mmaster.num_axis; mmvar->num_designs = mmaster.num_designs; mmvar->num_namedstyles = 0; /* Not supported */ /* while axis flags are meaningless here, we have to provide the array */ /* to make `FT_Get_Var_Axis_Flags' work: the function expects that the */ /* values directly follow the data of `FT_MM_Var' */ axis_flags = (FT_UShort*)( (char*)mmvar + mmvar_size ); for ( i = 0; i < mmaster.num_axis; i++ ) axis_flags[i] = 0; mmvar->axis = (FT_Var_Axis*)( (char*)axis_flags + axis_flags_size ); mmvar->namedstyle = NULL; for ( i = 0; i < mmaster.num_axis; i++ ) { mmvar->axis[i].name = mmaster.axis[i].name; mmvar->axis[i].minimum = INT_TO_FIXED( mmaster.axis[i].minimum ); mmvar->axis[i].maximum = INT_TO_FIXED( mmaster.axis[i].maximum ); mmvar->axis[i].strid = ~0U; /* Does not apply */ mmvar->axis[i].tag = ~0U; /* Does not apply */ if ( !mmvar->axis[i].name ) continue; if ( ft_strcmp( mmvar->axis[i].name, "Weight" ) == 0 ) mmvar->axis[i].tag = FT_MAKE_TAG( 'w', 'g', 'h', 't' ); else if ( ft_strcmp( mmvar->axis[i].name, "Width" ) == 0 ) mmvar->axis[i].tag = FT_MAKE_TAG( 'w', 'd', 't', 'h' ); else if ( ft_strcmp( mmvar->axis[i].name, "OpticalSize" ) == 0 ) mmvar->axis[i].tag = FT_MAKE_TAG( 'o', 'p', 's', 'z' ); } mm_weights_unmap( blend->default_weight_vector, axiscoords, blend->num_axis ); for ( i = 0; i < mmaster.num_axis; i++ ) mmvar->axis[i].def = mm_axis_unmap( &blend->design_map[i], axiscoords[i] ); *master = mmvar; Exit: return error; } static FT_Error t1_set_mm_blend( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ) { PS_Blend blend = face->blend; FT_UInt n, m; FT_Bool have_diff = 0; if ( !blend ) return FT_THROW( Invalid_Argument ); if ( num_coords > blend->num_axis ) num_coords = blend->num_axis; /* recompute the weight vector from the blend coordinates */ for ( n = 0; n < blend->num_designs; n++ ) { FT_Fixed result = 0x10000L; /* 1.0 fixed */ FT_Fixed factor; for ( m = 0; m < blend->num_axis; m++ ) { /* use a default value if we don't have a coordinate */ if ( m >= num_coords ) { result >>= 1; continue; } /* get current blend axis position */ factor = coords[m]; if ( ( n & ( 1 << m ) ) == 0 ) factor = 0x10000L - factor; if ( factor <= 0 ) { result = 0; break; } else if ( factor >= 0x10000L ) continue; result = FT_MulFix( result, factor ); } if ( blend->weight_vector[n] != result ) { blend->weight_vector[n] = result; have_diff = 1; } } /* return value -1 indicates `no change' */ return have_diff ? FT_Err_Ok : -1; } FT_LOCAL_DEF( FT_Error ) T1_Set_MM_Blend( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Error error; error = t1_set_mm_blend( face, num_coords, coords ); if ( error ) return error; if ( num_coords ) face->root.face_flags |= FT_FACE_FLAG_VARIATION; else face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Get_MM_Blend( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ) { PS_Blend blend = face->blend; FT_Fixed axiscoords[4]; FT_UInt i, nc; if ( !blend ) return FT_THROW( Invalid_Argument ); mm_weights_unmap( blend->weight_vector, axiscoords, blend->num_axis ); nc = num_coords; if ( num_coords > blend->num_axis ) { FT_TRACE2(( "T1_Get_MM_Blend: only using first %d of %d coordinates\n", blend->num_axis, num_coords )); nc = blend->num_axis; } for ( i = 0; i < nc; i++ ) coords[i] = axiscoords[i]; for ( ; i < num_coords; i++ ) coords[i] = 0x8000; return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Set_MM_WeightVector( T1_Face face, FT_UInt len, FT_Fixed* weightvector ) { PS_Blend blend = face->blend; FT_UInt i, n; if ( !blend ) return FT_THROW( Invalid_Argument ); if ( !len && !weightvector ) { for ( i = 0; i < blend->num_designs; i++ ) blend->weight_vector[i] = blend->default_weight_vector[i]; } else { if ( !weightvector ) return FT_THROW( Invalid_Argument ); n = len < blend->num_designs ? len : blend->num_designs; for ( i = 0; i < n; i++ ) blend->weight_vector[i] = weightvector[i]; for ( ; i < blend->num_designs; i++ ) blend->weight_vector[i] = (FT_Fixed)0; if ( len ) face->root.face_flags |= FT_FACE_FLAG_VARIATION; else face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; } return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Get_MM_WeightVector( T1_Face face, FT_UInt* len, FT_Fixed* weightvector ) { PS_Blend blend = face->blend; FT_UInt i; if ( !blend ) return FT_THROW( Invalid_Argument ); if ( *len < blend->num_designs ) { *len = blend->num_designs; return FT_THROW( Invalid_Argument ); } for ( i = 0; i < blend->num_designs; i++ ) weightvector[i] = blend->weight_vector[i]; for ( ; i < *len; i++ ) weightvector[i] = (FT_Fixed)0; *len = blend->num_designs; return FT_Err_Ok; } FT_LOCAL_DEF( FT_Error ) T1_Set_MM_Design( T1_Face face, FT_UInt num_coords, FT_Long* coords ) { FT_Error error; PS_Blend blend = face->blend; FT_UInt n; FT_Fixed final_blends[T1_MAX_MM_DESIGNS]; if ( !blend ) return FT_THROW( Invalid_Argument ); if ( num_coords > blend->num_axis ) num_coords = blend->num_axis; /* compute the blend coordinates through the blend design map */ for ( n = 0; n < blend->num_axis; n++ ) { FT_Long design; FT_Fixed the_blend; PS_DesignMap map = blend->design_map + n; FT_Long* designs = map->design_points; FT_Fixed* blends = map->blend_points; FT_Int p, before = -1, after = -1; /* use a default value if we don't have a coordinate */ if ( n < num_coords ) design = coords[n]; else design = ( designs[map->num_points - 1] - designs[0] ) / 2; for ( p = 0; p < (FT_Int)map->num_points; p++ ) { FT_Long p_design = designs[p]; /* exact match? */ if ( design == p_design ) { the_blend = blends[p]; goto Found; } if ( design < p_design ) { after = p; break; } before = p; } /* now interpolate if necessary */ if ( before < 0 ) the_blend = blends[0]; else if ( after < 0 ) the_blend = blends[map->num_points - 1]; else the_blend = FT_MulDiv( design - designs[before], blends [after] - blends [before], designs[after] - designs[before] ); Found: final_blends[n] = the_blend; } error = t1_set_mm_blend( face, blend->num_axis, final_blends ); if ( error ) return error; if ( num_coords ) face->root.face_flags |= FT_FACE_FLAG_VARIATION; else face->root.face_flags &= ~FT_FACE_FLAG_VARIATION; return FT_Err_Ok; } /* MM fonts don't have named instances, so only the design is reset */ FT_LOCAL_DEF( FT_Error ) T1_Reset_MM_Blend( T1_Face face, FT_UInt instance_index ) { FT_UNUSED( instance_index ); return T1_Set_MM_Blend( face, 0, NULL ); } /************************************************************************** * * Just a wrapper around T1_Set_MM_Design to support the different * arguments needed by the GX var distortable fonts. */ FT_LOCAL_DEF( FT_Error ) T1_Set_Var_Design( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ) { FT_Long lcoords[T1_MAX_MM_AXIS]; FT_UInt i; if ( num_coords > T1_MAX_MM_AXIS ) num_coords = T1_MAX_MM_AXIS; for ( i = 0; i < num_coords; i++ ) lcoords[i] = FIXED_TO_INT( coords[i] ); return T1_Set_MM_Design( face, num_coords, lcoords ); } FT_LOCAL_DEF( FT_Error ) T1_Get_Var_Design( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ) { PS_Blend blend = face->blend; FT_Fixed axiscoords[4]; FT_UInt i, nc; if ( !blend ) return FT_THROW( Invalid_Argument ); mm_weights_unmap( blend->weight_vector, axiscoords, blend->num_axis ); nc = num_coords; if ( num_coords > blend->num_axis ) { FT_TRACE2(( "T1_Get_Var_Design:" " only using first %d of %d coordinates\n", blend->num_axis, num_coords )); nc = blend->num_axis; } for ( i = 0; i < nc; i++ ) coords[i] = mm_axis_unmap( &blend->design_map[i], axiscoords[i] ); for ( ; i < num_coords; i++ ) coords[i] = 0; return FT_Err_Ok; } FT_LOCAL_DEF( void ) T1_Done_Blend( T1_Face face ) { FT_Memory memory = face->root.memory; PS_Blend blend = face->blend; if ( blend ) { FT_UInt num_designs = blend->num_designs; FT_UInt num_axis = blend->num_axis; FT_UInt n; /* release design pos table */ FT_FREE( blend->design_pos[0] ); for ( n = 1; n < num_designs; n++ ) blend->design_pos[n] = NULL; /* release blend `private' and `font info' dictionaries */ FT_FREE( blend->privates[1] ); FT_FREE( blend->font_infos[1] ); FT_FREE( blend->bboxes[1] ); for ( n = 0; n < num_designs; n++ ) { blend->privates [n] = NULL; blend->font_infos[n] = NULL; blend->bboxes [n] = NULL; } /* release weight vectors */ FT_FREE( blend->weight_vector ); blend->default_weight_vector = NULL; /* release axis names */ for ( n = 0; n < num_axis; n++ ) FT_FREE( blend->axis_names[n] ); /* release design map */ for ( n = 0; n < num_axis; n++ ) { PS_DesignMap dmap = blend->design_map + n; FT_FREE( dmap->design_points ); dmap->num_points = 0; } FT_FREE( face->blend ); } } static void parse_blend_axis_types( T1_Face face, T1_Loader loader ) { T1_TokenRec axis_tokens[T1_MAX_MM_AXIS]; FT_Int n, num_axis; FT_Error error = FT_Err_Ok; PS_Blend blend; FT_Memory memory; /* take an array of objects */ T1_ToTokenArray( &loader->parser, axis_tokens, T1_MAX_MM_AXIS, &num_axis ); if ( num_axis < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( num_axis == 0 || num_axis > T1_MAX_MM_AXIS ) { FT_ERROR(( "parse_blend_axis_types: incorrect number of axes: %d\n", num_axis )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* allocate blend if necessary */ error = t1_allocate_blend( face, 0, (FT_UInt)num_axis ); if ( error ) goto Exit; FT_TRACE4(( " [" )); blend = face->blend; memory = face->root.memory; /* each token is an immediate containing the name of the axis */ for ( n = 0; n < num_axis; n++ ) { T1_Token token = axis_tokens + n; FT_Byte* name; FT_UInt len; /* skip first slash, if any */ if ( token->start[0] == '/' ) token->start++; len = (FT_UInt)( token->limit - token->start ); if ( len == 0 ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } FT_TRACE4(( " /%.*s", len, token->start )); name = (FT_Byte*)blend->axis_names[n]; if ( name ) { FT_TRACE0(( "parse_blend_axis_types:" " overwriting axis name `%s' with `%.*s'\n", name, len, token->start )); FT_FREE( name ); } if ( FT_QALLOC( blend->axis_names[n], len + 1 ) ) goto Exit; name = (FT_Byte*)blend->axis_names[n]; FT_MEM_COPY( name, token->start, len ); name[len] = '\0'; } FT_TRACE4(( "]\n" )); Exit: loader->parser.root.error = error; } static void parse_blend_design_positions( T1_Face face, T1_Loader loader ) { T1_TokenRec design_tokens[T1_MAX_MM_DESIGNS]; FT_Int num_designs; FT_Int num_axis = 0; /* make compiler happy */ T1_Parser parser = &loader->parser; FT_Memory memory = face->root.memory; FT_Error error = FT_Err_Ok; FT_Fixed* design_pos[T1_MAX_MM_DESIGNS]; design_pos[0] = NULL; /* get the array of design tokens -- compute number of designs */ T1_ToTokenArray( parser, design_tokens, T1_MAX_MM_DESIGNS, &num_designs ); if ( num_designs < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( num_designs == 0 || num_designs > T1_MAX_MM_DESIGNS ) { FT_ERROR(( "parse_blend_design_positions:" " incorrect number of designs: %d\n", num_designs )); error = FT_THROW( Invalid_File_Format ); goto Exit; } { FT_Byte* old_cursor = parser->root.cursor; FT_Byte* old_limit = parser->root.limit; FT_Int n, nn; PS_Blend blend; FT_TRACE4(( " [" )); for ( n = 0; n < num_designs; n++ ) { T1_TokenRec axis_tokens[T1_MAX_MM_AXIS]; T1_Token token; FT_Int axis, n_axis; /* read axis/coordinates tokens */ token = design_tokens + n; parser->root.cursor = token->start; parser->root.limit = token->limit; T1_ToTokenArray( parser, axis_tokens, T1_MAX_MM_AXIS, &n_axis ); if ( n == 0 ) { if ( n_axis <= 0 || n_axis > T1_MAX_MM_AXIS ) { FT_ERROR(( "parse_blend_design_positions:" " invalid number of axes: %d\n", n_axis )); error = FT_THROW( Invalid_File_Format ); goto Exit; } num_axis = n_axis; error = t1_allocate_blend( face, (FT_UInt)num_designs, (FT_UInt)num_axis ); if ( error ) goto Exit; /* allocate a blend design pos table */ if ( FT_QNEW_ARRAY( design_pos[0], num_designs * num_axis ) ) goto Exit; for ( nn = 1; nn < num_designs; nn++ ) design_pos[nn] = design_pos[0] + num_axis * nn; } else if ( n_axis != num_axis ) { FT_ERROR(( "parse_blend_design_positions: incorrect table\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* now read each axis token into the design position */ FT_TRACE4(( " [" )) ; for ( axis = 0; axis < n_axis; axis++ ) { T1_Token token2 = axis_tokens + axis; parser->root.cursor = token2->start; parser->root.limit = token2->limit; design_pos[n][axis] = T1_ToFixed( parser, 0 ); FT_TRACE4(( " %f", (double)design_pos[n][axis] / 65536 )); } FT_TRACE4(( "]" )) ; } FT_TRACE4(( "]\n" )); loader->parser.root.cursor = old_cursor; loader->parser.root.limit = old_limit; /* a valid BlendDesignPosition has been parsed */ blend = face->blend; if ( blend->design_pos[0] ) FT_FREE( blend->design_pos[0] ); for ( n = 0; n < num_designs; n++ ) { blend->design_pos[n] = design_pos[n]; design_pos[n] = NULL; } } Exit: FT_FREE( design_pos[0] ); loader->parser.root.error = error; } static void parse_blend_design_map( T1_Face face, T1_Loader loader ) { FT_Error error = FT_Err_Ok; T1_Parser parser = &loader->parser; PS_Blend blend; T1_TokenRec axis_tokens[T1_MAX_MM_AXIS]; FT_Int n, num_axis; FT_Byte* old_cursor; FT_Byte* old_limit; FT_Memory memory = face->root.memory; T1_ToTokenArray( parser, axis_tokens, T1_MAX_MM_AXIS, &num_axis ); if ( num_axis < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( num_axis == 0 || num_axis > T1_MAX_MM_AXIS ) { FT_ERROR(( "parse_blend_design_map: incorrect number of axes: %d\n", num_axis )); error = FT_THROW( Invalid_File_Format ); goto Exit; } old_cursor = parser->root.cursor; old_limit = parser->root.limit; error = t1_allocate_blend( face, 0, (FT_UInt)num_axis ); if ( error ) goto Exit; blend = face->blend; FT_TRACE4(( " [" )); /* now read each axis design map */ for ( n = 0; n < num_axis; n++ ) { PS_DesignMap map = blend->design_map + n; T1_Token axis_token; T1_TokenRec point_tokens[T1_MAX_MM_MAP_POINTS]; FT_Int p, num_points; axis_token = axis_tokens + n; parser->root.cursor = axis_token->start; parser->root.limit = axis_token->limit; T1_ToTokenArray( parser, point_tokens, T1_MAX_MM_MAP_POINTS, &num_points ); FT_TRACE4(( " [" )); if ( num_points <= 0 || num_points > T1_MAX_MM_MAP_POINTS ) { FT_ERROR(( "parse_blend_design_map: incorrect table\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( map->design_points ) { FT_ERROR(( "parse_blend_design_map: duplicate table\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* allocate design map data */ if ( FT_QNEW_ARRAY( map->design_points, num_points * 2 ) ) goto Exit; map->blend_points = map->design_points + num_points; map->num_points = (FT_Byte)num_points; for ( p = 0; p < num_points; p++ ) { T1_Token point_token; point_token = point_tokens + p; /* don't include delimiting brackets */ parser->root.cursor = point_token->start + 1; parser->root.limit = point_token->limit - 1; map->design_points[p] = T1_ToInt( parser ); map->blend_points [p] = T1_ToFixed( parser, 0 ); FT_TRACE4(( " [%ld %f]", map->design_points[p], (double)map->blend_points[p] / 65536 )); } FT_TRACE4(( "]" )); } FT_TRACE4(( "]\n" )); parser->root.cursor = old_cursor; parser->root.limit = old_limit; Exit: parser->root.error = error; } static void parse_weight_vector( T1_Face face, T1_Loader loader ) { T1_TokenRec design_tokens[T1_MAX_MM_DESIGNS]; FT_Int num_designs; FT_Error error = FT_Err_Ok; FT_Memory memory = face->root.memory; T1_Parser parser = &loader->parser; PS_Blend blend = face->blend; T1_Token token; FT_Int n; FT_Byte* old_cursor; FT_Byte* old_limit; T1_ToTokenArray( parser, design_tokens, T1_MAX_MM_DESIGNS, &num_designs ); if ( num_designs < 0 ) { error = FT_ERR( Ignore ); goto Exit; } if ( num_designs == 0 || num_designs > T1_MAX_MM_DESIGNS ) { FT_ERROR(( "parse_weight_vector:" " incorrect number of designs: %d\n", num_designs )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( !blend || !blend->num_designs ) { error = t1_allocate_blend( face, (FT_UInt)num_designs, 0 ); if ( error ) goto Exit; blend = face->blend; } else if ( blend->num_designs != (FT_UInt)num_designs ) { FT_ERROR(( "parse_weight_vector:" " /BlendDesignPosition and /WeightVector have\n" )); FT_ERROR(( " " " different number of elements\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( !blend->weight_vector ) if ( FT_QNEW_ARRAY( blend->weight_vector, num_designs * 2 ) ) goto Exit; blend->default_weight_vector = blend->weight_vector + num_designs; old_cursor = parser->root.cursor; old_limit = parser->root.limit; FT_TRACE4(( "[" )); for ( n = 0; n < num_designs; n++ ) { token = design_tokens + n; parser->root.cursor = token->start; parser->root.limit = token->limit; blend->default_weight_vector[n] = blend->weight_vector[n] = T1_ToFixed( parser, 0 ); FT_TRACE4(( " %f", (double)blend->weight_vector[n] / 65536 )); } FT_TRACE4(( "]\n" )); parser->root.cursor = old_cursor; parser->root.limit = old_limit; Exit: parser->root.error = error; } /* e.g., /BuildCharArray [0 0 0 0 0 0 0 0] def */ /* we're only interested in the number of array elements */ static void parse_buildchar( T1_Face face, T1_Loader loader ) { face->len_buildchar = (FT_UInt)T1_ToFixedArray( &loader->parser, 0, NULL, 0 ); #ifdef FT_DEBUG_LEVEL_TRACE { FT_UInt i; FT_TRACE4(( " [" )); for ( i = 0; i < face->len_buildchar; i++ ) FT_TRACE4(( " 0" )); FT_TRACE4(( "]\n" )); } #endif return; } #endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** TYPE 1 SYMBOL PARSING *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ static FT_Error t1_load_keyword( T1_Face face, T1_Loader loader, const T1_Field field ) { FT_Error error; void* dummy_object; void** objects; FT_UInt max_objects; PS_Blend blend = face->blend; if ( blend && blend->num_designs == 0 ) blend = NULL; /* if the keyword has a dedicated callback, call it */ if ( field->type == T1_FIELD_TYPE_CALLBACK ) { FT_TRACE4(( " %s", field->ident )); field->reader( (FT_Face)face, loader ); error = loader->parser.root.error; goto Exit; } /* now, the keyword is either a simple field, or a table of fields; */ /* we are now going to take care of it */ switch ( field->location ) { case T1_FIELD_LOCATION_FONT_INFO: dummy_object = &face->type1.font_info; objects = &dummy_object; max_objects = 0; if ( blend ) { objects = (void**)blend->font_infos; max_objects = blend->num_designs; } break; case T1_FIELD_LOCATION_FONT_EXTRA: dummy_object = &face->type1.font_extra; objects = &dummy_object; max_objects = 0; break; case T1_FIELD_LOCATION_PRIVATE: dummy_object = &face->type1.private_dict; objects = &dummy_object; max_objects = 0; if ( blend ) { objects = (void**)blend->privates; max_objects = blend->num_designs; } break; case T1_FIELD_LOCATION_BBOX: dummy_object = &face->type1.font_bbox; objects = &dummy_object; max_objects = 0; if ( blend ) { objects = (void**)blend->bboxes; max_objects = blend->num_designs; } break; case T1_FIELD_LOCATION_LOADER: dummy_object = loader; objects = &dummy_object; max_objects = 0; break; case T1_FIELD_LOCATION_FACE: dummy_object = face; objects = &dummy_object; max_objects = 0; break; #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT case T1_FIELD_LOCATION_BLEND: dummy_object = face->blend; objects = &dummy_object; max_objects = 0; break; #endif default: dummy_object = &face->type1; objects = &dummy_object; max_objects = 0; } FT_TRACE4(( " %s", field->ident )); if ( *objects ) { if ( field->type == T1_FIELD_TYPE_INTEGER_ARRAY || field->type == T1_FIELD_TYPE_FIXED_ARRAY ) error = T1_Load_Field_Table( &loader->parser, field, objects, max_objects, 0 ); else error = T1_Load_Field( &loader->parser, field, objects, max_objects, 0 ); } else { FT_TRACE1(( "t1_load_keyword: ignoring keyword `%s'" " which is not valid at this point\n", field->ident )); FT_TRACE1(( " (probably due to missing keywords)\n" )); error = FT_Err_Ok; } FT_TRACE4(( "\n" )); Exit: return error; } static void parse_private( T1_Face face, T1_Loader loader ) { FT_UNUSED( face ); loader->keywords_encountered |= T1_PRIVATE; FT_TRACE4(( "\n" )); } /* return 1 in case of success */ static int read_binary_data( T1_Parser parser, FT_ULong* size, FT_Byte** base, FT_Bool incremental ) { FT_Byte* cur; FT_Byte* limit = parser->root.limit; /* the binary data has one of the following formats */ /* */ /* `size' [white*] RD white ....... ND */ /* `size' [white*] -| white ....... |- */ /* */ T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur < limit && ft_isdigit( *cur ) ) { FT_Long s = T1_ToInt( parser ); T1_Skip_PS_Token( parser ); /* `RD' or `-|' or something else */ /* there is only one whitespace char after the */ /* `RD' or `-|' token */ *base = parser->root.cursor + 1; if ( s >= 0 && s < limit - *base ) { parser->root.cursor += s + 1; *size = (FT_ULong)s; return !parser->root.error; } } if( !incremental ) { FT_ERROR(( "read_binary_data: invalid size field\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); } return 0; } /* We now define the routines to handle the `/Encoding', `/Subrs', */ /* and `/CharStrings' dictionaries. */ static void t1_parse_font_matrix( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Face root = (FT_Face)&face->root; FT_Fixed temp[6]; FT_Fixed temp_scale; FT_Int result; /* input is scaled by 1000 to accommodate default FontMatrix */ result = T1_ToFixedArray( parser, 6, temp, 3 ); if ( result < 6 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } FT_TRACE4(( " [%f %f %f %f %f %f]\n", (double)temp[0] / 65536 / 1000, (double)temp[1] / 65536 / 1000, (double)temp[2] / 65536 / 1000, (double)temp[3] / 65536 / 1000, (double)temp[4] / 65536 / 1000, (double)temp[5] / 65536 / 1000 )); temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* atypical case */ if ( temp_scale != 0x10000L ) { /* set units per EM based on FontMatrix values */ root->units_per_EM = (FT_UShort)FT_DivFix( 1000, temp_scale ); temp[0] = FT_DivFix( temp[0], temp_scale ); temp[1] = FT_DivFix( temp[1], temp_scale ); temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; if ( !FT_Matrix_Check( matrix ) ) { FT_ERROR(( "t1_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; } static void parse_encoding( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Byte* cur; FT_Byte* limit = parser->root.limit; PSAux_Service psaux = (PSAux_Service)face->psaux; T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) { FT_ERROR(( "parse_encoding: out of bounds\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* if we have a number or `[', the encoding is an array, */ /* and we must load it now */ if ( ft_isdigit( *cur ) || *cur == '[' ) { T1_Encoding encode = &face->type1.encoding; FT_Int count, array_size, n; PS_Table char_table = &loader->encoding_table; FT_Memory memory = parser->root.memory; FT_Error error; FT_Bool only_immediates = 0; /* read the number of entries in the encoding; should be 256 */ if ( *cur == '[' ) { count = 256; only_immediates = 1; parser->root.cursor++; } else count = (FT_Int)T1_ToInt( parser ); array_size = count; if ( count > 256 ) { FT_TRACE2(( "parse_encoding:" " only using first 256 encoding array entries\n" )); array_size = 256; } T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit ) return; /* PostScript happily allows overwriting of encoding arrays */ if ( encode->char_index ) { FT_FREE( encode->char_index ); FT_FREE( encode->char_name ); T1_Release_Table( char_table ); } /* we use a T1_Table to store our charnames */ loader->num_chars = encode->num_chars = array_size; if ( FT_QNEW_ARRAY( encode->char_index, array_size ) || FT_QNEW_ARRAY( encode->char_name, array_size ) || FT_SET_ERROR( psaux->ps_table_funcs->init( char_table, array_size, memory ) ) ) { parser->root.error = error; return; } /* We need to `zero' out encoding_table.elements */ for ( n = 0; n < array_size; n++ ) (void)T1_Add_Table( char_table, n, ".notdef", 8 ); /* Now we need to read records of the form */ /* */ /* ... charcode /charname ... */ /* */ /* for each entry in our table. */ /* */ /* We simply look for a number followed by an immediate */ /* name. Note that this ignores correctly the sequence */ /* that is often seen in type1 fonts: */ /* */ /* 0 1 255 { 1 index exch /.notdef put } for dup */ /* */ /* used to clean the encoding array before anything else. */ /* */ /* Alternatively, if the array is directly given as */ /* */ /* /Encoding [ ... ] */ /* */ /* we only read immediates. */ n = 0; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { cur = parser->root.cursor; /* we stop when we encounter a `def' or `]' */ if ( *cur == 'd' && cur + 3 < limit ) { if ( cur[1] == 'e' && cur[2] == 'f' && IS_PS_DELIM( cur[3] ) ) { FT_TRACE6(( "encoding end\n" )); cur += 3; break; } } if ( *cur == ']' ) { FT_TRACE6(( "encoding end\n" )); cur++; break; } /* check whether we've found an entry */ if ( ft_isdigit( *cur ) || only_immediates ) { FT_Int charcode; if ( only_immediates ) charcode = n; else { charcode = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); /* protect against invalid charcode */ if ( cur == parser->root.cursor ) { parser->root.error = FT_THROW( Unknown_File_Format ); return; } } cur = parser->root.cursor; if ( cur + 2 < limit && *cur == '/' && n < count ) { FT_UInt len; cur++; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) return; if ( parser->root.error ) return; len = (FT_UInt)( parser->root.cursor - cur ); if ( n < array_size ) { parser->root.error = T1_Add_Table( char_table, charcode, cur, len + 1 ); if ( parser->root.error ) return; char_table->elements[charcode][len] = '\0'; } n++; } else if ( only_immediates ) { /* Since the current position is not updated for */ /* immediates-only mode we would get an infinite loop if */ /* we don't do anything here. */ /* */ /* This encoding array is not valid according to the type1 */ /* specification (it might be an encoding for a CID type1 */ /* font, however), so we conclude that this font is NOT a */ /* type1 font. */ parser->root.error = FT_THROW( Unknown_File_Format ); return; } } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; } T1_Skip_Spaces( parser ); } #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " [" )); /* XXX show encoding vector */ FT_TRACE4(( "..." )); FT_TRACE4(( "]\n" )); #endif face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY; parser->root.cursor = cur; } /* Otherwise, we should have either `StandardEncoding', */ /* `ExpertEncoding', or `ISOLatin1Encoding' */ else { if ( cur + 17 < limit && ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 ) { face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD; FT_TRACE4(( " StandardEncoding\n" )); } else if ( cur + 15 < limit && ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 ) { face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT; FT_TRACE4(( " ExpertEncoding\n" )); } else if ( cur + 18 < limit && ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 ) { face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1; FT_TRACE4(( " ISOLatin1Encoding\n" )); } else { parser->root.error = FT_ERR( Ignore ); FT_TRACE4(( "<unknown>\n" )); } } } static void parse_subrs( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; PS_Table table = &loader->subrs; FT_Memory memory = parser->root.memory; FT_Error error; FT_Int num_subrs; FT_UInt count; PSAux_Service psaux = (PSAux_Service)face->psaux; T1_Skip_Spaces( parser ); /* test for empty array */ if ( parser->root.cursor < parser->root.limit && *parser->root.cursor == '[' ) { T1_Skip_PS_Token( parser ); T1_Skip_Spaces ( parser ); if ( parser->root.cursor >= parser->root.limit || *parser->root.cursor != ']' ) parser->root.error = FT_THROW( Invalid_File_Format ); return; } num_subrs = (FT_Int)T1_ToInt( parser ); if ( num_subrs < 0 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* we certainly need more than 8 bytes per subroutine */ if ( parser->root.limit >= parser->root.cursor && num_subrs > ( parser->root.limit - parser->root.cursor ) >> 3 ) { /* * There are two possibilities. Either the font contains an invalid * value for `num_subrs', or we have a subsetted font where the * subroutine indices are not adjusted, e.g. * * /Subrs 812 array * dup 0 { ... } NP * dup 51 { ... } NP * dup 681 { ... } NP * ND * * In both cases, we use a number hash that maps from subr indices to * actual array elements. */ FT_TRACE0(( "parse_subrs: adjusting number of subroutines" " (from %d to %ld)\n", num_subrs, ( parser->root.limit - parser->root.cursor ) >> 3 )); num_subrs = ( parser->root.limit - parser->root.cursor ) >> 3; if ( !loader->subrs_hash ) { if ( FT_QNEW( loader->subrs_hash ) ) goto Fail; error = ft_hash_num_init( loader->subrs_hash, memory ); if ( error ) goto Fail; } } /* position the parser right before the `dup' of the first subr */ T1_Skip_PS_Token( parser ); /* `array' */ if ( parser->root.error ) return; T1_Skip_Spaces( parser ); /* initialize subrs array -- with synthetic fonts it is possible */ /* we get here twice */ if ( !loader->num_subrs ) { error = psaux->ps_table_funcs->init( table, num_subrs, memory ); if ( error ) goto Fail; } /* the format is simple: */ /* */ /* `index' + binary data */ /* */ for ( count = 0; ; count++ ) { FT_Long idx; FT_ULong size; FT_Byte* base; /* If we are out of data, or if the next token isn't `dup', */ /* we are done. */ if ( parser->root.cursor + 4 >= parser->root.limit || ft_strncmp( (char*)parser->root.cursor, "dup", 3 ) != 0 ) break; T1_Skip_PS_Token( parser ); /* `dup' */ idx = T1_ToInt( parser ); if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) ) return; /* The binary string is followed by one token, e.g. `NP' */ /* (bound to `noaccess put') or by two separate tokens: */ /* `noaccess' & `put'. We position the parser right */ /* before the next `dup', if any. */ T1_Skip_PS_Token( parser ); /* `NP' or `|' or `noaccess' */ if ( parser->root.error ) return; T1_Skip_Spaces ( parser ); if ( parser->root.cursor + 4 < parser->root.limit && ft_strncmp( (char*)parser->root.cursor, "put", 3 ) == 0 ) { T1_Skip_PS_Token( parser ); /* skip `put' */ T1_Skip_Spaces ( parser ); } /* if we use a hash, the subrs index is the key, and a running */ /* counter specified for `T1_Add_Table' acts as the value */ if ( loader->subrs_hash ) { ft_hash_num_insert( idx, count, loader->subrs_hash, memory ); idx = count; } /* with synthetic fonts it is possible we get here twice */ if ( loader->num_subrs ) continue; /* some fonts use a value of -1 for lenIV to indicate that */ /* the charstrings are unencoded */ /* */ /* thanks to Tom Kacvinsky for pointing this out */ /* */ if ( face->type1.private_dict.lenIV >= 0 ) { FT_Byte* temp = NULL; /* some fonts define empty subr records -- this is not totally */ /* compliant to the specification (which says they should at */ /* least contain a `return'), but we support them anyway */ if ( size < (FT_ULong)face->type1.private_dict.lenIV ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* t1_decrypt() shouldn't write to base -- make temporary copy */ if ( FT_QALLOC( temp, size ) ) goto Fail; FT_MEM_COPY( temp, base, size ); psaux->t1_decrypt( temp, size, 4330 ); size -= (FT_ULong)face->type1.private_dict.lenIV; error = T1_Add_Table( table, (FT_Int)idx, temp + face->type1.private_dict.lenIV, size ); FT_FREE( temp ); } else error = T1_Add_Table( table, (FT_Int)idx, base, size ); if ( error ) goto Fail; } if ( !loader->num_subrs ) loader->num_subrs = num_subrs; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " <" )); /* XXX show subrs? */ FT_TRACE4(( "%d elements", num_subrs )); FT_TRACE4(( ">\n" )); #endif return; Fail: parser->root.error = error; } #define TABLE_EXTEND 5 static void parse_charstrings( T1_Face face, T1_Loader loader ) { T1_Parser parser = &loader->parser; PS_Table code_table = &loader->charstrings; PS_Table name_table = &loader->glyph_names; PS_Table swap_table = &loader->swap_table; FT_Memory memory = parser->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_Byte* cur = parser->root.cursor; FT_Byte* limit = parser->root.limit; FT_Int n, num_glyphs; FT_Int notdef_index = 0; FT_Byte notdef_found = 0; num_glyphs = (FT_Int)T1_ToInt( parser ); if ( num_glyphs < 0 ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* we certainly need more than 8 bytes per glyph */ if ( num_glyphs > ( limit - cur ) >> 3 ) { FT_TRACE0(( "parse_charstrings: adjusting number of glyphs" " (from %d to %ld)\n", num_glyphs, ( limit - cur ) >> 3 )); num_glyphs = ( limit - cur ) >> 3; } /* some fonts like Optima-Oblique not only define the /CharStrings */ /* array but access it also */ if ( num_glyphs == 0 || parser->root.error ) return; /* initialize tables, leaving space for addition of .notdef, */ /* if necessary, and a few other glyphs to handle buggy */ /* fonts which have more glyphs than specified. */ /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( !loader->num_glyphs ) { error = psaux->ps_table_funcs->init( code_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; error = psaux->ps_table_funcs->init( name_table, num_glyphs + 1 + TABLE_EXTEND, memory ); if ( error ) goto Fail; /* Initialize table for swapping index notdef_index and */ /* index 0 names and codes (if necessary). */ error = psaux->ps_table_funcs->init( swap_table, 4, memory ); if ( error ) goto Fail; } n = 0; for (;;) { FT_ULong size; FT_Byte* base; /* the format is simple: */ /* `/glyphname' + binary data */ T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) break; /* we stop when we find a `def' or `end' keyword */ if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) ) { if ( cur[0] == 'd' && cur[1] == 'e' && cur[2] == 'f' ) { /* There are fonts which have this: */ /* */ /* /CharStrings 118 dict def */ /* Private begin */ /* CharStrings begin */ /* ... */ /* */ /* To catch this we ignore `def' if */ /* no charstring has actually been */ /* seen. */ if ( n ) break; } if ( cur[0] == 'e' && cur[1] == 'n' && cur[2] == 'd' ) break; } T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( parser->root.error ) return; if ( *cur == '/' ) { FT_UInt len; if ( cur + 2 >= limit ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } cur++; /* skip `/' */ len = (FT_UInt)( parser->root.cursor - cur ); if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) ) return; /* for some non-standard fonts like `Optima' which provides */ /* different outlines depending on the resolution it is */ /* possible to get here twice */ if ( loader->num_glyphs ) continue; error = T1_Add_Table( name_table, n, cur, len + 1 ); if ( error ) goto Fail; /* add a trailing zero to the name table */ name_table->elements[n][len] = '\0'; /* record index of /.notdef */ if ( *cur == '.' && ft_strcmp( ".notdef", (const char*)(name_table->elements[n]) ) == 0 ) { notdef_index = n; notdef_found = 1; } if ( face->type1.private_dict.lenIV >= 0 && n < num_glyphs + TABLE_EXTEND ) { FT_Byte* temp = NULL; if ( size <= (FT_ULong)face->type1.private_dict.lenIV ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } /* t1_decrypt() shouldn't write to base -- make temporary copy */ if ( FT_QALLOC( temp, size ) ) goto Fail; FT_MEM_COPY( temp, base, size ); psaux->t1_decrypt( temp, size, 4330 ); size -= (FT_ULong)face->type1.private_dict.lenIV; error = T1_Add_Table( code_table, n, temp + face->type1.private_dict.lenIV, size ); FT_FREE( temp ); } else error = T1_Add_Table( code_table, n, base, size ); if ( error ) goto Fail; n++; } } if ( !n ) { error = FT_THROW( Invalid_File_Format ); goto Fail; } loader->num_glyphs = n; /* if /.notdef is found but does not occupy index 0, do our magic. */ if ( notdef_found && ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) ) { /* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */ /* name and code entries to swap_table. Then place notdef_index */ /* name and code entries into swap_table. Then swap name and code */ /* entries at indices notdef_index and 0 using values stored in */ /* swap_table. */ /* Index 0 name */ error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; /* Index 0 code */ error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; /* Index notdef_index name */ error = T1_Add_Table( swap_table, 2, name_table->elements[notdef_index], name_table->lengths [notdef_index] ); if ( error ) goto Fail; /* Index notdef_index code */ error = T1_Add_Table( swap_table, 3, code_table->elements[notdef_index], code_table->lengths [notdef_index] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, notdef_index, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, notdef_index, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, swap_table->elements[2], swap_table->lengths [2] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, swap_table->elements[3], swap_table->lengths [3] ); if ( error ) goto Fail; } else if ( !notdef_found ) { /* notdef_index is already 0, or /.notdef is undefined in */ /* charstrings dictionary. Worry about /.notdef undefined. */ /* We take index 0 and add it to the end of the table(s) */ /* and add our own /.notdef glyph to index 0. */ /* 0 333 hsbw endchar */ FT_Byte notdef_glyph[] = { 0x8B, 0xF7, 0xE1, 0x0D, 0x0E }; error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, ".notdef", 8 ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, notdef_glyph, 5 ); if ( error ) goto Fail; error = T1_Add_Table( name_table, n, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, n, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; /* we added a glyph. */ loader->num_glyphs += 1; } #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " <" )); /* XXX show charstrings? */ FT_TRACE4(( "%d elements", loader->num_glyphs )); FT_TRACE4(( ">\n" )); #endif return; Fail: parser->root.error = error; } /************************************************************************** * * Define the token field static variables. This is a set of * T1_FieldRec variables. * */ static const T1_FieldRec t1_keywords[] = { #include "t1tokens.h" /* now add the special functions... */ T1_FIELD_CALLBACK( "FontMatrix", t1_parse_font_matrix, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "Encoding", parse_encoding, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "Subrs", parse_subrs, T1_FIELD_DICT_PRIVATE ) T1_FIELD_CALLBACK( "CharStrings", parse_charstrings, T1_FIELD_DICT_PRIVATE ) T1_FIELD_CALLBACK( "Private", parse_private, T1_FIELD_DICT_FONTDICT ) #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT T1_FIELD_CALLBACK( "BlendDesignPositions", parse_blend_design_positions, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "BlendDesignMap", parse_blend_design_map, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "BlendAxisTypes", parse_blend_axis_types, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "WeightVector", parse_weight_vector, T1_FIELD_DICT_FONTDICT ) T1_FIELD_CALLBACK( "BuildCharArray", parse_buildchar, T1_FIELD_DICT_PRIVATE ) #endif { 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 } }; static FT_Error parse_dict( T1_Face face, T1_Loader loader, FT_Byte* base, FT_ULong size ) { T1_Parser parser = &loader->parser; FT_Byte *limit, *start_binary = NULL; FT_Bool have_integer = 0; parser->root.cursor = base; parser->root.limit = base + size; parser->root.error = FT_Err_Ok; limit = parser->root.limit; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { FT_Byte* cur; cur = parser->root.cursor; /* look for `eexec' */ if ( IS_PS_TOKEN( cur, limit, "eexec" ) ) break; /* look for `closefile' which ends the eexec section */ else if ( IS_PS_TOKEN( cur, limit, "closefile" ) ) break; /* in a synthetic font the base font starts after a */ /* `FontDictionary' token that is placed after a Private dict */ else if ( IS_PS_TOKEN( cur, limit, "FontDirectory" ) ) { if ( loader->keywords_encountered & T1_PRIVATE ) loader->keywords_encountered |= T1_FONTDIR_AFTER_PRIVATE; parser->root.cursor += 13; } /* check whether we have an integer */ else if ( ft_isdigit( *cur ) ) { start_binary = cur; T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; have_integer = 1; } /* in valid Type 1 fonts we don't see `RD' or `-|' directly */ /* since those tokens are handled by parse_subrs and */ /* parse_charstrings */ else if ( *cur == 'R' && cur + 6 < limit && *(cur + 1) == 'D' && have_integer ) { FT_ULong s; FT_Byte* b; parser->root.cursor = start_binary; if ( !read_binary_data( parser, &s, &b, IS_INCREMENTAL ) ) return FT_THROW( Invalid_File_Format ); have_integer = 0; } else if ( *cur == '-' && cur + 6 < limit && *(cur + 1) == '|' && have_integer ) { FT_ULong s; FT_Byte* b; parser->root.cursor = start_binary; if ( !read_binary_data( parser, &s, &b, IS_INCREMENTAL ) ) return FT_THROW( Invalid_File_Format ); have_integer = 0; } /* look for immediates */ else if ( *cur == '/' && cur + 2 < limit ) { FT_UInt len; cur++; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; len = (FT_UInt)( parser->root.cursor - cur ); if ( len > 0 && len < 22 && parser->root.cursor < limit ) { /* now compare the immediate name to the keyword table */ T1_Field keyword = (T1_Field)t1_keywords; for (;;) { FT_Byte* name; name = (FT_Byte*)keyword->ident; if ( !name ) break; if ( cur[0] == name[0] && len == ft_strlen( (const char *)name ) && ft_memcmp( cur, name, len ) == 0 ) { /* We found it -- run the parsing callback! */ /* We record every instance of every field */ /* (until we reach the base font of a */ /* synthetic font) to deal adequately with */ /* multiple master fonts; this is also */ /* necessary because later PostScript */ /* definitions override earlier ones. */ /* Once we encounter `FontDirectory' after */ /* `/Private', we know that this is a synthetic */ /* font; except for `/CharStrings' we are not */ /* interested in anything that follows this */ /* `FontDirectory'. */ /* MM fonts have more than one /Private token at */ /* the top level; let's hope that all the junk */ /* that follows the first /Private token is not */ /* interesting to us. */ /* According to Adobe Tech Note #5175 (CID-Keyed */ /* Font Installation for ATM Software) a `begin' */ /* must be followed by exactly one `end', and */ /* `begin' -- `end' pairs must be accurately */ /* paired. We could use this to distinguish */ /* between the global Private and the Private */ /* dict that is a member of the Blend dict. */ const FT_UInt dict = ( loader->keywords_encountered & T1_PRIVATE ) ? T1_FIELD_DICT_PRIVATE : T1_FIELD_DICT_FONTDICT; if ( !( dict & keyword->dict ) ) { FT_TRACE1(( "parse_dict: found `%s' but ignoring it" " since it is in the wrong dictionary\n", keyword->ident )); break; } if ( !( loader->keywords_encountered & T1_FONTDIR_AFTER_PRIVATE ) || ft_strcmp( (const char*)name, "CharStrings" ) == 0 ) { parser->root.error = t1_load_keyword( face, loader, keyword ); if ( parser->root.error ) { if ( FT_ERR_EQ( parser->root.error, Ignore ) ) parser->root.error = FT_Err_Ok; else return parser->root.error; } } break; } keyword++; } } have_integer = 0; } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; have_integer = 0; } T1_Skip_Spaces( parser ); } Exit: return parser->root.error; } static void t1_init_loader( T1_Loader loader, T1_Face face ) { FT_UNUSED( face ); FT_ZERO( loader ); } static void t1_done_loader( T1_Loader loader ) { T1_Parser parser = &loader->parser; FT_Memory memory = parser->root.memory; /* finalize tables */ T1_Release_Table( &loader->encoding_table ); T1_Release_Table( &loader->charstrings ); T1_Release_Table( &loader->glyph_names ); T1_Release_Table( &loader->swap_table ); T1_Release_Table( &loader->subrs ); /* finalize hash */ ft_hash_num_free( loader->subrs_hash, memory ); FT_FREE( loader->subrs_hash ); /* finalize parser */ T1_Finalize_Parser( parser ); } FT_LOCAL_DEF( FT_Error ) T1_Open_Face( T1_Face face ) { T1_LoaderRec loader; T1_Parser parser; T1_Font type1 = &face->type1; PS_Private priv = &type1->private_dict; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; t1_init_loader( &loader, face ); /* default values */ face->ndv_idx = -1; face->cdv_idx = -1; face->len_buildchar = 0; priv->blue_shift = 7; priv->blue_fuzz = 1; priv->lenIV = 4; priv->expansion_factor = (FT_Fixed)( 0.06 * 0x10000L ); priv->blue_scale = (FT_Fixed)( 0.039625 * 0x10000L * 1000 ); parser = &loader.parser; error = T1_New_Parser( parser, face->root.stream, face->root.memory, psaux ); if ( error ) goto Exit; FT_TRACE4(( " top dictionary:\n" )); error = parse_dict( face, &loader, parser->base_dict, parser->base_len ); if ( error ) goto Exit; error = T1_Get_Private_Dict( parser, psaux ); if ( error ) goto Exit; FT_TRACE4(( " private dictionary:\n" )); error = parse_dict( face, &loader, parser->private_dict, parser->private_len ); if ( error ) goto Exit; /* ensure even-ness of `num_blue_values' */ priv->num_blue_values &= ~1; #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT /* we don't support Multiple Master fonts with intermediate designs; */ /* this implies that `num_designs' must be equal to `2^^num_axis' */ if ( face->blend && face->blend->num_designs != ( 1U << face->blend->num_axis ) ) { FT_ERROR(( "T1_Open_Face:" " number-of-designs != 2 ^^ number-of-axes\n" )); T1_Done_Blend( face ); } if ( face->blend && face->blend->num_default_design_vector != 0 && face->blend->num_default_design_vector != face->blend->num_axis ) { /* we don't use it currently so just warn, reset, and ignore */ FT_ERROR(( "T1_Open_Face(): /DesignVector contains %u entries " "while there are %u axes.\n", face->blend->num_default_design_vector, face->blend->num_axis )); face->blend->num_default_design_vector = 0; } /* the following can happen for MM instances; we then treat the */ /* font as a normal PS font */ if ( face->blend && ( !face->blend->num_designs || !face->blend->num_axis ) ) T1_Done_Blend( face ); /* the font may have no valid WeightVector */ if ( face->blend && !face->blend->weight_vector ) T1_Done_Blend( face ); /* the font may have no valid BlendDesignPositions */ if ( face->blend && !face->blend->design_pos[0] ) T1_Done_Blend( face ); /* the font may have no valid BlendDesignMap */ if ( face->blend ) { FT_UInt i; for ( i = 0; i < face->blend->num_axis; i++ ) if ( !face->blend->design_map[i].num_points ) { T1_Done_Blend( face ); break; } } if ( face->blend ) { if ( face->len_buildchar > 0 ) { FT_Memory memory = face->root.memory; if ( FT_NEW_ARRAY( face->buildchar, face->len_buildchar ) ) { FT_ERROR(( "T1_Open_Face: cannot allocate BuildCharArray\n" )); face->len_buildchar = 0; goto Exit; } } } else face->len_buildchar = 0; #endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */ /* now, propagate the subrs, charstrings, and glyphnames tables */ /* to the Type1 data */ type1->num_glyphs = loader.num_glyphs; if ( loader.subrs.init ) { type1->num_subrs = loader.num_subrs; type1->subrs_block = loader.subrs.block; type1->subrs = loader.subrs.elements; type1->subrs_len = loader.subrs.lengths; type1->subrs_hash = loader.subrs_hash; /* prevent `t1_done_loader' from freeing the propagated data */ loader.subrs.init = 0; loader.subrs_hash = NULL; } if ( !IS_INCREMENTAL ) if ( !loader.charstrings.init ) { FT_ERROR(( "T1_Open_Face: no `/CharStrings' array in face\n" )); error = FT_THROW( Invalid_File_Format ); } loader.charstrings.init = 0; type1->charstrings_block = loader.charstrings.block; type1->charstrings = loader.charstrings.elements; type1->charstrings_len = loader.charstrings.lengths; /* we copy the glyph names `block' and `elements' fields; */ /* the `lengths' field must be released later */ type1->glyph_names_block = loader.glyph_names.block; type1->glyph_names = (FT_String**)loader.glyph_names.elements; loader.glyph_names.block = NULL; loader.glyph_names.elements = NULL; /* we must now build type1.encoding when we have a custom array */ if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY ) { FT_Int charcode, idx, min_char, max_char; /* OK, we do the following: for each element in the encoding */ /* table, look up the index of the glyph having the same name */ /* the index is then stored in type1.encoding.char_index, and */ /* the name to type1.encoding.char_name */ min_char = 0; max_char = 0; charcode = 0; for ( ; charcode < loader.encoding_table.max_elems; charcode++ ) { const FT_String* char_name = (const FT_String*)loader.encoding_table.elements[charcode]; type1->encoding.char_index[charcode] = 0; type1->encoding.char_name [charcode] = ".notdef"; if ( char_name ) for ( idx = 0; idx < type1->num_glyphs; idx++ ) { const FT_String* glyph_name = type1->glyph_names[idx]; if ( ft_strcmp( char_name, glyph_name ) == 0 ) { type1->encoding.char_index[charcode] = (FT_UShort)idx; type1->encoding.char_name [charcode] = glyph_name; /* Change min/max encoded char only if glyph name is */ /* not /.notdef */ if ( ft_strcmp( ".notdef", glyph_name ) != 0 ) { if ( charcode < min_char ) min_char = charcode; if ( charcode >= max_char ) max_char = charcode + 1; } break; } } } type1->encoding.code_first = min_char; type1->encoding.code_last = max_char; type1->encoding.num_chars = loader.num_chars; } /* some sanitizing to avoid overflows later on; */ /* the upper limits are ad-hoc values */ if ( priv->blue_shift > 1000 || priv->blue_shift < 0 ) { FT_TRACE2(( "T1_Open_Face:" " setting unlikely BlueShift value %d to default (7)\n", priv->blue_shift )); priv->blue_shift = 7; } if ( priv->blue_fuzz > 1000 || priv->blue_fuzz < 0 ) { FT_TRACE2(( "T1_Open_Face:" " setting unlikely BlueFuzz value %d to default (1)\n", priv->blue_fuzz )); priv->blue_fuzz = 1; } Exit: t1_done_loader( &loader ); return error; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1load.c
C++
gpl-3.0
80,366
/**************************************************************************** * * t1load.h * * Type 1 font loader (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1LOAD_H_ #define T1LOAD_H_ #include <freetype/internal/ftstream.h> #include <freetype/internal/psaux.h> #include <freetype/ftmm.h> #include "t1parse.h" FT_BEGIN_HEADER typedef struct T1_Loader_ { T1_ParserRec parser; /* parser used to read the stream */ FT_Int num_chars; /* number of characters in encoding */ PS_TableRec encoding_table; /* PS_Table used to store the */ /* encoding character names */ FT_Int num_glyphs; PS_TableRec glyph_names; PS_TableRec charstrings; PS_TableRec swap_table; /* For moving .notdef glyph to index 0. */ FT_Int num_subrs; PS_TableRec subrs; FT_Hash subrs_hash; FT_Bool fontdata; FT_UInt keywords_encountered; /* T1_LOADER_ENCOUNTERED_XXX */ } T1_LoaderRec, *T1_Loader; /* treatment of some keywords differs depending on whether */ /* they precede or follow certain other keywords */ #define T1_PRIVATE ( 1 << 0 ) #define T1_FONTDIR_AFTER_PRIVATE ( 1 << 1 ) FT_LOCAL( FT_Error ) T1_Open_Face( T1_Face face ); #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT FT_LOCAL( FT_Error ) T1_Get_Multi_Master( T1_Face face, FT_Multi_Master* master ); FT_LOCAL( FT_Error ) T1_Get_MM_Var( T1_Face face, FT_MM_Var* *master ); FT_LOCAL( FT_Error ) T1_Set_MM_Blend( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) T1_Get_MM_Blend( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) T1_Set_MM_Design( T1_Face face, FT_UInt num_coords, FT_Long* coords ); FT_LOCAL( FT_Error ) T1_Reset_MM_Blend( T1_Face face, FT_UInt instance_index ); FT_LOCAL( FT_Error ) T1_Get_Var_Design( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( FT_Error ) T1_Set_Var_Design( T1_Face face, FT_UInt num_coords, FT_Fixed* coords ); FT_LOCAL( void ) T1_Done_Blend( T1_Face face ); FT_LOCAL( FT_Error ) T1_Set_MM_WeightVector( T1_Face face, FT_UInt len, FT_Fixed* weightvector ); FT_LOCAL( FT_Error ) T1_Get_MM_WeightVector( T1_Face face, FT_UInt* len, FT_Fixed* weightvector ); #endif /* !T1_CONFIG_OPTION_NO_MM_SUPPORT */ FT_END_HEADER #endif /* T1LOAD_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1load.h
C++
gpl-3.0
3,285
/**************************************************************************** * * t1objs.c * * Type 1 objects manager (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/internal/ftcalc.h> #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/ttnameid.h> #include <freetype/ftdriver.h> #include "t1gload.h" #include "t1load.h" #include "t1errors.h" #ifndef T1_CONFIG_OPTION_NO_AFM #include "t1afm.h" #endif #include <freetype/internal/services/svpscmap.h> #include <freetype/internal/psaux.h> /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1objs /************************************************************************** * * SIZE FUNCTIONS * */ static PSH_Globals_Funcs T1_Size_Get_Globals_Funcs( T1_Size size ) { T1_Face face = (T1_Face)size->root.face; PSHinter_Service pshinter = (PSHinter_Service)face->pshinter; FT_Module module; module = FT_Get_Module( size->root.face->driver->root.library, "pshinter" ); return ( module && pshinter && pshinter->get_globals_funcs ) ? pshinter->get_globals_funcs( module ) : 0; } FT_LOCAL_DEF( void ) T1_Size_Done( FT_Size t1size ) /* T1_Size */ { T1_Size size = (T1_Size)t1size; if ( t1size->internal->module_data ) { PSH_Globals_Funcs funcs; funcs = T1_Size_Get_Globals_Funcs( size ); if ( funcs ) funcs->destroy( (PSH_Globals)t1size->internal->module_data ); t1size->internal->module_data = NULL; } } FT_LOCAL_DEF( FT_Error ) T1_Size_Init( FT_Size t1size ) /* T1_Size */ { T1_Size size = (T1_Size)t1size; FT_Error error = FT_Err_Ok; PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size ); if ( funcs ) { PSH_Globals globals; T1_Face face = (T1_Face)size->root.face; error = funcs->create( size->root.face->memory, &face->type1.private_dict, &globals ); if ( !error ) t1size->internal->module_data = globals; } return error; } FT_LOCAL_DEF( FT_Error ) T1_Size_Request( FT_Size t1size, /* T1_Size */ FT_Size_Request req ) { FT_Error error; T1_Size size = (T1_Size)t1size; PSH_Globals_Funcs funcs = T1_Size_Get_Globals_Funcs( size ); error = FT_Request_Metrics( size->root.face, req ); if ( error ) goto Exit; if ( funcs ) funcs->set_scale( (PSH_Globals)t1size->internal->module_data, size->root.metrics.x_scale, size->root.metrics.y_scale, 0, 0 ); Exit: return error; } /************************************************************************** * * SLOT FUNCTIONS * */ FT_LOCAL_DEF( void ) T1_GlyphSlot_Done( FT_GlyphSlot slot ) { slot->internal->glyph_hints = NULL; } FT_LOCAL_DEF( FT_Error ) T1_GlyphSlot_Init( FT_GlyphSlot slot ) { T1_Face face; PSHinter_Service pshinter; face = (T1_Face)slot->face; pshinter = (PSHinter_Service)face->pshinter; if ( pshinter ) { FT_Module module; module = FT_Get_Module( slot->face->driver->root.library, "pshinter" ); if ( module ) { T1_Hints_Funcs funcs; funcs = pshinter->get_t1_funcs( module ); slot->internal->glyph_hints = (void*)funcs; } } return 0; } /************************************************************************** * * FACE FUNCTIONS * */ /************************************************************************** * * @Function: * T1_Face_Done * * @Description: * The face object destructor. * * @Input: * face :: * A typeless pointer to the face object to destroy. */ FT_LOCAL_DEF( void ) T1_Face_Done( FT_Face t1face ) /* T1_Face */ { T1_Face face = (T1_Face)t1face; FT_Memory memory; T1_Font type1; if ( !face ) return; memory = face->root.memory; type1 = &face->type1; #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT /* release multiple masters information */ FT_ASSERT( ( face->len_buildchar == 0 ) == ( face->buildchar == NULL ) ); if ( face->buildchar ) { FT_FREE( face->buildchar ); face->len_buildchar = 0; } T1_Done_Blend( face ); face->blend = NULL; #endif /* release font info strings */ { PS_FontInfo info = &type1->font_info; FT_FREE( info->version ); FT_FREE( info->notice ); FT_FREE( info->full_name ); FT_FREE( info->family_name ); FT_FREE( info->weight ); } /* release top dictionary */ FT_FREE( type1->charstrings_len ); FT_FREE( type1->charstrings ); FT_FREE( type1->glyph_names ); FT_FREE( type1->subrs ); FT_FREE( type1->subrs_len ); ft_hash_num_free( type1->subrs_hash, memory ); FT_FREE( type1->subrs_hash ); FT_FREE( type1->subrs_block ); FT_FREE( type1->charstrings_block ); FT_FREE( type1->glyph_names_block ); FT_FREE( type1->encoding.char_index ); FT_FREE( type1->encoding.char_name ); FT_FREE( type1->font_name ); #ifndef T1_CONFIG_OPTION_NO_AFM /* release afm data if present */ if ( face->afm_data ) T1_Done_Metrics( memory, (AFM_FontInfo)face->afm_data ); #endif /* release unicode map, if any */ #if 0 FT_FREE( face->unicode_map_rec.maps ); face->unicode_map_rec.num_maps = 0; face->unicode_map = NULL; #endif face->root.family_name = NULL; face->root.style_name = NULL; } /************************************************************************** * * @Function: * T1_Face_Init * * @Description: * The face object constructor. * * @Input: * stream :: * input stream where to load font data. * * face_index :: * The index of the font face in the resource. * * num_params :: * Number of additional generic parameters. Ignored. * * params :: * Additional generic parameters. Ignored. * * @InOut: * face :: * The face record to build. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) T1_Face_Init( FT_Stream stream, FT_Face t1face, /* T1_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T1_Face face = (T1_Face)t1face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T1_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } face->pshinter = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "pshinter" ); FT_TRACE2(( "Type 1 driver\n" )); /* open the tokenizer; this will also check the font format */ error = T1_Open_Face( face ); if ( error ) goto Exit; FT_TRACE2(( "T1_Face_Init: %p (index %d)\n", (void *)face, face_index )); /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( ( face_index & 0xFFFF ) > 0 ) { FT_ERROR(( "T1_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* now load the font program into the face object */ /* initialize the face object fields */ /* set up root face fields */ { FT_Face root = (FT_Face)&face->root; root->num_glyphs = type1->num_glyphs; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES | FT_FACE_FLAG_HINTER; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; if ( face->blend ) root->face_flags |= FT_FACE_FLAG_MULTIPLE_MASTERS; /* The following code to extract the family and the style is very */ /* simplistic and might get some things wrong. For a full-featured */ /* algorithm you might have a look at the whitepaper given at */ /* */ /* https://blogs.msdn.com/text/archive/2007/04/23/wpf-font-selection-model.aspx */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; root->style_name = NULL; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { FT_Bool the_same = TRUE; while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { the_same = FALSE; if ( !*family ) root->style_name = full; break; } } } if ( the_same ) root->style_name = (char *)"Regular"; } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } if ( !root->style_name ) { if ( info->weight ) root->style_name = info->weight; else /* assume `Regular' style because we don't know better */ root->style_name = (char *)"Regular"; } /* compute style flags */ root->style_flags = 0; if ( info->italic_angle ) root->style_flags |= FT_STYLE_FLAG_ITALIC; if ( info->weight ) { if ( !ft_strcmp( info->weight, "Bold" ) || !ft_strcmp( info->weight, "Black" ) ) root->style_flags |= FT_STYLE_FLAG_BOLD; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = NULL; root->bbox.xMin = type1->font_bbox.xMin >> 16; root->bbox.yMin = type1->font_bbox.yMin >> 16; /* no `U' suffix here to 0xFFFF! */ root->bbox.xMax = ( type1->font_bbox.xMax + 0xFFFF ) >> 16; root->bbox.yMax = ( type1->font_bbox.yMax + 0xFFFF ) >> 16; /* Set units_per_EM if we didn't set it in t1_parse_font_matrix. */ if ( !root->units_per_EM ) root->units_per_EM = 1000; root->ascender = (FT_Short)( root->bbox.yMax ); root->descender = (FT_Short)( root->bbox.yMin ); root->height = (FT_Short)( ( root->units_per_EM * 12 ) / 10 ); if ( root->height < root->ascender - root->descender ) root->height = (FT_Short)( root->ascender - root->descender ); /* now compute the maximum advance width */ root->max_advance_width = (FT_Short)( root->bbox.xMax ); { FT_Pos max_advance; error = T1_Compute_Max_Advance( face, &max_advance ); /* in case of error, keep the standard width */ if ( !error ) root->max_advance_width = (FT_Short)FIXED_TO_INT( max_advance ); else error = FT_Err_Ok; /* clear error */ } root->max_advance_height = root->height; root->underline_position = (FT_Short)info->underline_position; root->underline_thickness = (FT_Short)info->underline_thickness; } { FT_Face root = &face->root; if ( psnames ) { FT_CharMapRec charmap; T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes; FT_CMap_Class clazz; charmap.face = root; /* first of all, try to synthesize a Unicode charmap */ charmap.platform_id = TT_PLATFORM_MICROSOFT; charmap.encoding_id = TT_MS_ID_UNICODE_CS; charmap.encoding = FT_ENCODING_UNICODE; error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL ); if ( error && FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) && FT_ERR_NEQ( error, Unimplemented_Feature ) ) goto Exit; error = FT_Err_Ok; /* now, generate an Adobe Standard encoding when appropriate */ charmap.platform_id = TT_PLATFORM_ADOBE; clazz = NULL; switch ( type1->encoding_type ) { case T1_ENCODING_TYPE_STANDARD: charmap.encoding = FT_ENCODING_ADOBE_STANDARD; charmap.encoding_id = TT_ADOBE_ID_STANDARD; clazz = cmap_classes->standard; break; case T1_ENCODING_TYPE_EXPERT: charmap.encoding = FT_ENCODING_ADOBE_EXPERT; charmap.encoding_id = TT_ADOBE_ID_EXPERT; clazz = cmap_classes->expert; break; case T1_ENCODING_TYPE_ARRAY: charmap.encoding = FT_ENCODING_ADOBE_CUSTOM; charmap.encoding_id = TT_ADOBE_ID_CUSTOM; clazz = cmap_classes->custom; break; case T1_ENCODING_TYPE_ISOLATIN1: charmap.encoding = FT_ENCODING_ADOBE_LATIN_1; charmap.encoding_id = TT_ADOBE_ID_LATIN_1; clazz = cmap_classes->unicode; break; default: ; } if ( clazz ) error = FT_CMap_New( clazz, NULL, &charmap, NULL ); } } Exit: return error; } /************************************************************************** * * @Function: * T1_Driver_Init * * @Description: * Initializes a given Type 1 driver object. * * @Input: * driver :: * A handle to the target driver object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) T1_Driver_Init( FT_Module module ) { PS_Driver driver = (PS_Driver)module; FT_UInt32 seed; /* set default property values, cf. `ftt1drv.h' */ driver->hinting_engine = FT_HINTING_ADOBE; driver->no_stem_darkening = TRUE; driver->darken_params[0] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1; driver->darken_params[1] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1; driver->darken_params[2] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2; driver->darken_params[3] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2; driver->darken_params[4] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3; driver->darken_params[5] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3; driver->darken_params[6] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4; driver->darken_params[7] = CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4; /* compute random seed from some memory addresses */ seed = (FT_UInt32)( (FT_Offset)(char*)&seed ^ (FT_Offset)(char*)&module ^ (FT_Offset)(char*)module->memory ); seed = seed ^ ( seed >> 10 ) ^ ( seed >> 20 ); driver->random_seed = (FT_Int32)seed; if ( driver->random_seed < 0 ) driver->random_seed = -driver->random_seed; else if ( driver->random_seed == 0 ) driver->random_seed = 123456789; return FT_Err_Ok; } /************************************************************************** * * @Function: * T1_Driver_Done * * @Description: * Finalizes a given Type 1 driver. * * @Input: * driver :: * A handle to the target Type 1 driver. */ FT_LOCAL_DEF( void ) T1_Driver_Done( FT_Module driver ) { FT_UNUSED( driver ); } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1objs.c
C++
gpl-3.0
17,386
/**************************************************************************** * * t1objs.h * * Type 1 objects manager (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1OBJS_H_ #define T1OBJS_H_ #include <ft2build.h> #include <freetype/internal/ftobjs.h> #include FT_CONFIG_CONFIG_H #include <freetype/internal/t1types.h> FT_BEGIN_HEADER /* The following structures must be defined by the hinter */ typedef struct T1_Size_Hints_ T1_Size_Hints; typedef struct T1_Glyph_Hints_ T1_Glyph_Hints; /************************************************************************** * * @Type: * T1_Size * * @Description: * A handle to a Type 1 size object. */ typedef struct T1_SizeRec_* T1_Size; /************************************************************************** * * @Type: * T1_GlyphSlot * * @Description: * A handle to a Type 1 glyph slot object. */ typedef struct T1_GlyphSlotRec_* T1_GlyphSlot; /************************************************************************** * * @Type: * T1_CharMap * * @Description: * A handle to a Type 1 character mapping object. * * @Note: * The Type 1 format doesn't use a charmap but an encoding table. * The driver is responsible for making up charmap objects * corresponding to these tables. */ typedef struct T1_CharMapRec_* T1_CharMap; /************************************************************************** * * HERE BEGINS THE TYPE1 SPECIFIC STUFF * */ /************************************************************************** * * @Type: * T1_SizeRec * * @Description: * Type 1 size record. */ typedef struct T1_SizeRec_ { FT_SizeRec root; } T1_SizeRec; FT_LOCAL( void ) T1_Size_Done( FT_Size size ); FT_LOCAL( FT_Error ) T1_Size_Request( FT_Size size, FT_Size_Request req ); FT_LOCAL( FT_Error ) T1_Size_Init( FT_Size size ); /************************************************************************** * * @Type: * T1_GlyphSlotRec * * @Description: * Type 1 glyph slot record. */ typedef struct T1_GlyphSlotRec_ { FT_GlyphSlotRec root; FT_Bool hint; FT_Bool scaled; FT_Fixed x_scale; FT_Fixed y_scale; FT_Int max_points; FT_Int max_contours; } T1_GlyphSlotRec; FT_LOCAL( FT_Error ) T1_Face_Init( FT_Stream stream, FT_Face face, FT_Int face_index, FT_Int num_params, FT_Parameter* params ); FT_LOCAL( void ) T1_Face_Done( FT_Face face ); FT_LOCAL( FT_Error ) T1_GlyphSlot_Init( FT_GlyphSlot slot ); FT_LOCAL( void ) T1_GlyphSlot_Done( FT_GlyphSlot slot ); FT_LOCAL( FT_Error ) T1_Driver_Init( FT_Module driver ); FT_LOCAL( void ) T1_Driver_Done( FT_Module driver ); FT_END_HEADER #endif /* T1OBJS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1objs.h
C++
gpl-3.0
3,452
/**************************************************************************** * * t1parse.c * * Type 1 parser (body). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * The Type 1 parser is in charge of the following: * * - provide an implementation of a growing sequence of objects called * a `T1_Table' (used to build various tables needed by the loader). * * - opening .pfb and .pfa files to extract their top-level and private * dictionaries. * * - read numbers, arrays & strings from any dictionary. * * See `t1load.c' to see how data is loaded from the font file. * */ #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/psaux.h> #include "t1parse.h" #include "t1errors.h" /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t1parse /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /***** *****/ /***** INPUT STREAM PARSER *****/ /***** *****/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* see Adobe Technical Note 5040.Download_Fonts.pdf */ static FT_Error read_pfb_tag( FT_Stream stream, FT_UShort *atag, FT_ULong *asize ) { FT_Error error; FT_UShort tag; FT_ULong size; *atag = 0; *asize = 0; if ( !FT_READ_USHORT( tag ) ) { if ( tag == 0x8001U || tag == 0x8002U ) { if ( !FT_READ_ULONG_LE( size ) ) *asize = size; } *atag = tag; } return error; } static FT_Error check_type1_format( FT_Stream stream, const char* header_string, size_t header_length ) { FT_Error error; FT_UShort tag; FT_ULong dummy; if ( FT_STREAM_SEEK( 0 ) ) goto Exit; error = read_pfb_tag( stream, &tag, &dummy ); if ( error ) goto Exit; /* We assume that the first segment in a PFB is always encoded as */ /* text. This might be wrong (and the specification doesn't insist */ /* on that), but we have never seen a counterexample. */ if ( tag != 0x8001U && FT_STREAM_SEEK( 0 ) ) goto Exit; if ( !FT_FRAME_ENTER( header_length ) ) { error = FT_Err_Ok; if ( ft_memcmp( stream->cursor, header_string, header_length ) != 0 ) error = FT_THROW( Unknown_File_Format ); FT_FRAME_EXIT(); } Exit: return error; } FT_LOCAL_DEF( FT_Error ) T1_New_Parser( T1_Parser parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ) { FT_Error error; FT_UShort tag; FT_ULong size; psaux->ps_parser_funcs->init( &parser->root, NULL, NULL, memory ); parser->stream = stream; parser->base_len = 0; parser->base_dict = NULL; parser->private_len = 0; parser->private_dict = NULL; parser->in_pfb = 0; parser->in_memory = 0; parser->single_block = 0; /* check the header format */ error = check_type1_format( stream, "%!PS-AdobeFont", 14 ); if ( error ) { if ( FT_ERR_NEQ( error, Unknown_File_Format ) ) goto Exit; error = check_type1_format( stream, "%!FontType", 10 ); if ( error ) { FT_TRACE2(( " not a Type 1 font\n" )); goto Exit; } } /******************************************************************* * * Here a short summary of what is going on: * * When creating a new Type 1 parser, we try to locate and load * the base dictionary if this is possible (i.e., for PFB * files). Otherwise, we load the whole font into memory. * * When `loading' the base dictionary, we only setup pointers * in the case of a memory-based stream. Otherwise, we * allocate and load the base dictionary in it. * * parser->in_pfb is set if we are in a binary (`.pfb') font. * parser->in_memory is set if we have a memory stream. */ /* try to compute the size of the base dictionary; */ /* look for a Postscript binary file tag, i.e., 0x8001 */ if ( FT_STREAM_SEEK( 0L ) ) goto Exit; error = read_pfb_tag( stream, &tag, &size ); if ( error ) goto Exit; if ( tag != 0x8001U ) { /* assume that this is a PFA file for now; an error will */ /* be produced later when more things are checked */ if ( FT_STREAM_SEEK( 0L ) ) goto Exit; size = stream->size; } else parser->in_pfb = 1; /* now, try to load `size' bytes of the `base' dictionary we */ /* found previously */ /* if it is a memory-based resource, set up pointers */ if ( !stream->read ) { parser->base_dict = (FT_Byte*)stream->base + stream->pos; parser->base_len = size; parser->in_memory = 1; /* check that the `size' field is valid */ if ( FT_STREAM_SKIP( size ) ) goto Exit; } else { /* read segment in memory -- this is clumsy, but so does the format */ if ( FT_QALLOC( parser->base_dict, size ) || FT_STREAM_READ( parser->base_dict, size ) ) goto Exit; parser->base_len = size; } parser->root.base = parser->base_dict; parser->root.cursor = parser->base_dict; parser->root.limit = parser->root.cursor + parser->base_len; Exit: if ( error && !parser->in_memory ) FT_FREE( parser->base_dict ); return error; } FT_LOCAL_DEF( void ) T1_Finalize_Parser( T1_Parser parser ) { FT_Memory memory = parser->root.memory; /* always free the private dictionary */ FT_FREE( parser->private_dict ); /* free the base dictionary only when we have a disk stream */ if ( !parser->in_memory ) FT_FREE( parser->base_dict ); parser->root.funcs.done( &parser->root ); } FT_LOCAL_DEF( FT_Error ) T1_Get_Private_Dict( T1_Parser parser, PSAux_Service psaux ) { FT_Stream stream = parser->stream; FT_Memory memory = parser->root.memory; FT_Error error = FT_Err_Ok; FT_ULong size; if ( parser->in_pfb ) { /* in the case of the PFB format, the private dictionary can be */ /* made of several segments. We thus first read the number of */ /* segments to compute the total size of the private dictionary */ /* then re-read them into memory. */ FT_ULong start_pos = FT_STREAM_POS(); FT_UShort tag; parser->private_len = 0; for (;;) { error = read_pfb_tag( stream, &tag, &size ); if ( error ) goto Fail; if ( tag != 0x8002U ) break; parser->private_len += size; if ( FT_STREAM_SKIP( size ) ) goto Fail; } /* Check that we have a private dictionary there */ /* and allocate private dictionary buffer */ if ( parser->private_len == 0 ) { FT_ERROR(( "T1_Get_Private_Dict:" " invalid private dictionary section\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( FT_STREAM_SEEK( start_pos ) || FT_QALLOC( parser->private_dict, parser->private_len ) ) goto Fail; parser->private_len = 0; for (;;) { error = read_pfb_tag( stream, &tag, &size ); if ( error || tag != 0x8002U ) { error = FT_Err_Ok; break; } if ( FT_STREAM_READ( parser->private_dict + parser->private_len, size ) ) goto Fail; parser->private_len += size; } } else { /* We have already `loaded' the whole PFA font file into memory; */ /* if this is a memory resource, allocate a new block to hold */ /* the private dict. Otherwise, simply overwrite into the base */ /* dictionary block in the heap. */ /* first of all, look at the `eexec' keyword */ FT_Byte* cur = parser->base_dict; FT_Byte* limit = cur + parser->base_len; FT_Pointer pos_lf; FT_Bool test_cr; Again: for (;;) { if ( cur[0] == 'e' && cur + 9 < limit ) /* 9 = 5 letters for `eexec' + */ /* whitespace + 4 chars */ { if ( cur[1] == 'e' && cur[2] == 'x' && cur[3] == 'e' && cur[4] == 'c' ) break; } cur++; if ( cur >= limit ) { FT_ERROR(( "T1_Get_Private_Dict:" " could not find `eexec' keyword\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } } /* check whether `eexec' was real -- it could be in a comment */ /* or string (as e.g. in u003043t.gsf from ghostscript) */ parser->root.cursor = parser->base_dict; /* set limit to `eexec' + whitespace + 4 characters */ parser->root.limit = cur + 10; cur = parser->root.cursor; limit = parser->root.limit; while ( cur < limit ) { if ( cur[0] == 'e' && cur + 5 < limit ) { if ( cur[1] == 'e' && cur[2] == 'x' && cur[3] == 'e' && cur[4] == 'c' ) goto Found; } T1_Skip_PS_Token( parser ); if ( parser->root.error ) break; T1_Skip_Spaces ( parser ); cur = parser->root.cursor; } /* we haven't found the correct `eexec'; go back and continue */ /* searching */ cur = limit; limit = parser->base_dict + parser->base_len; if ( cur >= limit ) { FT_ERROR(( "T1_Get_Private_Dict:" " premature end in private dictionary\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } goto Again; /* now determine where to write the _encrypted_ binary private */ /* dictionary. We overwrite the base dictionary for disk-based */ /* resources and allocate a new block otherwise */ Found: parser->root.limit = parser->base_dict + parser->base_len; T1_Skip_PS_Token( parser ); cur = parser->root.cursor; limit = parser->root.limit; /* According to the Type 1 spec, the first cipher byte must not be */ /* an ASCII whitespace character code (blank, tab, carriage return */ /* or line feed). We have seen Type 1 fonts with two line feed */ /* characters... So skip now all whitespace character codes. */ /* */ /* On the other hand, Adobe's Type 1 parser handles fonts just */ /* fine that are violating this limitation, so we add a heuristic */ /* test to stop at \r only if it is not used for EOL. */ pos_lf = ft_memchr( cur, '\n', (size_t)( limit - cur ) ); test_cr = FT_BOOL( !pos_lf || pos_lf > ft_memchr( cur, '\r', (size_t)( limit - cur ) ) ); while ( cur < limit && ( *cur == ' ' || *cur == '\t' || (test_cr && *cur == '\r' ) || *cur == '\n' ) ) cur++; if ( cur >= limit ) { FT_ERROR(( "T1_Get_Private_Dict:" " `eexec' not properly terminated\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } size = parser->base_len - (FT_ULong)( cur - parser->base_dict ); if ( parser->in_memory ) { /* note that we allocate one more byte to put a terminating `0' */ if ( FT_QALLOC( parser->private_dict, size + 1 ) ) goto Fail; parser->private_len = size; } else { parser->single_block = 1; parser->private_dict = parser->base_dict; parser->private_len = size; parser->base_dict = NULL; parser->base_len = 0; } /* now determine whether the private dictionary is encoded in binary */ /* or hexadecimal ASCII format -- decode it accordingly */ /* we need to access the next 4 bytes (after the final whitespace */ /* following the `eexec' keyword); if they all are hexadecimal */ /* digits, then we have a case of ASCII storage */ if ( cur + 3 < limit && ft_isxdigit( cur[0] ) && ft_isxdigit( cur[1] ) && ft_isxdigit( cur[2] ) && ft_isxdigit( cur[3] ) ) { /* ASCII hexadecimal encoding */ FT_ULong len; parser->root.cursor = cur; (void)psaux->ps_parser_funcs->to_bytes( &parser->root, parser->private_dict, parser->private_len, &len, 0 ); parser->private_len = len; /* put a safeguard */ parser->private_dict[len] = '\0'; } else /* binary encoding -- copy the private dict */ FT_MEM_MOVE( parser->private_dict, cur, size ); } /* we now decrypt the encoded binary private dictionary */ psaux->t1_decrypt( parser->private_dict, parser->private_len, 55665U ); if ( parser->private_len < 4 ) { FT_ERROR(( "T1_Get_Private_Dict:" " invalid private dictionary section\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* replace the four random bytes at the beginning with whitespace */ parser->private_dict[0] = ' '; parser->private_dict[1] = ' '; parser->private_dict[2] = ' '; parser->private_dict[3] = ' '; parser->root.base = parser->private_dict; parser->root.cursor = parser->private_dict; parser->root.limit = parser->root.cursor + parser->private_len; Fail: Exit: return error; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1parse.c
C++
gpl-3.0
15,788
/**************************************************************************** * * t1parse.h * * Type 1 parser (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T1PARSE_H_ #define T1PARSE_H_ #include <freetype/internal/t1types.h> #include <freetype/internal/ftstream.h> FT_BEGIN_HEADER /************************************************************************** * * @Struct: * T1_ParserRec * * @Description: * A PS_ParserRec is an object used to parse a Type 1 fonts very * quickly. * * @Fields: * root :: * The root parser. * * stream :: * The current input stream. * * base_dict :: * A pointer to the top-level dictionary. * * base_len :: * The length in bytes of the top dictionary. * * private_dict :: * A pointer to the private dictionary. * * private_len :: * The length in bytes of the private dictionary. * * in_pfb :: * A boolean. Indicates that we are handling a PFB * file. * * in_memory :: * A boolean. Indicates a memory-based stream. * * single_block :: * A boolean. Indicates that the private dictionary * is stored in lieu of the base dictionary. */ typedef struct T1_ParserRec_ { PS_ParserRec root; FT_Stream stream; FT_Byte* base_dict; FT_ULong base_len; FT_Byte* private_dict; FT_ULong private_len; FT_Bool in_pfb; FT_Bool in_memory; FT_Bool single_block; } T1_ParserRec, *T1_Parser; #define T1_Add_Table( p, i, o, l ) (p)->funcs.add( (p), i, o, l ) #define T1_Release_Table( p ) \ do \ { \ if ( (p)->funcs.release ) \ (p)->funcs.release( p ); \ } while ( 0 ) #define T1_Skip_Spaces( p ) (p)->root.funcs.skip_spaces( &(p)->root ) #define T1_Skip_PS_Token( p ) (p)->root.funcs.skip_PS_token( &(p)->root ) #define T1_ToInt( p ) (p)->root.funcs.to_int( &(p)->root ) #define T1_ToFixed( p, t ) (p)->root.funcs.to_fixed( &(p)->root, t ) #define T1_ToCoordArray( p, m, c ) \ (p)->root.funcs.to_coord_array( &(p)->root, m, c ) #define T1_ToFixedArray( p, m, f, t ) \ (p)->root.funcs.to_fixed_array( &(p)->root, m, f, t ) #define T1_ToToken( p, t ) \ (p)->root.funcs.to_token( &(p)->root, t ) #define T1_ToTokenArray( p, t, m, c ) \ (p)->root.funcs.to_token_array( &(p)->root, t, m, c ) #define T1_Load_Field( p, f, o, m, pf ) \ (p)->root.funcs.load_field( &(p)->root, f, o, m, pf ) #define T1_Load_Field_Table( p, f, o, m, pf ) \ (p)->root.funcs.load_field_table( &(p)->root, f, o, m, pf ) FT_LOCAL( FT_Error ) T1_New_Parser( T1_Parser parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ); FT_LOCAL( FT_Error ) T1_Get_Private_Dict( T1_Parser parser, PSAux_Service psaux ); FT_LOCAL( void ) T1_Finalize_Parser( T1_Parser parser ); FT_END_HEADER #endif /* T1PARSE_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1parse.h
C++
gpl-3.0
3,735
/**************************************************************************** * * t1tokens.h * * Type 1 tokenizer (specification). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #undef FT_STRUCTURE #define FT_STRUCTURE PS_FontInfoRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_INFO T1_FIELD_STRING( "version", version, T1_FIELD_DICT_FONTDICT ) T1_FIELD_STRING( "Notice", notice, T1_FIELD_DICT_FONTDICT ) T1_FIELD_STRING( "FullName", full_name, T1_FIELD_DICT_FONTDICT ) T1_FIELD_STRING( "FamilyName", family_name, T1_FIELD_DICT_FONTDICT ) T1_FIELD_STRING( "Weight", weight, T1_FIELD_DICT_FONTDICT ) /* we use pointers to detect modifications made by synthetic fonts */ T1_FIELD_NUM ( "ItalicAngle", italic_angle, T1_FIELD_DICT_FONTDICT ) T1_FIELD_BOOL ( "isFixedPitch", is_fixed_pitch, T1_FIELD_DICT_FONTDICT ) T1_FIELD_NUM ( "UnderlinePosition", underline_position, T1_FIELD_DICT_FONTDICT ) T1_FIELD_NUM ( "UnderlineThickness", underline_thickness, T1_FIELD_DICT_FONTDICT ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_FontExtraRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_EXTRA T1_FIELD_NUM ( "FSType", fs_type, T1_FIELD_DICT_FONTDICT ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_PrivateRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_PRIVATE T1_FIELD_NUM ( "UniqueID", unique_id, T1_FIELD_DICT_FONTDICT | T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM ( "lenIV", lenIV, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM ( "LanguageGroup", language_group, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM ( "password", password, T1_FIELD_DICT_PRIVATE ) T1_FIELD_FIXED_1000( "BlueScale", blue_scale, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM ( "BlueShift", blue_shift, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM ( "BlueFuzz", blue_fuzz, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "BlueValues", blue_values, 14, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "OtherBlues", other_blues, 10, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "FamilyBlues", family_blues, 14, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "FamilyOtherBlues", family_other_blues, 10, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE2( "StdHW", standard_width, 1, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE2( "StdVW", standard_height, 1, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE2( "MinFeature", min_feature, 2, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "StemSnapH", snap_widths, 12, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM_TABLE ( "StemSnapV", snap_heights, 12, T1_FIELD_DICT_PRIVATE ) T1_FIELD_FIXED ( "ExpansionFactor", expansion_factor, T1_FIELD_DICT_PRIVATE ) T1_FIELD_BOOL ( "ForceBold", force_bold, T1_FIELD_DICT_PRIVATE ) #undef FT_STRUCTURE #define FT_STRUCTURE T1_FontRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_DICT T1_FIELD_KEY ( "FontName", font_name, T1_FIELD_DICT_FONTDICT ) T1_FIELD_NUM ( "PaintType", paint_type, T1_FIELD_DICT_FONTDICT ) T1_FIELD_NUM ( "FontType", font_type, T1_FIELD_DICT_FONTDICT ) T1_FIELD_FIXED( "StrokeWidth", stroke_width, T1_FIELD_DICT_FONTDICT ) #undef FT_STRUCTURE #define FT_STRUCTURE FT_BBox #undef T1CODE #define T1CODE T1_FIELD_LOCATION_BBOX T1_FIELD_BBOX( "FontBBox", xMin, T1_FIELD_DICT_FONTDICT ) #ifndef T1_CONFIG_OPTION_NO_MM_SUPPORT #undef FT_STRUCTURE #define FT_STRUCTURE T1_FaceRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FACE T1_FIELD_NUM( "NDV", ndv_idx, T1_FIELD_DICT_PRIVATE ) T1_FIELD_NUM( "CDV", cdv_idx, T1_FIELD_DICT_PRIVATE ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_BlendRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_BLEND T1_FIELD_NUM_TABLE( "DesignVector", default_design_vector, T1_MAX_MM_DESIGNS, T1_FIELD_DICT_FONTDICT ) #endif /* T1_CONFIG_OPTION_NO_MM_SUPPORT */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/t1tokens.h
C++
gpl-3.0
5,083
/**************************************************************************** * * type1.c * * FreeType Type 1 driver component (body only). * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #define FT_MAKE_OPTION_SINGLE_OBJECT #include "t1afm.c" #include "t1driver.c" #include "t1gload.c" #include "t1load.c" #include "t1objs.c" #include "t1parse.c" /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type1/type1.c
C++
gpl-3.0
720
# # FreeType 2 Type42 module definition # # Copyright (C) 2002-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += TYPE42_DRIVER define TYPE42_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, t42_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)type42 $(ECHO_DRIVER_DESC)Type 42 font files with no known extension$(ECHO_DRIVER_DONE) endef # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/module.mk
mk
gpl-3.0
672
# # FreeType 2 Type42 driver configuration rules # # Copyright (C) 2002-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # Type42 driver directory # T42_DIR := $(SRC_DIR)/type42 # compilation flags for the driver # T42_COMPILE := $(CC) $(ANSIFLAGS) \ $I$(subst /,$(COMPILER_SEP),$(T42_DIR)) \ $(INCLUDE_FLAGS) \ $(FT_CFLAGS) # Type42 driver source # T42_DRV_SRC := $(T42_DIR)/t42objs.c \ $(T42_DIR)/t42parse.c \ $(T42_DIR)/t42drivr.c # Type42 driver headers # T42_DRV_H := $(T42_DRV_SRC:%.c=%.h) \ $(T42_DIR)/t42error.h \ $(T42_DIR)/t42types.h # Type42 driver object(s) # # T42_DRV_OBJ_M is used during `multi' builds # T42_DRV_OBJ_S is used during `single' builds # T42_DRV_OBJ_M := $(T42_DRV_SRC:$(T42_DIR)/%.c=$(OBJ_DIR)/%.$O) T42_DRV_OBJ_S := $(OBJ_DIR)/type42.$O # Type42 driver source file for single build # T42_DRV_SRC_S := $(T42_DIR)/type42.c # Type42 driver - single object # $(T42_DRV_OBJ_S): $(T42_DRV_SRC_S) $(T42_DRV_SRC) $(FREETYPE_H) $(T42_DRV_H) $(T42_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(T42_DRV_SRC_S)) # Type42 driver - multiple objects # $(OBJ_DIR)/%.$O: $(T42_DIR)/%.c $(FREETYPE_H) $(T42_DRV_H) $(T42_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(T42_DRV_OBJ_S) DRV_OBJS_M += $(T42_DRV_OBJ_M) # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/rules.mk
mk
gpl-3.0
1,785
/**************************************************************************** * * t42drivr.c * * High-level Type 42 driver interface (body). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This driver implements Type42 fonts as described in the * Technical Note #5012 from Adobe, with these limitations: * * 1) CID Fonts are not currently supported. * 2) Incremental fonts making use of the GlyphDirectory keyword * will be loaded, but the rendering will be using the TrueType * tables. * 3) As for Type1 fonts, CDevProc is not supported. * 4) The Metrics dictionary is not supported. * 5) AFM metrics are not supported. * * In other words, this driver supports Type42 fonts derived from * TrueType fonts in a non-CID manner, as done by usual conversion * programs. * */ #include "t42drivr.h" #include "t42objs.h" #include "t42error.h" #include <freetype/internal/ftdebug.h> #include <freetype/internal/services/svfntfmt.h> #include <freetype/internal/services/svgldict.h> #include <freetype/internal/services/svpostnm.h> #include <freetype/internal/services/svpsinfo.h> #undef FT_COMPONENT #define FT_COMPONENT t42 /* * * GLYPH DICT SERVICE * */ static FT_Error t42_get_glyph_name( T42_Face face, FT_UInt glyph_index, FT_Pointer buffer, FT_UInt buffer_max ) { FT_STRCPYN( buffer, face->type1.glyph_names[glyph_index], buffer_max ); return FT_Err_Ok; } static FT_UInt t42_get_name_index( T42_Face face, const FT_String* glyph_name ) { FT_Int i; for ( i = 0; i < face->type1.num_glyphs; i++ ) { FT_String* gname = face->type1.glyph_names[i]; if ( glyph_name[0] == gname[0] && !ft_strcmp( glyph_name, gname ) ) return (FT_UInt)ft_strtol( (const char *)face->type1.charstrings[i], NULL, 10 ); } return 0; } static const FT_Service_GlyphDictRec t42_service_glyph_dict = { (FT_GlyphDict_GetNameFunc) t42_get_glyph_name, /* get_name */ (FT_GlyphDict_NameIndexFunc)t42_get_name_index /* name_index */ }; /* * * POSTSCRIPT NAME SERVICE * */ static const char* t42_get_ps_font_name( T42_Face face ) { return (const char*)face->type1.font_name; } static const FT_Service_PsFontNameRec t42_service_ps_font_name = { (FT_PsName_GetFunc)t42_get_ps_font_name /* get_ps_font_name */ }; /* * * POSTSCRIPT INFO SERVICE * */ static FT_Error t42_ps_get_font_info( FT_Face face, PS_FontInfoRec* afont_info ) { *afont_info = ((T42_Face)face)->type1.font_info; return FT_Err_Ok; } static FT_Error t42_ps_get_font_extra( FT_Face face, PS_FontExtraRec* afont_extra ) { *afont_extra = ((T42_Face)face)->type1.font_extra; return FT_Err_Ok; } static FT_Int t42_ps_has_glyph_names( FT_Face face ) { FT_UNUSED( face ); return 1; } static const FT_Service_PsInfoRec t42_service_ps_info = { (PS_GetFontInfoFunc) t42_ps_get_font_info, /* ps_get_font_info */ (PS_GetFontExtraFunc) t42_ps_get_font_extra, /* ps_get_font_extra */ (PS_HasGlyphNamesFunc) t42_ps_has_glyph_names, /* ps_has_glyph_names */ /* Type42 fonts don't have a Private dict */ (PS_GetFontPrivateFunc)NULL, /* ps_get_font_private */ /* not implemented */ (PS_GetFontValueFunc) NULL /* ps_get_font_value */ }; /* * * SERVICE LIST * */ static const FT_ServiceDescRec t42_services[] = { { FT_SERVICE_ID_GLYPH_DICT, &t42_service_glyph_dict }, { FT_SERVICE_ID_POSTSCRIPT_FONT_NAME, &t42_service_ps_font_name }, { FT_SERVICE_ID_POSTSCRIPT_INFO, &t42_service_ps_info }, { FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_TYPE_42 }, { NULL, NULL } }; FT_CALLBACK_DEF( FT_Module_Interface ) T42_Get_Interface( FT_Module module, const FT_String* t42_interface ) { FT_UNUSED( module ); return ft_service_list_lookup( t42_services, t42_interface ); } const FT_Driver_ClassRec t42_driver_class = { { FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_SCALABLE | #ifdef TT_USE_BYTECODE_INTERPRETER FT_MODULE_DRIVER_HAS_HINTER, #else 0, #endif sizeof ( T42_DriverRec ), "type42", 0x10000L, 0x20000L, NULL, /* module-specific interface */ T42_Driver_Init, /* FT_Module_Constructor module_init */ T42_Driver_Done, /* FT_Module_Destructor module_done */ T42_Get_Interface, /* FT_Module_Requester get_interface */ }, sizeof ( T42_FaceRec ), sizeof ( T42_SizeRec ), sizeof ( T42_GlyphSlotRec ), T42_Face_Init, /* FT_Face_InitFunc init_face */ T42_Face_Done, /* FT_Face_DoneFunc done_face */ T42_Size_Init, /* FT_Size_InitFunc init_size */ T42_Size_Done, /* FT_Size_DoneFunc done_size */ T42_GlyphSlot_Init, /* FT_Slot_InitFunc init_slot */ T42_GlyphSlot_Done, /* FT_Slot_DoneFunc done_slot */ T42_GlyphSlot_Load, /* FT_Slot_LoadFunc load_glyph */ NULL, /* FT_Face_GetKerningFunc get_kerning */ NULL, /* FT_Face_AttachFunc attach_file */ NULL, /* FT_Face_GetAdvancesFunc get_advances */ T42_Size_Request, /* FT_Size_RequestFunc request_size */ T42_Size_Select /* FT_Size_SelectFunc select_size */ }; /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42drivr.c
C++
gpl-3.0
6,230
/**************************************************************************** * * t42drivr.h * * High-level Type 42 driver interface (specification). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T42DRIVR_H_ #define T42DRIVR_H_ #include <freetype/internal/ftdrv.h> FT_BEGIN_HEADER FT_EXPORT_VAR( const FT_Driver_ClassRec ) t42_driver_class; FT_END_HEADER #endif /* T42DRIVR_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42drivr.h
C++
gpl-3.0
739
/**************************************************************************** * * t42error.h * * Type 42 error codes (specification only). * * Copyright (C) 2002-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This file is used to define the Type 42 error enumeration constants. * */ #ifndef T42ERROR_H_ #define T42ERROR_H_ #include <freetype/ftmoderr.h> #undef FTERRORS_H_ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX T42_Err_ #define FT_ERR_BASE FT_Mod_Err_Type42 #include <freetype/fterrors.h> #endif /* T42ERROR_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42error.h
C++
gpl-3.0
973
/**************************************************************************** * * t42objs.c * * Type 42 objects manager (body). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "t42objs.h" #include "t42parse.h" #include "t42error.h" #include <freetype/internal/ftdebug.h> #include <freetype/ftlist.h> #include <freetype/ttnameid.h> #undef FT_COMPONENT #define FT_COMPONENT t42 static FT_Error T42_Open_Face( T42_Face face ) { T42_LoaderRec loader; T42_Parser parser; T1_Font type1 = &face->type1; FT_Memory memory = face->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; t42_loader_init( &loader, face ); parser = &loader.parser; face->ttf_data = NULL; face->ttf_size = 0; error = t42_parser_init( parser, face->root.stream, memory, psaux); if ( error ) goto Exit; error = t42_parse_dict( face, &loader, parser->base_dict, parser->base_len ); if ( error ) goto Exit; if ( type1->font_type != 42 ) { FT_ERROR(( "T42_Open_Face: cannot handle FontType %d\n", type1->font_type )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* now, propagate the charstrings and glyphnames tables */ /* to the Type1 data */ type1->num_glyphs = loader.num_glyphs; if ( !loader.charstrings.init ) { FT_ERROR(( "T42_Open_Face: no charstrings array in face\n" )); error = FT_THROW( Invalid_File_Format ); } loader.charstrings.init = 0; type1->charstrings_block = loader.charstrings.block; type1->charstrings = loader.charstrings.elements; type1->charstrings_len = loader.charstrings.lengths; /* we copy the glyph names `block' and `elements' fields; */ /* the `lengths' field must be released later */ type1->glyph_names_block = loader.glyph_names.block; type1->glyph_names = (FT_String**)loader.glyph_names.elements; loader.glyph_names.block = NULL; loader.glyph_names.elements = NULL; /* we must now build type1.encoding when we have a custom array */ if ( type1->encoding_type == T1_ENCODING_TYPE_ARRAY ) { FT_Int charcode, idx, min_char, max_char; /* OK, we do the following: for each element in the encoding */ /* table, look up the index of the glyph having the same name */ /* as defined in the CharStrings array. */ /* The index is then stored in type1.encoding.char_index, and */ /* the name in type1.encoding.char_name */ min_char = 0; max_char = 0; charcode = 0; for ( ; charcode < loader.encoding_table.max_elems; charcode++ ) { const FT_String* char_name = (const FT_String*)loader.encoding_table.elements[charcode]; type1->encoding.char_index[charcode] = 0; type1->encoding.char_name [charcode] = ".notdef"; if ( char_name ) for ( idx = 0; idx < type1->num_glyphs; idx++ ) { const FT_String* glyph_name = type1->glyph_names[idx]; if ( ft_strcmp( char_name, glyph_name ) == 0 ) { type1->encoding.char_index[charcode] = (FT_UShort)idx; type1->encoding.char_name [charcode] = glyph_name; /* Change min/max encoded char only if glyph name is */ /* not /.notdef */ if ( ft_strcmp( ".notdef", glyph_name ) != 0 ) { if ( charcode < min_char ) min_char = charcode; if ( charcode >= max_char ) max_char = charcode + 1; } break; } } } type1->encoding.code_first = min_char; type1->encoding.code_last = max_char; type1->encoding.num_chars = loader.num_chars; } Exit: t42_loader_done( &loader ); if ( error ) { FT_FREE(face->ttf_data); face->ttf_size = 0; } return error; } /***************** Driver Functions *************/ FT_LOCAL_DEF( FT_Error ) T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( ( face_index & 0xFFFF ) > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = NULL; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY | FT_OPEN_DRIVER; args.driver = FT_Get_Module( FT_FACE_LIBRARY( face ), "truetype" ); args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; if ( num_params ) { args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); } if ( error ) goto Exit; FT_Done_Size( face->ttf_face->size ); /* Ignore info in FontInfo dictionary and use the info from the */ /* loaded TTF font. The PostScript interpreter also ignores it. */ root->bbox = face->ttf_face->bbox; root->units_per_EM = face->ttf_face->units_per_EM; root->ascender = face->ttf_face->ascender; root->descender = face->ttf_face->descender; root->height = face->ttf_face->height; root->max_advance_width = face->ttf_face->max_advance_width; root->max_advance_height = face->ttf_face->max_advance_height; root->underline_position = (FT_Short)info->underline_position; root->underline_thickness = (FT_Short)info->underline_thickness; /* compute style flags */ root->style_flags = 0; if ( info->italic_angle ) root->style_flags |= FT_STYLE_FLAG_ITALIC; if ( face->ttf_face->style_flags & FT_STYLE_FLAG_BOLD ) root->style_flags |= FT_STYLE_FLAG_BOLD; if ( face->ttf_face->face_flags & FT_FACE_FLAG_VERTICAL ) root->face_flags |= FT_FACE_FLAG_VERTICAL; { if ( psnames ) { FT_CharMapRec charmap; T1_CMap_Classes cmap_classes = psaux->t1_cmap_classes; FT_CMap_Class clazz; charmap.face = root; /* first of all, try to synthesize a Unicode charmap */ charmap.platform_id = TT_PLATFORM_MICROSOFT; charmap.encoding_id = TT_MS_ID_UNICODE_CS; charmap.encoding = FT_ENCODING_UNICODE; error = FT_CMap_New( cmap_classes->unicode, NULL, &charmap, NULL ); if ( error && FT_ERR_NEQ( error, No_Unicode_Glyph_Name ) && FT_ERR_NEQ( error, Unimplemented_Feature ) ) goto Exit; error = FT_Err_Ok; /* now, generate an Adobe Standard encoding when appropriate */ charmap.platform_id = TT_PLATFORM_ADOBE; clazz = NULL; switch ( type1->encoding_type ) { case T1_ENCODING_TYPE_STANDARD: charmap.encoding = FT_ENCODING_ADOBE_STANDARD; charmap.encoding_id = TT_ADOBE_ID_STANDARD; clazz = cmap_classes->standard; break; case T1_ENCODING_TYPE_EXPERT: charmap.encoding = FT_ENCODING_ADOBE_EXPERT; charmap.encoding_id = TT_ADOBE_ID_EXPERT; clazz = cmap_classes->expert; break; case T1_ENCODING_TYPE_ARRAY: charmap.encoding = FT_ENCODING_ADOBE_CUSTOM; charmap.encoding_id = TT_ADOBE_ID_CUSTOM; clazz = cmap_classes->custom; break; case T1_ENCODING_TYPE_ISOLATIN1: charmap.encoding = FT_ENCODING_ADOBE_LATIN_1; charmap.encoding_id = TT_ADOBE_ID_LATIN_1; clazz = cmap_classes->unicode; break; default: ; } if ( clazz ) error = FT_CMap_New( clazz, NULL, &charmap, NULL ); } } Exit: return error; } FT_LOCAL_DEF( void ) T42_Face_Done( FT_Face t42face ) { T42_Face face = (T42_Face)t42face; T1_Font type1; PS_FontInfo info; FT_Memory memory; if ( !face ) return; type1 = &face->type1; info = &type1->font_info; memory = face->root.memory; /* delete internal ttf face prior to freeing face->ttf_data */ if ( face->ttf_face ) FT_Done_Face( face->ttf_face ); /* release font info strings */ FT_FREE( info->version ); FT_FREE( info->notice ); FT_FREE( info->full_name ); FT_FREE( info->family_name ); FT_FREE( info->weight ); /* release top dictionary */ FT_FREE( type1->charstrings_len ); FT_FREE( type1->charstrings ); FT_FREE( type1->glyph_names ); FT_FREE( type1->charstrings_block ); FT_FREE( type1->glyph_names_block ); FT_FREE( type1->encoding.char_index ); FT_FREE( type1->encoding.char_name ); FT_FREE( type1->font_name ); FT_FREE( face->ttf_data ); #if 0 /* release afm data if present */ if ( face->afm_data ) T1_Done_AFM( memory, (T1_AFM*)face->afm_data ); #endif /* release unicode map, if any */ FT_FREE( face->unicode_map.maps ); face->unicode_map.num_maps = 0; face->root.family_name = NULL; face->root.style_name = NULL; } /************************************************************************** * * @Function: * T42_Driver_Init * * @Description: * Initializes a given Type 42 driver object. * * @Input: * driver :: * A handle to the target driver object. * * @Return: * FreeType error code. 0 means success. */ FT_LOCAL_DEF( FT_Error ) T42_Driver_Init( FT_Module module ) /* T42_Driver */ { T42_Driver driver = (T42_Driver)module; FT_Module ttmodule; ttmodule = FT_Get_Module( module->library, "truetype" ); if ( !ttmodule ) { FT_ERROR(( "T42_Driver_Init: cannot access `truetype' module\n" )); return FT_THROW( Missing_Module ); } driver->ttclazz = (FT_Driver_Class)ttmodule->clazz; return FT_Err_Ok; } FT_LOCAL_DEF( void ) T42_Driver_Done( FT_Module module ) { FT_UNUSED( module ); } FT_LOCAL_DEF( FT_Error ) T42_Size_Init( FT_Size size ) /* T42_Size */ { T42_Size t42size = (T42_Size)size; FT_Face face = size->face; T42_Face t42face = (T42_Face)face; FT_Size ttsize; FT_Error error; error = FT_New_Size( t42face->ttf_face, &ttsize ); if ( !error ) t42size->ttsize = ttsize; FT_Activate_Size( ttsize ); return error; } FT_LOCAL_DEF( FT_Error ) T42_Size_Request( FT_Size t42size, /* T42_Size */ FT_Size_Request req ) { T42_Size size = (T42_Size)t42size; T42_Face face = (T42_Face)t42size->face; FT_Error error; FT_Activate_Size( size->ttsize ); error = FT_Request_Size( face->ttf_face, req ); if ( !error ) t42size->metrics = face->ttf_face->size->metrics; return error; } FT_LOCAL_DEF( FT_Error ) T42_Size_Select( FT_Size t42size, /* T42_Size */ FT_ULong strike_index ) { T42_Size size = (T42_Size)t42size; T42_Face face = (T42_Face)t42size->face; FT_Error error; FT_Activate_Size( size->ttsize ); error = FT_Select_Size( face->ttf_face, (FT_Int)strike_index ); if ( !error ) t42size->metrics = face->ttf_face->size->metrics; return error; } FT_LOCAL_DEF( void ) T42_Size_Done( FT_Size t42size ) /* T42_Size */ { T42_Size size = (T42_Size)t42size; FT_Face face = t42size->face; T42_Face t42face = (T42_Face)face; FT_ListNode node; node = FT_List_Find( &t42face->ttf_face->sizes_list, size->ttsize ); if ( node ) { FT_Done_Size( size->ttsize ); size->ttsize = NULL; } } FT_LOCAL_DEF( FT_Error ) T42_GlyphSlot_Init( FT_GlyphSlot t42slot ) /* T42_GlyphSlot */ { T42_GlyphSlot slot = (T42_GlyphSlot)t42slot; FT_Face face = t42slot->face; T42_Face t42face = (T42_Face)face; FT_GlyphSlot ttslot; FT_Memory memory = face->memory; FT_Error error = FT_Err_Ok; if ( !face->glyph ) { /* First glyph slot for this face */ slot->ttslot = t42face->ttf_face->glyph; } else { error = FT_New_GlyphSlot( t42face->ttf_face, &ttslot ); if ( !error ) slot->ttslot = ttslot; } /* share the loader so that the autohinter can see it */ FT_GlyphLoader_Done( slot->ttslot->internal->loader ); FT_FREE( slot->ttslot->internal ); slot->ttslot->internal = t42slot->internal; return error; } FT_LOCAL_DEF( void ) T42_GlyphSlot_Done( FT_GlyphSlot t42slot ) /* T42_GlyphSlot */ { T42_GlyphSlot slot = (T42_GlyphSlot)t42slot; /* do not destroy the inherited internal structure just yet */ slot->ttslot->internal = NULL; FT_Done_GlyphSlot( slot->ttslot ); } static void t42_glyphslot_clear( FT_GlyphSlot slot ) { /* free bitmap if needed */ ft_glyphslot_free_bitmap( slot ); /* clear all public fields in the glyph slot */ FT_ZERO( &slot->metrics ); FT_ZERO( &slot->outline ); FT_ZERO( &slot->bitmap ); slot->bitmap_left = 0; slot->bitmap_top = 0; slot->num_subglyphs = 0; slot->subglyphs = NULL; slot->control_data = NULL; slot->control_len = 0; slot->other = NULL; slot->format = FT_GLYPH_FORMAT_NONE; slot->linearHoriAdvance = 0; slot->linearVertAdvance = 0; } FT_LOCAL_DEF( FT_Error ) T42_GlyphSlot_Load( FT_GlyphSlot glyph, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FT_Error error; T42_GlyphSlot t42slot = (T42_GlyphSlot)glyph; T42_Size t42size = (T42_Size)size; T42_Face t42face = (T42_Face)size->face; FT_Driver_Class ttclazz = ((T42_Driver)glyph->face->driver)->ttclazz; FT_TRACE1(( "T42_GlyphSlot_Load: glyph index %d\n", glyph_index )); /* map T42 glyph index to embedded TTF's glyph index */ glyph_index = (FT_UInt)ft_strtol( (const char *)t42face->type1.charstrings[glyph_index], NULL, 10 ); t42_glyphslot_clear( t42slot->ttslot ); error = ttclazz->load_glyph( t42slot->ttslot, t42size->ttsize, glyph_index, load_flags | FT_LOAD_NO_BITMAP ); if ( !error ) { glyph->metrics = t42slot->ttslot->metrics; glyph->linearHoriAdvance = t42slot->ttslot->linearHoriAdvance; glyph->linearVertAdvance = t42slot->ttslot->linearVertAdvance; glyph->format = t42slot->ttslot->format; glyph->outline = t42slot->ttslot->outline; glyph->bitmap = t42slot->ttslot->bitmap; glyph->bitmap_left = t42slot->ttslot->bitmap_left; glyph->bitmap_top = t42slot->ttslot->bitmap_top; glyph->num_subglyphs = t42slot->ttslot->num_subglyphs; glyph->subglyphs = t42slot->ttslot->subglyphs; glyph->control_data = t42slot->ttslot->control_data; glyph->control_len = t42slot->ttslot->control_len; } return error; } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42objs.c
C++
gpl-3.0
19,224
/**************************************************************************** * * t42objs.h * * Type 42 objects manager (specification). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T42OBJS_H_ #define T42OBJS_H_ #include <freetype/freetype.h> #include <freetype/t1tables.h> #include <freetype/internal/t1types.h> #include "t42types.h" #include <freetype/internal/ftobjs.h> #include <freetype/internal/ftdrv.h> #include <freetype/internal/services/svpscmap.h> #include <freetype/internal/pshints.h> FT_BEGIN_HEADER /* Type42 size */ typedef struct T42_SizeRec_ { FT_SizeRec root; FT_Size ttsize; } T42_SizeRec, *T42_Size; /* Type42 slot */ typedef struct T42_GlyphSlotRec_ { FT_GlyphSlotRec root; FT_GlyphSlot ttslot; } T42_GlyphSlotRec, *T42_GlyphSlot; /* Type 42 driver */ typedef struct T42_DriverRec_ { FT_DriverRec root; FT_Driver_Class ttclazz; } T42_DriverRec, *T42_Driver; /* */ FT_LOCAL( FT_Error ) T42_Face_Init( FT_Stream stream, FT_Face face, FT_Int face_index, FT_Int num_params, FT_Parameter* params ); FT_LOCAL( void ) T42_Face_Done( FT_Face face ); FT_LOCAL( FT_Error ) T42_Size_Init( FT_Size size ); FT_LOCAL( FT_Error ) T42_Size_Request( FT_Size size, FT_Size_Request req ); FT_LOCAL( FT_Error ) T42_Size_Select( FT_Size size, FT_ULong strike_index ); FT_LOCAL( void ) T42_Size_Done( FT_Size size ); FT_LOCAL( FT_Error ) T42_GlyphSlot_Init( FT_GlyphSlot slot ); FT_LOCAL( FT_Error ) T42_GlyphSlot_Load( FT_GlyphSlot glyph, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ); FT_LOCAL( void ) T42_GlyphSlot_Done( FT_GlyphSlot slot ); FT_LOCAL( FT_Error ) T42_Driver_Init( FT_Module module ); FT_LOCAL( void ) T42_Driver_Done( FT_Module module ); /* */ FT_END_HEADER #endif /* T42OBJS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42objs.h
C++
gpl-3.0
2,452
/**************************************************************************** * * t42parse.c * * Type 42 font parser (body). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include "t42parse.h" #include "t42error.h" #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/psaux.h> /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT t42 static void t42_parse_font_matrix( T42_Face face, T42_Loader loader ); static void t42_parse_encoding( T42_Face face, T42_Loader loader ); static void t42_parse_charstrings( T42_Face face, T42_Loader loader ); static void t42_parse_sfnts( T42_Face face, T42_Loader loader ); /* as Type42 fonts have no Private dict, */ /* we set the last argument of T1_FIELD_XXX to 0 */ static const T1_FieldRec t42_keywords[] = { #undef FT_STRUCTURE #define FT_STRUCTURE T1_FontInfo #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_INFO T1_FIELD_STRING( "version", version, 0 ) T1_FIELD_STRING( "Notice", notice, 0 ) T1_FIELD_STRING( "FullName", full_name, 0 ) T1_FIELD_STRING( "FamilyName", family_name, 0 ) T1_FIELD_STRING( "Weight", weight, 0 ) T1_FIELD_NUM ( "ItalicAngle", italic_angle, 0 ) T1_FIELD_BOOL ( "isFixedPitch", is_fixed_pitch, 0 ) T1_FIELD_NUM ( "UnderlinePosition", underline_position, 0 ) T1_FIELD_NUM ( "UnderlineThickness", underline_thickness, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE PS_FontExtraRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_EXTRA T1_FIELD_NUM ( "FSType", fs_type, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE T1_FontRec #undef T1CODE #define T1CODE T1_FIELD_LOCATION_FONT_DICT T1_FIELD_KEY ( "FontName", font_name, 0 ) T1_FIELD_NUM ( "PaintType", paint_type, 0 ) T1_FIELD_NUM ( "FontType", font_type, 0 ) T1_FIELD_FIXED( "StrokeWidth", stroke_width, 0 ) #undef FT_STRUCTURE #define FT_STRUCTURE FT_BBox #undef T1CODE #define T1CODE T1_FIELD_LOCATION_BBOX T1_FIELD_BBOX("FontBBox", xMin, 0 ) T1_FIELD_CALLBACK( "FontMatrix", t42_parse_font_matrix, 0 ) T1_FIELD_CALLBACK( "Encoding", t42_parse_encoding, 0 ) T1_FIELD_CALLBACK( "CharStrings", t42_parse_charstrings, 0 ) T1_FIELD_CALLBACK( "sfnts", t42_parse_sfnts, 0 ) { 0, T1_FIELD_LOCATION_CID_INFO, T1_FIELD_TYPE_NONE, 0, 0, 0, 0, 0, 0 } }; #define T1_Add_Table( p, i, o, l ) (p)->funcs.add( (p), i, o, l ) #define T1_Release_Table( p ) \ do \ { \ if ( (p)->funcs.release ) \ (p)->funcs.release( p ); \ } while ( 0 ) #define T1_Skip_Spaces( p ) (p)->root.funcs.skip_spaces( &(p)->root ) #define T1_Skip_PS_Token( p ) (p)->root.funcs.skip_PS_token( &(p)->root ) #define T1_ToInt( p ) \ (p)->root.funcs.to_int( &(p)->root ) #define T1_ToBytes( p, b, m, n, d ) \ (p)->root.funcs.to_bytes( &(p)->root, b, m, n, d ) #define T1_ToFixedArray( p, m, f, t ) \ (p)->root.funcs.to_fixed_array( &(p)->root, m, f, t ) #define T1_ToToken( p, t ) \ (p)->root.funcs.to_token( &(p)->root, t ) #define T1_Load_Field( p, f, o, m, pf ) \ (p)->root.funcs.load_field( &(p)->root, f, o, m, pf ) #define T1_Load_Field_Table( p, f, o, m, pf ) \ (p)->root.funcs.load_field_table( &(p)->root, f, o, m, pf ) /********************* Parsing Functions ******************/ FT_LOCAL_DEF( FT_Error ) t42_parser_init( T42_Parser parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ) { FT_Error error = FT_Err_Ok; FT_Long size; psaux->ps_parser_funcs->init( &parser->root, NULL, NULL, memory ); parser->stream = stream; parser->base_len = 0; parser->base_dict = NULL; parser->in_memory = 0; /******************************************************************** * * Here a short summary of what is going on: * * When creating a new Type 42 parser, we try to locate and load * the base dictionary, loading the whole font into memory. * * When `loading' the base dictionary, we only set up pointers * in the case of a memory-based stream. Otherwise, we allocate * and load the base dictionary in it. * * parser->in_memory is set if we have a memory stream. */ if ( FT_STREAM_SEEK( 0L ) || FT_FRAME_ENTER( 17 ) ) goto Exit; if ( ft_memcmp( stream->cursor, "%!PS-TrueTypeFont", 17 ) != 0 ) { FT_TRACE2(( " not a Type42 font\n" )); error = FT_THROW( Unknown_File_Format ); } FT_FRAME_EXIT(); if ( error || FT_STREAM_SEEK( 0 ) ) goto Exit; size = (FT_Long)stream->size; /* now, try to load `size' bytes of the `base' dictionary we */ /* found previously */ /* if it is a memory-based resource, set up pointers */ if ( !stream->read ) { parser->base_dict = (FT_Byte*)stream->base + stream->pos; parser->base_len = size; parser->in_memory = 1; /* check that the `size' field is valid */ if ( FT_STREAM_SKIP( size ) ) goto Exit; } else { /* read segment in memory */ if ( FT_QALLOC( parser->base_dict, size ) || FT_STREAM_READ( parser->base_dict, size ) ) goto Exit; parser->base_len = size; } parser->root.base = parser->base_dict; parser->root.cursor = parser->base_dict; parser->root.limit = parser->root.cursor + parser->base_len; Exit: if ( error && !parser->in_memory ) FT_FREE( parser->base_dict ); return error; } FT_LOCAL_DEF( void ) t42_parser_done( T42_Parser parser ) { FT_Memory memory = parser->root.memory; /* free the base dictionary only when we have a disk stream */ if ( !parser->in_memory ) FT_FREE( parser->base_dict ); if ( parser->root.funcs.done ) parser->root.funcs.done( &parser->root ); } static int t42_is_space( FT_Byte c ) { return ( c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\0' ); } static void t42_parse_font_matrix( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Matrix* matrix = &face->type1.font_matrix; FT_Vector* offset = &face->type1.font_offset; FT_Fixed temp[6]; FT_Fixed temp_scale; FT_Int result; result = T1_ToFixedArray( parser, 6, temp, 0 ); if ( result < 6 ) { parser->root.error = FT_THROW( Invalid_File_Format ); return; } temp_scale = FT_ABS( temp[3] ); if ( temp_scale == 0 ) { FT_ERROR(( "t42_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* atypical case */ if ( temp_scale != 0x10000L ) { temp[0] = FT_DivFix( temp[0], temp_scale ); temp[1] = FT_DivFix( temp[1], temp_scale ); temp[2] = FT_DivFix( temp[2], temp_scale ); temp[4] = FT_DivFix( temp[4], temp_scale ); temp[5] = FT_DivFix( temp[5], temp_scale ); temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L; } matrix->xx = temp[0]; matrix->yx = temp[1]; matrix->xy = temp[2]; matrix->yy = temp[3]; if ( !FT_Matrix_Check( matrix ) ) { FT_ERROR(( "t42_parse_font_matrix: invalid font matrix\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* note that the offsets must be expressed in integer font units */ offset->x = temp[4] >> 16; offset->y = temp[5] >> 16; } static void t42_parse_encoding( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Byte* cur; FT_Byte* limit = parser->root.limit; PSAux_Service psaux = (PSAux_Service)face->psaux; T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) { FT_ERROR(( "t42_parse_encoding: out of bounds\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } /* if we have a number or `[', the encoding is an array, */ /* and we must load it now */ if ( ft_isdigit( *cur ) || *cur == '[' ) { T1_Encoding encode = &face->type1.encoding; FT_Int count, n; PS_Table char_table = &loader->encoding_table; FT_Memory memory = parser->root.memory; FT_Error error; FT_Bool only_immediates = 0; /* read the number of entries in the encoding; should be 256 */ if ( *cur == '[' ) { count = 256; only_immediates = 1; parser->root.cursor++; } else count = (FT_Int)T1_ToInt( parser ); /* only composite fonts (which we don't support) */ /* can have larger values */ if ( count > 256 ) { FT_ERROR(( "t42_parse_encoding: invalid encoding array size\n" )); parser->root.error = FT_THROW( Invalid_File_Format ); return; } T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit ) return; /* PostScript happily allows overwriting of encoding arrays */ if ( encode->char_index ) { FT_FREE( encode->char_index ); FT_FREE( encode->char_name ); T1_Release_Table( char_table ); } /* we use a T1_Table to store our charnames */ loader->num_chars = encode->num_chars = count; if ( FT_QNEW_ARRAY( encode->char_index, count ) || FT_QNEW_ARRAY( encode->char_name, count ) || FT_SET_ERROR( psaux->ps_table_funcs->init( char_table, count, memory ) ) ) { parser->root.error = error; return; } /* We need to `zero' out encoding_table.elements */ for ( n = 0; n < count; n++ ) (void)T1_Add_Table( char_table, n, ".notdef", 8 ); /* Now we need to read records of the form */ /* */ /* ... charcode /charname ... */ /* */ /* for each entry in our table. */ /* */ /* We simply look for a number followed by an immediate */ /* name. Note that this ignores correctly the sequence */ /* that is often seen in type42 fonts: */ /* */ /* 0 1 255 { 1 index exch /.notdef put } for dup */ /* */ /* used to clean the encoding array before anything else. */ /* */ /* Alternatively, if the array is directly given as */ /* */ /* /Encoding [ ... ] */ /* */ /* we only read immediates. */ n = 0; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { cur = parser->root.cursor; /* we stop when we encounter `def' or `]' */ if ( *cur == 'd' && cur + 3 < limit ) { if ( cur[1] == 'e' && cur[2] == 'f' && t42_is_space( cur[3] ) ) { FT_TRACE6(( "encoding end\n" )); cur += 3; break; } } if ( *cur == ']' ) { FT_TRACE6(( "encoding end\n" )); cur++; break; } /* check whether we have found an entry */ if ( ft_isdigit( *cur ) || only_immediates ) { FT_Int charcode; if ( only_immediates ) charcode = n; else { charcode = (FT_Int)T1_ToInt( parser ); T1_Skip_Spaces( parser ); /* protect against invalid charcode */ if ( cur == parser->root.cursor ) { parser->root.error = FT_THROW( Unknown_File_Format ); return; } } cur = parser->root.cursor; if ( cur + 2 < limit && *cur == '/' && n < count ) { FT_UInt len; cur++; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) return; if ( parser->root.error ) return; len = (FT_UInt)( parser->root.cursor - cur ); parser->root.error = T1_Add_Table( char_table, charcode, cur, len + 1 ); if ( parser->root.error ) return; char_table->elements[charcode][len] = '\0'; n++; } else if ( only_immediates ) { /* Since the current position is not updated for */ /* immediates-only mode we would get an infinite loop if */ /* we don't do anything here. */ /* */ /* This encoding array is not valid according to the */ /* type42 specification (it might be an encoding for a CID */ /* type42 font, however), so we conclude that this font is */ /* NOT a type42 font. */ parser->root.error = FT_THROW( Unknown_File_Format ); return; } } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; } T1_Skip_Spaces( parser ); } face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY; parser->root.cursor = cur; } /* Otherwise, we should have either `StandardEncoding', */ /* `ExpertEncoding', or `ISOLatin1Encoding' */ else { if ( cur + 17 < limit && ft_strncmp( (const char*)cur, "StandardEncoding", 16 ) == 0 ) face->type1.encoding_type = T1_ENCODING_TYPE_STANDARD; else if ( cur + 15 < limit && ft_strncmp( (const char*)cur, "ExpertEncoding", 14 ) == 0 ) face->type1.encoding_type = T1_ENCODING_TYPE_EXPERT; else if ( cur + 18 < limit && ft_strncmp( (const char*)cur, "ISOLatin1Encoding", 17 ) == 0 ) face->type1.encoding_type = T1_ENCODING_TYPE_ISOLATIN1; else parser->root.error = FT_ERR( Ignore ); } } typedef enum T42_Load_Status_ { BEFORE_START, BEFORE_TABLE_DIR, OTHER_TABLES } T42_Load_Status; static void t42_parse_sfnts( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; FT_Memory memory = parser->root.memory; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Error error; FT_Int num_tables = 0; FT_Long ttf_count; FT_Long ttf_reserved; FT_ULong n, string_size, old_string_size, real_size; FT_Byte* string_buf = NULL; FT_Bool allocated = 0; T42_Load_Status status; /** There should only be one sfnts array, but free any previous. */ FT_FREE( face->ttf_data ); face->ttf_size = 0; /* The format is */ /* */ /* /sfnts [ <hexstring> <hexstring> ... ] def */ /* */ /* or */ /* */ /* /sfnts [ */ /* <num_bin_bytes> RD <binary data> */ /* <num_bin_bytes> RD <binary data> */ /* ... */ /* ] def */ /* */ /* with exactly one space after the `RD' token. */ T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit || *parser->root.cursor++ != '[' ) { FT_ERROR(( "t42_parse_sfnts: can't find begin of sfnts vector\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_Spaces( parser ); status = BEFORE_START; string_size = 0; old_string_size = 0; ttf_count = 0; ttf_reserved = 12; if ( FT_QALLOC( face->ttf_data, ttf_reserved ) ) goto Fail; FT_TRACE2(( "\n" )); FT_TRACE2(( "t42_parse_sfnts:\n" )); while ( parser->root.cursor < limit ) { FT_ULong size; cur = parser->root.cursor; if ( *cur == ']' ) { parser->root.cursor++; face->ttf_size = ttf_count; goto Exit; } else if ( *cur == '<' ) { if ( string_buf && !allocated ) { FT_ERROR(( "t42_parse_sfnts: " "can't handle mixed binary and hex strings\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; /* don't include delimiters */ string_size = (FT_ULong)( ( parser->root.cursor - cur - 2 + 1 ) / 2 ); if ( !string_size ) { FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( FT_QREALLOC( string_buf, old_string_size, string_size ) ) goto Fail; allocated = 1; parser->root.cursor = cur; (void)T1_ToBytes( parser, string_buf, string_size, &real_size, 1 ); old_string_size = string_size; string_size = real_size; } else if ( ft_isdigit( *cur ) ) { FT_Long tmp; if ( allocated ) { FT_ERROR(( "t42_parse_sfnts: " "can't handle mixed binary and hex strings\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } tmp = T1_ToInt( parser ); if ( tmp < 0 ) { FT_ERROR(( "t42_parse_sfnts: invalid string size\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } else string_size = (FT_ULong)tmp; T1_Skip_PS_Token( parser ); /* `RD' */ if ( parser->root.error ) return; string_buf = parser->root.cursor + 1; /* one space after `RD' */ if ( (FT_ULong)( limit - parser->root.cursor ) <= string_size ) { FT_ERROR(( "t42_parse_sfnts: too much binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } else parser->root.cursor += string_size + 1; } if ( !string_buf ) { FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* A string can have a trailing zero (odd) byte for padding. */ /* Ignore it. */ if ( ( string_size & 1 ) && string_buf[string_size - 1] == 0 ) string_size--; if ( !string_size ) { FT_ERROR(( "t42_parse_sfnts: invalid string\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } FT_TRACE2(( " PS string size %5lu bytes, offset 0x%08lx (%lu)\n", string_size, ttf_count, ttf_count )); /* The whole TTF is now loaded into `string_buf'. We are */ /* checking its contents while copying it to `ttf_data'. */ size = (FT_ULong)( limit - parser->root.cursor ); for ( n = 0; n < string_size; n++ ) { switch ( status ) { case BEFORE_START: /* load offset table, 12 bytes */ if ( ttf_count < 12 ) { face->ttf_data[ttf_count++] = string_buf[n]; continue; } else { FT_Long ttf_reserved_prev = ttf_reserved; num_tables = 16 * face->ttf_data[4] + face->ttf_data[5]; status = BEFORE_TABLE_DIR; ttf_reserved = 12 + 16 * num_tables; FT_TRACE2(( " SFNT directory contains %d tables\n", num_tables )); if ( (FT_Long)size < ttf_reserved ) { FT_ERROR(( "t42_parse_sfnts: invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( FT_QREALLOC( face->ttf_data, ttf_reserved_prev, ttf_reserved ) ) goto Fail; } /* fall through */ case BEFORE_TABLE_DIR: /* the offset table is read; read the table directory */ if ( ttf_count < ttf_reserved ) { face->ttf_data[ttf_count++] = string_buf[n]; continue; } else { int i; FT_ULong len; FT_Long ttf_reserved_prev = ttf_reserved; FT_TRACE2(( "\n" )); FT_TRACE2(( " table length\n" )); FT_TRACE2(( " ------------------------------\n" )); for ( i = 0; i < num_tables; i++ ) { FT_Byte* p = face->ttf_data + 12 + 16 * i + 12; len = FT_PEEK_ULONG( p ); FT_TRACE2(( " %4i 0x%08lx (%lu)\n", i, len, len )); if ( len > size || ttf_reserved > (FT_Long)( size - len ) ) { FT_ERROR(( "t42_parse_sfnts:" " invalid data in sfnts array\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* Pad to a 4-byte boundary length */ ttf_reserved += (FT_Long)( ( len + 3 ) & ~3U ); } ttf_reserved += 1; status = OTHER_TABLES; FT_TRACE2(( "\n" )); FT_TRACE2(( " allocating %ld bytes\n", ttf_reserved )); FT_TRACE2(( "\n" )); if ( FT_QREALLOC( face->ttf_data, ttf_reserved_prev, ttf_reserved ) ) goto Fail; } /* fall through */ case OTHER_TABLES: /* all other tables are just copied */ if ( ttf_count >= ttf_reserved ) { FT_ERROR(( "t42_parse_sfnts: too much binary data\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } face->ttf_data[ttf_count++] = string_buf[n]; } } T1_Skip_Spaces( parser ); } /* if control reaches this point, the format was not valid */ error = FT_THROW( Invalid_File_Format ); Fail: parser->root.error = error; Exit: if ( parser->root.error ) { FT_FREE( face->ttf_data ); face->ttf_size = 0; } if ( allocated ) FT_FREE( string_buf ); } static void t42_parse_charstrings( T42_Face face, T42_Loader loader ) { T42_Parser parser = &loader->parser; PS_Table code_table = &loader->charstrings; PS_Table name_table = &loader->glyph_names; PS_Table swap_table = &loader->swap_table; FT_Memory memory = parser->root.memory; FT_Error error; PSAux_Service psaux = (PSAux_Service)face->psaux; FT_Byte* cur; FT_Byte* limit = parser->root.limit; FT_Int n; FT_Int notdef_index = 0; FT_Byte notdef_found = 0; T1_Skip_Spaces( parser ); if ( parser->root.cursor >= limit ) { FT_ERROR(( "t42_parse_charstrings: out of bounds\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( ft_isdigit( *parser->root.cursor ) ) { loader->num_glyphs = T1_ToInt( parser ); if ( parser->root.error ) return; if ( loader->num_glyphs < 0 ) { FT_ERROR(( "t42_parse_encoding: invalid number of glyphs\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* we certainly need more than 4 bytes per glyph */ if ( loader->num_glyphs > ( limit - parser->root.cursor ) >> 2 ) { FT_TRACE0(( "t42_parse_charstrings: adjusting number of glyphs" " (from %d to %ld)\n", loader->num_glyphs, ( limit - parser->root.cursor ) >> 2 )); loader->num_glyphs = ( limit - parser->root.cursor ) >> 2; } } else if ( *parser->root.cursor == '<' ) { /* We have `<< ... >>'. Count the number of `/' in the dictionary */ /* to get its size. */ FT_Int count = 0; T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; T1_Skip_Spaces( parser ); cur = parser->root.cursor; while ( parser->root.cursor < limit ) { if ( *parser->root.cursor == '/' ) count++; else if ( *parser->root.cursor == '>' ) { loader->num_glyphs = count; parser->root.cursor = cur; /* rewind */ break; } T1_Skip_PS_Token( parser ); if ( parser->root.error ) return; T1_Skip_Spaces( parser ); } } else { FT_ERROR(( "t42_parse_charstrings: invalid token\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( parser->root.cursor >= limit ) { FT_ERROR(( "t42_parse_charstrings: out of bounds\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* initialize tables */ /* contrary to Type1, we disallow multiple CharStrings arrays */ if ( swap_table->init ) { FT_ERROR(( "t42_parse_charstrings:" " only one CharStrings array allowed\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } error = psaux->ps_table_funcs->init( code_table, loader->num_glyphs, memory ); if ( error ) goto Fail; error = psaux->ps_table_funcs->init( name_table, loader->num_glyphs, memory ); if ( error ) goto Fail; /* Initialize table for swapping index notdef_index and */ /* index 0 names and codes (if necessary). */ error = psaux->ps_table_funcs->init( swap_table, 4, memory ); if ( error ) goto Fail; n = 0; for (;;) { /* We support two formats. */ /* */ /* `/glyphname' + index [+ `def'] */ /* `(glyphname)' [+ `cvn'] + index [+ `def'] */ /* */ /* The latter format gets created by the */ /* LilyPond typesetting program. */ T1_Skip_Spaces( parser ); cur = parser->root.cursor; if ( cur >= limit ) break; /* We stop when we find an `end' keyword or '>' */ if ( *cur == 'e' && cur + 3 < limit && cur[1] == 'n' && cur[2] == 'd' && t42_is_space( cur[3] ) ) break; if ( *cur == '>' ) break; T1_Skip_PS_Token( parser ); if ( parser->root.cursor >= limit ) { FT_ERROR(( "t42_parse_charstrings: out of bounds\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } if ( parser->root.error ) return; if ( *cur == '/' || *cur == '(' ) { FT_UInt len; FT_Bool have_literal = FT_BOOL( *cur == '(' ); if ( cur + ( have_literal ? 3 : 2 ) >= limit ) { FT_ERROR(( "t42_parse_charstrings: out of bounds\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } cur++; /* skip `/' */ len = (FT_UInt)( parser->root.cursor - cur ); if ( have_literal ) len--; error = T1_Add_Table( name_table, n, cur, len + 1 ); if ( error ) goto Fail; /* add a trailing zero to the name table */ name_table->elements[n][len] = '\0'; /* record index of /.notdef */ if ( *cur == '.' && ft_strcmp( ".notdef", (const char*)(name_table->elements[n]) ) == 0 ) { notdef_index = n; notdef_found = 1; } T1_Skip_Spaces( parser ); if ( have_literal ) T1_Skip_PS_Token( parser ); cur = parser->root.cursor; (void)T1_ToInt( parser ); if ( parser->root.cursor >= limit ) { FT_ERROR(( "t42_parse_charstrings: out of bounds\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } len = (FT_UInt)( parser->root.cursor - cur ); error = T1_Add_Table( code_table, n, cur, len + 1 ); if ( error ) goto Fail; code_table->elements[n][len] = '\0'; n++; if ( n >= loader->num_glyphs ) break; } } loader->num_glyphs = n; if ( !notdef_found ) { FT_ERROR(( "t42_parse_charstrings: no /.notdef glyph\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* if /.notdef does not occupy index 0, do our magic. */ if ( ft_strcmp( ".notdef", (const char*)name_table->elements[0] ) ) { /* Swap glyph in index 0 with /.notdef glyph. First, add index 0 */ /* name and code entries to swap_table. Then place notdef_index */ /* name and code entries into swap_table. Then swap name and code */ /* entries at indices notdef_index and 0 using values stored in */ /* swap_table. */ /* Index 0 name */ error = T1_Add_Table( swap_table, 0, name_table->elements[0], name_table->lengths [0] ); if ( error ) goto Fail; /* Index 0 code */ error = T1_Add_Table( swap_table, 1, code_table->elements[0], code_table->lengths [0] ); if ( error ) goto Fail; /* Index notdef_index name */ error = T1_Add_Table( swap_table, 2, name_table->elements[notdef_index], name_table->lengths [notdef_index] ); if ( error ) goto Fail; /* Index notdef_index code */ error = T1_Add_Table( swap_table, 3, code_table->elements[notdef_index], code_table->lengths [notdef_index] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, notdef_index, swap_table->elements[0], swap_table->lengths [0] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, notdef_index, swap_table->elements[1], swap_table->lengths [1] ); if ( error ) goto Fail; error = T1_Add_Table( name_table, 0, swap_table->elements[2], swap_table->lengths [2] ); if ( error ) goto Fail; error = T1_Add_Table( code_table, 0, swap_table->elements[3], swap_table->lengths [3] ); if ( error ) goto Fail; } return; Fail: parser->root.error = error; } static FT_Error t42_load_keyword( T42_Face face, T42_Loader loader, T1_Field field ) { FT_Error error; void* dummy_object; void** objects; FT_UInt max_objects = 0; /* if the keyword has a dedicated callback, call it */ if ( field->type == T1_FIELD_TYPE_CALLBACK ) { field->reader( (FT_Face)face, loader ); error = loader->parser.root.error; goto Exit; } /* now the keyword is either a simple field or a table of fields; */ /* we are now going to take care of it */ switch ( field->location ) { case T1_FIELD_LOCATION_FONT_INFO: dummy_object = &face->type1.font_info; break; case T1_FIELD_LOCATION_FONT_EXTRA: dummy_object = &face->type1.font_extra; break; case T1_FIELD_LOCATION_BBOX: dummy_object = &face->type1.font_bbox; break; default: dummy_object = &face->type1; } objects = &dummy_object; if ( field->type == T1_FIELD_TYPE_INTEGER_ARRAY || field->type == T1_FIELD_TYPE_FIXED_ARRAY ) error = T1_Load_Field_Table( &loader->parser, field, objects, max_objects, 0 ); else error = T1_Load_Field( &loader->parser, field, objects, max_objects, 0 ); Exit: return error; } FT_LOCAL_DEF( FT_Error ) t42_parse_dict( T42_Face face, T42_Loader loader, FT_Byte* base, FT_Long size ) { T42_Parser parser = &loader->parser; FT_Byte* limit; FT_Int n_keywords = (FT_Int)( sizeof ( t42_keywords ) / sizeof ( t42_keywords[0] ) ); parser->root.cursor = base; parser->root.limit = base + size; parser->root.error = FT_Err_Ok; limit = parser->root.limit; T1_Skip_Spaces( parser ); while ( parser->root.cursor < limit ) { FT_Byte* cur; cur = parser->root.cursor; /* look for `FontDirectory' which causes problems for some fonts */ if ( *cur == 'F' && cur + 25 < limit && ft_strncmp( (char*)cur, "FontDirectory", 13 ) == 0 ) { FT_Byte* cur2; /* skip the `FontDirectory' keyword */ T1_Skip_PS_Token( parser ); T1_Skip_Spaces ( parser ); cur = cur2 = parser->root.cursor; /* look up the `known' keyword */ while ( cur < limit ) { if ( *cur == 'k' && cur + 5 < limit && ft_strncmp( (char*)cur, "known", 5 ) == 0 ) break; T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; T1_Skip_Spaces ( parser ); cur = parser->root.cursor; } if ( cur < limit ) { T1_TokenRec token; /* skip the `known' keyword and the token following it */ T1_Skip_PS_Token( parser ); T1_ToToken( parser, &token ); /* if the last token was an array, skip it! */ if ( token.type == T1_TOKEN_TYPE_ARRAY ) cur2 = parser->root.cursor; } parser->root.cursor = cur2; } /* look for immediates */ else if ( *cur == '/' && cur + 2 < limit ) { FT_UInt len; cur++; parser->root.cursor = cur; T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; len = (FT_UInt)( parser->root.cursor - cur ); if ( len > 0 && len < 22 && parser->root.cursor < limit ) { int i; /* now compare the immediate name to the keyword table */ /* loop through all known keywords */ for ( i = 0; i < n_keywords; i++ ) { T1_Field keyword = (T1_Field)&t42_keywords[i]; FT_Byte *name = (FT_Byte*)keyword->ident; if ( !name ) continue; if ( cur[0] == name[0] && len == ft_strlen( (const char *)name ) && ft_memcmp( cur, name, len ) == 0 ) { /* we found it -- run the parsing callback! */ parser->root.error = t42_load_keyword( face, loader, keyword ); if ( parser->root.error ) return parser->root.error; break; } } } } else { T1_Skip_PS_Token( parser ); if ( parser->root.error ) goto Exit; } T1_Skip_Spaces( parser ); } Exit: return parser->root.error; } FT_LOCAL_DEF( void ) t42_loader_init( T42_Loader loader, T42_Face face ) { FT_UNUSED( face ); FT_ZERO( loader ); loader->num_glyphs = 0; loader->num_chars = 0; /* initialize the tables -- simply set their `init' field to 0 */ loader->encoding_table.init = 0; loader->charstrings.init = 0; loader->glyph_names.init = 0; } FT_LOCAL_DEF( void ) t42_loader_done( T42_Loader loader ) { T42_Parser parser = &loader->parser; /* finalize tables */ T1_Release_Table( &loader->encoding_table ); T1_Release_Table( &loader->charstrings ); T1_Release_Table( &loader->glyph_names ); T1_Release_Table( &loader->swap_table ); /* finalize parser */ t42_parser_done( parser ); } /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42parse.c
C++
gpl-3.0
39,575
/**************************************************************************** * * t42parse.h * * Type 42 font parser (specification). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T42PARSE_H_ #define T42PARSE_H_ #include "t42objs.h" #include <freetype/internal/psaux.h> FT_BEGIN_HEADER typedef struct T42_ParserRec_ { PS_ParserRec root; FT_Stream stream; FT_Byte* base_dict; FT_Long base_len; FT_Bool in_memory; } T42_ParserRec, *T42_Parser; typedef struct T42_Loader_ { T42_ParserRec parser; /* parser used to read the stream */ FT_Int num_chars; /* number of characters in encoding */ PS_TableRec encoding_table; /* PS_Table used to store the */ /* encoding character names */ FT_Int num_glyphs; PS_TableRec glyph_names; PS_TableRec charstrings; PS_TableRec swap_table; /* For moving .notdef glyph to index 0. */ } T42_LoaderRec, *T42_Loader; FT_LOCAL( FT_Error ) t42_parser_init( T42_Parser parser, FT_Stream stream, FT_Memory memory, PSAux_Service psaux ); FT_LOCAL( void ) t42_parser_done( T42_Parser parser ); FT_LOCAL( FT_Error ) t42_parse_dict( T42_Face face, T42_Loader loader, FT_Byte* base, FT_Long size ); FT_LOCAL( void ) t42_loader_init( T42_Loader loader, T42_Face face ); FT_LOCAL( void ) t42_loader_done( T42_Loader loader ); /* */ FT_END_HEADER #endif /* T42PARSE_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42parse.h
C++
gpl-3.0
2,029
/**************************************************************************** * * t42types.h * * Type 42 font data types (specification only). * * Copyright (C) 2002-2022 by * Roberto Alameda. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef T42TYPES_H_ #define T42TYPES_H_ #include <freetype/freetype.h> #include <freetype/t1tables.h> #include <freetype/internal/t1types.h> #include <freetype/internal/pshints.h> FT_BEGIN_HEADER typedef struct T42_FaceRec_ { FT_FaceRec root; T1_FontRec type1; const void* psnames; const void* psaux; #if 0 const void* afm_data; #endif FT_Byte* ttf_data; FT_Long ttf_size; FT_Face ttf_face; FT_CharMapRec charmaprecs[2]; FT_CharMap charmaps[2]; PS_UnicodesRec unicode_map; } T42_FaceRec, *T42_Face; FT_END_HEADER #endif /* T42TYPES_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/t42types.h
C++
gpl-3.0
1,181
/**************************************************************************** * * type42.c * * FreeType Type 42 driver component. * * Copyright (C) 2002-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #define FT_MAKE_OPTION_SINGLE_OBJECT #include "t42drivr.c" #include "t42objs.c" #include "t42parse.c" /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/type42/type42.c
C++
gpl-3.0
652
/**************************************************************************** * * fnterrs.h * * Win FNT/FON error codes (specification only). * * Copyright (C) 2001-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ /************************************************************************** * * This file is used to define the Windows FNT/FON error enumeration * constants. * */ #ifndef FNTERRS_H_ #define FNTERRS_H_ #include <freetype/ftmoderr.h> #undef FTERRORS_H_ #undef FT_ERR_PREFIX #define FT_ERR_PREFIX FNT_Err_ #define FT_ERR_BASE FT_Mod_Err_Winfonts #include <freetype/fterrors.h> #endif /* FNTERRS_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/winfonts/fnterrs.h
C++
gpl-3.0
988
# # FreeType 2 Windows FNT/FON module definition # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. FTMODULE_H_COMMANDS += WINDOWS_DRIVER define WINDOWS_DRIVER $(OPEN_DRIVER) FT_Driver_ClassRec, winfnt_driver_class $(CLOSE_DRIVER) $(ECHO_DRIVER)winfnt $(ECHO_DRIVER_DESC)Windows bitmap fonts with extension *.fnt or *.fon$(ECHO_DRIVER_DONE) endef # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/winfonts/module.mk
mk
gpl-3.0
694
# # FreeType 2 Windows FNT/FON driver configuration rules # # Copyright (C) 1996-2022 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. # Windows driver directory # FNT_DIR := $(SRC_DIR)/winfonts FNT_COMPILE := $(CC) $(ANSIFLAGS) \ $I$(subst /,$(COMPILER_SEP),$(FNT_DIR)) \ $(INCLUDE_FLAGS) \ $(FT_CFLAGS) # Windows driver sources (i.e., C files) # FNT_DRV_SRC := $(FNT_DIR)/winfnt.c # Windows driver headers # FNT_DRV_H := $(FNT_DRV_SRC:%.c=%.h) \ $(FNT_DIR)/fnterrs.h # Windows driver object(s) # # FNT_DRV_OBJ_M is used during `multi' builds # FNT_DRV_OBJ_S is used during `single' builds # FNT_DRV_OBJ_M := $(FNT_DRV_SRC:$(FNT_DIR)/%.c=$(OBJ_DIR)/%.$O) FNT_DRV_OBJ_S := $(OBJ_DIR)/winfnt.$O # Windows driver source file for single build # FNT_DRV_SRC_S := $(FNT_DIR)/winfnt.c # Windows driver - single object # $(FNT_DRV_OBJ_S): $(FNT_DRV_SRC_S) $(FNT_DRV_SRC) $(FREETYPE_H) $(FNT_DRV_H) $(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $(FNT_DRV_SRC_S)) # Windows driver - multiple objects # $(OBJ_DIR)/%.$O: $(FNT_DIR)/%.c $(FREETYPE_H) $(FNT_DRV_H) $(FNT_COMPILE) $T$(subst /,$(COMPILER_SEP),$@ $<) # update main driver object lists # DRV_OBJS_S += $(FNT_DRV_OBJ_S) DRV_OBJS_M += $(FNT_DRV_OBJ_M) # EOF
whupdup/frame
real/third_party/freetype-2.12.0/src/winfonts/rules.mk
mk
gpl-3.0
1,664
/**************************************************************************** * * winfnt.c * * FreeType font driver for Windows FNT/FON files * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * Copyright 2003 Huw D M Davies for Codeweavers * Copyright 2007 Dmitry Timoshkov for Codeweavers * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #include <freetype/ftwinfnt.h> #include <freetype/internal/ftdebug.h> #include <freetype/internal/ftstream.h> #include <freetype/internal/ftobjs.h> #include <freetype/ttnameid.h> #include "winfnt.h" #include "fnterrs.h" #include <freetype/internal/services/svwinfnt.h> #include <freetype/internal/services/svfntfmt.h> /************************************************************************** * * The macro FT_COMPONENT is used in trace mode. It is an implicit * parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log * messages during execution. */ #undef FT_COMPONENT #define FT_COMPONENT winfnt static const FT_Frame_Field winmz_header_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinMZ_HeaderRec FT_FRAME_START( 64 ), FT_FRAME_USHORT_LE ( magic ), FT_FRAME_SKIP_BYTES( 29 * 2 ), FT_FRAME_ULONG_LE ( lfanew ), FT_FRAME_END }; static const FT_Frame_Field winne_header_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinNE_HeaderRec FT_FRAME_START( 40 ), FT_FRAME_USHORT_LE ( magic ), FT_FRAME_SKIP_BYTES( 34 ), FT_FRAME_USHORT_LE ( resource_tab_offset ), FT_FRAME_USHORT_LE ( rname_tab_offset ), FT_FRAME_END }; static const FT_Frame_Field winpe32_header_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinPE32_HeaderRec FT_FRAME_START( 248 ), FT_FRAME_ULONG_LE ( magic ), /* PE00 */ FT_FRAME_USHORT_LE ( machine ), /* 0x014C - i386 */ FT_FRAME_USHORT_LE ( number_of_sections ), FT_FRAME_SKIP_BYTES( 12 ), FT_FRAME_USHORT_LE ( size_of_optional_header ), FT_FRAME_SKIP_BYTES( 2 ), FT_FRAME_USHORT_LE ( magic32 ), /* 0x10B */ FT_FRAME_SKIP_BYTES( 110 ), FT_FRAME_ULONG_LE ( rsrc_virtual_address ), FT_FRAME_ULONG_LE ( rsrc_size ), FT_FRAME_SKIP_BYTES( 104 ), FT_FRAME_END }; static const FT_Frame_Field winpe32_section_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinPE32_SectionRec FT_FRAME_START( 40 ), FT_FRAME_BYTES ( name, 8 ), FT_FRAME_SKIP_BYTES( 4 ), FT_FRAME_ULONG_LE ( virtual_address ), FT_FRAME_ULONG_LE ( size_of_raw_data ), FT_FRAME_ULONG_LE ( pointer_to_raw_data ), FT_FRAME_SKIP_BYTES( 16 ), FT_FRAME_END }; static const FT_Frame_Field winpe_rsrc_dir_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinPE_RsrcDirRec FT_FRAME_START( 16 ), FT_FRAME_ULONG_LE ( characteristics ), FT_FRAME_ULONG_LE ( time_date_stamp ), FT_FRAME_USHORT_LE( major_version ), FT_FRAME_USHORT_LE( minor_version ), FT_FRAME_USHORT_LE( number_of_named_entries ), FT_FRAME_USHORT_LE( number_of_id_entries ), FT_FRAME_END }; static const FT_Frame_Field winpe_rsrc_dir_entry_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinPE_RsrcDirEntryRec FT_FRAME_START( 8 ), FT_FRAME_ULONG_LE( name ), FT_FRAME_ULONG_LE( offset ), FT_FRAME_END }; static const FT_Frame_Field winpe_rsrc_data_entry_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE WinPE_RsrcDataEntryRec FT_FRAME_START( 16 ), FT_FRAME_ULONG_LE( offset_to_data ), FT_FRAME_ULONG_LE( size ), FT_FRAME_ULONG_LE( code_page ), FT_FRAME_ULONG_LE( reserved ), FT_FRAME_END }; static const FT_Frame_Field winfnt_header_fields[] = { #undef FT_STRUCTURE #define FT_STRUCTURE FT_WinFNT_HeaderRec FT_FRAME_START( 148 ), FT_FRAME_USHORT_LE( version ), FT_FRAME_ULONG_LE ( file_size ), FT_FRAME_BYTES ( copyright, 60 ), FT_FRAME_USHORT_LE( file_type ), FT_FRAME_USHORT_LE( nominal_point_size ), FT_FRAME_USHORT_LE( vertical_resolution ), FT_FRAME_USHORT_LE( horizontal_resolution ), FT_FRAME_USHORT_LE( ascent ), FT_FRAME_USHORT_LE( internal_leading ), FT_FRAME_USHORT_LE( external_leading ), FT_FRAME_BYTE ( italic ), FT_FRAME_BYTE ( underline ), FT_FRAME_BYTE ( strike_out ), FT_FRAME_USHORT_LE( weight ), FT_FRAME_BYTE ( charset ), FT_FRAME_USHORT_LE( pixel_width ), FT_FRAME_USHORT_LE( pixel_height ), FT_FRAME_BYTE ( pitch_and_family ), FT_FRAME_USHORT_LE( avg_width ), FT_FRAME_USHORT_LE( max_width ), FT_FRAME_BYTE ( first_char ), FT_FRAME_BYTE ( last_char ), FT_FRAME_BYTE ( default_char ), FT_FRAME_BYTE ( break_char ), FT_FRAME_USHORT_LE( bytes_per_row ), FT_FRAME_ULONG_LE ( device_offset ), FT_FRAME_ULONG_LE ( face_name_offset ), FT_FRAME_ULONG_LE ( bits_pointer ), FT_FRAME_ULONG_LE ( bits_offset ), FT_FRAME_BYTE ( reserved ), FT_FRAME_ULONG_LE ( flags ), FT_FRAME_USHORT_LE( A_space ), FT_FRAME_USHORT_LE( B_space ), FT_FRAME_USHORT_LE( C_space ), FT_FRAME_ULONG_LE ( color_table_offset ), FT_FRAME_BYTES ( reserved1, 16 ), FT_FRAME_END }; static void fnt_font_done( FNT_Face face ) { FT_Memory memory = FT_FACE( face )->memory; FT_Stream stream = FT_FACE( face )->stream; FNT_Font font = face->font; if ( !font ) return; if ( font->fnt_frame ) FT_FRAME_RELEASE( font->fnt_frame ); FT_FREE( font->family_name ); FT_FREE( font ); face->font = NULL; } static FT_Error fnt_font_load( FNT_Font font, FT_Stream stream ) { FT_Error error; FT_WinFNT_Header header = &font->header; FT_Bool new_format; FT_UInt size; /* first of all, read the FNT header */ if ( FT_STREAM_SEEK( font->offset ) || FT_STREAM_READ_FIELDS( winfnt_header_fields, header ) ) { FT_TRACE2(( " not a Windows FNT file\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* check header */ if ( header->version != 0x200 && header->version != 0x300 ) { FT_TRACE2(( " not a Windows FNT file\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } new_format = FT_BOOL( font->header.version == 0x300 ); size = new_format ? 148 : 118; if ( header->file_size < size ) { FT_TRACE2(( " not a Windows FNT file\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* Version 2 doesn't have these fields */ if ( header->version == 0x200 ) { header->flags = 0; header->A_space = 0; header->B_space = 0; header->C_space = 0; header->color_table_offset = 0; } if ( header->file_type & 1 ) { FT_TRACE2(( "[can't handle vector FNT fonts]\n" )); error = FT_THROW( Unknown_File_Format ); goto Exit; } /* this is a FNT file/table; extract its frame */ if ( FT_STREAM_SEEK( font->offset ) || FT_FRAME_EXTRACT( header->file_size, font->fnt_frame ) ) goto Exit; Exit: return error; } static FT_Error fnt_face_get_dll_font( FNT_Face face, FT_Int face_instance_index ) { FT_Error error; FT_Stream stream = FT_FACE( face )->stream; FT_Memory memory = FT_FACE( face )->memory; WinMZ_HeaderRec mz_header; FT_Long face_index; face->font = NULL; face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* does it begin with an MZ header? */ if ( FT_STREAM_SEEK( 0 ) || FT_STREAM_READ_FIELDS( winmz_header_fields, &mz_header ) ) { error = FT_ERR( Unknown_File_Format ); goto Exit; } error = FT_ERR( Unknown_File_Format ); if ( mz_header.magic == WINFNT_MZ_MAGIC ) { /* yes, now look for an NE header in the file */ WinNE_HeaderRec ne_header; FT_TRACE2(( "MZ signature found\n" )); if ( FT_STREAM_SEEK( mz_header.lfanew ) || FT_STREAM_READ_FIELDS( winne_header_fields, &ne_header ) ) goto Exit; error = FT_ERR( Unknown_File_Format ); if ( ne_header.magic == WINFNT_NE_MAGIC ) { /* good, now look into the resource table for each FNT resource */ FT_ULong res_offset = mz_header.lfanew + ne_header.resource_tab_offset; FT_UShort size_shift; FT_UShort font_count = 0; FT_ULong font_offset = 0; FT_TRACE2(( "NE signature found\n" )); if ( FT_STREAM_SEEK( res_offset ) || FT_FRAME_ENTER( ne_header.rname_tab_offset - ne_header.resource_tab_offset ) ) goto Exit; size_shift = FT_GET_USHORT_LE(); /* Microsoft's specification of the executable-file header format */ /* for `New Executable' (NE) doesn't give a limit for the */ /* alignment shift count; however, in 1985, the year of the */ /* specification release, only 32bit values were supported, thus */ /* anything larger than 16 doesn't make sense in general, given */ /* that file offsets are 16bit values, shifted by the alignment */ /* shift count */ if ( size_shift > 16 ) { FT_TRACE2(( "invalid alignment shift count for resource data\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit1; } for (;;) { FT_UShort type_id, count; type_id = FT_GET_USHORT_LE(); if ( !type_id ) break; count = FT_GET_USHORT_LE(); FT_TRACE2(( type_id == 0x8007U ? "RT_FONTDIR count %hu\n" : type_id == 0x8008U ? "RT_FONT count %hu\n" : "", count )); if ( type_id == 0x8008U ) { font_count = count; font_offset = FT_STREAM_POS() + 4 + (FT_ULong)( stream->cursor - stream->limit ); break; } stream->cursor += 4 + count * 12; } FT_FRAME_EXIT(); if ( !font_count || !font_offset ) { FT_TRACE2(( "this file doesn't contain any FNT resources\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* loading `winfnt_header_fields' needs at least 118 bytes; */ /* use this as a rough measure to check the expected font size */ if ( font_count * 118UL > stream->size ) { FT_TRACE2(( "invalid number of faces\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } face->root.num_faces = font_count; if ( face_instance_index < 0 ) goto Exit; if ( face_index >= font_count ) { error = FT_THROW( Invalid_Argument ); goto Exit; } if ( FT_NEW( face->font ) ) goto Exit; if ( FT_STREAM_SEEK( font_offset + (FT_ULong)face_index * 12 ) || FT_FRAME_ENTER( 12 ) ) goto Fail; face->font->offset = (FT_ULong)FT_GET_USHORT_LE() << size_shift; face->font->fnt_size = (FT_ULong)FT_GET_USHORT_LE() << size_shift; stream->cursor += 8; FT_FRAME_EXIT(); error = fnt_font_load( face->font, stream ); } else if ( ne_header.magic == WINFNT_PE_MAGIC ) { WinPE32_HeaderRec pe32_header; WinPE32_SectionRec pe32_section; WinPE_RsrcDirRec root_dir, name_dir, lang_dir; WinPE_RsrcDirEntryRec dir_entry1, dir_entry2, dir_entry3; WinPE_RsrcDataEntryRec data_entry; FT_ULong root_dir_offset, name_dir_offset, lang_dir_offset; FT_UShort i, j, k; FT_TRACE2(( "PE signature found\n" )); if ( FT_STREAM_SEEK( mz_header.lfanew ) || FT_STREAM_READ_FIELDS( winpe32_header_fields, &pe32_header ) ) goto Exit; FT_TRACE2(( "magic %04lx, machine %02x, number_of_sections %u, " "size_of_optional_header %02x\n", pe32_header.magic, pe32_header.machine, pe32_header.number_of_sections, pe32_header.size_of_optional_header )); FT_TRACE2(( "magic32 %02x, rsrc_virtual_address %04lx, " "rsrc_size %04lx\n", pe32_header.magic32, pe32_header.rsrc_virtual_address, pe32_header.rsrc_size )); if ( pe32_header.magic != WINFNT_PE_MAGIC /* check full signature */ || pe32_header.machine != 0x014C /* i386 */ || pe32_header.size_of_optional_header != 0xE0 /* FIXME */ || pe32_header.magic32 != 0x10B ) { FT_TRACE2(( "this file has an invalid PE header\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } face->root.num_faces = 0; for ( i = 0; i < pe32_header.number_of_sections; i++ ) { if ( FT_STREAM_READ_FIELDS( winpe32_section_fields, &pe32_section ) ) goto Exit; FT_TRACE2(( "name %.8s, va %04lx, size %04lx, offset %04lx\n", pe32_section.name, pe32_section.virtual_address, pe32_section.size_of_raw_data, pe32_section.pointer_to_raw_data )); if ( pe32_header.rsrc_virtual_address == pe32_section.virtual_address ) goto Found_rsrc_section; } FT_TRACE2(( "this file doesn't contain any resources\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; Found_rsrc_section: FT_TRACE2(( "found resources section %.8s\n", pe32_section.name )); if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &root_dir ) ) goto Exit; root_dir_offset = pe32_section.pointer_to_raw_data; for ( i = 0; i < root_dir.number_of_named_entries + root_dir.number_of_id_entries; i++ ) { if ( FT_STREAM_SEEK( root_dir_offset + 16 + i * 8 ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields, &dir_entry1 ) ) goto Exit; if ( !(dir_entry1.offset & 0x80000000UL ) /* DataIsDirectory */ ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } dir_entry1.offset &= ~0x80000000UL; name_dir_offset = pe32_section.pointer_to_raw_data + dir_entry1.offset; if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data + dir_entry1.offset ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &name_dir ) ) goto Exit; for ( j = 0; j < name_dir.number_of_named_entries + name_dir.number_of_id_entries; j++ ) { if ( FT_STREAM_SEEK( name_dir_offset + 16 + j * 8 ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields, &dir_entry2 ) ) goto Exit; if ( !(dir_entry2.offset & 0x80000000UL ) /* DataIsDirectory */ ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } dir_entry2.offset &= ~0x80000000UL; lang_dir_offset = pe32_section.pointer_to_raw_data + dir_entry2.offset; if ( FT_STREAM_SEEK( pe32_section.pointer_to_raw_data + dir_entry2.offset ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_fields, &lang_dir ) ) goto Exit; for ( k = 0; k < lang_dir.number_of_named_entries + lang_dir.number_of_id_entries; k++ ) { if ( FT_STREAM_SEEK( lang_dir_offset + 16 + k * 8 ) || FT_STREAM_READ_FIELDS( winpe_rsrc_dir_entry_fields, &dir_entry3 ) ) goto Exit; if ( dir_entry2.offset & 0x80000000UL /* DataIsDirectory */ ) { error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( dir_entry1.name == 8 /* RT_FONT */ ) { if ( FT_STREAM_SEEK( root_dir_offset + dir_entry3.offset ) || FT_STREAM_READ_FIELDS( winpe_rsrc_data_entry_fields, &data_entry ) ) goto Exit; FT_TRACE2(( "found font #%lu, offset %04lx, " "size %04lx, cp %lu\n", dir_entry2.name, pe32_section.pointer_to_raw_data + data_entry.offset_to_data - pe32_section.virtual_address, data_entry.size, data_entry.code_page )); if ( face_index == face->root.num_faces ) { if ( FT_NEW( face->font ) ) goto Exit; face->font->offset = pe32_section.pointer_to_raw_data + data_entry.offset_to_data - pe32_section.virtual_address; face->font->fnt_size = data_entry.size; error = fnt_font_load( face->font, stream ); if ( error ) { FT_TRACE2(( "font #%lu load error 0x%x\n", dir_entry2.name, error )); goto Fail; } else FT_TRACE2(( "font #%lu successfully loaded\n", dir_entry2.name )); } face->root.num_faces++; } } } } } if ( !face->root.num_faces ) { FT_TRACE2(( "this file doesn't contain any RT_FONT resources\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } if ( face_index >= face->root.num_faces ) { error = FT_THROW( Invalid_Argument ); goto Exit; } } Fail: if ( error ) fnt_font_done( face ); Exit: return error; Exit1: FT_FRAME_EXIT(); goto Exit; } typedef struct FNT_CMapRec_ { FT_CMapRec cmap; FT_UInt32 first; FT_UInt32 count; } FNT_CMapRec, *FNT_CMap; static FT_Error fnt_cmap_init( FNT_CMap cmap, FT_Pointer pointer ) { FNT_Face face = (FNT_Face)FT_CMAP_FACE( cmap ); FNT_Font font = face->font; FT_UNUSED( pointer ); cmap->first = (FT_UInt32) font->header.first_char; cmap->count = (FT_UInt32)( font->header.last_char - cmap->first + 1 ); return 0; } static FT_UInt fnt_cmap_char_index( FNT_CMap cmap, FT_UInt32 char_code ) { FT_UInt gindex = 0; char_code -= cmap->first; if ( char_code < cmap->count ) /* we artificially increase the glyph index; */ /* FNT_Load_Glyph reverts to the right one */ gindex = (FT_UInt)( char_code + 1 ); return gindex; } static FT_UInt32 fnt_cmap_char_next( FNT_CMap cmap, FT_UInt32 *pchar_code ) { FT_UInt gindex = 0; FT_UInt32 result = 0; FT_UInt32 char_code = *pchar_code + 1; if ( char_code <= cmap->first ) { result = cmap->first; gindex = 1; } else { char_code -= cmap->first; if ( char_code < cmap->count ) { result = cmap->first + char_code; gindex = (FT_UInt)( char_code + 1 ); } } *pchar_code = result; return gindex; } static const FT_CMap_ClassRec fnt_cmap_class_rec = { sizeof ( FNT_CMapRec ), (FT_CMap_InitFunc) fnt_cmap_init, (FT_CMap_DoneFunc) NULL, (FT_CMap_CharIndexFunc)fnt_cmap_char_index, (FT_CMap_CharNextFunc) fnt_cmap_char_next, NULL, NULL, NULL, NULL, NULL }; static FT_CMap_Class const fnt_cmap_class = &fnt_cmap_class_rec; static void FNT_Face_Done( FT_Face fntface ) /* FNT_Face */ { FNT_Face face = (FNT_Face)fntface; FT_Memory memory; if ( !face ) return; memory = FT_FACE_MEMORY( face ); fnt_font_done( face ); FT_FREE( fntface->available_sizes ); fntface->num_fixed_sizes = 0; } static FT_Error FNT_Face_Init( FT_Stream stream, FT_Face fntface, /* FNT_Face */ FT_Int face_instance_index, FT_Int num_params, FT_Parameter* params ) { FNT_Face face = (FNT_Face)fntface; FT_Error error; FT_Memory memory = FT_FACE_MEMORY( face ); FT_Int face_index; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_TRACE2(( "Windows FNT driver\n" )); face_index = FT_ABS( face_instance_index ) & 0xFFFF; /* try to load font from a DLL */ error = fnt_face_get_dll_font( face, face_instance_index ); if ( !error && face_instance_index < 0 ) goto Exit; if ( FT_ERR_EQ( error, Unknown_File_Format ) ) { /* this didn't work; try to load a single FNT font */ FNT_Font font; if ( FT_NEW( face->font ) ) goto Exit; fntface->num_faces = 1; font = face->font; font->offset = 0; font->fnt_size = stream->size; error = fnt_font_load( font, stream ); if ( !error ) { if ( face_instance_index < 0 ) goto Exit; if ( face_index > 0 ) error = FT_THROW( Invalid_Argument ); } } if ( error ) goto Fail; /* sanity check */ if ( !face->font->header.pixel_height ) { FT_TRACE2(( "invalid pixel height\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* we now need to fill the root FT_Face fields */ /* with relevant information */ { FT_Face root = FT_FACE( face ); FNT_Font font = face->font; FT_ULong family_size; root->face_index = face_index; root->face_flags |= FT_FACE_FLAG_FIXED_SIZES | FT_FACE_FLAG_HORIZONTAL; if ( font->header.avg_width == font->header.max_width ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; if ( font->header.italic ) root->style_flags |= FT_STYLE_FLAG_ITALIC; if ( font->header.weight >= 800 ) root->style_flags |= FT_STYLE_FLAG_BOLD; /* set up the `fixed_sizes' array */ if ( FT_QNEW( root->available_sizes ) ) goto Fail; root->num_fixed_sizes = 1; { FT_Bitmap_Size* bsize = root->available_sizes; FT_UShort x_res, y_res; bsize->width = (FT_Short)font->header.avg_width; bsize->height = (FT_Short)( font->header.pixel_height + font->header.external_leading ); bsize->size = font->header.nominal_point_size << 6; x_res = font->header.horizontal_resolution; if ( !x_res ) x_res = 72; y_res = font->header.vertical_resolution; if ( !y_res ) y_res = 72; bsize->y_ppem = FT_MulDiv( bsize->size, y_res, 72 ); bsize->y_ppem = FT_PIX_ROUND( bsize->y_ppem ); /* * this reads: * * the nominal height is larger than the bbox's height * * => nominal_point_size contains incorrect value; * use pixel_height as the nominal height */ if ( bsize->y_ppem > ( font->header.pixel_height << 6 ) ) { FT_TRACE2(( "use pixel_height as the nominal height\n" )); bsize->y_ppem = font->header.pixel_height << 6; bsize->size = FT_MulDiv( bsize->y_ppem, 72, y_res ); } bsize->x_ppem = FT_MulDiv( bsize->size, x_res, 72 ); bsize->x_ppem = FT_PIX_ROUND( bsize->x_ppem ); } { FT_CharMapRec charmap; charmap.encoding = FT_ENCODING_NONE; /* initial platform/encoding should indicate unset status? */ charmap.platform_id = TT_PLATFORM_APPLE_UNICODE; charmap.encoding_id = TT_APPLE_ID_DEFAULT; charmap.face = root; if ( font->header.charset == FT_WinFNT_ID_MAC ) { charmap.encoding = FT_ENCODING_APPLE_ROMAN; charmap.platform_id = TT_PLATFORM_MACINTOSH; /* charmap.encoding_id = TT_MAC_ID_ROMAN; */ } error = FT_CMap_New( fnt_cmap_class, NULL, &charmap, NULL ); if ( error ) goto Fail; } /* set up remaining flags */ if ( font->header.last_char < font->header.first_char ) { FT_TRACE2(( "invalid number of glyphs\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } /* reserve one slot for the .notdef glyph at index 0 */ root->num_glyphs = font->header.last_char - font->header.first_char + 1 + 1; if ( font->header.face_name_offset >= font->header.file_size ) { FT_TRACE2(( "invalid family name offset\n" )); error = FT_THROW( Invalid_File_Format ); goto Fail; } family_size = font->header.file_size - font->header.face_name_offset; /* Some broken fonts don't delimit the face name with a final */ /* null byte -- the frame is erroneously one byte too small. */ /* We thus allocate one more byte, setting it explicitly to */ /* zero. */ if ( FT_QALLOC( font->family_name, family_size + 1 ) ) goto Fail; FT_MEM_COPY( font->family_name, font->fnt_frame + font->header.face_name_offset, family_size ); font->family_name[family_size] = '\0'; /* shrink it to the actual length */ if ( FT_QREALLOC( font->family_name, family_size + 1, ft_strlen( font->family_name ) + 1 ) ) goto Fail; root->family_name = font->family_name; root->style_name = (char *)"Regular"; if ( root->style_flags & FT_STYLE_FLAG_BOLD ) { if ( root->style_flags & FT_STYLE_FLAG_ITALIC ) root->style_name = (char *)"Bold Italic"; else root->style_name = (char *)"Bold"; } else if ( root->style_flags & FT_STYLE_FLAG_ITALIC ) root->style_name = (char *)"Italic"; } goto Exit; Fail: FNT_Face_Done( fntface ); Exit: return error; } static FT_Error FNT_Size_Select( FT_Size size, FT_ULong strike_index ) { FNT_Face face = (FNT_Face)size->face; FT_WinFNT_Header header = &face->font->header; FT_UNUSED( strike_index ); FT_Select_Metrics( size->face, 0 ); size->metrics.ascender = header->ascent * 64; size->metrics.descender = -( header->pixel_height - header->ascent ) * 64; size->metrics.max_advance = header->max_width * 64; return FT_Err_Ok; } static FT_Error FNT_Size_Request( FT_Size size, FT_Size_Request req ) { FNT_Face face = (FNT_Face)size->face; FT_WinFNT_Header header = &face->font->header; FT_Bitmap_Size* bsize = size->face->available_sizes; FT_Error error = FT_ERR( Invalid_Pixel_Size ); FT_Long height; height = FT_REQUEST_HEIGHT( req ); height = ( height + 32 ) >> 6; switch ( req->type ) { case FT_SIZE_REQUEST_TYPE_NOMINAL: if ( height == ( ( bsize->y_ppem + 32 ) >> 6 ) ) error = FT_Err_Ok; break; case FT_SIZE_REQUEST_TYPE_REAL_DIM: if ( height == header->pixel_height ) error = FT_Err_Ok; break; default: error = FT_THROW( Unimplemented_Feature ); break; } if ( error ) return error; else return FNT_Size_Select( size, 0 ); } static FT_Error FNT_Load_Glyph( FT_GlyphSlot slot, FT_Size size, FT_UInt glyph_index, FT_Int32 load_flags ) { FNT_Face face = (FNT_Face)FT_SIZE_FACE( size ); FNT_Font font; FT_Error error = FT_Err_Ok; FT_Byte* p; FT_UInt len; FT_Bitmap* bitmap = &slot->bitmap; FT_ULong offset; FT_Bool new_format; if ( !face ) { error = FT_THROW( Invalid_Face_Handle ); goto Exit; } font = face->font; if ( !font || glyph_index >= (FT_UInt)( FT_FACE( face )->num_glyphs ) ) { error = FT_THROW( Invalid_Argument ); goto Exit; } FT_TRACE1(( "FNT_Load_Glyph: glyph index %d\n", glyph_index )); if ( glyph_index > 0 ) glyph_index--; /* revert to real index */ else glyph_index = font->header.default_char; /* the `.notdef' glyph */ new_format = FT_BOOL( font->header.version == 0x300 ); len = new_format ? 6 : 4; /* get glyph width and offset */ offset = ( new_format ? 148 : 118 ) + len * glyph_index; if ( offset >= font->header.file_size - 2 - ( new_format ? 4 : 2 ) ) { FT_TRACE2(( "invalid FNT offset\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } p = font->fnt_frame + offset; bitmap->width = FT_NEXT_USHORT_LE( p ); /* jump to glyph entry */ if ( new_format ) offset = FT_NEXT_ULONG_LE( p ); else offset = FT_NEXT_USHORT_LE( p ); if ( offset >= font->header.file_size ) { FT_TRACE2(( "invalid FNT offset\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } bitmap->rows = font->header.pixel_height; bitmap->pixel_mode = FT_PIXEL_MODE_MONO; slot->bitmap_left = 0; slot->bitmap_top = font->header.ascent; slot->format = FT_GLYPH_FORMAT_BITMAP; /* now set up metrics */ slot->metrics.width = (FT_Pos)( bitmap->width << 6 ); slot->metrics.height = (FT_Pos)( bitmap->rows << 6 ); slot->metrics.horiAdvance = (FT_Pos)( bitmap->width << 6 ); slot->metrics.horiBearingX = 0; slot->metrics.horiBearingY = slot->bitmap_top << 6; ft_synthesize_vertical_metrics( &slot->metrics, (FT_Pos)( bitmap->rows << 6 ) ); if ( load_flags & FT_LOAD_BITMAP_METRICS_ONLY ) goto Exit; /* jump to glyph data */ p = font->fnt_frame + /* font->header.bits_offset */ + offset; /* allocate and build bitmap */ { FT_Memory memory = FT_FACE_MEMORY( slot->face ); FT_UInt pitch = ( bitmap->width + 7 ) >> 3; FT_Byte* column; FT_Byte* write; bitmap->pitch = (int)pitch; if ( !pitch || offset + pitch * bitmap->rows > font->header.file_size ) { FT_TRACE2(( "invalid bitmap width\n" )); error = FT_THROW( Invalid_File_Format ); goto Exit; } /* note: since glyphs are stored in columns and not in rows we */ /* can't use ft_glyphslot_set_bitmap */ if ( FT_QALLOC_MULT( bitmap->buffer, bitmap->rows, pitch ) ) goto Exit; column = (FT_Byte*)bitmap->buffer; for ( ; pitch > 0; pitch--, column++ ) { FT_Byte* limit = p + bitmap->rows; for ( write = column; p < limit; p++, write += bitmap->pitch ) *write = *p; } slot->internal->flags = FT_GLYPH_OWN_BITMAP; } Exit: return error; } static FT_Error winfnt_get_header( FT_Face face, FT_WinFNT_HeaderRec *aheader ) { FNT_Font font = ((FNT_Face)face)->font; *aheader = font->header; return 0; } static const FT_Service_WinFntRec winfnt_service_rec = { winfnt_get_header /* get_header */ }; /* * SERVICE LIST * */ static const FT_ServiceDescRec winfnt_services[] = { { FT_SERVICE_ID_FONT_FORMAT, FT_FONT_FORMAT_WINFNT }, { FT_SERVICE_ID_WINFNT, &winfnt_service_rec }, { NULL, NULL } }; static FT_Module_Interface winfnt_get_service( FT_Module module, const FT_String* service_id ) { FT_UNUSED( module ); return ft_service_list_lookup( winfnt_services, service_id ); } FT_CALLBACK_TABLE_DEF const FT_Driver_ClassRec winfnt_driver_class = { { FT_MODULE_FONT_DRIVER | FT_MODULE_DRIVER_NO_OUTLINES, sizeof ( FT_DriverRec ), "winfonts", 0x10000L, 0x20000L, NULL, /* module-specific interface */ NULL, /* FT_Module_Constructor module_init */ NULL, /* FT_Module_Destructor module_done */ winfnt_get_service /* FT_Module_Requester get_interface */ }, sizeof ( FNT_FaceRec ), sizeof ( FT_SizeRec ), sizeof ( FT_GlyphSlotRec ), FNT_Face_Init, /* FT_Face_InitFunc init_face */ FNT_Face_Done, /* FT_Face_DoneFunc done_face */ NULL, /* FT_Size_InitFunc init_size */ NULL, /* FT_Size_DoneFunc done_size */ NULL, /* FT_Slot_InitFunc init_slot */ NULL, /* FT_Slot_DoneFunc done_slot */ FNT_Load_Glyph, /* FT_Slot_LoadFunc load_glyph */ NULL, /* FT_Face_GetKerningFunc get_kerning */ NULL, /* FT_Face_AttachFunc attach_file */ NULL, /* FT_Face_GetAdvancesFunc get_advances */ FNT_Size_Request, /* FT_Size_RequestFunc request_size */ FNT_Size_Select /* FT_Size_SelectFunc select_size */ }; /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/winfonts/winfnt.c
C++
gpl-3.0
35,525
/**************************************************************************** * * winfnt.h * * FreeType font driver for Windows FNT/FON files * * Copyright (C) 1996-2022 by * David Turner, Robert Wilhelm, and Werner Lemberg. * Copyright 2007 Dmitry Timoshkov for Codeweavers * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef WINFNT_H_ #define WINFNT_H_ #include <freetype/ftwinfnt.h> #include <freetype/internal/ftdrv.h> FT_BEGIN_HEADER typedef struct WinMZ_HeaderRec_ { FT_UShort magic; /* skipped content */ FT_UShort lfanew; } WinMZ_HeaderRec; typedef struct WinNE_HeaderRec_ { FT_UShort magic; /* skipped content */ FT_UShort resource_tab_offset; FT_UShort rname_tab_offset; } WinNE_HeaderRec; typedef struct WinPE32_HeaderRec_ { FT_ULong magic; FT_UShort machine; FT_UShort number_of_sections; /* skipped content */ FT_UShort size_of_optional_header; /* skipped content */ FT_UShort magic32; /* skipped content */ FT_ULong rsrc_virtual_address; FT_ULong rsrc_size; /* skipped content */ } WinPE32_HeaderRec; typedef struct WinPE32_SectionRec_ { FT_Byte name[8]; /* skipped content */ FT_ULong virtual_address; FT_ULong size_of_raw_data; FT_ULong pointer_to_raw_data; /* skipped content */ } WinPE32_SectionRec; typedef struct WinPE_RsrcDirRec_ { FT_ULong characteristics; FT_ULong time_date_stamp; FT_UShort major_version; FT_UShort minor_version; FT_UShort number_of_named_entries; FT_UShort number_of_id_entries; } WinPE_RsrcDirRec; typedef struct WinPE_RsrcDirEntryRec_ { FT_ULong name; FT_ULong offset; } WinPE_RsrcDirEntryRec; typedef struct WinPE_RsrcDataEntryRec_ { FT_ULong offset_to_data; FT_ULong size; FT_ULong code_page; FT_ULong reserved; } WinPE_RsrcDataEntryRec; typedef struct WinNameInfoRec_ { FT_UShort offset; FT_UShort length; FT_UShort flags; FT_UShort id; FT_UShort handle; FT_UShort usage; } WinNameInfoRec; typedef struct WinResourceInfoRec_ { FT_UShort type_id; FT_UShort count; } WinResourceInfoRec; #define WINFNT_MZ_MAGIC 0x5A4D #define WINFNT_NE_MAGIC 0x454E #define WINFNT_PE_MAGIC 0x4550 typedef struct FNT_FontRec_ { FT_ULong offset; FT_WinFNT_HeaderRec header; FT_Byte* fnt_frame; FT_ULong fnt_size; FT_String* family_name; } FNT_FontRec, *FNT_Font; typedef struct FNT_FaceRec_ { FT_FaceRec root; FNT_Font font; } FNT_FaceRec, *FNT_Face; FT_EXPORT_VAR( const FT_Driver_ClassRec ) winfnt_driver_class; FT_END_HEADER #endif /* WINFNT_H_ */ /* END */
whupdup/frame
real/third_party/freetype-2.12.0/src/winfonts/winfnt.h
C++
gpl-3.0
3,104
# Unit and regression tests for the FreeType library ## Quick Start ### Download test fonts Run the `tests/scripts/download-fonts.py` script, which will download test fonts to the `tests/data/` directory first. ### Build the test programs The tests are only built with the Meson build system, and are disabled by default, enable the 'tests' option to compile them, as in: meson setup out -Dtests=enabled meson compile -C out ### Run the test programs meson test -C out
whupdup/frame
real/third_party/freetype-2.12.0/tests/README.md
Markdown
gpl-3.0
484
#include <stdio.h> #include <freetype/freetype.h> #include <ft2build.h> int main( void ) { FT_Library library; FT_Face face = NULL; /* * We assume that `FREETYPE_TESTS_DATA_DIR` was set by `meson test`. * Otherwise we default to `../tests/data`. * * TODO (David): Rewrite this to pass the test directory through the * command-line. */ const char* testdata_dir = getenv( "FREETYPE_TESTS_DATA_DIR" ); char filepath[FILENAME_MAX]; snprintf( filepath, sizeof( filepath ), "%s/%s", testdata_dir ? testdata_dir : "../tests/data", "As.I.Lay.Dying.ttf" ); FT_Init_FreeType( &library ); if ( FT_New_Face( library, filepath, 0, &face ) != 0 ) { fprintf( stderr, "Could not open file: %s\n", filepath ); return 1; } for ( FT_ULong i = 59; i < 171; i++ ) { FT_UInt gid = FT_Get_Char_Index( face, i ); FT_Error code = FT_Load_Glyph( face, gid, FT_LOAD_DEFAULT ); if ( code ) printf( "unknown %d for char %lu, gid %u\n", code, i, gid ); } return 0; } /* EOF */
whupdup/frame
real/third_party/freetype-2.12.0/tests/issue-1063/main.c
C++
gpl-3.0
1,074
test_issue_1063 = executable('issue-1063', files([ 'issue-1063/main.c' ]), dependencies: freetype_dep, ) test_env = ['FREETYPE_TESTS_DATA_DIR=' + join_paths(meson.current_source_dir(), 'data')] test('issue-1063', test_issue_1063, env: test_env, suite: 'regression') # EOF
whupdup/frame
real/third_party/freetype-2.12.0/tests/meson.build
build
gpl-3.0
297
#!/usr/bin/env python3 """Download test fonts used by the FreeType regression test programs. These will be copied to $FREETYPE/tests/data/ by default.""" import argparse import collections import hashlib import io import os import requests import sys import zipfile from typing import Callable, List, Optional, Tuple # The list of download items describing the font files to install. Each # download item is a dictionary with one of the following schemas: # # - File item: # # file_url # Type: URL string. # Required: Yes. # Description: URL to download the file from. # # install_name # Type: file name string # Required: No # Description: Installation name for the font file, only provided if # it must be different from the original URL's basename. # # hex_digest # Type: hexadecimal string # Required: No # Description: Digest of the input font file. # # - Zip items: # # These items correspond to one or more font files that are embedded in a # remote zip archive. Each entry has the following fields: # # zip_url # Type: URL string. # Required: Yes. # Description: URL to download the zip archive from. # # zip_files # Type: List of file entries (see below) # Required: Yes # Description: A list of entries describing a single font file to be # extracted from the archive # # Apart from that, some schemas are used for dictionaries used inside # download items: # # - File entries: # # These are dictionaries describing a single font file to extract from an # archive. # # filename # Type: file path string # Required: Yes # Description: Path of source file, relative to the archive's # top-level directory. # # install_name # Type: file name string # Required: No # Description: Installation name for the font file; only provided if # it must be different from the original filename value. # # hex_digest # Type: hexadecimal string # Required: No # Description: Digest of the input source file # _DOWNLOAD_ITEMS = [ { "zip_url": "https://github.com/python-pillow/Pillow/files/6622147/As.I.Lay.Dying.zip", "zip_files": [ { "filename": "As I Lay Dying.ttf", "install_name": "As.I.Lay.Dying.ttf", "hex_digest": "ef146bbc2673b387", }, ], }, ] def digest_data(data: bytes): """Compute the digest of a given input byte string, which are the first 8 bytes of its sha256 hash.""" m = hashlib.sha256() m.update(data) return m.digest()[:8] def check_existing(path: str, hex_digest: str): """Return True if |path| exists and matches |hex_digest|.""" if not os.path.exists(path) or hex_digest is None: return False with open(path, "rb") as f: existing_content = f.read() return bytes.fromhex(hex_digest) == digest_data(existing_content) def install_file(content: bytes, dest_path: str): """Write a byte string to a given destination file. Args: content: Input data, as a byte string dest_path: Installation path """ parent_path = os.path.dirname(dest_path) if not os.path.exists(parent_path): os.makedirs(parent_path) with open(dest_path, "wb") as f: f.write(content) def download_file(url: str, expected_digest: Optional[bytes] = None): """Download a file from a given URL. Args: url: Input URL expected_digest: Optional digest of the file as a byte string Returns: URL content as binary string. """ r = requests.get(url, allow_redirects=True) content = r.content if expected_digest is not None: digest = digest_data(r.content) if digest != expected_digest: raise ValueError( "%s has invalid digest %s (expected %s)" % (url, digest.hex(), expected_digest.hex()) ) return content def extract_file_from_zip_archive( archive: zipfile.ZipFile, archive_name: str, filepath: str, expected_digest: Optional[bytes] = None, ): """Extract a file from a given zipfile.ZipFile archive. Args: archive: Input ZipFile objec. archive_name: Archive name or URL, only used to generate a human-readable error message. filepath: Input filepath in archive. expected_digest: Optional digest for the file. Returns: A new File instance corresponding to the extract file. Raises: ValueError if expected_digest is not None and does not match the extracted file. """ file = archive.open(filepath) if expected_digest is not None: digest = digest_data(archive.open(filepath).read()) if digest != expected_digest: raise ValueError( "%s in zip archive at %s has invalid digest %s (expected %s)" % (filepath, archive_name, digest.hex(), expected_digest.hex()) ) return file.read() def _get_and_install_file( install_path: str, hex_digest: Optional[str], force_download: bool, get_content: Callable[[], bytes], ) -> bool: if not force_download and hex_digest is not None \ and os.path.exists(install_path): with open(install_path, "rb") as f: content: bytes = f.read() if bytes.fromhex(hex_digest) == digest_data(content): return False content = get_content() install_file(content, install_path) return True def download_and_install_item( item: dict, install_dir: str, force_download: bool ) -> List[Tuple[str, bool]]: """Download and install one item. Args: item: Download item as a dictionary, see above for schema. install_dir: Installation directory. force_download: Set to True to force download and installation, even if the font file is already installed with the right content. Returns: A list of (install_name, status) tuples, where 'install_name' is the file's installation name under 'install_dir', and 'status' is a boolean that is True to indicate that the file was downloaded and installed, or False to indicate that the file is already installed with the right content. """ if "file_url" in item: file_url = item["file_url"] install_name = item.get("install_name", os.path.basename(file_url)) install_path = os.path.join(install_dir, install_name) hex_digest = item.get("hex_digest") def get_content(): return download_file(file_url, hex_digest) status = _get_and_install_file( install_path, hex_digest, force_download, get_content ) return [(install_name, status)] if "zip_url" in item: # One or more files from a zip archive. archive_url = item["zip_url"] archive = zipfile.ZipFile(io.BytesIO(download_file(archive_url))) result = [] for f in item["zip_files"]: filename = f["filename"] install_name = f.get("install_name", filename) hex_digest = f.get("hex_digest") def get_content(): return extract_file_from_zip_archive( archive, archive_url, filename, bytes.fromhex(hex_digest) if hex_digest else None, ) status = _get_and_install_file( os.path.join(install_dir, install_name), hex_digest, force_download, get_content, ) result.append((install_name, status)) return result else: raise ValueError("Unknown download item schema: %s" % item) def main(): parser = argparse.ArgumentParser(description=__doc__) # Assume this script is under tests/scripts/ and tests/data/ # is the default installation directory. install_dir = os.path.normpath( os.path.join(os.path.dirname(__file__), "..", "data") ) parser.add_argument( "--force", action="store_true", default=False, help="Force download and installation of font files", ) parser.add_argument( "--install-dir", default=install_dir, help="Specify installation directory [%s]" % install_dir, ) args = parser.parse_args() for item in _DOWNLOAD_ITEMS: for install_name, status in download_and_install_item( item, args.install_dir, args.force ): print("%s %s" % (install_name, "INSTALLED" if status else "UP-TO-DATE")) return 0 if __name__ == "__main__": sys.exit(main()) # EOF
whupdup/frame
real/third_party/freetype-2.12.0/tests/scripts/download-test-fonts.py
Python
gpl-3.0
8,869
$! make FreeType 2 under OpenVMS $! $! Copyright (C) 2003-2022 by $! David Turner, Robert Wilhelm, and Werner Lemberg. $! $! This file is part of the FreeType project, and may only be used, modified, $! and distributed under the terms of the FreeType project license, $! LICENSE.TXT. By continuing to use, modify, or distribute this file you $! indicate that you have read the license and understand and accept it $! fully. $! $! $! External libraries (like FreeType, XPM, etc.) are supported via the $! config file VMSLIB.DAT. Please check the sample file, which is part of this $! distribution, for the information you need to provide $! $! This procedure currently does support the following commandline options $! in arbitrary order $! $! * DEBUG - Compile modules with /noopt/debug and link shareable image $! with /debug $! * LOPTS - Options to be passed to the link command $! * CCOPT - Options to be passed to the C compiler $! $! In case of problems with the install you might contact me at $! zinser@zinser.no-ip.info (preferred) or $! zinser@sysdev.deutsche-boerse.com (work) $! $! Make procedure history for FreeType 2 $! $!------------------------------------------------------------------------------ $! Version history $! 0.01 20040401 First version to receive a number $! 0.02 20041030 Add error handling, FreeType 2.1.9 $! $ on error then goto err_exit $ true = 1 $ false = 0 $ tmpnam = "temp_" + f$getjpi("","pid") $ tt = tmpnam + ".txt" $ tc = tmpnam + ".c" $ th = tmpnam + ".h" $ its_decc = false $ its_vaxc = false $ its_gnuc = false $! $! Setup variables holding "config" information $! $ Make = "" $ ccopt = "/name=(as_is,short)/float=ieee" $ lopts = "" $ dnsrl = "" $ aconf_in_file = "config.hin" $ name = "Freetype2" $ mapfile = name + ".map" $ optfile = name + ".opt" $ s_case = false $ liblist = "" $! $ whoami = f$parse(f$environment("Procedure"),,,,"NO_CONCEAL") $ mydef = F$parse(whoami,,,"DEVICE") $ mydir = f$parse(whoami,,,"DIRECTORY") - "][" $ myproc = f$parse(whoami,,,"Name") + f$parse(whoami,,,"type") $! $! Check for MMK/MMS $! $ If F$Search ("Sys$System:MMS.EXE") .nes. "" Then Make = "MMS" $ If F$Type (MMK) .eqs. "STRING" Then Make = "MMK" $! $! Which command parameters were given $! $ gosub check_opts $! $! Create option file $! $ open/write optf 'optfile' $! $! Pull in external libraries $! $ create libs.opt $ open/write libsf libs.opt $ gosub check_create_vmslib $! $! Create objects $! $ if libdefs .nes. "" $ then $ ccopt = ccopt + "/define=(" + f$extract(0,f$length(libdefs)-1,libdefs) + ")" $ endif $! $ if f$locate("AS_IS",f$edit(ccopt,"UPCASE")) .lt. f$length(ccopt) - then s_case = true $ gosub crea_mms $! $ 'Make' /macro=(comp_flags="''ccopt'") $ purge/nolog [...]descrip.mms $! $! Add them to options $! $FLOOP: $ file = f$edit(f$search("[...]*.obj"),"UPCASE") $ if (file .nes. "") $ then $ if f$locate("DEMOS",file) .eqs. f$length(file) then write optf file $ goto floop $ endif $! $ close optf $! $! $! Alpha gets a shareable image $! $ If f$getsyi("HW_MODEL") .gt. 1024 $ Then $ write sys$output "Creating freetype2shr.exe" $ If f$getsyi("HW_MODEL") .le. 2048 $ Then $ call anal_obj_axp 'optfile' _link.opt $ Else $ copy _link.opt_ia64 _link.opt $ close libsf $ copy libs.opt_ia64 libs.opt $ endif $ open/append optf 'optfile' $ if s_case then WRITE optf "case_sensitive=YES" $ close optf $ LINK_/NODEB/SHARE=[.lib]freetype2shr.exe - 'optfile'/opt,libs.opt/opt,_link.opt/opt $ endif $! $ exit $! $ $ERR_LIB: $ write sys$output "Error reading config file vmslib.dat" $ goto err_exit $FT2_ERR: $ write sys$output "Could not locate FreeType 2 include files" $ goto err_exit $ERR_EXIT: $ set message/facil/ident/sever/text $ close/nolog optf $ close/nolog out $ close/nolog libdata $ close/nolog in $ close/nolog atmp $ close/nolog xtmp $ write sys$output "Exiting..." $ exit 2 $! $!------------------------------------------------------------------------------ $! $! If MMS/MMK are available dump out the descrip.mms if required $! $CREA_MMS: $ write sys$output "Creating descrip.mms files ..." $ write sys$output "... Main directory" $ create descrip.mms $ open/append out descrip.mms $ copy sys$input: out $ deck # # FreeType 2 build system -- top-level Makefile for OpenVMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. $ EOD $ write out "CFLAGS = ", ccopt $ copy sys$input: out $ deck all : define config [--.include.freetype.config] define internal [--.include.freetype.internal] define autofit [-.autofit] define base [-.base] define cache [-.cache] define cff [-.cff] define cid [-.cid] define freetype [--.include.freetype] define pcf [-.pcf] define psaux [-.psaux] define psnames [-.psnames] define raster [-.raster] define sfnt [-.sfnt] define smooth [-.smooth] define truetype [-.truetype] define type1 [-.type1] define winfonts [-.winfonts] if f$search("lib.dir") .eqs. "" then create/directory [.lib] set default [.builds.vms] $(MMS)$(MMSQUALIFIERS) set default [--.src.autofit] $(MMS)$(MMSQUALIFIERS) set default [-.base] $(MMS)$(MMSQUALIFIERS) set default [-.bdf] $(MMS)$(MMSQUALIFIERS) set default [-.cache] $(MMS)$(MMSQUALIFIERS) set default [-.cff] $(MMS)$(MMSQUALIFIERS) set default [-.cid] $(MMS)$(MMSQUALIFIERS) set default [-.gxvalid] $(MMS)$(MMSQUALIFIERS) set default [-.gzip] $(MMS)$(MMSQUALIFIERS) set default [-.bzip2] $(MMS)$(MMSQUALIFIERS) set default [-.lzw] $(MMS)$(MMSQUALIFIERS) set default [-.otvalid] $(MMS)$(MMSQUALIFIERS) set default [-.pcf] $(MMS)$(MMSQUALIFIERS) set default [-.pfr] $(MMS)$(MMSQUALIFIERS) set default [-.psaux] $(MMS)$(MMSQUALIFIERS) set default [-.pshinter] $(MMS)$(MMSQUALIFIERS) set default [-.psnames] $(MMS)$(MMSQUALIFIERS) set default [-.raster] $(MMS)$(MMSQUALIFIERS) set default [-.sfnt] $(MMS)$(MMSQUALIFIERS) set default [-.smooth] $(MMS)$(MMSQUALIFIERS) set default [-.truetype] $(MMS)$(MMSQUALIFIERS) set default [-.type1] $(MMS)$(MMSQUALIFIERS) set default [-.type42] $(MMS)$(MMSQUALIFIERS) set default [-.winfonts] $(MMS)$(MMSQUALIFIERS) set default [--] # EOF $ eod $ close out $ write sys$output "... [.builds.vms] directory" $ create [.builds.vms]descrip.mms $ open/append out [.builds.vms]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 system rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/list/show=all/include=([],[--.include],[--.src.base]) OBJS=ftsystem.obj all : $(OBJS) library/create [--.lib]freetype.olb $(OBJS) ftsystem.obj : ftsystem.c ftconfig.h # EOF $ eod $ close out $ write sys$output "... [.src.autofit] directory" $ create [.src.autofit]descrip.mms $ open/append out [.src.autofit]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 auto-fit module compilation rules for VMS # # Copyright 2002-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.autofit]) OBJS=autofit.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.base] directory" $ create [.src.base]descrip.mms $ open/append out [.src.base]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 base layer compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.builds.vms],[--.include],[--.src.base]) OBJS=ftbase.obj,\ ftbbox.obj,\ ftbdf.obj,\ ftbitmap.obj,\ ftcid.obj,\ ftdebug.obj,\ ftfstype.obj,\ ftgasp.obj,\ ftglyph.obj,\ ftinit.obj,\ ftmm.obj,\ ftpfr.obj,\ ftstroke.obj,\ ftsynth.obj,\ fttype1.obj,\ ftwinfnt.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.bdf] directory" $ create [.src.bdf]descrip.mms $ open/append out [.src.bdf]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 BDF driver compilation rules for VMS # # Copyright 2002-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.bdf]) OBJS=bdf.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.cache] directory" $ create [.src.cache]descrip.mms $ open/append out [.src.cache]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 Cache compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.cache])/nowarn OBJS=ftcache.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.cff] directory" $ create [.src.cff]descrip.mms $ open/append out [.src.cff]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 OpenType/CFF driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.cff]) OBJS=cff.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.cid] directory" $ create [.src.cid]descrip.mms $ open/append out [.src.cid]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 CID driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.cid]) OBJS=type1cid.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.gxvalid] directory" $ create [.src.gxvalid]descrip.mms $ open/append out [.src.gxvalid]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 TrueTypeGX/AAT validation driver configuration rules for VMS # # Copyright 2004-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.gxvalid]) OBJS=gxvalid.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.gzip] directory" $ create [.src.gzip]descrip.mms $ open/append out [.src.gzip]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 GZip support compilation rules for VMS # # Copyright 2002-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. $EOD $ if libincs .nes. "" then write out "LIBINCS = ", libincs - ",", "," $ write out "COMP_FLAGS = ", ccopt $ copy sys$input: out $ deck CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=($(LIBINCS)[--.include],[--.src.gzip]) OBJS=ftgzip.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.bzip2] directory" $ create [.src.bzip2]descrip.mms $ open/append out [.src.bzip2]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 BZIP2 support compilation rules for VMS # # Copyright 2010-2019 by # Joel Klinghed. # # based on `src/lzw/rules.mk' # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. $EOD $ if libincs .nes. "" then write out "LIBINCS = ", libincs - ",", "," $ write out "COMP_FLAGS = ", ccopt $ copy sys$input: out $ deck CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.bzip2]) OBJS=ftbzip2.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.lzw] directory" $ create [.src.lzw]descrip.mms $ open/append out [.src.lzw]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 LZW support compilation rules for VMS # # Copyright 2004-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. $EOD $ if libincs .nes. "" then write out "LIBINCS = ", libincs - ",", "," $ write out "COMP_FLAGS = ", ccopt $ copy sys$input: out $ deck CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=($(LIBINCS)[--.include],[--.src.lzw]) OBJS=ftlzw.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.otvalid] directory" $ create [.src.otvalid]descrip.mms $ open/append out [.src.otvalid]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 OpenType validation module compilation rules for VMS # # Copyright 2004-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.otvalid]) OBJS=otvalid.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.pcf] directory" $ create [.src.pcf]descrip.mms $ open/append out [.src.pcf]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 pcf driver compilation rules for VMS # # Copyright (C) 2001, 2002 by # Francesco Zappa Nardelli # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.pcf]) OBJS=pcf.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.pfr] directory" $ create [.src.pfr]descrip.mms $ open/append out [.src.pfr]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 PFR driver compilation rules for VMS # # Copyright 2002-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.pfr]) OBJS=pfr.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.psaux] directory" $ create [.src.psaux]descrip.mms $ open/append out [.src.psaux]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 PSaux driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.psaux]) OBJS=psaux.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.pshinter] directory" $ create [.src.pshinter]descrip.mms $ open/append out [.src.pshinter]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 PSHinter driver compilation rules for OpenVMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.psnames]) OBJS=pshinter.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.psnames] directory" $ create [.src.psnames]descrip.mms $ open/append out [.src.psnames]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 psnames driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.psnames]) OBJS=psnames.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.raster] directory" $ create [.src.raster]descrip.mms $ open/append out [.src.raster]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 renderer module compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.raster]) OBJS=raster.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.sfnt] directory" $ create [.src.sfnt]descrip.mms $ open/append out [.src.sfnt]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 SFNT driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.sfnt]) OBJS=sfnt.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.smooth] directory" $ create [.src.smooth]descrip.mms $ open/append out [.src.smooth]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 smooth renderer module compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.smooth]) OBJS=smooth.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.truetype] directory" $ create [.src.truetype]descrip.mms $ open/append out [.src.truetype]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 TrueType driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.truetype]) OBJS=truetype.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.type1] directory" $ create [.src.type1]descrip.mms $ open/append out [.src.type1]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 Type1 driver compilation rules for VMS # # Copyright 1996-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.type1]) OBJS=type1.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.type42] directory" $ create [.src.type42]descrip.mms $ open/append out [.src.type42]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 Type 42 driver compilation rules for VMS # # Copyright 2002-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.type42]) OBJS=type42.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ write sys$output "... [.src.winfonts] directory" $ create [.src.winfonts]descrip.mms $ open/append out [.src.winfonts]descrip.mms $ copy sys$input: out $ deck # # FreeType 2 Windows FNT/FON driver compilation rules for VMS # # Copyright 2001-2019 by # David Turner, Robert Wilhelm, and Werner Lemberg. # # This file is part of the FreeType project, and may only be used, modified, # and distributed under the terms of the FreeType project license, # LICENSE.TXT. By continuing to use, modify, or distribute this file you # indicate that you have read the license and understand and accept it # fully. CFLAGS=$(COMP_FLAGS)$(DEBUG)/include=([--.include],[--.src.winfonts]) OBJS=winfnt.obj all : $(OBJS) library [--.lib]freetype.olb $(OBJS) # EOF $ eod $ close out $ return $!------------------------------------------------------------------------------ $! $! Check command line options and set symbols accordingly $! $ CHECK_OPTS: $ i = 1 $ OPT_LOOP: $ if i .lt. 9 $ then $ cparm = f$edit(p'i',"upcase") $ if cparm .eqs. "DEBUG" $ then $ ccopt = ccopt + "/noopt/deb" $ lopts = lopts + "/deb" $ endif $ if f$locate("CCOPT=",cparm) .lt. f$length(cparm) $ then $ start = f$locate("=",cparm) + 1 $ len = f$length(cparm) - start $ ccopt = ccopt + f$extract(start,len,cparm) $ endif $ if cparm .eqs. "LINK" then linkonly = true $ if f$locate("LOPTS=",cparm) .lt. f$length(cparm) $ then $ start = f$locate("=",cparm) + 1 $ len = f$length(cparm) - start $ lopts = lopts + f$extract(start,len,cparm) $ endif $ if f$locate("CC=",cparm) .lt. f$length(cparm) $ then $ start = f$locate("=",cparm) + 1 $ len = f$length(cparm) - start $ cc_com = f$extract(start,len,cparm) if (cc_com .nes. "DECC") .and. - (cc_com .nes. "VAXC") .and. - (cc_com .nes. "GNUC") $ then $ write sys$output "Unsupported compiler choice ''cc_com' ignored" $ write sys$output "Use DECC, VAXC, or GNUC instead" $ else $ if cc_com .eqs. "DECC" then its_decc = true $ if cc_com .eqs. "VAXC" then its_vaxc = true $ if cc_com .eqs. "GNUC" then its_gnuc = true $ endif $ endif $ if f$locate("MAKE=",cparm) .lt. f$length(cparm) $ then $ start = f$locate("=",cparm) + 1 $ len = f$length(cparm) - start $ mmks = f$extract(start,len,cparm) $ if (mmks .eqs. "MMK") .or. (mmks .eqs. "MMS") $ then $ make = mmks $ else $ write sys$output "Unsupported make choice ''mmks' ignored" $ write sys$output "Use MMK or MMS instead" $ endif $ endif $ i = i + 1 $ goto opt_loop $ endif $ return $!------------------------------------------------------------------------------ $! $! Take care of driver file with information about external libraries $! $! Version history $! 0.01 20040220 First version to receive a number $! 0.02 20040229 Echo current procedure name; use general error exit handler $! Remove xpm hack -> Replaced by more general dnsrl handling $CHECK_CREATE_VMSLIB: $! $ if f$search("VMSLIB.DAT") .eqs. "" $ then $ type/out=vmslib.dat sys$input ! ! This is a simple driver file with information used by vms_make.com to ! check if external libraries (like t1lib and FreeType) are available on ! the system. ! ! Layout of the file: ! ! - Lines starting with ! are treated as comments ! - Elements in a data line are separated by # signs ! - The elements need to be listed in the following order ! 1.) Name of the Library (only used for informative messages ! from vms_make.com) ! 2.) Location where the object library can be found ! 3.) Location where the include files for the library can be found ! 4.) Include file used to verify library location ! 5.) CPP define to pass to the build to indicate availability of ! the library ! ! Example: The following lines show how definitions ! might look like. They are site specific and the locations of the ! library and include files need almost certainly to be changed. ! ! Location: All of the libraries can be found at the following addresses ! ! ZLIB: http://zinser.no-ip.info/vms/sw/zlib.htmlx ! ZLIB # sys$library:libz.olb # sys$library: # zlib.h # FT_CONFIG_OPTION_SYSTEM_ZLIB $ write sys$output "New driver file vmslib.dat created." $ write sys$output "Please customize library locations for your site" $ write sys$output "and afterwards re-execute ''myproc'" $ goto err_exit $ endif $! $! Init symbols used to hold CPP definitions and include path $! $ libdefs = "FT2_BUILD_LIBRARY,FT_CONFIG_OPTION_OLD_INTERNALS," $ libincs = "" $! $! Open data file with location of libraries $! $ open/read/end=end_lib/err=err_lib libdata VMSLIB.DAT $LIB_LOOP: $ read/end=end_lib libdata libline $ libline = f$edit(libline, "UNCOMMENT,COLLAPSE") $ if libline .eqs. "" then goto LIB_LOOP ! Comment line $ libname = f$edit(f$element(0,"#",libline),"UPCASE") $ write sys$output "Processing ''libname' setup ..." $ libloc = f$element(1,"#",libline) $ libsrc = f$element(2,"#",libline) $ testinc = f$element(3,"#",libline) $ cppdef = f$element(4,"#",libline) $ old_cpp = f$locate("=1",cppdef) $ if old_cpp.lt.f$length(cppdef) then cppdef = f$extract(0,old_cpp,cppdef) $ if f$search("''libloc'").eqs. "" $ then $ write sys$output "Can not find library ''libloc' - Skipping ''libname'" $ goto LIB_LOOP $ endif $ libsrc_elem = 0 $ libsrc_found = false $LIBSRC_LOOP: $ libsrcdir = f$element(libsrc_elem,",",libsrc) $ if (libsrcdir .eqs. ",") then goto END_LIBSRC $ if f$search("''libsrcdir'''testinc'") .nes. "" then libsrc_found = true $ libsrc_elem = libsrc_elem + 1 $ goto LIBSRC_LOOP $END_LIBSRC: $ if .not. libsrc_found $ then $ write sys$output "Can not find includes at ''libsrc' - Skipping ''libname'" $ goto LIB_LOOP $ endif $ if (cppdef .nes. "") then libdefs = libdefs + cppdef + "," $ libincs = libincs + "," + libsrc $ lqual = "/lib" $ libtype = f$edit(f$parse(libloc,,,"TYPE"),"UPCASE") $ if f$locate("EXE",libtype) .lt. f$length(libtype) then lqual = "/share" $ write optf libloc , lqual $ if (f$trnlnm("topt") .nes. "") then write topt libloc , lqual $! $! Nasty hack to get the FreeType includes to work $! $ ft2def = false $ if ((libname .eqs. "FREETYPE") .and. - (f$locate("FREETYPE2",cppdef) .lt. f$length(cppdef))) $ then $ if ((f$search("freetype:freetype.h") .nes. "") .and. - (f$search("freetype:[internal]ftobjs.h") .nes. "")) $ then $ write sys$output "Will use local definition of freetype logical" $ else $ ft2elem = 0 $FT2_LOOP: $ ft2srcdir = f$element(ft2elem,",",libsrc) $ if f$search("''ft2srcdir'''testinc'") .nes. "" $ then $ if f$search("''ft2srcdir'internal.dir") .nes. "" $ then $ ft2dev = f$parse("''ft2srcdir'",,,"device","no_conceal") $ ft2dir = f$parse("''ft2srcdir'",,,"directory","no_conceal") $ ft2conc = f$locate("][",ft2dir) $ ft2len = f$length(ft2dir) $ if ft2conc .lt. ft2len $ then $ ft2dir = f$extract(0,ft2conc,ft2dir) + - f$extract(ft2conc+2,ft2len-2,ft2dir) $ endif $ ft2dir = ft2dir - "]" + ".]" $ define freetype 'ft2dev''ft2dir','ft2srcdir' $ ft2def = true $ else $ goto ft2_err $ endif $ else $ ft2elem = ft2elem + 1 $ goto ft2_loop $ endif $ endif $ endif $ goto LIB_LOOP $END_LIB: $ close libdata $ return $!------------------------------------------------------------------------------ $! $! Analyze Object files for OpenVMS AXP to extract Procedure and Data $! information to build a symbol vector for a shareable image $! All the "brains" of this logic was suggested by Hartmut Becker $! (Hartmut.Becker@compaq.com). All the bugs were introduced by me $! (zinser@zinser.no-ip.info), so if you do have problem reports please do not $! bother Hartmut/HP, but get in touch with me $! $! Version history $! 0.01 20040006 Skip over shareable images in option file $! $ ANAL_OBJ_AXP: Subroutine $ V = 'F$Verify(0) $ SAY := "WRITE_ SYS$OUTPUT" $ $ IF F$SEARCH("''P1'") .EQS. "" $ THEN $ SAY "ANAL_OBJ_AXP-E-NOSUCHFILE: Error, inputfile ''p1' not available" $ goto exit_aa $ ENDIF $ IF "''P2'" .EQS. "" $ THEN $ SAY "ANAL_OBJ_AXP: Error, no output file provided" $ goto exit_aa $ ENDIF $ $ open/read in 'p1 $ create a.tmp $ open/append atmp a.tmp $ loop: $ read/end=end_loop in line $ if f$locate("/SHARE",f$edit(line,"upcase")) .lt. f$length(line) $ then $ write sys$output "ANAL_SKP_SHR-i-skipshare, ''line'" $ goto loop $ endif $ if f$locate("/LIB",f$edit(line,"upcase")) .lt. f$length(line) $ then $ write libsf line $ write sys$output "ANAL_SKP_LIB-i-skiplib, ''line'" $ goto loop $ endif $ f= f$search(line) $ if f .eqs. "" $ then $ write sys$output "ANAL_OBJ_AXP-w-nosuchfile, ''line'" $ goto loop $ endif $ def/user sys$output nl: $ def/user sys$error nl: $ anal/obj/gsd 'f /out=x.tmp $ open/read xtmp x.tmp $ XLOOP: $ read/end=end_xloop xtmp xline $ xline = f$edit(xline,"compress") $ write atmp xline $ goto xloop $ END_XLOOP: $ close xtmp $ goto loop $ end_loop: $ close in $ close atmp $ if f$search("a.tmp") .eqs. "" - then $ exit $ ! all global definitions $ search a.tmp "symbol:","EGSY$V_DEF 1","EGSY$V_NORM 1"/out=b.tmp $ ! all procedures $ search b.tmp "EGSY$V_NORM 1"/wind=(0,1) /out=c.tmp $ search c.tmp "symbol:"/out=d.tmp $ def/user sys$output nl: $ edito/edt/command=sys$input d.tmp sub/symbol: "/symbol_vector=(/whole sub/"/=PROCEDURE)/whole exit $ ! all data $ search b.tmp "EGSY$V_DEF 1"/wind=(0,1) /out=e.tmp $ search e.tmp "symbol:"/out=f.tmp $ def/user sys$output nl: $ edito/edt/command=sys$input f.tmp sub/symbol: "/symbol_vector=(/whole sub/"/=DATA)/whole exit $ sort/nodupl d.tmp,f.tmp 'p2' $ delete a.tmp;*,b.tmp;*,c.tmp;*,d.tmp;*,e.tmp;*,f.tmp;* $ if f$search("x.tmp") .nes. "" - then $ delete x.tmp;* $! $ close libsf $ EXIT_AA: $ if V then set verify $ endsubroutine
whupdup/frame
real/third_party/freetype-2.12.0/vms_make.com
com
gpl-3.0
36,034
/* ** Copyright (c) 2014-2020 The Khronos Group Inc. ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and/or associated documentation files (the "Materials"), ** to deal in the Materials without restriction, including without limitation ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** and/or sell copies of the Materials, and to permit persons to whom the ** Materials are furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Materials. ** ** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS ** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND ** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ ** ** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ** FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS ** IN THE MATERIALS. */ /* ** This header is automatically generated by the same tool that creates ** the Binary Section of the SPIR-V specification. */ /* ** Enumeration tokens for SPIR-V, in various styles: ** C, C++, C++11, JSON, Lua, Python, C#, D ** ** - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL ** - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL ** - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL ** - Lua will use tables, e.g.: spv.SourceLanguage.GLSL ** - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] ** - C# will use enum classes in the Specification class located in the "Spv" namespace, ** e.g.: Spv.Specification.SourceLanguage.GLSL ** - D will have tokens under the "spv" module, e.g: spv.SourceLanguage.GLSL ** ** Some tokens act like mask values, which can be OR'd together, ** while others are mutually exclusive. The mask-like ones have ** "Mask" in their name, and a parallel enum that has the shift ** amount (1 << x) for each corresponding enumerant. */ #ifndef spirv_H #define spirv_H typedef unsigned int SpvId; #define SPV_VERSION 0x10600 #define SPV_REVISION 1 static const unsigned int SpvMagicNumber = 0x07230203; static const unsigned int SpvVersion = 0x00010600; static const unsigned int SpvRevision = 1; static const unsigned int SpvOpCodeMask = 0xffff; static const unsigned int SpvWordCountShift = 16; typedef enum SpvSourceLanguage_ { SpvSourceLanguageUnknown = 0, SpvSourceLanguageESSL = 1, SpvSourceLanguageGLSL = 2, SpvSourceLanguageOpenCL_C = 3, SpvSourceLanguageOpenCL_CPP = 4, SpvSourceLanguageHLSL = 5, SpvSourceLanguageCPP_for_OpenCL = 6, SpvSourceLanguageMax = 0x7fffffff, } SpvSourceLanguage; typedef enum SpvExecutionModel_ { SpvExecutionModelVertex = 0, SpvExecutionModelTessellationControl = 1, SpvExecutionModelTessellationEvaluation = 2, SpvExecutionModelGeometry = 3, SpvExecutionModelFragment = 4, SpvExecutionModelGLCompute = 5, SpvExecutionModelKernel = 6, SpvExecutionModelTaskNV = 5267, SpvExecutionModelMeshNV = 5268, SpvExecutionModelRayGenerationKHR = 5313, SpvExecutionModelRayGenerationNV = 5313, SpvExecutionModelIntersectionKHR = 5314, SpvExecutionModelIntersectionNV = 5314, SpvExecutionModelAnyHitKHR = 5315, SpvExecutionModelAnyHitNV = 5315, SpvExecutionModelClosestHitKHR = 5316, SpvExecutionModelClosestHitNV = 5316, SpvExecutionModelMissKHR = 5317, SpvExecutionModelMissNV = 5317, SpvExecutionModelCallableKHR = 5318, SpvExecutionModelCallableNV = 5318, SpvExecutionModelMax = 0x7fffffff, } SpvExecutionModel; typedef enum SpvAddressingModel_ { SpvAddressingModelLogical = 0, SpvAddressingModelPhysical32 = 1, SpvAddressingModelPhysical64 = 2, SpvAddressingModelPhysicalStorageBuffer64 = 5348, SpvAddressingModelPhysicalStorageBuffer64EXT = 5348, SpvAddressingModelMax = 0x7fffffff, } SpvAddressingModel; typedef enum SpvMemoryModel_ { SpvMemoryModelSimple = 0, SpvMemoryModelGLSL450 = 1, SpvMemoryModelOpenCL = 2, SpvMemoryModelVulkan = 3, SpvMemoryModelVulkanKHR = 3, SpvMemoryModelMax = 0x7fffffff, } SpvMemoryModel; typedef enum SpvExecutionMode_ { SpvExecutionModeInvocations = 0, SpvExecutionModeSpacingEqual = 1, SpvExecutionModeSpacingFractionalEven = 2, SpvExecutionModeSpacingFractionalOdd = 3, SpvExecutionModeVertexOrderCw = 4, SpvExecutionModeVertexOrderCcw = 5, SpvExecutionModePixelCenterInteger = 6, SpvExecutionModeOriginUpperLeft = 7, SpvExecutionModeOriginLowerLeft = 8, SpvExecutionModeEarlyFragmentTests = 9, SpvExecutionModePointMode = 10, SpvExecutionModeXfb = 11, SpvExecutionModeDepthReplacing = 12, SpvExecutionModeDepthGreater = 14, SpvExecutionModeDepthLess = 15, SpvExecutionModeDepthUnchanged = 16, SpvExecutionModeLocalSize = 17, SpvExecutionModeLocalSizeHint = 18, SpvExecutionModeInputPoints = 19, SpvExecutionModeInputLines = 20, SpvExecutionModeInputLinesAdjacency = 21, SpvExecutionModeTriangles = 22, SpvExecutionModeInputTrianglesAdjacency = 23, SpvExecutionModeQuads = 24, SpvExecutionModeIsolines = 25, SpvExecutionModeOutputVertices = 26, SpvExecutionModeOutputPoints = 27, SpvExecutionModeOutputLineStrip = 28, SpvExecutionModeOutputTriangleStrip = 29, SpvExecutionModeVecTypeHint = 30, SpvExecutionModeContractionOff = 31, SpvExecutionModeInitializer = 33, SpvExecutionModeFinalizer = 34, SpvExecutionModeSubgroupSize = 35, SpvExecutionModeSubgroupsPerWorkgroup = 36, SpvExecutionModeSubgroupsPerWorkgroupId = 37, SpvExecutionModeLocalSizeId = 38, SpvExecutionModeLocalSizeHintId = 39, SpvExecutionModeSubgroupUniformControlFlowKHR = 4421, SpvExecutionModePostDepthCoverage = 4446, SpvExecutionModeDenormPreserve = 4459, SpvExecutionModeDenormFlushToZero = 4460, SpvExecutionModeSignedZeroInfNanPreserve = 4461, SpvExecutionModeRoundingModeRTE = 4462, SpvExecutionModeRoundingModeRTZ = 4463, SpvExecutionModeStencilRefReplacingEXT = 5027, SpvExecutionModeOutputLinesNV = 5269, SpvExecutionModeOutputPrimitivesNV = 5270, SpvExecutionModeDerivativeGroupQuadsNV = 5289, SpvExecutionModeDerivativeGroupLinearNV = 5290, SpvExecutionModeOutputTrianglesNV = 5298, SpvExecutionModePixelInterlockOrderedEXT = 5366, SpvExecutionModePixelInterlockUnorderedEXT = 5367, SpvExecutionModeSampleInterlockOrderedEXT = 5368, SpvExecutionModeSampleInterlockUnorderedEXT = 5369, SpvExecutionModeShadingRateInterlockOrderedEXT = 5370, SpvExecutionModeShadingRateInterlockUnorderedEXT = 5371, SpvExecutionModeSharedLocalMemorySizeINTEL = 5618, SpvExecutionModeRoundingModeRTPINTEL = 5620, SpvExecutionModeRoundingModeRTNINTEL = 5621, SpvExecutionModeFloatingPointModeALTINTEL = 5622, SpvExecutionModeFloatingPointModeIEEEINTEL = 5623, SpvExecutionModeMaxWorkgroupSizeINTEL = 5893, SpvExecutionModeMaxWorkDimINTEL = 5894, SpvExecutionModeNoGlobalOffsetINTEL = 5895, SpvExecutionModeNumSIMDWorkitemsINTEL = 5896, SpvExecutionModeSchedulerTargetFmaxMhzINTEL = 5903, SpvExecutionModeMax = 0x7fffffff, } SpvExecutionMode; typedef enum SpvStorageClass_ { SpvStorageClassUniformConstant = 0, SpvStorageClassInput = 1, SpvStorageClassUniform = 2, SpvStorageClassOutput = 3, SpvStorageClassWorkgroup = 4, SpvStorageClassCrossWorkgroup = 5, SpvStorageClassPrivate = 6, SpvStorageClassFunction = 7, SpvStorageClassGeneric = 8, SpvStorageClassPushConstant = 9, SpvStorageClassAtomicCounter = 10, SpvStorageClassImage = 11, SpvStorageClassStorageBuffer = 12, SpvStorageClassCallableDataKHR = 5328, SpvStorageClassCallableDataNV = 5328, SpvStorageClassIncomingCallableDataKHR = 5329, SpvStorageClassIncomingCallableDataNV = 5329, SpvStorageClassRayPayloadKHR = 5338, SpvStorageClassRayPayloadNV = 5338, SpvStorageClassHitAttributeKHR = 5339, SpvStorageClassHitAttributeNV = 5339, SpvStorageClassIncomingRayPayloadKHR = 5342, SpvStorageClassIncomingRayPayloadNV = 5342, SpvStorageClassShaderRecordBufferKHR = 5343, SpvStorageClassShaderRecordBufferNV = 5343, SpvStorageClassPhysicalStorageBuffer = 5349, SpvStorageClassPhysicalStorageBufferEXT = 5349, SpvStorageClassCodeSectionINTEL = 5605, SpvStorageClassDeviceOnlyINTEL = 5936, SpvStorageClassHostOnlyINTEL = 5937, SpvStorageClassMax = 0x7fffffff, } SpvStorageClass; typedef enum SpvDim_ { SpvDim1D = 0, SpvDim2D = 1, SpvDim3D = 2, SpvDimCube = 3, SpvDimRect = 4, SpvDimBuffer = 5, SpvDimSubpassData = 6, SpvDimMax = 0x7fffffff, } SpvDim; typedef enum SpvSamplerAddressingMode_ { SpvSamplerAddressingModeNone = 0, SpvSamplerAddressingModeClampToEdge = 1, SpvSamplerAddressingModeClamp = 2, SpvSamplerAddressingModeRepeat = 3, SpvSamplerAddressingModeRepeatMirrored = 4, SpvSamplerAddressingModeMax = 0x7fffffff, } SpvSamplerAddressingMode; typedef enum SpvSamplerFilterMode_ { SpvSamplerFilterModeNearest = 0, SpvSamplerFilterModeLinear = 1, SpvSamplerFilterModeMax = 0x7fffffff, } SpvSamplerFilterMode; typedef enum SpvImageFormat_ { SpvImageFormatUnknown = 0, SpvImageFormatRgba32f = 1, SpvImageFormatRgba16f = 2, SpvImageFormatR32f = 3, SpvImageFormatRgba8 = 4, SpvImageFormatRgba8Snorm = 5, SpvImageFormatRg32f = 6, SpvImageFormatRg16f = 7, SpvImageFormatR11fG11fB10f = 8, SpvImageFormatR16f = 9, SpvImageFormatRgba16 = 10, SpvImageFormatRgb10A2 = 11, SpvImageFormatRg16 = 12, SpvImageFormatRg8 = 13, SpvImageFormatR16 = 14, SpvImageFormatR8 = 15, SpvImageFormatRgba16Snorm = 16, SpvImageFormatRg16Snorm = 17, SpvImageFormatRg8Snorm = 18, SpvImageFormatR16Snorm = 19, SpvImageFormatR8Snorm = 20, SpvImageFormatRgba32i = 21, SpvImageFormatRgba16i = 22, SpvImageFormatRgba8i = 23, SpvImageFormatR32i = 24, SpvImageFormatRg32i = 25, SpvImageFormatRg16i = 26, SpvImageFormatRg8i = 27, SpvImageFormatR16i = 28, SpvImageFormatR8i = 29, SpvImageFormatRgba32ui = 30, SpvImageFormatRgba16ui = 31, SpvImageFormatRgba8ui = 32, SpvImageFormatR32ui = 33, SpvImageFormatRgb10a2ui = 34, SpvImageFormatRg32ui = 35, SpvImageFormatRg16ui = 36, SpvImageFormatRg8ui = 37, SpvImageFormatR16ui = 38, SpvImageFormatR8ui = 39, SpvImageFormatR64ui = 40, SpvImageFormatR64i = 41, SpvImageFormatMax = 0x7fffffff, } SpvImageFormat; typedef enum SpvImageChannelOrder_ { SpvImageChannelOrderR = 0, SpvImageChannelOrderA = 1, SpvImageChannelOrderRG = 2, SpvImageChannelOrderRA = 3, SpvImageChannelOrderRGB = 4, SpvImageChannelOrderRGBA = 5, SpvImageChannelOrderBGRA = 6, SpvImageChannelOrderARGB = 7, SpvImageChannelOrderIntensity = 8, SpvImageChannelOrderLuminance = 9, SpvImageChannelOrderRx = 10, SpvImageChannelOrderRGx = 11, SpvImageChannelOrderRGBx = 12, SpvImageChannelOrderDepth = 13, SpvImageChannelOrderDepthStencil = 14, SpvImageChannelOrdersRGB = 15, SpvImageChannelOrdersRGBx = 16, SpvImageChannelOrdersRGBA = 17, SpvImageChannelOrdersBGRA = 18, SpvImageChannelOrderABGR = 19, SpvImageChannelOrderMax = 0x7fffffff, } SpvImageChannelOrder; typedef enum SpvImageChannelDataType_ { SpvImageChannelDataTypeSnormInt8 = 0, SpvImageChannelDataTypeSnormInt16 = 1, SpvImageChannelDataTypeUnormInt8 = 2, SpvImageChannelDataTypeUnormInt16 = 3, SpvImageChannelDataTypeUnormShort565 = 4, SpvImageChannelDataTypeUnormShort555 = 5, SpvImageChannelDataTypeUnormInt101010 = 6, SpvImageChannelDataTypeSignedInt8 = 7, SpvImageChannelDataTypeSignedInt16 = 8, SpvImageChannelDataTypeSignedInt32 = 9, SpvImageChannelDataTypeUnsignedInt8 = 10, SpvImageChannelDataTypeUnsignedInt16 = 11, SpvImageChannelDataTypeUnsignedInt32 = 12, SpvImageChannelDataTypeHalfFloat = 13, SpvImageChannelDataTypeFloat = 14, SpvImageChannelDataTypeUnormInt24 = 15, SpvImageChannelDataTypeUnormInt101010_2 = 16, SpvImageChannelDataTypeMax = 0x7fffffff, } SpvImageChannelDataType; typedef enum SpvImageOperandsShift_ { SpvImageOperandsBiasShift = 0, SpvImageOperandsLodShift = 1, SpvImageOperandsGradShift = 2, SpvImageOperandsConstOffsetShift = 3, SpvImageOperandsOffsetShift = 4, SpvImageOperandsConstOffsetsShift = 5, SpvImageOperandsSampleShift = 6, SpvImageOperandsMinLodShift = 7, SpvImageOperandsMakeTexelAvailableShift = 8, SpvImageOperandsMakeTexelAvailableKHRShift = 8, SpvImageOperandsMakeTexelVisibleShift = 9, SpvImageOperandsMakeTexelVisibleKHRShift = 9, SpvImageOperandsNonPrivateTexelShift = 10, SpvImageOperandsNonPrivateTexelKHRShift = 10, SpvImageOperandsVolatileTexelShift = 11, SpvImageOperandsVolatileTexelKHRShift = 11, SpvImageOperandsSignExtendShift = 12, SpvImageOperandsZeroExtendShift = 13, SpvImageOperandsNontemporalShift = 14, SpvImageOperandsOffsetsShift = 16, SpvImageOperandsMax = 0x7fffffff, } SpvImageOperandsShift; typedef enum SpvImageOperandsMask_ { SpvImageOperandsMaskNone = 0, SpvImageOperandsBiasMask = 0x00000001, SpvImageOperandsLodMask = 0x00000002, SpvImageOperandsGradMask = 0x00000004, SpvImageOperandsConstOffsetMask = 0x00000008, SpvImageOperandsOffsetMask = 0x00000010, SpvImageOperandsConstOffsetsMask = 0x00000020, SpvImageOperandsSampleMask = 0x00000040, SpvImageOperandsMinLodMask = 0x00000080, SpvImageOperandsMakeTexelAvailableMask = 0x00000100, SpvImageOperandsMakeTexelAvailableKHRMask = 0x00000100, SpvImageOperandsMakeTexelVisibleMask = 0x00000200, SpvImageOperandsMakeTexelVisibleKHRMask = 0x00000200, SpvImageOperandsNonPrivateTexelMask = 0x00000400, SpvImageOperandsNonPrivateTexelKHRMask = 0x00000400, SpvImageOperandsVolatileTexelMask = 0x00000800, SpvImageOperandsVolatileTexelKHRMask = 0x00000800, SpvImageOperandsSignExtendMask = 0x00001000, SpvImageOperandsZeroExtendMask = 0x00002000, SpvImageOperandsNontemporalMask = 0x00004000, SpvImageOperandsOffsetsMask = 0x00010000, } SpvImageOperandsMask; typedef enum SpvFPFastMathModeShift_ { SpvFPFastMathModeNotNaNShift = 0, SpvFPFastMathModeNotInfShift = 1, SpvFPFastMathModeNSZShift = 2, SpvFPFastMathModeAllowRecipShift = 3, SpvFPFastMathModeFastShift = 4, SpvFPFastMathModeAllowContractFastINTELShift = 16, SpvFPFastMathModeAllowReassocINTELShift = 17, SpvFPFastMathModeMax = 0x7fffffff, } SpvFPFastMathModeShift; typedef enum SpvFPFastMathModeMask_ { SpvFPFastMathModeMaskNone = 0, SpvFPFastMathModeNotNaNMask = 0x00000001, SpvFPFastMathModeNotInfMask = 0x00000002, SpvFPFastMathModeNSZMask = 0x00000004, SpvFPFastMathModeAllowRecipMask = 0x00000008, SpvFPFastMathModeFastMask = 0x00000010, SpvFPFastMathModeAllowContractFastINTELMask = 0x00010000, SpvFPFastMathModeAllowReassocINTELMask = 0x00020000, } SpvFPFastMathModeMask; typedef enum SpvFPRoundingMode_ { SpvFPRoundingModeRTE = 0, SpvFPRoundingModeRTZ = 1, SpvFPRoundingModeRTP = 2, SpvFPRoundingModeRTN = 3, SpvFPRoundingModeMax = 0x7fffffff, } SpvFPRoundingMode; typedef enum SpvLinkageType_ { SpvLinkageTypeExport = 0, SpvLinkageTypeImport = 1, SpvLinkageTypeLinkOnceODR = 2, SpvLinkageTypeMax = 0x7fffffff, } SpvLinkageType; typedef enum SpvAccessQualifier_ { SpvAccessQualifierReadOnly = 0, SpvAccessQualifierWriteOnly = 1, SpvAccessQualifierReadWrite = 2, SpvAccessQualifierMax = 0x7fffffff, } SpvAccessQualifier; typedef enum SpvFunctionParameterAttribute_ { SpvFunctionParameterAttributeZext = 0, SpvFunctionParameterAttributeSext = 1, SpvFunctionParameterAttributeByVal = 2, SpvFunctionParameterAttributeSret = 3, SpvFunctionParameterAttributeNoAlias = 4, SpvFunctionParameterAttributeNoCapture = 5, SpvFunctionParameterAttributeNoWrite = 6, SpvFunctionParameterAttributeNoReadWrite = 7, SpvFunctionParameterAttributeMax = 0x7fffffff, } SpvFunctionParameterAttribute; typedef enum SpvDecoration_ { SpvDecorationRelaxedPrecision = 0, SpvDecorationSpecId = 1, SpvDecorationBlock = 2, SpvDecorationBufferBlock = 3, SpvDecorationRowMajor = 4, SpvDecorationColMajor = 5, SpvDecorationArrayStride = 6, SpvDecorationMatrixStride = 7, SpvDecorationGLSLShared = 8, SpvDecorationGLSLPacked = 9, SpvDecorationCPacked = 10, SpvDecorationBuiltIn = 11, SpvDecorationNoPerspective = 13, SpvDecorationFlat = 14, SpvDecorationPatch = 15, SpvDecorationCentroid = 16, SpvDecorationSample = 17, SpvDecorationInvariant = 18, SpvDecorationRestrict = 19, SpvDecorationAliased = 20, SpvDecorationVolatile = 21, SpvDecorationConstant = 22, SpvDecorationCoherent = 23, SpvDecorationNonWritable = 24, SpvDecorationNonReadable = 25, SpvDecorationUniform = 26, SpvDecorationUniformId = 27, SpvDecorationSaturatedConversion = 28, SpvDecorationStream = 29, SpvDecorationLocation = 30, SpvDecorationComponent = 31, SpvDecorationIndex = 32, SpvDecorationBinding = 33, SpvDecorationDescriptorSet = 34, SpvDecorationOffset = 35, SpvDecorationXfbBuffer = 36, SpvDecorationXfbStride = 37, SpvDecorationFuncParamAttr = 38, SpvDecorationFPRoundingMode = 39, SpvDecorationFPFastMathMode = 40, SpvDecorationLinkageAttributes = 41, SpvDecorationNoContraction = 42, SpvDecorationInputAttachmentIndex = 43, SpvDecorationAlignment = 44, SpvDecorationMaxByteOffset = 45, SpvDecorationAlignmentId = 46, SpvDecorationMaxByteOffsetId = 47, SpvDecorationNoSignedWrap = 4469, SpvDecorationNoUnsignedWrap = 4470, SpvDecorationExplicitInterpAMD = 4999, SpvDecorationOverrideCoverageNV = 5248, SpvDecorationPassthroughNV = 5250, SpvDecorationViewportRelativeNV = 5252, SpvDecorationSecondaryViewportRelativeNV = 5256, SpvDecorationPerPrimitiveNV = 5271, SpvDecorationPerViewNV = 5272, SpvDecorationPerTaskNV = 5273, SpvDecorationPerVertexKHR = 5285, SpvDecorationPerVertexNV = 5285, SpvDecorationNonUniform = 5300, SpvDecorationNonUniformEXT = 5300, SpvDecorationRestrictPointer = 5355, SpvDecorationRestrictPointerEXT = 5355, SpvDecorationAliasedPointer = 5356, SpvDecorationAliasedPointerEXT = 5356, SpvDecorationBindlessSamplerNV = 5398, SpvDecorationBindlessImageNV = 5399, SpvDecorationBoundSamplerNV = 5400, SpvDecorationBoundImageNV = 5401, SpvDecorationSIMTCallINTEL = 5599, SpvDecorationReferencedIndirectlyINTEL = 5602, SpvDecorationClobberINTEL = 5607, SpvDecorationSideEffectsINTEL = 5608, SpvDecorationVectorComputeVariableINTEL = 5624, SpvDecorationFuncParamIOKindINTEL = 5625, SpvDecorationVectorComputeFunctionINTEL = 5626, SpvDecorationStackCallINTEL = 5627, SpvDecorationGlobalVariableOffsetINTEL = 5628, SpvDecorationCounterBuffer = 5634, SpvDecorationHlslCounterBufferGOOGLE = 5634, SpvDecorationHlslSemanticGOOGLE = 5635, SpvDecorationUserSemantic = 5635, SpvDecorationUserTypeGOOGLE = 5636, SpvDecorationFunctionRoundingModeINTEL = 5822, SpvDecorationFunctionDenormModeINTEL = 5823, SpvDecorationRegisterINTEL = 5825, SpvDecorationMemoryINTEL = 5826, SpvDecorationNumbanksINTEL = 5827, SpvDecorationBankwidthINTEL = 5828, SpvDecorationMaxPrivateCopiesINTEL = 5829, SpvDecorationSinglepumpINTEL = 5830, SpvDecorationDoublepumpINTEL = 5831, SpvDecorationMaxReplicatesINTEL = 5832, SpvDecorationSimpleDualPortINTEL = 5833, SpvDecorationMergeINTEL = 5834, SpvDecorationBankBitsINTEL = 5835, SpvDecorationForcePow2DepthINTEL = 5836, SpvDecorationBurstCoalesceINTEL = 5899, SpvDecorationCacheSizeINTEL = 5900, SpvDecorationDontStaticallyCoalesceINTEL = 5901, SpvDecorationPrefetchINTEL = 5902, SpvDecorationStallEnableINTEL = 5905, SpvDecorationFuseLoopsInFunctionINTEL = 5907, SpvDecorationBufferLocationINTEL = 5921, SpvDecorationIOPipeStorageINTEL = 5944, SpvDecorationFunctionFloatingPointModeINTEL = 6080, SpvDecorationSingleElementVectorINTEL = 6085, SpvDecorationVectorComputeCallableFunctionINTEL = 6087, SpvDecorationMediaBlockIOINTEL = 6140, SpvDecorationMax = 0x7fffffff, } SpvDecoration; typedef enum SpvBuiltIn_ { SpvBuiltInPosition = 0, SpvBuiltInPointSize = 1, SpvBuiltInClipDistance = 3, SpvBuiltInCullDistance = 4, SpvBuiltInVertexId = 5, SpvBuiltInInstanceId = 6, SpvBuiltInPrimitiveId = 7, SpvBuiltInInvocationId = 8, SpvBuiltInLayer = 9, SpvBuiltInViewportIndex = 10, SpvBuiltInTessLevelOuter = 11, SpvBuiltInTessLevelInner = 12, SpvBuiltInTessCoord = 13, SpvBuiltInPatchVertices = 14, SpvBuiltInFragCoord = 15, SpvBuiltInPointCoord = 16, SpvBuiltInFrontFacing = 17, SpvBuiltInSampleId = 18, SpvBuiltInSamplePosition = 19, SpvBuiltInSampleMask = 20, SpvBuiltInFragDepth = 22, SpvBuiltInHelperInvocation = 23, SpvBuiltInNumWorkgroups = 24, SpvBuiltInWorkgroupSize = 25, SpvBuiltInWorkgroupId = 26, SpvBuiltInLocalInvocationId = 27, SpvBuiltInGlobalInvocationId = 28, SpvBuiltInLocalInvocationIndex = 29, SpvBuiltInWorkDim = 30, SpvBuiltInGlobalSize = 31, SpvBuiltInEnqueuedWorkgroupSize = 32, SpvBuiltInGlobalOffset = 33, SpvBuiltInGlobalLinearId = 34, SpvBuiltInSubgroupSize = 36, SpvBuiltInSubgroupMaxSize = 37, SpvBuiltInNumSubgroups = 38, SpvBuiltInNumEnqueuedSubgroups = 39, SpvBuiltInSubgroupId = 40, SpvBuiltInSubgroupLocalInvocationId = 41, SpvBuiltInVertexIndex = 42, SpvBuiltInInstanceIndex = 43, SpvBuiltInSubgroupEqMask = 4416, SpvBuiltInSubgroupEqMaskKHR = 4416, SpvBuiltInSubgroupGeMask = 4417, SpvBuiltInSubgroupGeMaskKHR = 4417, SpvBuiltInSubgroupGtMask = 4418, SpvBuiltInSubgroupGtMaskKHR = 4418, SpvBuiltInSubgroupLeMask = 4419, SpvBuiltInSubgroupLeMaskKHR = 4419, SpvBuiltInSubgroupLtMask = 4420, SpvBuiltInSubgroupLtMaskKHR = 4420, SpvBuiltInBaseVertex = 4424, SpvBuiltInBaseInstance = 4425, SpvBuiltInDrawIndex = 4426, SpvBuiltInPrimitiveShadingRateKHR = 4432, SpvBuiltInDeviceIndex = 4438, SpvBuiltInViewIndex = 4440, SpvBuiltInShadingRateKHR = 4444, SpvBuiltInBaryCoordNoPerspAMD = 4992, SpvBuiltInBaryCoordNoPerspCentroidAMD = 4993, SpvBuiltInBaryCoordNoPerspSampleAMD = 4994, SpvBuiltInBaryCoordSmoothAMD = 4995, SpvBuiltInBaryCoordSmoothCentroidAMD = 4996, SpvBuiltInBaryCoordSmoothSampleAMD = 4997, SpvBuiltInBaryCoordPullModelAMD = 4998, SpvBuiltInFragStencilRefEXT = 5014, SpvBuiltInViewportMaskNV = 5253, SpvBuiltInSecondaryPositionNV = 5257, SpvBuiltInSecondaryViewportMaskNV = 5258, SpvBuiltInPositionPerViewNV = 5261, SpvBuiltInViewportMaskPerViewNV = 5262, SpvBuiltInFullyCoveredEXT = 5264, SpvBuiltInTaskCountNV = 5274, SpvBuiltInPrimitiveCountNV = 5275, SpvBuiltInPrimitiveIndicesNV = 5276, SpvBuiltInClipDistancePerViewNV = 5277, SpvBuiltInCullDistancePerViewNV = 5278, SpvBuiltInLayerPerViewNV = 5279, SpvBuiltInMeshViewCountNV = 5280, SpvBuiltInMeshViewIndicesNV = 5281, SpvBuiltInBaryCoordKHR = 5286, SpvBuiltInBaryCoordNV = 5286, SpvBuiltInBaryCoordNoPerspKHR = 5287, SpvBuiltInBaryCoordNoPerspNV = 5287, SpvBuiltInFragSizeEXT = 5292, SpvBuiltInFragmentSizeNV = 5292, SpvBuiltInFragInvocationCountEXT = 5293, SpvBuiltInInvocationsPerPixelNV = 5293, SpvBuiltInLaunchIdKHR = 5319, SpvBuiltInLaunchIdNV = 5319, SpvBuiltInLaunchSizeKHR = 5320, SpvBuiltInLaunchSizeNV = 5320, SpvBuiltInWorldRayOriginKHR = 5321, SpvBuiltInWorldRayOriginNV = 5321, SpvBuiltInWorldRayDirectionKHR = 5322, SpvBuiltInWorldRayDirectionNV = 5322, SpvBuiltInObjectRayOriginKHR = 5323, SpvBuiltInObjectRayOriginNV = 5323, SpvBuiltInObjectRayDirectionKHR = 5324, SpvBuiltInObjectRayDirectionNV = 5324, SpvBuiltInRayTminKHR = 5325, SpvBuiltInRayTminNV = 5325, SpvBuiltInRayTmaxKHR = 5326, SpvBuiltInRayTmaxNV = 5326, SpvBuiltInInstanceCustomIndexKHR = 5327, SpvBuiltInInstanceCustomIndexNV = 5327, SpvBuiltInObjectToWorldKHR = 5330, SpvBuiltInObjectToWorldNV = 5330, SpvBuiltInWorldToObjectKHR = 5331, SpvBuiltInWorldToObjectNV = 5331, SpvBuiltInHitTNV = 5332, SpvBuiltInHitKindKHR = 5333, SpvBuiltInHitKindNV = 5333, SpvBuiltInCurrentRayTimeNV = 5334, SpvBuiltInIncomingRayFlagsKHR = 5351, SpvBuiltInIncomingRayFlagsNV = 5351, SpvBuiltInRayGeometryIndexKHR = 5352, SpvBuiltInWarpsPerSMNV = 5374, SpvBuiltInSMCountNV = 5375, SpvBuiltInWarpIDNV = 5376, SpvBuiltInSMIDNV = 5377, SpvBuiltInMax = 0x7fffffff, } SpvBuiltIn; typedef enum SpvSelectionControlShift_ { SpvSelectionControlFlattenShift = 0, SpvSelectionControlDontFlattenShift = 1, SpvSelectionControlMax = 0x7fffffff, } SpvSelectionControlShift; typedef enum SpvSelectionControlMask_ { SpvSelectionControlMaskNone = 0, SpvSelectionControlFlattenMask = 0x00000001, SpvSelectionControlDontFlattenMask = 0x00000002, } SpvSelectionControlMask; typedef enum SpvLoopControlShift_ { SpvLoopControlUnrollShift = 0, SpvLoopControlDontUnrollShift = 1, SpvLoopControlDependencyInfiniteShift = 2, SpvLoopControlDependencyLengthShift = 3, SpvLoopControlMinIterationsShift = 4, SpvLoopControlMaxIterationsShift = 5, SpvLoopControlIterationMultipleShift = 6, SpvLoopControlPeelCountShift = 7, SpvLoopControlPartialCountShift = 8, SpvLoopControlInitiationIntervalINTELShift = 16, SpvLoopControlMaxConcurrencyINTELShift = 17, SpvLoopControlDependencyArrayINTELShift = 18, SpvLoopControlPipelineEnableINTELShift = 19, SpvLoopControlLoopCoalesceINTELShift = 20, SpvLoopControlMaxInterleavingINTELShift = 21, SpvLoopControlSpeculatedIterationsINTELShift = 22, SpvLoopControlNoFusionINTELShift = 23, SpvLoopControlMax = 0x7fffffff, } SpvLoopControlShift; typedef enum SpvLoopControlMask_ { SpvLoopControlMaskNone = 0, SpvLoopControlUnrollMask = 0x00000001, SpvLoopControlDontUnrollMask = 0x00000002, SpvLoopControlDependencyInfiniteMask = 0x00000004, SpvLoopControlDependencyLengthMask = 0x00000008, SpvLoopControlMinIterationsMask = 0x00000010, SpvLoopControlMaxIterationsMask = 0x00000020, SpvLoopControlIterationMultipleMask = 0x00000040, SpvLoopControlPeelCountMask = 0x00000080, SpvLoopControlPartialCountMask = 0x00000100, SpvLoopControlInitiationIntervalINTELMask = 0x00010000, SpvLoopControlMaxConcurrencyINTELMask = 0x00020000, SpvLoopControlDependencyArrayINTELMask = 0x00040000, SpvLoopControlPipelineEnableINTELMask = 0x00080000, SpvLoopControlLoopCoalesceINTELMask = 0x00100000, SpvLoopControlMaxInterleavingINTELMask = 0x00200000, SpvLoopControlSpeculatedIterationsINTELMask = 0x00400000, SpvLoopControlNoFusionINTELMask = 0x00800000, } SpvLoopControlMask; typedef enum SpvFunctionControlShift_ { SpvFunctionControlInlineShift = 0, SpvFunctionControlDontInlineShift = 1, SpvFunctionControlPureShift = 2, SpvFunctionControlConstShift = 3, SpvFunctionControlOptNoneINTELShift = 16, SpvFunctionControlMax = 0x7fffffff, } SpvFunctionControlShift; typedef enum SpvFunctionControlMask_ { SpvFunctionControlMaskNone = 0, SpvFunctionControlInlineMask = 0x00000001, SpvFunctionControlDontInlineMask = 0x00000002, SpvFunctionControlPureMask = 0x00000004, SpvFunctionControlConstMask = 0x00000008, SpvFunctionControlOptNoneINTELMask = 0x00010000, } SpvFunctionControlMask; typedef enum SpvMemorySemanticsShift_ { SpvMemorySemanticsAcquireShift = 1, SpvMemorySemanticsReleaseShift = 2, SpvMemorySemanticsAcquireReleaseShift = 3, SpvMemorySemanticsSequentiallyConsistentShift = 4, SpvMemorySemanticsUniformMemoryShift = 6, SpvMemorySemanticsSubgroupMemoryShift = 7, SpvMemorySemanticsWorkgroupMemoryShift = 8, SpvMemorySemanticsCrossWorkgroupMemoryShift = 9, SpvMemorySemanticsAtomicCounterMemoryShift = 10, SpvMemorySemanticsImageMemoryShift = 11, SpvMemorySemanticsOutputMemoryShift = 12, SpvMemorySemanticsOutputMemoryKHRShift = 12, SpvMemorySemanticsMakeAvailableShift = 13, SpvMemorySemanticsMakeAvailableKHRShift = 13, SpvMemorySemanticsMakeVisibleShift = 14, SpvMemorySemanticsMakeVisibleKHRShift = 14, SpvMemorySemanticsVolatileShift = 15, SpvMemorySemanticsMax = 0x7fffffff, } SpvMemorySemanticsShift; typedef enum SpvMemorySemanticsMask_ { SpvMemorySemanticsMaskNone = 0, SpvMemorySemanticsAcquireMask = 0x00000002, SpvMemorySemanticsReleaseMask = 0x00000004, SpvMemorySemanticsAcquireReleaseMask = 0x00000008, SpvMemorySemanticsSequentiallyConsistentMask = 0x00000010, SpvMemorySemanticsUniformMemoryMask = 0x00000040, SpvMemorySemanticsSubgroupMemoryMask = 0x00000080, SpvMemorySemanticsWorkgroupMemoryMask = 0x00000100, SpvMemorySemanticsCrossWorkgroupMemoryMask = 0x00000200, SpvMemorySemanticsAtomicCounterMemoryMask = 0x00000400, SpvMemorySemanticsImageMemoryMask = 0x00000800, SpvMemorySemanticsOutputMemoryMask = 0x00001000, SpvMemorySemanticsOutputMemoryKHRMask = 0x00001000, SpvMemorySemanticsMakeAvailableMask = 0x00002000, SpvMemorySemanticsMakeAvailableKHRMask = 0x00002000, SpvMemorySemanticsMakeVisibleMask = 0x00004000, SpvMemorySemanticsMakeVisibleKHRMask = 0x00004000, SpvMemorySemanticsVolatileMask = 0x00008000, } SpvMemorySemanticsMask; typedef enum SpvMemoryAccessShift_ { SpvMemoryAccessVolatileShift = 0, SpvMemoryAccessAlignedShift = 1, SpvMemoryAccessNontemporalShift = 2, SpvMemoryAccessMakePointerAvailableShift = 3, SpvMemoryAccessMakePointerAvailableKHRShift = 3, SpvMemoryAccessMakePointerVisibleShift = 4, SpvMemoryAccessMakePointerVisibleKHRShift = 4, SpvMemoryAccessNonPrivatePointerShift = 5, SpvMemoryAccessNonPrivatePointerKHRShift = 5, SpvMemoryAccessMax = 0x7fffffff, } SpvMemoryAccessShift; typedef enum SpvMemoryAccessMask_ { SpvMemoryAccessMaskNone = 0, SpvMemoryAccessVolatileMask = 0x00000001, SpvMemoryAccessAlignedMask = 0x00000002, SpvMemoryAccessNontemporalMask = 0x00000004, SpvMemoryAccessMakePointerAvailableMask = 0x00000008, SpvMemoryAccessMakePointerAvailableKHRMask = 0x00000008, SpvMemoryAccessMakePointerVisibleMask = 0x00000010, SpvMemoryAccessMakePointerVisibleKHRMask = 0x00000010, SpvMemoryAccessNonPrivatePointerMask = 0x00000020, SpvMemoryAccessNonPrivatePointerKHRMask = 0x00000020, } SpvMemoryAccessMask; typedef enum SpvScope_ { SpvScopeCrossDevice = 0, SpvScopeDevice = 1, SpvScopeWorkgroup = 2, SpvScopeSubgroup = 3, SpvScopeInvocation = 4, SpvScopeQueueFamily = 5, SpvScopeQueueFamilyKHR = 5, SpvScopeShaderCallKHR = 6, SpvScopeMax = 0x7fffffff, } SpvScope; typedef enum SpvGroupOperation_ { SpvGroupOperationReduce = 0, SpvGroupOperationInclusiveScan = 1, SpvGroupOperationExclusiveScan = 2, SpvGroupOperationClusteredReduce = 3, SpvGroupOperationPartitionedReduceNV = 6, SpvGroupOperationPartitionedInclusiveScanNV = 7, SpvGroupOperationPartitionedExclusiveScanNV = 8, SpvGroupOperationMax = 0x7fffffff, } SpvGroupOperation; typedef enum SpvKernelEnqueueFlags_ { SpvKernelEnqueueFlagsNoWait = 0, SpvKernelEnqueueFlagsWaitKernel = 1, SpvKernelEnqueueFlagsWaitWorkGroup = 2, SpvKernelEnqueueFlagsMax = 0x7fffffff, } SpvKernelEnqueueFlags; typedef enum SpvKernelProfilingInfoShift_ { SpvKernelProfilingInfoCmdExecTimeShift = 0, SpvKernelProfilingInfoMax = 0x7fffffff, } SpvKernelProfilingInfoShift; typedef enum SpvKernelProfilingInfoMask_ { SpvKernelProfilingInfoMaskNone = 0, SpvKernelProfilingInfoCmdExecTimeMask = 0x00000001, } SpvKernelProfilingInfoMask; typedef enum SpvCapability_ { SpvCapabilityMatrix = 0, SpvCapabilityShader = 1, SpvCapabilityGeometry = 2, SpvCapabilityTessellation = 3, SpvCapabilityAddresses = 4, SpvCapabilityLinkage = 5, SpvCapabilityKernel = 6, SpvCapabilityVector16 = 7, SpvCapabilityFloat16Buffer = 8, SpvCapabilityFloat16 = 9, SpvCapabilityFloat64 = 10, SpvCapabilityInt64 = 11, SpvCapabilityInt64Atomics = 12, SpvCapabilityImageBasic = 13, SpvCapabilityImageReadWrite = 14, SpvCapabilityImageMipmap = 15, SpvCapabilityPipes = 17, SpvCapabilityGroups = 18, SpvCapabilityDeviceEnqueue = 19, SpvCapabilityLiteralSampler = 20, SpvCapabilityAtomicStorage = 21, SpvCapabilityInt16 = 22, SpvCapabilityTessellationPointSize = 23, SpvCapabilityGeometryPointSize = 24, SpvCapabilityImageGatherExtended = 25, SpvCapabilityStorageImageMultisample = 27, SpvCapabilityUniformBufferArrayDynamicIndexing = 28, SpvCapabilitySampledImageArrayDynamicIndexing = 29, SpvCapabilityStorageBufferArrayDynamicIndexing = 30, SpvCapabilityStorageImageArrayDynamicIndexing = 31, SpvCapabilityClipDistance = 32, SpvCapabilityCullDistance = 33, SpvCapabilityImageCubeArray = 34, SpvCapabilitySampleRateShading = 35, SpvCapabilityImageRect = 36, SpvCapabilitySampledRect = 37, SpvCapabilityGenericPointer = 38, SpvCapabilityInt8 = 39, SpvCapabilityInputAttachment = 40, SpvCapabilitySparseResidency = 41, SpvCapabilityMinLod = 42, SpvCapabilitySampled1D = 43, SpvCapabilityImage1D = 44, SpvCapabilitySampledCubeArray = 45, SpvCapabilitySampledBuffer = 46, SpvCapabilityImageBuffer = 47, SpvCapabilityImageMSArray = 48, SpvCapabilityStorageImageExtendedFormats = 49, SpvCapabilityImageQuery = 50, SpvCapabilityDerivativeControl = 51, SpvCapabilityInterpolationFunction = 52, SpvCapabilityTransformFeedback = 53, SpvCapabilityGeometryStreams = 54, SpvCapabilityStorageImageReadWithoutFormat = 55, SpvCapabilityStorageImageWriteWithoutFormat = 56, SpvCapabilityMultiViewport = 57, SpvCapabilitySubgroupDispatch = 58, SpvCapabilityNamedBarrier = 59, SpvCapabilityPipeStorage = 60, SpvCapabilityGroupNonUniform = 61, SpvCapabilityGroupNonUniformVote = 62, SpvCapabilityGroupNonUniformArithmetic = 63, SpvCapabilityGroupNonUniformBallot = 64, SpvCapabilityGroupNonUniformShuffle = 65, SpvCapabilityGroupNonUniformShuffleRelative = 66, SpvCapabilityGroupNonUniformClustered = 67, SpvCapabilityGroupNonUniformQuad = 68, SpvCapabilityShaderLayer = 69, SpvCapabilityShaderViewportIndex = 70, SpvCapabilityUniformDecoration = 71, SpvCapabilityFragmentShadingRateKHR = 4422, SpvCapabilitySubgroupBallotKHR = 4423, SpvCapabilityDrawParameters = 4427, SpvCapabilityWorkgroupMemoryExplicitLayoutKHR = 4428, SpvCapabilityWorkgroupMemoryExplicitLayout8BitAccessKHR = 4429, SpvCapabilityWorkgroupMemoryExplicitLayout16BitAccessKHR = 4430, SpvCapabilitySubgroupVoteKHR = 4431, SpvCapabilityStorageBuffer16BitAccess = 4433, SpvCapabilityStorageUniformBufferBlock16 = 4433, SpvCapabilityStorageUniform16 = 4434, SpvCapabilityUniformAndStorageBuffer16BitAccess = 4434, SpvCapabilityStoragePushConstant16 = 4435, SpvCapabilityStorageInputOutput16 = 4436, SpvCapabilityDeviceGroup = 4437, SpvCapabilityMultiView = 4439, SpvCapabilityVariablePointersStorageBuffer = 4441, SpvCapabilityVariablePointers = 4442, SpvCapabilityAtomicStorageOps = 4445, SpvCapabilitySampleMaskPostDepthCoverage = 4447, SpvCapabilityStorageBuffer8BitAccess = 4448, SpvCapabilityUniformAndStorageBuffer8BitAccess = 4449, SpvCapabilityStoragePushConstant8 = 4450, SpvCapabilityDenormPreserve = 4464, SpvCapabilityDenormFlushToZero = 4465, SpvCapabilitySignedZeroInfNanPreserve = 4466, SpvCapabilityRoundingModeRTE = 4467, SpvCapabilityRoundingModeRTZ = 4468, SpvCapabilityRayQueryProvisionalKHR = 4471, SpvCapabilityRayQueryKHR = 4472, SpvCapabilityRayTraversalPrimitiveCullingKHR = 4478, SpvCapabilityRayTracingKHR = 4479, SpvCapabilityFloat16ImageAMD = 5008, SpvCapabilityImageGatherBiasLodAMD = 5009, SpvCapabilityFragmentMaskAMD = 5010, SpvCapabilityStencilExportEXT = 5013, SpvCapabilityImageReadWriteLodAMD = 5015, SpvCapabilityInt64ImageEXT = 5016, SpvCapabilityShaderClockKHR = 5055, SpvCapabilitySampleMaskOverrideCoverageNV = 5249, SpvCapabilityGeometryShaderPassthroughNV = 5251, SpvCapabilityShaderViewportIndexLayerEXT = 5254, SpvCapabilityShaderViewportIndexLayerNV = 5254, SpvCapabilityShaderViewportMaskNV = 5255, SpvCapabilityShaderStereoViewNV = 5259, SpvCapabilityPerViewAttributesNV = 5260, SpvCapabilityFragmentFullyCoveredEXT = 5265, SpvCapabilityMeshShadingNV = 5266, SpvCapabilityImageFootprintNV = 5282, SpvCapabilityFragmentBarycentricKHR = 5284, SpvCapabilityFragmentBarycentricNV = 5284, SpvCapabilityComputeDerivativeGroupQuadsNV = 5288, SpvCapabilityFragmentDensityEXT = 5291, SpvCapabilityShadingRateNV = 5291, SpvCapabilityGroupNonUniformPartitionedNV = 5297, SpvCapabilityShaderNonUniform = 5301, SpvCapabilityShaderNonUniformEXT = 5301, SpvCapabilityRuntimeDescriptorArray = 5302, SpvCapabilityRuntimeDescriptorArrayEXT = 5302, SpvCapabilityInputAttachmentArrayDynamicIndexing = 5303, SpvCapabilityInputAttachmentArrayDynamicIndexingEXT = 5303, SpvCapabilityUniformTexelBufferArrayDynamicIndexing = 5304, SpvCapabilityUniformTexelBufferArrayDynamicIndexingEXT = 5304, SpvCapabilityStorageTexelBufferArrayDynamicIndexing = 5305, SpvCapabilityStorageTexelBufferArrayDynamicIndexingEXT = 5305, SpvCapabilityUniformBufferArrayNonUniformIndexing = 5306, SpvCapabilityUniformBufferArrayNonUniformIndexingEXT = 5306, SpvCapabilitySampledImageArrayNonUniformIndexing = 5307, SpvCapabilitySampledImageArrayNonUniformIndexingEXT = 5307, SpvCapabilityStorageBufferArrayNonUniformIndexing = 5308, SpvCapabilityStorageBufferArrayNonUniformIndexingEXT = 5308, SpvCapabilityStorageImageArrayNonUniformIndexing = 5309, SpvCapabilityStorageImageArrayNonUniformIndexingEXT = 5309, SpvCapabilityInputAttachmentArrayNonUniformIndexing = 5310, SpvCapabilityInputAttachmentArrayNonUniformIndexingEXT = 5310, SpvCapabilityUniformTexelBufferArrayNonUniformIndexing = 5311, SpvCapabilityUniformTexelBufferArrayNonUniformIndexingEXT = 5311, SpvCapabilityStorageTexelBufferArrayNonUniformIndexing = 5312, SpvCapabilityStorageTexelBufferArrayNonUniformIndexingEXT = 5312, SpvCapabilityRayTracingNV = 5340, SpvCapabilityRayTracingMotionBlurNV = 5341, SpvCapabilityVulkanMemoryModel = 5345, SpvCapabilityVulkanMemoryModelKHR = 5345, SpvCapabilityVulkanMemoryModelDeviceScope = 5346, SpvCapabilityVulkanMemoryModelDeviceScopeKHR = 5346, SpvCapabilityPhysicalStorageBufferAddresses = 5347, SpvCapabilityPhysicalStorageBufferAddressesEXT = 5347, SpvCapabilityComputeDerivativeGroupLinearNV = 5350, SpvCapabilityRayTracingProvisionalKHR = 5353, SpvCapabilityCooperativeMatrixNV = 5357, SpvCapabilityFragmentShaderSampleInterlockEXT = 5363, SpvCapabilityFragmentShaderShadingRateInterlockEXT = 5372, SpvCapabilityShaderSMBuiltinsNV = 5373, SpvCapabilityFragmentShaderPixelInterlockEXT = 5378, SpvCapabilityDemoteToHelperInvocation = 5379, SpvCapabilityDemoteToHelperInvocationEXT = 5379, SpvCapabilityBindlessTextureNV = 5390, SpvCapabilitySubgroupShuffleINTEL = 5568, SpvCapabilitySubgroupBufferBlockIOINTEL = 5569, SpvCapabilitySubgroupImageBlockIOINTEL = 5570, SpvCapabilitySubgroupImageMediaBlockIOINTEL = 5579, SpvCapabilityRoundToInfinityINTEL = 5582, SpvCapabilityFloatingPointModeINTEL = 5583, SpvCapabilityIntegerFunctions2INTEL = 5584, SpvCapabilityFunctionPointersINTEL = 5603, SpvCapabilityIndirectReferencesINTEL = 5604, SpvCapabilityAsmINTEL = 5606, SpvCapabilityAtomicFloat32MinMaxEXT = 5612, SpvCapabilityAtomicFloat64MinMaxEXT = 5613, SpvCapabilityAtomicFloat16MinMaxEXT = 5616, SpvCapabilityVectorComputeINTEL = 5617, SpvCapabilityVectorAnyINTEL = 5619, SpvCapabilityExpectAssumeKHR = 5629, SpvCapabilitySubgroupAvcMotionEstimationINTEL = 5696, SpvCapabilitySubgroupAvcMotionEstimationIntraINTEL = 5697, SpvCapabilitySubgroupAvcMotionEstimationChromaINTEL = 5698, SpvCapabilityVariableLengthArrayINTEL = 5817, SpvCapabilityFunctionFloatControlINTEL = 5821, SpvCapabilityFPGAMemoryAttributesINTEL = 5824, SpvCapabilityFPFastMathModeINTEL = 5837, SpvCapabilityArbitraryPrecisionIntegersINTEL = 5844, SpvCapabilityArbitraryPrecisionFloatingPointINTEL = 5845, SpvCapabilityUnstructuredLoopControlsINTEL = 5886, SpvCapabilityFPGALoopControlsINTEL = 5888, SpvCapabilityKernelAttributesINTEL = 5892, SpvCapabilityFPGAKernelAttributesINTEL = 5897, SpvCapabilityFPGAMemoryAccessesINTEL = 5898, SpvCapabilityFPGAClusterAttributesINTEL = 5904, SpvCapabilityLoopFuseINTEL = 5906, SpvCapabilityFPGABufferLocationINTEL = 5920, SpvCapabilityArbitraryPrecisionFixedPointINTEL = 5922, SpvCapabilityUSMStorageClassesINTEL = 5935, SpvCapabilityIOPipesINTEL = 5943, SpvCapabilityBlockingPipesINTEL = 5945, SpvCapabilityFPGARegINTEL = 5948, SpvCapabilityDotProductInputAll = 6016, SpvCapabilityDotProductInputAllKHR = 6016, SpvCapabilityDotProductInput4x8Bit = 6017, SpvCapabilityDotProductInput4x8BitKHR = 6017, SpvCapabilityDotProductInput4x8BitPacked = 6018, SpvCapabilityDotProductInput4x8BitPackedKHR = 6018, SpvCapabilityDotProduct = 6019, SpvCapabilityDotProductKHR = 6019, SpvCapabilityBitInstructions = 6025, SpvCapabilityAtomicFloat32AddEXT = 6033, SpvCapabilityAtomicFloat64AddEXT = 6034, SpvCapabilityLongConstantCompositeINTEL = 6089, SpvCapabilityOptNoneINTEL = 6094, SpvCapabilityAtomicFloat16AddEXT = 6095, SpvCapabilityDebugInfoModuleINTEL = 6114, SpvCapabilityMax = 0x7fffffff, } SpvCapability; typedef enum SpvRayFlagsShift_ { SpvRayFlagsOpaqueKHRShift = 0, SpvRayFlagsNoOpaqueKHRShift = 1, SpvRayFlagsTerminateOnFirstHitKHRShift = 2, SpvRayFlagsSkipClosestHitShaderKHRShift = 3, SpvRayFlagsCullBackFacingTrianglesKHRShift = 4, SpvRayFlagsCullFrontFacingTrianglesKHRShift = 5, SpvRayFlagsCullOpaqueKHRShift = 6, SpvRayFlagsCullNoOpaqueKHRShift = 7, SpvRayFlagsSkipTrianglesKHRShift = 8, SpvRayFlagsSkipAABBsKHRShift = 9, SpvRayFlagsMax = 0x7fffffff, } SpvRayFlagsShift; typedef enum SpvRayFlagsMask_ { SpvRayFlagsMaskNone = 0, SpvRayFlagsOpaqueKHRMask = 0x00000001, SpvRayFlagsNoOpaqueKHRMask = 0x00000002, SpvRayFlagsTerminateOnFirstHitKHRMask = 0x00000004, SpvRayFlagsSkipClosestHitShaderKHRMask = 0x00000008, SpvRayFlagsCullBackFacingTrianglesKHRMask = 0x00000010, SpvRayFlagsCullFrontFacingTrianglesKHRMask = 0x00000020, SpvRayFlagsCullOpaqueKHRMask = 0x00000040, SpvRayFlagsCullNoOpaqueKHRMask = 0x00000080, SpvRayFlagsSkipTrianglesKHRMask = 0x00000100, SpvRayFlagsSkipAABBsKHRMask = 0x00000200, } SpvRayFlagsMask; typedef enum SpvRayQueryIntersection_ { SpvRayQueryIntersectionRayQueryCandidateIntersectionKHR = 0, SpvRayQueryIntersectionRayQueryCommittedIntersectionKHR = 1, SpvRayQueryIntersectionMax = 0x7fffffff, } SpvRayQueryIntersection; typedef enum SpvRayQueryCommittedIntersectionType_ { SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionNoneKHR = 0, SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionTriangleKHR = 1, SpvRayQueryCommittedIntersectionTypeRayQueryCommittedIntersectionGeneratedKHR = 2, SpvRayQueryCommittedIntersectionTypeMax = 0x7fffffff, } SpvRayQueryCommittedIntersectionType; typedef enum SpvRayQueryCandidateIntersectionType_ { SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionTriangleKHR = 0, SpvRayQueryCandidateIntersectionTypeRayQueryCandidateIntersectionAABBKHR = 1, SpvRayQueryCandidateIntersectionTypeMax = 0x7fffffff, } SpvRayQueryCandidateIntersectionType; typedef enum SpvFragmentShadingRateShift_ { SpvFragmentShadingRateVertical2PixelsShift = 0, SpvFragmentShadingRateVertical4PixelsShift = 1, SpvFragmentShadingRateHorizontal2PixelsShift = 2, SpvFragmentShadingRateHorizontal4PixelsShift = 3, SpvFragmentShadingRateMax = 0x7fffffff, } SpvFragmentShadingRateShift; typedef enum SpvFragmentShadingRateMask_ { SpvFragmentShadingRateMaskNone = 0, SpvFragmentShadingRateVertical2PixelsMask = 0x00000001, SpvFragmentShadingRateVertical4PixelsMask = 0x00000002, SpvFragmentShadingRateHorizontal2PixelsMask = 0x00000004, SpvFragmentShadingRateHorizontal4PixelsMask = 0x00000008, } SpvFragmentShadingRateMask; typedef enum SpvFPDenormMode_ { SpvFPDenormModePreserve = 0, SpvFPDenormModeFlushToZero = 1, SpvFPDenormModeMax = 0x7fffffff, } SpvFPDenormMode; typedef enum SpvFPOperationMode_ { SpvFPOperationModeIEEE = 0, SpvFPOperationModeALT = 1, SpvFPOperationModeMax = 0x7fffffff, } SpvFPOperationMode; typedef enum SpvQuantizationModes_ { SpvQuantizationModesTRN = 0, SpvQuantizationModesTRN_ZERO = 1, SpvQuantizationModesRND = 2, SpvQuantizationModesRND_ZERO = 3, SpvQuantizationModesRND_INF = 4, SpvQuantizationModesRND_MIN_INF = 5, SpvQuantizationModesRND_CONV = 6, SpvQuantizationModesRND_CONV_ODD = 7, SpvQuantizationModesMax = 0x7fffffff, } SpvQuantizationModes; typedef enum SpvOverflowModes_ { SpvOverflowModesWRAP = 0, SpvOverflowModesSAT = 1, SpvOverflowModesSAT_ZERO = 2, SpvOverflowModesSAT_SYM = 3, SpvOverflowModesMax = 0x7fffffff, } SpvOverflowModes; typedef enum SpvPackedVectorFormat_ { SpvPackedVectorFormatPackedVectorFormat4x8Bit = 0, SpvPackedVectorFormatPackedVectorFormat4x8BitKHR = 0, SpvPackedVectorFormatMax = 0x7fffffff, } SpvPackedVectorFormat; typedef enum SpvOp_ { SpvOpNop = 0, SpvOpUndef = 1, SpvOpSourceContinued = 2, SpvOpSource = 3, SpvOpSourceExtension = 4, SpvOpName = 5, SpvOpMemberName = 6, SpvOpString = 7, SpvOpLine = 8, SpvOpExtension = 10, SpvOpExtInstImport = 11, SpvOpExtInst = 12, SpvOpMemoryModel = 14, SpvOpEntryPoint = 15, SpvOpExecutionMode = 16, SpvOpCapability = 17, SpvOpTypeVoid = 19, SpvOpTypeBool = 20, SpvOpTypeInt = 21, SpvOpTypeFloat = 22, SpvOpTypeVector = 23, SpvOpTypeMatrix = 24, SpvOpTypeImage = 25, SpvOpTypeSampler = 26, SpvOpTypeSampledImage = 27, SpvOpTypeArray = 28, SpvOpTypeRuntimeArray = 29, SpvOpTypeStruct = 30, SpvOpTypeOpaque = 31, SpvOpTypePointer = 32, SpvOpTypeFunction = 33, SpvOpTypeEvent = 34, SpvOpTypeDeviceEvent = 35, SpvOpTypeReserveId = 36, SpvOpTypeQueue = 37, SpvOpTypePipe = 38, SpvOpTypeForwardPointer = 39, SpvOpConstantTrue = 41, SpvOpConstantFalse = 42, SpvOpConstant = 43, SpvOpConstantComposite = 44, SpvOpConstantSampler = 45, SpvOpConstantNull = 46, SpvOpSpecConstantTrue = 48, SpvOpSpecConstantFalse = 49, SpvOpSpecConstant = 50, SpvOpSpecConstantComposite = 51, SpvOpSpecConstantOp = 52, SpvOpFunction = 54, SpvOpFunctionParameter = 55, SpvOpFunctionEnd = 56, SpvOpFunctionCall = 57, SpvOpVariable = 59, SpvOpImageTexelPointer = 60, SpvOpLoad = 61, SpvOpStore = 62, SpvOpCopyMemory = 63, SpvOpCopyMemorySized = 64, SpvOpAccessChain = 65, SpvOpInBoundsAccessChain = 66, SpvOpPtrAccessChain = 67, SpvOpArrayLength = 68, SpvOpGenericPtrMemSemantics = 69, SpvOpInBoundsPtrAccessChain = 70, SpvOpDecorate = 71, SpvOpMemberDecorate = 72, SpvOpDecorationGroup = 73, SpvOpGroupDecorate = 74, SpvOpGroupMemberDecorate = 75, SpvOpVectorExtractDynamic = 77, SpvOpVectorInsertDynamic = 78, SpvOpVectorShuffle = 79, SpvOpCompositeConstruct = 80, SpvOpCompositeExtract = 81, SpvOpCompositeInsert = 82, SpvOpCopyObject = 83, SpvOpTranspose = 84, SpvOpSampledImage = 86, SpvOpImageSampleImplicitLod = 87, SpvOpImageSampleExplicitLod = 88, SpvOpImageSampleDrefImplicitLod = 89, SpvOpImageSampleDrefExplicitLod = 90, SpvOpImageSampleProjImplicitLod = 91, SpvOpImageSampleProjExplicitLod = 92, SpvOpImageSampleProjDrefImplicitLod = 93, SpvOpImageSampleProjDrefExplicitLod = 94, SpvOpImageFetch = 95, SpvOpImageGather = 96, SpvOpImageDrefGather = 97, SpvOpImageRead = 98, SpvOpImageWrite = 99, SpvOpImage = 100, SpvOpImageQueryFormat = 101, SpvOpImageQueryOrder = 102, SpvOpImageQuerySizeLod = 103, SpvOpImageQuerySize = 104, SpvOpImageQueryLod = 105, SpvOpImageQueryLevels = 106, SpvOpImageQuerySamples = 107, SpvOpConvertFToU = 109, SpvOpConvertFToS = 110, SpvOpConvertSToF = 111, SpvOpConvertUToF = 112, SpvOpUConvert = 113, SpvOpSConvert = 114, SpvOpFConvert = 115, SpvOpQuantizeToF16 = 116, SpvOpConvertPtrToU = 117, SpvOpSatConvertSToU = 118, SpvOpSatConvertUToS = 119, SpvOpConvertUToPtr = 120, SpvOpPtrCastToGeneric = 121, SpvOpGenericCastToPtr = 122, SpvOpGenericCastToPtrExplicit = 123, SpvOpBitcast = 124, SpvOpSNegate = 126, SpvOpFNegate = 127, SpvOpIAdd = 128, SpvOpFAdd = 129, SpvOpISub = 130, SpvOpFSub = 131, SpvOpIMul = 132, SpvOpFMul = 133, SpvOpUDiv = 134, SpvOpSDiv = 135, SpvOpFDiv = 136, SpvOpUMod = 137, SpvOpSRem = 138, SpvOpSMod = 139, SpvOpFRem = 140, SpvOpFMod = 141, SpvOpVectorTimesScalar = 142, SpvOpMatrixTimesScalar = 143, SpvOpVectorTimesMatrix = 144, SpvOpMatrixTimesVector = 145, SpvOpMatrixTimesMatrix = 146, SpvOpOuterProduct = 147, SpvOpDot = 148, SpvOpIAddCarry = 149, SpvOpISubBorrow = 150, SpvOpUMulExtended = 151, SpvOpSMulExtended = 152, SpvOpAny = 154, SpvOpAll = 155, SpvOpIsNan = 156, SpvOpIsInf = 157, SpvOpIsFinite = 158, SpvOpIsNormal = 159, SpvOpSignBitSet = 160, SpvOpLessOrGreater = 161, SpvOpOrdered = 162, SpvOpUnordered = 163, SpvOpLogicalEqual = 164, SpvOpLogicalNotEqual = 165, SpvOpLogicalOr = 166, SpvOpLogicalAnd = 167, SpvOpLogicalNot = 168, SpvOpSelect = 169, SpvOpIEqual = 170, SpvOpINotEqual = 171, SpvOpUGreaterThan = 172, SpvOpSGreaterThan = 173, SpvOpUGreaterThanEqual = 174, SpvOpSGreaterThanEqual = 175, SpvOpULessThan = 176, SpvOpSLessThan = 177, SpvOpULessThanEqual = 178, SpvOpSLessThanEqual = 179, SpvOpFOrdEqual = 180, SpvOpFUnordEqual = 181, SpvOpFOrdNotEqual = 182, SpvOpFUnordNotEqual = 183, SpvOpFOrdLessThan = 184, SpvOpFUnordLessThan = 185, SpvOpFOrdGreaterThan = 186, SpvOpFUnordGreaterThan = 187, SpvOpFOrdLessThanEqual = 188, SpvOpFUnordLessThanEqual = 189, SpvOpFOrdGreaterThanEqual = 190, SpvOpFUnordGreaterThanEqual = 191, SpvOpShiftRightLogical = 194, SpvOpShiftRightArithmetic = 195, SpvOpShiftLeftLogical = 196, SpvOpBitwiseOr = 197, SpvOpBitwiseXor = 198, SpvOpBitwiseAnd = 199, SpvOpNot = 200, SpvOpBitFieldInsert = 201, SpvOpBitFieldSExtract = 202, SpvOpBitFieldUExtract = 203, SpvOpBitReverse = 204, SpvOpBitCount = 205, SpvOpDPdx = 207, SpvOpDPdy = 208, SpvOpFwidth = 209, SpvOpDPdxFine = 210, SpvOpDPdyFine = 211, SpvOpFwidthFine = 212, SpvOpDPdxCoarse = 213, SpvOpDPdyCoarse = 214, SpvOpFwidthCoarse = 215, SpvOpEmitVertex = 218, SpvOpEndPrimitive = 219, SpvOpEmitStreamVertex = 220, SpvOpEndStreamPrimitive = 221, SpvOpControlBarrier = 224, SpvOpMemoryBarrier = 225, SpvOpAtomicLoad = 227, SpvOpAtomicStore = 228, SpvOpAtomicExchange = 229, SpvOpAtomicCompareExchange = 230, SpvOpAtomicCompareExchangeWeak = 231, SpvOpAtomicIIncrement = 232, SpvOpAtomicIDecrement = 233, SpvOpAtomicIAdd = 234, SpvOpAtomicISub = 235, SpvOpAtomicSMin = 236, SpvOpAtomicUMin = 237, SpvOpAtomicSMax = 238, SpvOpAtomicUMax = 239, SpvOpAtomicAnd = 240, SpvOpAtomicOr = 241, SpvOpAtomicXor = 242, SpvOpPhi = 245, SpvOpLoopMerge = 246, SpvOpSelectionMerge = 247, SpvOpLabel = 248, SpvOpBranch = 249, SpvOpBranchConditional = 250, SpvOpSwitch = 251, SpvOpKill = 252, SpvOpReturn = 253, SpvOpReturnValue = 254, SpvOpUnreachable = 255, SpvOpLifetimeStart = 256, SpvOpLifetimeStop = 257, SpvOpGroupAsyncCopy = 259, SpvOpGroupWaitEvents = 260, SpvOpGroupAll = 261, SpvOpGroupAny = 262, SpvOpGroupBroadcast = 263, SpvOpGroupIAdd = 264, SpvOpGroupFAdd = 265, SpvOpGroupFMin = 266, SpvOpGroupUMin = 267, SpvOpGroupSMin = 268, SpvOpGroupFMax = 269, SpvOpGroupUMax = 270, SpvOpGroupSMax = 271, SpvOpReadPipe = 274, SpvOpWritePipe = 275, SpvOpReservedReadPipe = 276, SpvOpReservedWritePipe = 277, SpvOpReserveReadPipePackets = 278, SpvOpReserveWritePipePackets = 279, SpvOpCommitReadPipe = 280, SpvOpCommitWritePipe = 281, SpvOpIsValidReserveId = 282, SpvOpGetNumPipePackets = 283, SpvOpGetMaxPipePackets = 284, SpvOpGroupReserveReadPipePackets = 285, SpvOpGroupReserveWritePipePackets = 286, SpvOpGroupCommitReadPipe = 287, SpvOpGroupCommitWritePipe = 288, SpvOpEnqueueMarker = 291, SpvOpEnqueueKernel = 292, SpvOpGetKernelNDrangeSubGroupCount = 293, SpvOpGetKernelNDrangeMaxSubGroupSize = 294, SpvOpGetKernelWorkGroupSize = 295, SpvOpGetKernelPreferredWorkGroupSizeMultiple = 296, SpvOpRetainEvent = 297, SpvOpReleaseEvent = 298, SpvOpCreateUserEvent = 299, SpvOpIsValidEvent = 300, SpvOpSetUserEventStatus = 301, SpvOpCaptureEventProfilingInfo = 302, SpvOpGetDefaultQueue = 303, SpvOpBuildNDRange = 304, SpvOpImageSparseSampleImplicitLod = 305, SpvOpImageSparseSampleExplicitLod = 306, SpvOpImageSparseSampleDrefImplicitLod = 307, SpvOpImageSparseSampleDrefExplicitLod = 308, SpvOpImageSparseSampleProjImplicitLod = 309, SpvOpImageSparseSampleProjExplicitLod = 310, SpvOpImageSparseSampleProjDrefImplicitLod = 311, SpvOpImageSparseSampleProjDrefExplicitLod = 312, SpvOpImageSparseFetch = 313, SpvOpImageSparseGather = 314, SpvOpImageSparseDrefGather = 315, SpvOpImageSparseTexelsResident = 316, SpvOpNoLine = 317, SpvOpAtomicFlagTestAndSet = 318, SpvOpAtomicFlagClear = 319, SpvOpImageSparseRead = 320, SpvOpSizeOf = 321, SpvOpTypePipeStorage = 322, SpvOpConstantPipeStorage = 323, SpvOpCreatePipeFromPipeStorage = 324, SpvOpGetKernelLocalSizeForSubgroupCount = 325, SpvOpGetKernelMaxNumSubgroups = 326, SpvOpTypeNamedBarrier = 327, SpvOpNamedBarrierInitialize = 328, SpvOpMemoryNamedBarrier = 329, SpvOpModuleProcessed = 330, SpvOpExecutionModeId = 331, SpvOpDecorateId = 332, SpvOpGroupNonUniformElect = 333, SpvOpGroupNonUniformAll = 334, SpvOpGroupNonUniformAny = 335, SpvOpGroupNonUniformAllEqual = 336, SpvOpGroupNonUniformBroadcast = 337, SpvOpGroupNonUniformBroadcastFirst = 338, SpvOpGroupNonUniformBallot = 339, SpvOpGroupNonUniformInverseBallot = 340, SpvOpGroupNonUniformBallotBitExtract = 341, SpvOpGroupNonUniformBallotBitCount = 342, SpvOpGroupNonUniformBallotFindLSB = 343, SpvOpGroupNonUniformBallotFindMSB = 344, SpvOpGroupNonUniformShuffle = 345, SpvOpGroupNonUniformShuffleXor = 346, SpvOpGroupNonUniformShuffleUp = 347, SpvOpGroupNonUniformShuffleDown = 348, SpvOpGroupNonUniformIAdd = 349, SpvOpGroupNonUniformFAdd = 350, SpvOpGroupNonUniformIMul = 351, SpvOpGroupNonUniformFMul = 352, SpvOpGroupNonUniformSMin = 353, SpvOpGroupNonUniformUMin = 354, SpvOpGroupNonUniformFMin = 355, SpvOpGroupNonUniformSMax = 356, SpvOpGroupNonUniformUMax = 357, SpvOpGroupNonUniformFMax = 358, SpvOpGroupNonUniformBitwiseAnd = 359, SpvOpGroupNonUniformBitwiseOr = 360, SpvOpGroupNonUniformBitwiseXor = 361, SpvOpGroupNonUniformLogicalAnd = 362, SpvOpGroupNonUniformLogicalOr = 363, SpvOpGroupNonUniformLogicalXor = 364, SpvOpGroupNonUniformQuadBroadcast = 365, SpvOpGroupNonUniformQuadSwap = 366, SpvOpCopyLogical = 400, SpvOpPtrEqual = 401, SpvOpPtrNotEqual = 402, SpvOpPtrDiff = 403, SpvOpTerminateInvocation = 4416, SpvOpSubgroupBallotKHR = 4421, SpvOpSubgroupFirstInvocationKHR = 4422, SpvOpSubgroupAllKHR = 4428, SpvOpSubgroupAnyKHR = 4429, SpvOpSubgroupAllEqualKHR = 4430, SpvOpSubgroupReadInvocationKHR = 4432, SpvOpTraceRayKHR = 4445, SpvOpExecuteCallableKHR = 4446, SpvOpConvertUToAccelerationStructureKHR = 4447, SpvOpIgnoreIntersectionKHR = 4448, SpvOpTerminateRayKHR = 4449, SpvOpSDot = 4450, SpvOpSDotKHR = 4450, SpvOpUDot = 4451, SpvOpUDotKHR = 4451, SpvOpSUDot = 4452, SpvOpSUDotKHR = 4452, SpvOpSDotAccSat = 4453, SpvOpSDotAccSatKHR = 4453, SpvOpUDotAccSat = 4454, SpvOpUDotAccSatKHR = 4454, SpvOpSUDotAccSat = 4455, SpvOpSUDotAccSatKHR = 4455, SpvOpTypeRayQueryKHR = 4472, SpvOpRayQueryInitializeKHR = 4473, SpvOpRayQueryTerminateKHR = 4474, SpvOpRayQueryGenerateIntersectionKHR = 4475, SpvOpRayQueryConfirmIntersectionKHR = 4476, SpvOpRayQueryProceedKHR = 4477, SpvOpRayQueryGetIntersectionTypeKHR = 4479, SpvOpGroupIAddNonUniformAMD = 5000, SpvOpGroupFAddNonUniformAMD = 5001, SpvOpGroupFMinNonUniformAMD = 5002, SpvOpGroupUMinNonUniformAMD = 5003, SpvOpGroupSMinNonUniformAMD = 5004, SpvOpGroupFMaxNonUniformAMD = 5005, SpvOpGroupUMaxNonUniformAMD = 5006, SpvOpGroupSMaxNonUniformAMD = 5007, SpvOpFragmentMaskFetchAMD = 5011, SpvOpFragmentFetchAMD = 5012, SpvOpReadClockKHR = 5056, SpvOpImageSampleFootprintNV = 5283, SpvOpGroupNonUniformPartitionNV = 5296, SpvOpWritePackedPrimitiveIndices4x8NV = 5299, SpvOpReportIntersectionKHR = 5334, SpvOpReportIntersectionNV = 5334, SpvOpIgnoreIntersectionNV = 5335, SpvOpTerminateRayNV = 5336, SpvOpTraceNV = 5337, SpvOpTraceMotionNV = 5338, SpvOpTraceRayMotionNV = 5339, SpvOpTypeAccelerationStructureKHR = 5341, SpvOpTypeAccelerationStructureNV = 5341, SpvOpExecuteCallableNV = 5344, SpvOpTypeCooperativeMatrixNV = 5358, SpvOpCooperativeMatrixLoadNV = 5359, SpvOpCooperativeMatrixStoreNV = 5360, SpvOpCooperativeMatrixMulAddNV = 5361, SpvOpCooperativeMatrixLengthNV = 5362, SpvOpBeginInvocationInterlockEXT = 5364, SpvOpEndInvocationInterlockEXT = 5365, SpvOpDemoteToHelperInvocation = 5380, SpvOpDemoteToHelperInvocationEXT = 5380, SpvOpIsHelperInvocationEXT = 5381, SpvOpConvertUToImageNV = 5391, SpvOpConvertUToSamplerNV = 5392, SpvOpConvertImageToUNV = 5393, SpvOpConvertSamplerToUNV = 5394, SpvOpConvertUToSampledImageNV = 5395, SpvOpConvertSampledImageToUNV = 5396, SpvOpSamplerImageAddressingModeNV = 5397, SpvOpSubgroupShuffleINTEL = 5571, SpvOpSubgroupShuffleDownINTEL = 5572, SpvOpSubgroupShuffleUpINTEL = 5573, SpvOpSubgroupShuffleXorINTEL = 5574, SpvOpSubgroupBlockReadINTEL = 5575, SpvOpSubgroupBlockWriteINTEL = 5576, SpvOpSubgroupImageBlockReadINTEL = 5577, SpvOpSubgroupImageBlockWriteINTEL = 5578, SpvOpSubgroupImageMediaBlockReadINTEL = 5580, SpvOpSubgroupImageMediaBlockWriteINTEL = 5581, SpvOpUCountLeadingZerosINTEL = 5585, SpvOpUCountTrailingZerosINTEL = 5586, SpvOpAbsISubINTEL = 5587, SpvOpAbsUSubINTEL = 5588, SpvOpIAddSatINTEL = 5589, SpvOpUAddSatINTEL = 5590, SpvOpIAverageINTEL = 5591, SpvOpUAverageINTEL = 5592, SpvOpIAverageRoundedINTEL = 5593, SpvOpUAverageRoundedINTEL = 5594, SpvOpISubSatINTEL = 5595, SpvOpUSubSatINTEL = 5596, SpvOpIMul32x16INTEL = 5597, SpvOpUMul32x16INTEL = 5598, SpvOpConstantFunctionPointerINTEL = 5600, SpvOpFunctionPointerCallINTEL = 5601, SpvOpAsmTargetINTEL = 5609, SpvOpAsmINTEL = 5610, SpvOpAsmCallINTEL = 5611, SpvOpAtomicFMinEXT = 5614, SpvOpAtomicFMaxEXT = 5615, SpvOpAssumeTrueKHR = 5630, SpvOpExpectKHR = 5631, SpvOpDecorateString = 5632, SpvOpDecorateStringGOOGLE = 5632, SpvOpMemberDecorateString = 5633, SpvOpMemberDecorateStringGOOGLE = 5633, SpvOpVmeImageINTEL = 5699, SpvOpTypeVmeImageINTEL = 5700, SpvOpTypeAvcImePayloadINTEL = 5701, SpvOpTypeAvcRefPayloadINTEL = 5702, SpvOpTypeAvcSicPayloadINTEL = 5703, SpvOpTypeAvcMcePayloadINTEL = 5704, SpvOpTypeAvcMceResultINTEL = 5705, SpvOpTypeAvcImeResultINTEL = 5706, SpvOpTypeAvcImeResultSingleReferenceStreamoutINTEL = 5707, SpvOpTypeAvcImeResultDualReferenceStreamoutINTEL = 5708, SpvOpTypeAvcImeSingleReferenceStreaminINTEL = 5709, SpvOpTypeAvcImeDualReferenceStreaminINTEL = 5710, SpvOpTypeAvcRefResultINTEL = 5711, SpvOpTypeAvcSicResultINTEL = 5712, SpvOpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL = 5713, SpvOpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL = 5714, SpvOpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL = 5715, SpvOpSubgroupAvcMceSetInterShapePenaltyINTEL = 5716, SpvOpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL = 5717, SpvOpSubgroupAvcMceSetInterDirectionPenaltyINTEL = 5718, SpvOpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL = 5719, SpvOpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL = 5720, SpvOpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL = 5721, SpvOpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL = 5722, SpvOpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL = 5723, SpvOpSubgroupAvcMceSetMotionVectorCostFunctionINTEL = 5724, SpvOpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL = 5725, SpvOpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL = 5726, SpvOpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL = 5727, SpvOpSubgroupAvcMceSetAcOnlyHaarINTEL = 5728, SpvOpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL = 5729, SpvOpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL = 5730, SpvOpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL = 5731, SpvOpSubgroupAvcMceConvertToImePayloadINTEL = 5732, SpvOpSubgroupAvcMceConvertToImeResultINTEL = 5733, SpvOpSubgroupAvcMceConvertToRefPayloadINTEL = 5734, SpvOpSubgroupAvcMceConvertToRefResultINTEL = 5735, SpvOpSubgroupAvcMceConvertToSicPayloadINTEL = 5736, SpvOpSubgroupAvcMceConvertToSicResultINTEL = 5737, SpvOpSubgroupAvcMceGetMotionVectorsINTEL = 5738, SpvOpSubgroupAvcMceGetInterDistortionsINTEL = 5739, SpvOpSubgroupAvcMceGetBestInterDistortionsINTEL = 5740, SpvOpSubgroupAvcMceGetInterMajorShapeINTEL = 5741, SpvOpSubgroupAvcMceGetInterMinorShapeINTEL = 5742, SpvOpSubgroupAvcMceGetInterDirectionsINTEL = 5743, SpvOpSubgroupAvcMceGetInterMotionVectorCountINTEL = 5744, SpvOpSubgroupAvcMceGetInterReferenceIdsINTEL = 5745, SpvOpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL = 5746, SpvOpSubgroupAvcImeInitializeINTEL = 5747, SpvOpSubgroupAvcImeSetSingleReferenceINTEL = 5748, SpvOpSubgroupAvcImeSetDualReferenceINTEL = 5749, SpvOpSubgroupAvcImeRefWindowSizeINTEL = 5750, SpvOpSubgroupAvcImeAdjustRefOffsetINTEL = 5751, SpvOpSubgroupAvcImeConvertToMcePayloadINTEL = 5752, SpvOpSubgroupAvcImeSetMaxMotionVectorCountINTEL = 5753, SpvOpSubgroupAvcImeSetUnidirectionalMixDisableINTEL = 5754, SpvOpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL = 5755, SpvOpSubgroupAvcImeSetWeightedSadINTEL = 5756, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceINTEL = 5757, SpvOpSubgroupAvcImeEvaluateWithDualReferenceINTEL = 5758, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL = 5759, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL = 5760, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL = 5761, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL = 5762, SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL = 5763, SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL = 5764, SpvOpSubgroupAvcImeConvertToMceResultINTEL = 5765, SpvOpSubgroupAvcImeGetSingleReferenceStreaminINTEL = 5766, SpvOpSubgroupAvcImeGetDualReferenceStreaminINTEL = 5767, SpvOpSubgroupAvcImeStripSingleReferenceStreamoutINTEL = 5768, SpvOpSubgroupAvcImeStripDualReferenceStreamoutINTEL = 5769, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL = 5770, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL = 5771, SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL = 5772, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL = 5773, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL = 5774, SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL = 5775, SpvOpSubgroupAvcImeGetBorderReachedINTEL = 5776, SpvOpSubgroupAvcImeGetTruncatedSearchIndicationINTEL = 5777, SpvOpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL = 5778, SpvOpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL = 5779, SpvOpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL = 5780, SpvOpSubgroupAvcFmeInitializeINTEL = 5781, SpvOpSubgroupAvcBmeInitializeINTEL = 5782, SpvOpSubgroupAvcRefConvertToMcePayloadINTEL = 5783, SpvOpSubgroupAvcRefSetBidirectionalMixDisableINTEL = 5784, SpvOpSubgroupAvcRefSetBilinearFilterEnableINTEL = 5785, SpvOpSubgroupAvcRefEvaluateWithSingleReferenceINTEL = 5786, SpvOpSubgroupAvcRefEvaluateWithDualReferenceINTEL = 5787, SpvOpSubgroupAvcRefEvaluateWithMultiReferenceINTEL = 5788, SpvOpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL = 5789, SpvOpSubgroupAvcRefConvertToMceResultINTEL = 5790, SpvOpSubgroupAvcSicInitializeINTEL = 5791, SpvOpSubgroupAvcSicConfigureSkcINTEL = 5792, SpvOpSubgroupAvcSicConfigureIpeLumaINTEL = 5793, SpvOpSubgroupAvcSicConfigureIpeLumaChromaINTEL = 5794, SpvOpSubgroupAvcSicGetMotionVectorMaskINTEL = 5795, SpvOpSubgroupAvcSicConvertToMcePayloadINTEL = 5796, SpvOpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL = 5797, SpvOpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL = 5798, SpvOpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL = 5799, SpvOpSubgroupAvcSicSetBilinearFilterEnableINTEL = 5800, SpvOpSubgroupAvcSicSetSkcForwardTransformEnableINTEL = 5801, SpvOpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL = 5802, SpvOpSubgroupAvcSicEvaluateIpeINTEL = 5803, SpvOpSubgroupAvcSicEvaluateWithSingleReferenceINTEL = 5804, SpvOpSubgroupAvcSicEvaluateWithDualReferenceINTEL = 5805, SpvOpSubgroupAvcSicEvaluateWithMultiReferenceINTEL = 5806, SpvOpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL = 5807, SpvOpSubgroupAvcSicConvertToMceResultINTEL = 5808, SpvOpSubgroupAvcSicGetIpeLumaShapeINTEL = 5809, SpvOpSubgroupAvcSicGetBestIpeLumaDistortionINTEL = 5810, SpvOpSubgroupAvcSicGetBestIpeChromaDistortionINTEL = 5811, SpvOpSubgroupAvcSicGetPackedIpeLumaModesINTEL = 5812, SpvOpSubgroupAvcSicGetIpeChromaModeINTEL = 5813, SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL = 5814, SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL = 5815, SpvOpSubgroupAvcSicGetInterRawSadsINTEL = 5816, SpvOpVariableLengthArrayINTEL = 5818, SpvOpSaveMemoryINTEL = 5819, SpvOpRestoreMemoryINTEL = 5820, SpvOpArbitraryFloatSinCosPiINTEL = 5840, SpvOpArbitraryFloatCastINTEL = 5841, SpvOpArbitraryFloatCastFromIntINTEL = 5842, SpvOpArbitraryFloatCastToIntINTEL = 5843, SpvOpArbitraryFloatAddINTEL = 5846, SpvOpArbitraryFloatSubINTEL = 5847, SpvOpArbitraryFloatMulINTEL = 5848, SpvOpArbitraryFloatDivINTEL = 5849, SpvOpArbitraryFloatGTINTEL = 5850, SpvOpArbitraryFloatGEINTEL = 5851, SpvOpArbitraryFloatLTINTEL = 5852, SpvOpArbitraryFloatLEINTEL = 5853, SpvOpArbitraryFloatEQINTEL = 5854, SpvOpArbitraryFloatRecipINTEL = 5855, SpvOpArbitraryFloatRSqrtINTEL = 5856, SpvOpArbitraryFloatCbrtINTEL = 5857, SpvOpArbitraryFloatHypotINTEL = 5858, SpvOpArbitraryFloatSqrtINTEL = 5859, SpvOpArbitraryFloatLogINTEL = 5860, SpvOpArbitraryFloatLog2INTEL = 5861, SpvOpArbitraryFloatLog10INTEL = 5862, SpvOpArbitraryFloatLog1pINTEL = 5863, SpvOpArbitraryFloatExpINTEL = 5864, SpvOpArbitraryFloatExp2INTEL = 5865, SpvOpArbitraryFloatExp10INTEL = 5866, SpvOpArbitraryFloatExpm1INTEL = 5867, SpvOpArbitraryFloatSinINTEL = 5868, SpvOpArbitraryFloatCosINTEL = 5869, SpvOpArbitraryFloatSinCosINTEL = 5870, SpvOpArbitraryFloatSinPiINTEL = 5871, SpvOpArbitraryFloatCosPiINTEL = 5872, SpvOpArbitraryFloatASinINTEL = 5873, SpvOpArbitraryFloatASinPiINTEL = 5874, SpvOpArbitraryFloatACosINTEL = 5875, SpvOpArbitraryFloatACosPiINTEL = 5876, SpvOpArbitraryFloatATanINTEL = 5877, SpvOpArbitraryFloatATanPiINTEL = 5878, SpvOpArbitraryFloatATan2INTEL = 5879, SpvOpArbitraryFloatPowINTEL = 5880, SpvOpArbitraryFloatPowRINTEL = 5881, SpvOpArbitraryFloatPowNINTEL = 5882, SpvOpLoopControlINTEL = 5887, SpvOpFixedSqrtINTEL = 5923, SpvOpFixedRecipINTEL = 5924, SpvOpFixedRsqrtINTEL = 5925, SpvOpFixedSinINTEL = 5926, SpvOpFixedCosINTEL = 5927, SpvOpFixedSinCosINTEL = 5928, SpvOpFixedSinPiINTEL = 5929, SpvOpFixedCosPiINTEL = 5930, SpvOpFixedSinCosPiINTEL = 5931, SpvOpFixedLogINTEL = 5932, SpvOpFixedExpINTEL = 5933, SpvOpPtrCastToCrossWorkgroupINTEL = 5934, SpvOpCrossWorkgroupCastToPtrINTEL = 5938, SpvOpReadPipeBlockingINTEL = 5946, SpvOpWritePipeBlockingINTEL = 5947, SpvOpFPGARegINTEL = 5949, SpvOpRayQueryGetRayTMinKHR = 6016, SpvOpRayQueryGetRayFlagsKHR = 6017, SpvOpRayQueryGetIntersectionTKHR = 6018, SpvOpRayQueryGetIntersectionInstanceCustomIndexKHR = 6019, SpvOpRayQueryGetIntersectionInstanceIdKHR = 6020, SpvOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR = 6021, SpvOpRayQueryGetIntersectionGeometryIndexKHR = 6022, SpvOpRayQueryGetIntersectionPrimitiveIndexKHR = 6023, SpvOpRayQueryGetIntersectionBarycentricsKHR = 6024, SpvOpRayQueryGetIntersectionFrontFaceKHR = 6025, SpvOpRayQueryGetIntersectionCandidateAABBOpaqueKHR = 6026, SpvOpRayQueryGetIntersectionObjectRayDirectionKHR = 6027, SpvOpRayQueryGetIntersectionObjectRayOriginKHR = 6028, SpvOpRayQueryGetWorldRayDirectionKHR = 6029, SpvOpRayQueryGetWorldRayOriginKHR = 6030, SpvOpRayQueryGetIntersectionObjectToWorldKHR = 6031, SpvOpRayQueryGetIntersectionWorldToObjectKHR = 6032, SpvOpAtomicFAddEXT = 6035, SpvOpTypeBufferSurfaceINTEL = 6086, SpvOpTypeStructContinuedINTEL = 6090, SpvOpConstantCompositeContinuedINTEL = 6091, SpvOpSpecConstantCompositeContinuedINTEL = 6092, SpvOpMax = 0x7fffffff, } SpvOp; #ifdef SPV_ENABLE_UTILITY_CODE inline void SpvHasResultAndType(SpvOp opcode, bool *hasResult, bool *hasResultType) { *hasResult = *hasResultType = false; switch (opcode) { default: /* unknown opcode */ break; case SpvOpNop: *hasResult = false; *hasResultType = false; break; case SpvOpUndef: *hasResult = true; *hasResultType = true; break; case SpvOpSourceContinued: *hasResult = false; *hasResultType = false; break; case SpvOpSource: *hasResult = false; *hasResultType = false; break; case SpvOpSourceExtension: *hasResult = false; *hasResultType = false; break; case SpvOpName: *hasResult = false; *hasResultType = false; break; case SpvOpMemberName: *hasResult = false; *hasResultType = false; break; case SpvOpString: *hasResult = true; *hasResultType = false; break; case SpvOpLine: *hasResult = false; *hasResultType = false; break; case SpvOpExtension: *hasResult = false; *hasResultType = false; break; case SpvOpExtInstImport: *hasResult = true; *hasResultType = false; break; case SpvOpExtInst: *hasResult = true; *hasResultType = true; break; case SpvOpMemoryModel: *hasResult = false; *hasResultType = false; break; case SpvOpEntryPoint: *hasResult = false; *hasResultType = false; break; case SpvOpExecutionMode: *hasResult = false; *hasResultType = false; break; case SpvOpCapability: *hasResult = false; *hasResultType = false; break; case SpvOpTypeVoid: *hasResult = true; *hasResultType = false; break; case SpvOpTypeBool: *hasResult = true; *hasResultType = false; break; case SpvOpTypeInt: *hasResult = true; *hasResultType = false; break; case SpvOpTypeFloat: *hasResult = true; *hasResultType = false; break; case SpvOpTypeVector: *hasResult = true; *hasResultType = false; break; case SpvOpTypeMatrix: *hasResult = true; *hasResultType = false; break; case SpvOpTypeImage: *hasResult = true; *hasResultType = false; break; case SpvOpTypeSampler: *hasResult = true; *hasResultType = false; break; case SpvOpTypeSampledImage: *hasResult = true; *hasResultType = false; break; case SpvOpTypeArray: *hasResult = true; *hasResultType = false; break; case SpvOpTypeRuntimeArray: *hasResult = true; *hasResultType = false; break; case SpvOpTypeStruct: *hasResult = true; *hasResultType = false; break; case SpvOpTypeOpaque: *hasResult = true; *hasResultType = false; break; case SpvOpTypePointer: *hasResult = true; *hasResultType = false; break; case SpvOpTypeFunction: *hasResult = true; *hasResultType = false; break; case SpvOpTypeEvent: *hasResult = true; *hasResultType = false; break; case SpvOpTypeDeviceEvent: *hasResult = true; *hasResultType = false; break; case SpvOpTypeReserveId: *hasResult = true; *hasResultType = false; break; case SpvOpTypeQueue: *hasResult = true; *hasResultType = false; break; case SpvOpTypePipe: *hasResult = true; *hasResultType = false; break; case SpvOpTypeForwardPointer: *hasResult = false; *hasResultType = false; break; case SpvOpConstantTrue: *hasResult = true; *hasResultType = true; break; case SpvOpConstantFalse: *hasResult = true; *hasResultType = true; break; case SpvOpConstant: *hasResult = true; *hasResultType = true; break; case SpvOpConstantComposite: *hasResult = true; *hasResultType = true; break; case SpvOpConstantSampler: *hasResult = true; *hasResultType = true; break; case SpvOpConstantNull: *hasResult = true; *hasResultType = true; break; case SpvOpSpecConstantTrue: *hasResult = true; *hasResultType = true; break; case SpvOpSpecConstantFalse: *hasResult = true; *hasResultType = true; break; case SpvOpSpecConstant: *hasResult = true; *hasResultType = true; break; case SpvOpSpecConstantComposite: *hasResult = true; *hasResultType = true; break; case SpvOpSpecConstantOp: *hasResult = true; *hasResultType = true; break; case SpvOpFunction: *hasResult = true; *hasResultType = true; break; case SpvOpFunctionParameter: *hasResult = true; *hasResultType = true; break; case SpvOpFunctionEnd: *hasResult = false; *hasResultType = false; break; case SpvOpFunctionCall: *hasResult = true; *hasResultType = true; break; case SpvOpVariable: *hasResult = true; *hasResultType = true; break; case SpvOpImageTexelPointer: *hasResult = true; *hasResultType = true; break; case SpvOpLoad: *hasResult = true; *hasResultType = true; break; case SpvOpStore: *hasResult = false; *hasResultType = false; break; case SpvOpCopyMemory: *hasResult = false; *hasResultType = false; break; case SpvOpCopyMemorySized: *hasResult = false; *hasResultType = false; break; case SpvOpAccessChain: *hasResult = true; *hasResultType = true; break; case SpvOpInBoundsAccessChain: *hasResult = true; *hasResultType = true; break; case SpvOpPtrAccessChain: *hasResult = true; *hasResultType = true; break; case SpvOpArrayLength: *hasResult = true; *hasResultType = true; break; case SpvOpGenericPtrMemSemantics: *hasResult = true; *hasResultType = true; break; case SpvOpInBoundsPtrAccessChain: *hasResult = true; *hasResultType = true; break; case SpvOpDecorate: *hasResult = false; *hasResultType = false; break; case SpvOpMemberDecorate: *hasResult = false; *hasResultType = false; break; case SpvOpDecorationGroup: *hasResult = true; *hasResultType = false; break; case SpvOpGroupDecorate: *hasResult = false; *hasResultType = false; break; case SpvOpGroupMemberDecorate: *hasResult = false; *hasResultType = false; break; case SpvOpVectorExtractDynamic: *hasResult = true; *hasResultType = true; break; case SpvOpVectorInsertDynamic: *hasResult = true; *hasResultType = true; break; case SpvOpVectorShuffle: *hasResult = true; *hasResultType = true; break; case SpvOpCompositeConstruct: *hasResult = true; *hasResultType = true; break; case SpvOpCompositeExtract: *hasResult = true; *hasResultType = true; break; case SpvOpCompositeInsert: *hasResult = true; *hasResultType = true; break; case SpvOpCopyObject: *hasResult = true; *hasResultType = true; break; case SpvOpTranspose: *hasResult = true; *hasResultType = true; break; case SpvOpSampledImage: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleDrefImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleDrefExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleProjImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleProjExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleProjDrefImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleProjDrefExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageFetch: *hasResult = true; *hasResultType = true; break; case SpvOpImageGather: *hasResult = true; *hasResultType = true; break; case SpvOpImageDrefGather: *hasResult = true; *hasResultType = true; break; case SpvOpImageRead: *hasResult = true; *hasResultType = true; break; case SpvOpImageWrite: *hasResult = false; *hasResultType = false; break; case SpvOpImage: *hasResult = true; *hasResultType = true; break; case SpvOpImageQueryFormat: *hasResult = true; *hasResultType = true; break; case SpvOpImageQueryOrder: *hasResult = true; *hasResultType = true; break; case SpvOpImageQuerySizeLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageQuerySize: *hasResult = true; *hasResultType = true; break; case SpvOpImageQueryLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageQueryLevels: *hasResult = true; *hasResultType = true; break; case SpvOpImageQuerySamples: *hasResult = true; *hasResultType = true; break; case SpvOpConvertFToU: *hasResult = true; *hasResultType = true; break; case SpvOpConvertFToS: *hasResult = true; *hasResultType = true; break; case SpvOpConvertSToF: *hasResult = true; *hasResultType = true; break; case SpvOpConvertUToF: *hasResult = true; *hasResultType = true; break; case SpvOpUConvert: *hasResult = true; *hasResultType = true; break; case SpvOpSConvert: *hasResult = true; *hasResultType = true; break; case SpvOpFConvert: *hasResult = true; *hasResultType = true; break; case SpvOpQuantizeToF16: *hasResult = true; *hasResultType = true; break; case SpvOpConvertPtrToU: *hasResult = true; *hasResultType = true; break; case SpvOpSatConvertSToU: *hasResult = true; *hasResultType = true; break; case SpvOpSatConvertUToS: *hasResult = true; *hasResultType = true; break; case SpvOpConvertUToPtr: *hasResult = true; *hasResultType = true; break; case SpvOpPtrCastToGeneric: *hasResult = true; *hasResultType = true; break; case SpvOpGenericCastToPtr: *hasResult = true; *hasResultType = true; break; case SpvOpGenericCastToPtrExplicit: *hasResult = true; *hasResultType = true; break; case SpvOpBitcast: *hasResult = true; *hasResultType = true; break; case SpvOpSNegate: *hasResult = true; *hasResultType = true; break; case SpvOpFNegate: *hasResult = true; *hasResultType = true; break; case SpvOpIAdd: *hasResult = true; *hasResultType = true; break; case SpvOpFAdd: *hasResult = true; *hasResultType = true; break; case SpvOpISub: *hasResult = true; *hasResultType = true; break; case SpvOpFSub: *hasResult = true; *hasResultType = true; break; case SpvOpIMul: *hasResult = true; *hasResultType = true; break; case SpvOpFMul: *hasResult = true; *hasResultType = true; break; case SpvOpUDiv: *hasResult = true; *hasResultType = true; break; case SpvOpSDiv: *hasResult = true; *hasResultType = true; break; case SpvOpFDiv: *hasResult = true; *hasResultType = true; break; case SpvOpUMod: *hasResult = true; *hasResultType = true; break; case SpvOpSRem: *hasResult = true; *hasResultType = true; break; case SpvOpSMod: *hasResult = true; *hasResultType = true; break; case SpvOpFRem: *hasResult = true; *hasResultType = true; break; case SpvOpFMod: *hasResult = true; *hasResultType = true; break; case SpvOpVectorTimesScalar: *hasResult = true; *hasResultType = true; break; case SpvOpMatrixTimesScalar: *hasResult = true; *hasResultType = true; break; case SpvOpVectorTimesMatrix: *hasResult = true; *hasResultType = true; break; case SpvOpMatrixTimesVector: *hasResult = true; *hasResultType = true; break; case SpvOpMatrixTimesMatrix: *hasResult = true; *hasResultType = true; break; case SpvOpOuterProduct: *hasResult = true; *hasResultType = true; break; case SpvOpDot: *hasResult = true; *hasResultType = true; break; case SpvOpIAddCarry: *hasResult = true; *hasResultType = true; break; case SpvOpISubBorrow: *hasResult = true; *hasResultType = true; break; case SpvOpUMulExtended: *hasResult = true; *hasResultType = true; break; case SpvOpSMulExtended: *hasResult = true; *hasResultType = true; break; case SpvOpAny: *hasResult = true; *hasResultType = true; break; case SpvOpAll: *hasResult = true; *hasResultType = true; break; case SpvOpIsNan: *hasResult = true; *hasResultType = true; break; case SpvOpIsInf: *hasResult = true; *hasResultType = true; break; case SpvOpIsFinite: *hasResult = true; *hasResultType = true; break; case SpvOpIsNormal: *hasResult = true; *hasResultType = true; break; case SpvOpSignBitSet: *hasResult = true; *hasResultType = true; break; case SpvOpLessOrGreater: *hasResult = true; *hasResultType = true; break; case SpvOpOrdered: *hasResult = true; *hasResultType = true; break; case SpvOpUnordered: *hasResult = true; *hasResultType = true; break; case SpvOpLogicalEqual: *hasResult = true; *hasResultType = true; break; case SpvOpLogicalNotEqual: *hasResult = true; *hasResultType = true; break; case SpvOpLogicalOr: *hasResult = true; *hasResultType = true; break; case SpvOpLogicalAnd: *hasResult = true; *hasResultType = true; break; case SpvOpLogicalNot: *hasResult = true; *hasResultType = true; break; case SpvOpSelect: *hasResult = true; *hasResultType = true; break; case SpvOpIEqual: *hasResult = true; *hasResultType = true; break; case SpvOpINotEqual: *hasResult = true; *hasResultType = true; break; case SpvOpUGreaterThan: *hasResult = true; *hasResultType = true; break; case SpvOpSGreaterThan: *hasResult = true; *hasResultType = true; break; case SpvOpUGreaterThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpSGreaterThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpULessThan: *hasResult = true; *hasResultType = true; break; case SpvOpSLessThan: *hasResult = true; *hasResultType = true; break; case SpvOpULessThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpSLessThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdNotEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordNotEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdLessThan: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordLessThan: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdGreaterThan: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordGreaterThan: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdLessThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordLessThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFOrdGreaterThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpFUnordGreaterThanEqual: *hasResult = true; *hasResultType = true; break; case SpvOpShiftRightLogical: *hasResult = true; *hasResultType = true; break; case SpvOpShiftRightArithmetic: *hasResult = true; *hasResultType = true; break; case SpvOpShiftLeftLogical: *hasResult = true; *hasResultType = true; break; case SpvOpBitwiseOr: *hasResult = true; *hasResultType = true; break; case SpvOpBitwiseXor: *hasResult = true; *hasResultType = true; break; case SpvOpBitwiseAnd: *hasResult = true; *hasResultType = true; break; case SpvOpNot: *hasResult = true; *hasResultType = true; break; case SpvOpBitFieldInsert: *hasResult = true; *hasResultType = true; break; case SpvOpBitFieldSExtract: *hasResult = true; *hasResultType = true; break; case SpvOpBitFieldUExtract: *hasResult = true; *hasResultType = true; break; case SpvOpBitReverse: *hasResult = true; *hasResultType = true; break; case SpvOpBitCount: *hasResult = true; *hasResultType = true; break; case SpvOpDPdx: *hasResult = true; *hasResultType = true; break; case SpvOpDPdy: *hasResult = true; *hasResultType = true; break; case SpvOpFwidth: *hasResult = true; *hasResultType = true; break; case SpvOpDPdxFine: *hasResult = true; *hasResultType = true; break; case SpvOpDPdyFine: *hasResult = true; *hasResultType = true; break; case SpvOpFwidthFine: *hasResult = true; *hasResultType = true; break; case SpvOpDPdxCoarse: *hasResult = true; *hasResultType = true; break; case SpvOpDPdyCoarse: *hasResult = true; *hasResultType = true; break; case SpvOpFwidthCoarse: *hasResult = true; *hasResultType = true; break; case SpvOpEmitVertex: *hasResult = false; *hasResultType = false; break; case SpvOpEndPrimitive: *hasResult = false; *hasResultType = false; break; case SpvOpEmitStreamVertex: *hasResult = false; *hasResultType = false; break; case SpvOpEndStreamPrimitive: *hasResult = false; *hasResultType = false; break; case SpvOpControlBarrier: *hasResult = false; *hasResultType = false; break; case SpvOpMemoryBarrier: *hasResult = false; *hasResultType = false; break; case SpvOpAtomicLoad: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicStore: *hasResult = false; *hasResultType = false; break; case SpvOpAtomicExchange: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicCompareExchange: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicCompareExchangeWeak: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicIIncrement: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicIDecrement: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicIAdd: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicISub: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicSMin: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicUMin: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicSMax: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicUMax: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicAnd: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicOr: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicXor: *hasResult = true; *hasResultType = true; break; case SpvOpPhi: *hasResult = true; *hasResultType = true; break; case SpvOpLoopMerge: *hasResult = false; *hasResultType = false; break; case SpvOpSelectionMerge: *hasResult = false; *hasResultType = false; break; case SpvOpLabel: *hasResult = true; *hasResultType = false; break; case SpvOpBranch: *hasResult = false; *hasResultType = false; break; case SpvOpBranchConditional: *hasResult = false; *hasResultType = false; break; case SpvOpSwitch: *hasResult = false; *hasResultType = false; break; case SpvOpKill: *hasResult = false; *hasResultType = false; break; case SpvOpReturn: *hasResult = false; *hasResultType = false; break; case SpvOpReturnValue: *hasResult = false; *hasResultType = false; break; case SpvOpUnreachable: *hasResult = false; *hasResultType = false; break; case SpvOpLifetimeStart: *hasResult = false; *hasResultType = false; break; case SpvOpLifetimeStop: *hasResult = false; *hasResultType = false; break; case SpvOpGroupAsyncCopy: *hasResult = true; *hasResultType = true; break; case SpvOpGroupWaitEvents: *hasResult = false; *hasResultType = false; break; case SpvOpGroupAll: *hasResult = true; *hasResultType = true; break; case SpvOpGroupAny: *hasResult = true; *hasResultType = true; break; case SpvOpGroupBroadcast: *hasResult = true; *hasResultType = true; break; case SpvOpGroupIAdd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFAdd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupUMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupSMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFMax: *hasResult = true; *hasResultType = true; break; case SpvOpGroupUMax: *hasResult = true; *hasResultType = true; break; case SpvOpGroupSMax: *hasResult = true; *hasResultType = true; break; case SpvOpReadPipe: *hasResult = true; *hasResultType = true; break; case SpvOpWritePipe: *hasResult = true; *hasResultType = true; break; case SpvOpReservedReadPipe: *hasResult = true; *hasResultType = true; break; case SpvOpReservedWritePipe: *hasResult = true; *hasResultType = true; break; case SpvOpReserveReadPipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpReserveWritePipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpCommitReadPipe: *hasResult = false; *hasResultType = false; break; case SpvOpCommitWritePipe: *hasResult = false; *hasResultType = false; break; case SpvOpIsValidReserveId: *hasResult = true; *hasResultType = true; break; case SpvOpGetNumPipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpGetMaxPipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpGroupReserveReadPipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpGroupReserveWritePipePackets: *hasResult = true; *hasResultType = true; break; case SpvOpGroupCommitReadPipe: *hasResult = false; *hasResultType = false; break; case SpvOpGroupCommitWritePipe: *hasResult = false; *hasResultType = false; break; case SpvOpEnqueueMarker: *hasResult = true; *hasResultType = true; break; case SpvOpEnqueueKernel: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelNDrangeSubGroupCount: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelNDrangeMaxSubGroupSize: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelWorkGroupSize: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelPreferredWorkGroupSizeMultiple: *hasResult = true; *hasResultType = true; break; case SpvOpRetainEvent: *hasResult = false; *hasResultType = false; break; case SpvOpReleaseEvent: *hasResult = false; *hasResultType = false; break; case SpvOpCreateUserEvent: *hasResult = true; *hasResultType = true; break; case SpvOpIsValidEvent: *hasResult = true; *hasResultType = true; break; case SpvOpSetUserEventStatus: *hasResult = false; *hasResultType = false; break; case SpvOpCaptureEventProfilingInfo: *hasResult = false; *hasResultType = false; break; case SpvOpGetDefaultQueue: *hasResult = true; *hasResultType = true; break; case SpvOpBuildNDRange: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleDrefImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleDrefExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleProjImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleProjExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleProjDrefImplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseSampleProjDrefExplicitLod: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseFetch: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseGather: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseDrefGather: *hasResult = true; *hasResultType = true; break; case SpvOpImageSparseTexelsResident: *hasResult = true; *hasResultType = true; break; case SpvOpNoLine: *hasResult = false; *hasResultType = false; break; case SpvOpAtomicFlagTestAndSet: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicFlagClear: *hasResult = false; *hasResultType = false; break; case SpvOpImageSparseRead: *hasResult = true; *hasResultType = true; break; case SpvOpSizeOf: *hasResult = true; *hasResultType = true; break; case SpvOpTypePipeStorage: *hasResult = true; *hasResultType = false; break; case SpvOpConstantPipeStorage: *hasResult = true; *hasResultType = true; break; case SpvOpCreatePipeFromPipeStorage: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelLocalSizeForSubgroupCount: *hasResult = true; *hasResultType = true; break; case SpvOpGetKernelMaxNumSubgroups: *hasResult = true; *hasResultType = true; break; case SpvOpTypeNamedBarrier: *hasResult = true; *hasResultType = false; break; case SpvOpNamedBarrierInitialize: *hasResult = true; *hasResultType = true; break; case SpvOpMemoryNamedBarrier: *hasResult = false; *hasResultType = false; break; case SpvOpModuleProcessed: *hasResult = false; *hasResultType = false; break; case SpvOpExecutionModeId: *hasResult = false; *hasResultType = false; break; case SpvOpDecorateId: *hasResult = false; *hasResultType = false; break; case SpvOpGroupNonUniformElect: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformAll: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformAny: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformAllEqual: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBroadcast: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBroadcastFirst: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBallot: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformInverseBallot: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBallotBitExtract: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBallotBitCount: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBallotFindLSB: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBallotFindMSB: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformShuffle: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformShuffleXor: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformShuffleUp: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformShuffleDown: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformIAdd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformFAdd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformIMul: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformFMul: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformSMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformUMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformFMin: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformSMax: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformUMax: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformFMax: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBitwiseAnd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBitwiseOr: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformBitwiseXor: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformLogicalAnd: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformLogicalOr: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformLogicalXor: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformQuadBroadcast: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformQuadSwap: *hasResult = true; *hasResultType = true; break; case SpvOpCopyLogical: *hasResult = true; *hasResultType = true; break; case SpvOpPtrEqual: *hasResult = true; *hasResultType = true; break; case SpvOpPtrNotEqual: *hasResult = true; *hasResultType = true; break; case SpvOpPtrDiff: *hasResult = true; *hasResultType = true; break; case SpvOpTerminateInvocation: *hasResult = false; *hasResultType = false; break; case SpvOpSubgroupBallotKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupFirstInvocationKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAllKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAnyKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAllEqualKHR: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupReadInvocationKHR: *hasResult = true; *hasResultType = true; break; case SpvOpTraceRayKHR: *hasResult = false; *hasResultType = false; break; case SpvOpExecuteCallableKHR: *hasResult = false; *hasResultType = false; break; case SpvOpConvertUToAccelerationStructureKHR: *hasResult = true; *hasResultType = true; break; case SpvOpIgnoreIntersectionKHR: *hasResult = false; *hasResultType = false; break; case SpvOpTerminateRayKHR: *hasResult = false; *hasResultType = false; break; case SpvOpSDot: *hasResult = true; *hasResultType = true; break; case SpvOpUDot: *hasResult = true; *hasResultType = true; break; case SpvOpSUDot: *hasResult = true; *hasResultType = true; break; case SpvOpSDotAccSat: *hasResult = true; *hasResultType = true; break; case SpvOpUDotAccSat: *hasResult = true; *hasResultType = true; break; case SpvOpSUDotAccSat: *hasResult = true; *hasResultType = true; break; case SpvOpTypeRayQueryKHR: *hasResult = true; *hasResultType = false; break; case SpvOpRayQueryInitializeKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryTerminateKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryGenerateIntersectionKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryConfirmIntersectionKHR: *hasResult = false; *hasResultType = false; break; case SpvOpRayQueryProceedKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionTypeKHR: *hasResult = true; *hasResultType = true; break; case SpvOpGroupIAddNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFAddNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFMinNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupUMinNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupSMinNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupFMaxNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupUMaxNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpGroupSMaxNonUniformAMD: *hasResult = true; *hasResultType = true; break; case SpvOpFragmentMaskFetchAMD: *hasResult = true; *hasResultType = true; break; case SpvOpFragmentFetchAMD: *hasResult = true; *hasResultType = true; break; case SpvOpReadClockKHR: *hasResult = true; *hasResultType = true; break; case SpvOpImageSampleFootprintNV: *hasResult = true; *hasResultType = true; break; case SpvOpGroupNonUniformPartitionNV: *hasResult = true; *hasResultType = true; break; case SpvOpWritePackedPrimitiveIndices4x8NV: *hasResult = false; *hasResultType = false; break; case SpvOpReportIntersectionNV: *hasResult = true; *hasResultType = true; break; case SpvOpIgnoreIntersectionNV: *hasResult = false; *hasResultType = false; break; case SpvOpTerminateRayNV: *hasResult = false; *hasResultType = false; break; case SpvOpTraceNV: *hasResult = false; *hasResultType = false; break; case SpvOpTraceMotionNV: *hasResult = false; *hasResultType = false; break; case SpvOpTraceRayMotionNV: *hasResult = false; *hasResultType = false; break; case SpvOpTypeAccelerationStructureNV: *hasResult = true; *hasResultType = false; break; case SpvOpExecuteCallableNV: *hasResult = false; *hasResultType = false; break; case SpvOpTypeCooperativeMatrixNV: *hasResult = true; *hasResultType = false; break; case SpvOpCooperativeMatrixLoadNV: *hasResult = true; *hasResultType = true; break; case SpvOpCooperativeMatrixStoreNV: *hasResult = false; *hasResultType = false; break; case SpvOpCooperativeMatrixMulAddNV: *hasResult = true; *hasResultType = true; break; case SpvOpCooperativeMatrixLengthNV: *hasResult = true; *hasResultType = true; break; case SpvOpBeginInvocationInterlockEXT: *hasResult = false; *hasResultType = false; break; case SpvOpEndInvocationInterlockEXT: *hasResult = false; *hasResultType = false; break; case SpvOpDemoteToHelperInvocation: *hasResult = false; *hasResultType = false; break; case SpvOpIsHelperInvocationEXT: *hasResult = true; *hasResultType = true; break; case SpvOpConvertUToImageNV: *hasResult = true; *hasResultType = true; break; case SpvOpConvertUToSamplerNV: *hasResult = true; *hasResultType = true; break; case SpvOpConvertImageToUNV: *hasResult = true; *hasResultType = true; break; case SpvOpConvertSamplerToUNV: *hasResult = true; *hasResultType = true; break; case SpvOpConvertUToSampledImageNV: *hasResult = true; *hasResultType = true; break; case SpvOpConvertSampledImageToUNV: *hasResult = true; *hasResultType = true; break; case SpvOpSamplerImageAddressingModeNV: *hasResult = false; *hasResultType = false; break; case SpvOpSubgroupShuffleINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupShuffleDownINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupShuffleUpINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupShuffleXorINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupBlockReadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupBlockWriteINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpSubgroupImageBlockReadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupImageBlockWriteINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpSubgroupImageMediaBlockReadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupImageMediaBlockWriteINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpUCountLeadingZerosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUCountTrailingZerosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAbsISubINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAbsUSubINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpIAddSatINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUAddSatINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpIAverageINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUAverageINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpIAverageRoundedINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUAverageRoundedINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpISubSatINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUSubSatINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpIMul32x16INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpUMul32x16INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpConstantFunctionPointerINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFunctionPointerCallINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAsmTargetINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAsmINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAsmCallINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicFMinEXT: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicFMaxEXT: *hasResult = true; *hasResultType = true; break; case SpvOpAssumeTrueKHR: *hasResult = false; *hasResultType = false; break; case SpvOpExpectKHR: *hasResult = true; *hasResultType = true; break; case SpvOpDecorateString: *hasResult = false; *hasResultType = false; break; case SpvOpMemberDecorateString: *hasResult = false; *hasResultType = false; break; case SpvOpVmeImageINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpTypeVmeImageINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImePayloadINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcRefPayloadINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcSicPayloadINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcMcePayloadINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcMceResultINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImeResultINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImeResultSingleReferenceStreamoutINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImeResultDualReferenceStreamoutINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImeSingleReferenceStreaminINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcImeDualReferenceStreaminINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcRefResultINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeAvcSicResultINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpSubgroupAvcMceGetDefaultInterBaseMultiReferencePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetInterBaseMultiReferencePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultInterShapePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetInterShapePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultInterDirectionPenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetInterDirectionPenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultIntraLumaShapePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultInterMotionVectorCostTableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultHighPenaltyCostTableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultMediumPenaltyCostTableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultLowPenaltyCostTableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetMotionVectorCostFunctionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultIntraLumaModePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultNonDcLumaIntraPenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetDefaultIntraChromaModeBasePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetAcOnlyHaarINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetSourceInterlacedFieldPolarityINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetSingleReferenceInterlacedFieldPolarityINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceSetDualReferenceInterlacedFieldPolaritiesINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToImePayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToImeResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToRefPayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToRefResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToSicPayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceConvertToSicResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetMotionVectorsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterDistortionsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetBestInterDistortionsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterMajorShapeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterMinorShapeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterDirectionsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterMotionVectorCountINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterReferenceIdsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcMceGetInterReferenceInterlacedFieldPolaritiesINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeInitializeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetSingleReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetDualReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeRefWindowSizeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeAdjustRefOffsetINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeConvertToMcePayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetMaxMotionVectorCountINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetUnidirectionalMixDisableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetEarlySearchTerminationThresholdINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeSetWeightedSadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithSingleReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithDualReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreamoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreamoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithSingleReferenceStreaminoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeEvaluateWithDualReferenceStreaminoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeConvertToMceResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetSingleReferenceStreaminINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetDualReferenceStreaminINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeStripSingleReferenceStreamoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeStripDualReferenceStreamoutINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeMotionVectorsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeDistortionsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutSingleReferenceMajorShapeReferenceIdsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeMotionVectorsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeDistortionsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetStreamoutDualReferenceMajorShapeReferenceIdsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetBorderReachedINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetTruncatedSearchIndicationINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetUnidirectionalEarlySearchTerminationINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetWeightingPatternMinimumMotionVectorINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcImeGetWeightingPatternMinimumDistortionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcFmeInitializeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcBmeInitializeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefConvertToMcePayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefSetBidirectionalMixDisableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefSetBilinearFilterEnableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefEvaluateWithSingleReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefEvaluateWithDualReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefEvaluateWithMultiReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefEvaluateWithMultiReferenceInterlacedINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcRefConvertToMceResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicInitializeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicConfigureSkcINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicConfigureIpeLumaINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicConfigureIpeLumaChromaINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetMotionVectorMaskINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicConvertToMcePayloadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetIntraLumaShapePenaltyINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetIntraLumaModeCostFunctionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetIntraChromaModeCostFunctionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetBilinearFilterEnableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetSkcForwardTransformEnableINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicSetBlockBasedRawSkipSadINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicEvaluateIpeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicEvaluateWithSingleReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicEvaluateWithDualReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicEvaluateWithMultiReferenceINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicEvaluateWithMultiReferenceInterlacedINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicConvertToMceResultINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetIpeLumaShapeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetBestIpeLumaDistortionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetBestIpeChromaDistortionINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetPackedIpeLumaModesINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetIpeChromaModeINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetPackedSkcLumaCountThresholdINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetPackedSkcLumaSumThresholdINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSubgroupAvcSicGetInterRawSadsINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpVariableLengthArrayINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpSaveMemoryINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpRestoreMemoryINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpArbitraryFloatSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCastINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCastFromIntINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCastToIntINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatAddINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatSubINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatMulINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatDivINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatGTINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatGEINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLTINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLEINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatEQINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatRecipINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatRSqrtINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCbrtINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatHypotINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatSqrtINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLogINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLog2INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLog10INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatLog1pINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatExpINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatExp2INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatExp10INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatExpm1INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatSinINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatSinCosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatSinPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatCosPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatASinINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatASinPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatACosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatACosPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatATanINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatATanPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatATan2INTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatPowINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatPowRINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpArbitraryFloatPowNINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpLoopControlINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpFixedSqrtINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedRecipINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedRsqrtINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedSinINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedCosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedSinCosINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedSinPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedCosPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedSinCosPiINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedLogINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFixedExpINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpPtrCastToCrossWorkgroupINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpCrossWorkgroupCastToPtrINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpReadPipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpWritePipeBlockingINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpFPGARegINTEL: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetRayTMinKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetRayFlagsKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionTKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionInstanceCustomIndexKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionInstanceIdKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionGeometryIndexKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionPrimitiveIndexKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionBarycentricsKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionFrontFaceKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionCandidateAABBOpaqueKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionObjectRayDirectionKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionObjectRayOriginKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetWorldRayDirectionKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetWorldRayOriginKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionObjectToWorldKHR: *hasResult = true; *hasResultType = true; break; case SpvOpRayQueryGetIntersectionWorldToObjectKHR: *hasResult = true; *hasResultType = true; break; case SpvOpAtomicFAddEXT: *hasResult = true; *hasResultType = true; break; case SpvOpTypeBufferSurfaceINTEL: *hasResult = true; *hasResultType = false; break; case SpvOpTypeStructContinuedINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; case SpvOpSpecConstantCompositeContinuedINTEL: *hasResult = false; *hasResultType = false; break; } } #endif /* SPV_ENABLE_UTILITY_CODE */ #endif
whupdup/frame
real/third_party/spirv_reflect/include/spirv/unified1/spirv.h
C++
gpl-3.0
128,688
/* Copyright 2017-2022 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "spirv_reflect.h" #include <assert.h> #include <stdbool.h> #include <string.h> #if defined(WIN32) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #else #include <stdlib.h> #endif #if defined(SPIRV_REFLECT_ENABLE_ASSERTS) #define SPV_REFLECT_ASSERT(COND) \ assert(COND); #else #define SPV_REFLECT_ASSERT(COND) #endif // Temporary enums until these make it into SPIR-V/Vulkan // clang-format off enum { SpvReflectOpDecorateId = 332, SpvReflectOpDecorateStringGOOGLE = 5632, SpvReflectOpMemberDecorateStringGOOGLE = 5633, SpvReflectDecorationHlslCounterBufferGOOGLE = 5634, SpvReflectDecorationHlslSemanticGOOGLE = 5635 }; // clang-format on // clang-format off enum { SPIRV_STARTING_WORD_INDEX = 5, SPIRV_WORD_SIZE = sizeof(uint32_t), SPIRV_BYTE_WIDTH = 8, SPIRV_MINIMUM_FILE_SIZE = SPIRV_STARTING_WORD_INDEX * SPIRV_WORD_SIZE, SPIRV_DATA_ALIGNMENT = 4 * SPIRV_WORD_SIZE, // 16 SPIRV_ACCESS_CHAIN_INDEX_OFFSET = 4, }; // clang-format on // clang-format off enum { INVALID_VALUE = 0xFFFFFFFF, }; // clang-format on // clang-format off enum { MAX_NODE_NAME_LENGTH = 1024, }; // clang-format on // clang-format off enum { IMAGE_SAMPLED = 1, IMAGE_STORAGE = 2 }; // clang-format on // clang-format off typedef struct SpvReflectPrvArrayTraits { uint32_t element_type_id; uint32_t length_id; } SpvReflectPrvArrayTraits; // clang-format on // clang-format off typedef struct SpvReflectPrvImageTraits { uint32_t sampled_type_id; SpvDim dim; uint32_t depth; uint32_t arrayed; uint32_t ms; uint32_t sampled; SpvImageFormat image_format; } SpvReflectPrvImageTraits; // clang-format on // clang-format off typedef struct SpvReflectPrvNumberDecoration { uint32_t word_offset; uint32_t value; } SpvReflectPrvNumberDecoration; // clang-format on // clang-format off typedef struct SpvReflectPrvStringDecoration { uint32_t word_offset; const char* value; } SpvReflectPrvStringDecoration; // clang-format on // clang-format off typedef struct SpvReflectPrvDecorations { bool is_relaxed_precision; bool is_block; bool is_buffer_block; bool is_row_major; bool is_column_major; bool is_built_in; bool is_noperspective; bool is_flat; bool is_non_writable; SpvReflectPrvNumberDecoration set; SpvReflectPrvNumberDecoration binding; SpvReflectPrvNumberDecoration input_attachment_index; SpvReflectPrvNumberDecoration location; SpvReflectPrvNumberDecoration offset; SpvReflectPrvNumberDecoration uav_counter_buffer; SpvReflectPrvStringDecoration semantic; uint32_t array_stride; uint32_t matrix_stride; SpvBuiltIn built_in; } SpvReflectPrvDecorations; // clang-format on // clang-format off typedef struct SpvReflectPrvNode { uint32_t result_id; SpvOp op; uint32_t result_type_id; uint32_t type_id; SpvStorageClass storage_class; uint32_t word_offset; uint32_t word_count; bool is_type; SpvReflectPrvArrayTraits array_traits; SpvReflectPrvImageTraits image_traits; uint32_t image_type_id; const char* name; SpvReflectPrvDecorations decorations; uint32_t member_count; const char** member_names; SpvReflectPrvDecorations* member_decorations; } SpvReflectPrvNode; // clang-format on // clang-format off typedef struct SpvReflectPrvString { uint32_t result_id; const char* string; } SpvReflectPrvString; // clang-format on // clang-format off typedef struct SpvReflectPrvFunction { uint32_t id; uint32_t callee_count; uint32_t* callees; struct SpvReflectPrvFunction** callee_ptrs; uint32_t accessed_ptr_count; uint32_t* accessed_ptrs; } SpvReflectPrvFunction; // clang-format on // clang-format off typedef struct SpvReflectPrvAccessChain { uint32_t result_id; uint32_t result_type_id; // // Pointing to the base of a composite object. // Generally the id of descriptor block variable uint32_t base_id; // // From spec: // The first index in Indexes will select the // top-level member/element/component/element // of the base composite uint32_t index_count; uint32_t* indexes; } SpvReflectPrvAccessChain; // clang-format on // clang-format off typedef struct SpvReflectPrvParser { size_t spirv_word_count; uint32_t* spirv_code; uint32_t string_count; SpvReflectPrvString* strings; SpvSourceLanguage source_language; uint32_t source_language_version; uint32_t source_file_id; const char* source_embedded; size_t node_count; SpvReflectPrvNode* nodes; uint32_t entry_point_count; uint32_t function_count; SpvReflectPrvFunction* functions; uint32_t access_chain_count; SpvReflectPrvAccessChain* access_chains; uint32_t type_count; uint32_t descriptor_count; uint32_t push_constant_count; } SpvReflectPrvParser; // clang-format on static uint32_t Max( uint32_t a, uint32_t b) { return a > b ? a : b; } static uint32_t RoundUp( uint32_t value, uint32_t multiple) { assert(multiple && ((multiple & (multiple - 1)) == 0)); return (value + multiple - 1) & ~(multiple - 1); } #define IsNull(ptr) \ (ptr == NULL) #define IsNotNull(ptr) \ (ptr != NULL) #define SafeFree(ptr) \ { \ free((void*)ptr); \ ptr = NULL; \ } static int SortCompareUint32( const void* a, const void* b) { const uint32_t* p_a = (const uint32_t*)a; const uint32_t* p_b = (const uint32_t*)b; return (int)*p_a - (int)*p_b; } // // De-duplicates a sorted array and returns the new size. // // Note: The array doesn't actually need to be sorted, just // arranged into "runs" so that all the entries with one // value are adjacent. // static size_t DedupSortedUint32(uint32_t* arr, size_t size) { if (size == 0) { return 0; } size_t dedup_idx = 0; for (size_t i = 0; i < size; ++i) { if (arr[dedup_idx] != arr[i]) { ++dedup_idx; arr[dedup_idx] = arr[i]; } } return dedup_idx+1; } static bool SearchSortedUint32( const uint32_t* arr, size_t size, uint32_t target) { size_t lo = 0; size_t hi = size; while (lo < hi) { size_t mid = (hi - lo) / 2 + lo; if (arr[mid] == target) { return true; } else if (arr[mid] < target) { lo = mid+1; } else { hi = mid; } } return false; } static SpvReflectResult IntersectSortedUint32( const uint32_t* p_arr0, size_t arr0_size, const uint32_t* p_arr1, size_t arr1_size, uint32_t** pp_res, size_t* res_size ) { *res_size = 0; const uint32_t* arr0_end = p_arr0 + arr0_size; const uint32_t* arr1_end = p_arr1 + arr1_size; const uint32_t* idx0 = p_arr0; const uint32_t* idx1 = p_arr1; while (idx0 != arr0_end && idx1 != arr1_end) { if (*idx0 < *idx1) { ++idx0; } else if (*idx0 > *idx1) { ++idx1; } else { ++*res_size; ++idx0; ++idx1; } } *pp_res = NULL; if (*res_size > 0) { *pp_res = (uint32_t*)calloc(*res_size, sizeof(**pp_res)); if (IsNull(*pp_res)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } uint32_t* idxr = *pp_res; idx0 = p_arr0; idx1 = p_arr1; while (idx0 != arr0_end && idx1 != arr1_end) { if (*idx0 < *idx1) { ++idx0; } else if (*idx0 > *idx1) { ++idx1; } else { *(idxr++) = *idx0; ++idx0; ++idx1; } } } return SPV_REFLECT_RESULT_SUCCESS; } static bool InRange( const SpvReflectPrvParser* p_parser, uint32_t index) { bool in_range = false; if (IsNotNull(p_parser)) { in_range = (index < p_parser->spirv_word_count); } return in_range; } static SpvReflectResult ReadU32( SpvReflectPrvParser* p_parser, uint32_t word_offset, uint32_t* p_value) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(InRange(p_parser, word_offset)); SpvReflectResult result = SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_EOF; if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && InRange(p_parser, word_offset)) { *p_value = *(p_parser->spirv_code + word_offset); result = SPV_REFLECT_RESULT_SUCCESS; } return result; } #define CHECKED_READU32(parser, word_offset, value) \ { \ SpvReflectResult checked_readu32_result = ReadU32(parser, \ word_offset, (uint32_t*)&(value)); \ if (checked_readu32_result != SPV_REFLECT_RESULT_SUCCESS) { \ return checked_readu32_result; \ } \ } #define CHECKED_READU32_CAST(parser, word_offset, cast_to_type, value) \ { \ uint32_t checked_readu32_cast_u32 = UINT32_MAX; \ SpvReflectResult checked_readu32_cast_result = ReadU32(parser, \ word_offset, \ (uint32_t*)&(checked_readu32_cast_u32)); \ if (checked_readu32_cast_result != SPV_REFLECT_RESULT_SUCCESS) { \ return checked_readu32_cast_result; \ } \ value = (cast_to_type)checked_readu32_cast_u32; \ } #define IF_READU32(result, parser, word_offset, value) \ if ((result) == SPV_REFLECT_RESULT_SUCCESS) { \ result = ReadU32(parser, word_offset, (uint32_t*)&(value)); \ } #define IF_READU32_CAST(result, parser, word_offset, cast_to_type, value) \ if ((result) == SPV_REFLECT_RESULT_SUCCESS) { \ uint32_t if_readu32_cast_u32 = UINT32_MAX; \ result = ReadU32(parser, word_offset, &if_readu32_cast_u32); \ if ((result) == SPV_REFLECT_RESULT_SUCCESS) { \ value = (cast_to_type)if_readu32_cast_u32; \ } \ } static SpvReflectResult ReadStr( SpvReflectPrvParser* p_parser, uint32_t word_offset, uint32_t word_index, uint32_t word_count, uint32_t* p_buf_size, char* p_buf ) { uint32_t limit = (word_offset + word_count); assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(InRange(p_parser, limit)); SpvReflectResult result = SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_EOF; if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && InRange(p_parser, limit)) { const char* c_str = (const char*)(p_parser->spirv_code + word_offset + word_index); uint32_t n = word_count * SPIRV_WORD_SIZE; uint32_t length_with_terminator = 0; for (uint32_t i = 0; i < n; ++i) { char c = *(c_str + i); if (c == 0) { length_with_terminator = i + 1; break; } } if (length_with_terminator > 0) { result = SPV_REFLECT_RESULT_ERROR_NULL_POINTER; if (IsNotNull(p_buf_size) && IsNotNull(p_buf)) { result = SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED; if (length_with_terminator <= *p_buf_size) { memset(p_buf, 0, *p_buf_size); memcpy(p_buf, c_str, length_with_terminator); result = SPV_REFLECT_RESULT_SUCCESS; } } else { if (IsNotNull(p_buf_size)) { *p_buf_size = length_with_terminator; result = SPV_REFLECT_RESULT_SUCCESS; } } } } return result; } static SpvReflectDecorationFlags ApplyDecorations(const SpvReflectPrvDecorations* p_decoration_fields) { SpvReflectDecorationFlags decorations = SPV_REFLECT_DECORATION_NONE; if (p_decoration_fields->is_relaxed_precision) { decorations |= SPV_REFLECT_DECORATION_RELAXED_PRECISION; } if (p_decoration_fields->is_block) { decorations |= SPV_REFLECT_DECORATION_BLOCK; } if (p_decoration_fields->is_buffer_block) { decorations |= SPV_REFLECT_DECORATION_BUFFER_BLOCK; } if (p_decoration_fields->is_row_major) { decorations |= SPV_REFLECT_DECORATION_ROW_MAJOR; } if (p_decoration_fields->is_column_major) { decorations |= SPV_REFLECT_DECORATION_COLUMN_MAJOR; } if (p_decoration_fields->is_built_in) { decorations |= SPV_REFLECT_DECORATION_BUILT_IN; } if (p_decoration_fields->is_noperspective) { decorations |= SPV_REFLECT_DECORATION_NOPERSPECTIVE; } if (p_decoration_fields->is_flat) { decorations |= SPV_REFLECT_DECORATION_FLAT; } if (p_decoration_fields->is_non_writable) { decorations |= SPV_REFLECT_DECORATION_NON_WRITABLE; } return decorations; } static void ApplyNumericTraits(const SpvReflectTypeDescription* p_type, SpvReflectNumericTraits* p_numeric_traits) { memcpy(p_numeric_traits, &p_type->traits.numeric, sizeof(p_type->traits.numeric)); } static void ApplyArrayTraits(const SpvReflectTypeDescription* p_type, SpvReflectArrayTraits* p_array_traits) { memcpy(p_array_traits, &p_type->traits.array, sizeof(p_type->traits.array)); } static SpvReflectPrvNode* FindNode( SpvReflectPrvParser* p_parser, uint32_t result_id) { SpvReflectPrvNode* p_node = NULL; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_elem = &(p_parser->nodes[i]); if (p_elem->result_id == result_id) { p_node = p_elem; break; } } return p_node; } static SpvReflectTypeDescription* FindType(SpvReflectShaderModule* p_module, uint32_t type_id) { SpvReflectTypeDescription* p_type = NULL; for (size_t i = 0; i < p_module->_internal->type_description_count; ++i) { SpvReflectTypeDescription* p_elem = &(p_module->_internal->type_descriptions[i]); if (p_elem->id == type_id) { p_type = p_elem; break; } } return p_type; } static SpvReflectResult CreateParser( size_t size, void* p_code, SpvReflectPrvParser* p_parser) { if (p_code == NULL) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (size < SPIRV_MINIMUM_FILE_SIZE) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_CODE_SIZE; } if ((size % 4) != 0) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_CODE_SIZE; } p_parser->spirv_word_count = size / SPIRV_WORD_SIZE; p_parser->spirv_code = (uint32_t*)p_code; if (p_parser->spirv_code[0] != SpvMagicNumber) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_MAGIC_NUMBER; } return SPV_REFLECT_RESULT_SUCCESS; } static void DestroyParser(SpvReflectPrvParser* p_parser) { if (!IsNull(p_parser->nodes)) { // Free nodes for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (IsNotNull(p_node->member_names)) { SafeFree(p_node->member_names); } if (IsNotNull(p_node->member_decorations)) { SafeFree(p_node->member_decorations); } } // Free functions for (size_t i = 0; i < p_parser->function_count; ++i) { SafeFree(p_parser->functions[i].callees); SafeFree(p_parser->functions[i].callee_ptrs); SafeFree(p_parser->functions[i].accessed_ptrs); } // Free access chains for (uint32_t i = 0; i < p_parser->access_chain_count; ++i) { SafeFree(p_parser->access_chains[i].indexes); } SafeFree(p_parser->nodes); SafeFree(p_parser->strings); SafeFree(p_parser->source_embedded); SafeFree(p_parser->functions); SafeFree(p_parser->access_chains); p_parser->node_count = 0; } } static SpvReflectResult ParseNodes(SpvReflectPrvParser* p_parser) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); uint32_t* p_spirv = p_parser->spirv_code; uint32_t spirv_word_index = SPIRV_STARTING_WORD_INDEX; // Count nodes uint32_t node_count = 0; while (spirv_word_index < p_parser->spirv_word_count) { uint32_t word = p_spirv[spirv_word_index]; SpvOp op = (SpvOp)(word & 0xFFFF); uint32_t node_word_count = (word >> 16) & 0xFFFF; if (node_word_count == 0) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_INSTRUCTION; } if (op == SpvOpAccessChain) { ++(p_parser->access_chain_count); } spirv_word_index += node_word_count; ++node_count; } if (node_count == 0) { return SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_EOF; } // Allocate nodes p_parser->node_count = node_count; p_parser->nodes = (SpvReflectPrvNode*)calloc(p_parser->node_count, sizeof(*(p_parser->nodes))); if (IsNull(p_parser->nodes)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Mark all nodes with an invalid state for (uint32_t i = 0; i < node_count; ++i) { p_parser->nodes[i].op = (SpvOp)INVALID_VALUE; p_parser->nodes[i].storage_class = (SpvStorageClass)INVALID_VALUE; p_parser->nodes[i].decorations.set.value = (uint32_t)INVALID_VALUE; p_parser->nodes[i].decorations.binding.value = (uint32_t)INVALID_VALUE; p_parser->nodes[i].decorations.location.value = (uint32_t)INVALID_VALUE; p_parser->nodes[i].decorations.offset.value = (uint32_t)INVALID_VALUE; p_parser->nodes[i].decorations.uav_counter_buffer.value = (uint32_t)INVALID_VALUE; p_parser->nodes[i].decorations.built_in = (SpvBuiltIn)INVALID_VALUE; } // Mark source file id node p_parser->source_file_id = (uint32_t)INVALID_VALUE; p_parser->source_embedded = NULL; // Function node uint32_t function_node = (uint32_t)INVALID_VALUE; // Allocate access chain if (p_parser->access_chain_count > 0) { p_parser->access_chains = (SpvReflectPrvAccessChain*)calloc(p_parser->access_chain_count, sizeof(*(p_parser->access_chains))); if (IsNull(p_parser->access_chains)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } // Parse nodes uint32_t node_index = 0; uint32_t access_chain_index = 0; spirv_word_index = SPIRV_STARTING_WORD_INDEX; while (spirv_word_index < p_parser->spirv_word_count) { uint32_t word = p_spirv[spirv_word_index]; SpvOp op = (SpvOp)(word & 0xFFFF); uint32_t node_word_count = (word >> 16) & 0xFFFF; SpvReflectPrvNode* p_node = &(p_parser->nodes[node_index]); p_node->op = op; p_node->word_offset = spirv_word_index; p_node->word_count = node_word_count; switch (p_node->op) { default: break; case SpvOpString: { ++(p_parser->string_count); } break; case SpvOpSource: { CHECKED_READU32_CAST(p_parser, p_node->word_offset + 1, SpvSourceLanguage, p_parser->source_language); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_parser->source_language_version); if (p_node->word_count >= 4) { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_parser->source_file_id); } if (p_node->word_count >= 5) { const char* p_source = (const char*)(p_parser->spirv_code + p_node->word_offset + 4); const size_t source_len = strlen(p_source); char* p_source_temp = (char*)calloc(source_len + 1, sizeof(char*)); if (IsNull(p_source_temp)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } #ifdef _WIN32 strcpy_s(p_source_temp, source_len + 1, p_source); #else strcpy(p_source_temp, p_source); #endif p_parser->source_embedded = p_source_temp; } } break; case SpvOpSourceContinued: { const char* p_source = (const char*)(p_parser->spirv_code + p_node->word_offset + 1); const size_t source_len = strlen(p_source); const size_t embedded_source_len = strlen(p_parser->source_embedded); char* p_continued_source = (char*)calloc(source_len + embedded_source_len + 1, sizeof(char*)); if (IsNull(p_continued_source)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } #ifdef _WIN32 strcpy_s(p_continued_source, embedded_source_len + 1, p_parser->source_embedded); strcat_s(p_continued_source, source_len + 1, p_source); #else strcpy(p_continued_source, p_parser->source_embedded); strcat(p_continued_source, p_source); #endif SafeFree(p_parser->source_embedded); p_parser->source_embedded = p_continued_source; } break; case SpvOpEntryPoint: { ++(p_parser->entry_point_count); } break; case SpvOpName: case SpvOpMemberName: { uint32_t member_offset = (p_node->op == SpvOpMemberName) ? 1 : 0; uint32_t name_start = p_node->word_offset + member_offset + 2; p_node->name = (const char*)(p_parser->spirv_code + name_start); } break; case SpvOpTypeStruct: { p_node->member_count = p_node->word_count - 2; } // Fall through case SpvOpTypeVoid: case SpvOpTypeBool: case SpvOpTypeInt: case SpvOpTypeFloat: case SpvOpTypeVector: case SpvOpTypeMatrix: case SpvOpTypeSampler: case SpvOpTypeOpaque: case SpvOpTypeFunction: case SpvOpTypeEvent: case SpvOpTypeDeviceEvent: case SpvOpTypeReserveId: case SpvOpTypeQueue: case SpvOpTypePipe: case SpvOpTypeAccelerationStructureKHR: case SpvOpTypeRayQueryKHR: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); p_node->is_type = true; } break; case SpvOpTypeImage: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->image_traits.sampled_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_node->image_traits.dim); CHECKED_READU32(p_parser, p_node->word_offset + 4, p_node->image_traits.depth); CHECKED_READU32(p_parser, p_node->word_offset + 5, p_node->image_traits.arrayed); CHECKED_READU32(p_parser, p_node->word_offset + 6, p_node->image_traits.ms); CHECKED_READU32(p_parser, p_node->word_offset + 7, p_node->image_traits.sampled); CHECKED_READU32(p_parser, p_node->word_offset + 8, p_node->image_traits.image_format); p_node->is_type = true; } break; case SpvOpTypeSampledImage: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->image_type_id); p_node->is_type = true; } break; case SpvOpTypeArray: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->array_traits.element_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_node->array_traits.length_id); p_node->is_type = true; } break; case SpvOpTypeRuntimeArray: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->array_traits.element_type_id); p_node->is_type = true; } break; case SpvOpTypePointer: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->storage_class); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_node->type_id); p_node->is_type = true; } break; case SpvOpTypeForwardPointer: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->storage_class); p_node->is_type = true; } break; case SpvOpConstantTrue: case SpvOpConstantFalse: case SpvOpConstant: case SpvOpConstantComposite: case SpvOpConstantSampler: case SpvOpConstantNull: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->result_id); } break; case SpvOpSpecConstantTrue: case SpvOpSpecConstantFalse: case SpvOpSpecConstant: case SpvOpSpecConstantComposite: case SpvOpSpecConstantOp: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->result_id); } break; case SpvOpVariable: { CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->type_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_node->storage_class); } break; case SpvOpLoad: { // Only load enough so OpDecorate can reference the node, skip the remaining operands. CHECKED_READU32(p_parser, p_node->word_offset + 1, p_node->result_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->result_id); } break; case SpvOpAccessChain: { SpvReflectPrvAccessChain* p_access_chain = &(p_parser->access_chains[access_chain_index]); CHECKED_READU32(p_parser, p_node->word_offset + 1, p_access_chain->result_type_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_access_chain->result_id); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_access_chain->base_id); // // SPIRV_ACCESS_CHAIN_INDEX_OFFSET (4) is the number of words up until the first index: // [Node, Result Type Id, Result Id, Base Id, <Indexes>] // p_access_chain->index_count = (node_word_count - SPIRV_ACCESS_CHAIN_INDEX_OFFSET); if (p_access_chain->index_count > 0) { p_access_chain->indexes = (uint32_t*)calloc(p_access_chain->index_count, sizeof(*(p_access_chain->indexes))); if (IsNull( p_access_chain->indexes)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Parse any index values for access chain for (uint32_t index_index = 0; index_index < p_access_chain->index_count; ++index_index) { // Read index id uint32_t index_id = 0; CHECKED_READU32(p_parser, p_node->word_offset + SPIRV_ACCESS_CHAIN_INDEX_OFFSET + index_index, index_id); // Find OpConstant node that contains index value SpvReflectPrvNode* p_index_value_node = FindNode(p_parser, index_id); if ((p_index_value_node != NULL) && (p_index_value_node->op == SpvOpConstant)) { // Read index value uint32_t index_value = UINT32_MAX; CHECKED_READU32(p_parser, p_index_value_node->word_offset + 3, index_value); assert(index_value != UINT32_MAX); // Write index value to array p_access_chain->indexes[index_index] = index_value; } } } ++access_chain_index; } break; case SpvOpFunction: { CHECKED_READU32(p_parser, p_node->word_offset + 2, p_node->result_id); // Count function definitions, not function declarations. To determine // the difference, set an in-function variable, and then if an OpLabel // is reached before the end of the function increment the function // count. function_node = node_index; } break; case SpvOpLabel: { if (function_node != (uint32_t)INVALID_VALUE) { SpvReflectPrvNode* p_func_node = &(p_parser->nodes[function_node]); CHECKED_READU32(p_parser, p_func_node->word_offset + 2, p_func_node->result_id); ++(p_parser->function_count); } } // Fall through case SpvOpFunctionEnd: { function_node = (uint32_t)INVALID_VALUE; } break; } if (p_node->is_type) { ++(p_parser->type_count); } spirv_word_index += node_word_count; ++node_index; } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseStrings(SpvReflectPrvParser* p_parser) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(IsNotNull(p_parser->nodes)); // Early out if (p_parser->string_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && IsNotNull(p_parser->nodes)) { // Allocate string storage p_parser->strings = (SpvReflectPrvString*)calloc(p_parser->string_count, sizeof(*(p_parser->strings))); uint32_t string_index = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->op != SpvOpString) { continue; } // Paranoid check against string count assert(string_index < p_parser->string_count); if (string_index >= p_parser->string_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } // Result id SpvReflectPrvString* p_string = &(p_parser->strings[string_index]); CHECKED_READU32(p_parser, p_node->word_offset + 1, p_string->result_id); // String uint32_t string_start = p_node->word_offset + 2; p_string->string = (const char*)(p_parser->spirv_code + string_start); // Increment string index ++string_index; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseSource(SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code)) { // Source file if (IsNotNull(p_parser->strings)) { for (uint32_t i = 0; i < p_parser->string_count; ++i) { SpvReflectPrvString* p_string = &(p_parser->strings[i]); if (p_string->result_id == p_parser->source_file_id) { p_module->source_file = p_string->string; break; } } } //Source code if (IsNotNull(p_parser->source_embedded)) { const size_t source_len = strlen(p_parser->source_embedded); char* p_source = (char*)calloc(source_len + 1, sizeof(char*)); if (IsNull(p_source)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } #ifdef _WIN32 strcpy_s(p_source, source_len + 1, p_parser->source_embedded); #else strcpy(p_source, p_parser->source_embedded); #endif p_module->source_source = p_source; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseFunction( SpvReflectPrvParser* p_parser, SpvReflectPrvNode* p_func_node, SpvReflectPrvFunction* p_func, size_t first_label_index) { p_func->id = p_func_node->result_id; p_func->callee_count = 0; p_func->accessed_ptr_count = 0; for (size_t i = first_label_index; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->op == SpvOpFunctionEnd) { break; } switch (p_node->op) { case SpvOpFunctionCall: { ++(p_func->callee_count); } break; case SpvOpLoad: case SpvOpAccessChain: case SpvOpInBoundsAccessChain: case SpvOpPtrAccessChain: case SpvOpArrayLength: case SpvOpGenericPtrMemSemantics: case SpvOpInBoundsPtrAccessChain: case SpvOpStore: case SpvOpImageTexelPointer: { ++(p_func->accessed_ptr_count); } break; case SpvOpCopyMemory: case SpvOpCopyMemorySized: { p_func->accessed_ptr_count += 2; } break; default: break; } } if (p_func->callee_count > 0) { p_func->callees = (uint32_t*)calloc(p_func->callee_count, sizeof(*(p_func->callees))); if (IsNull(p_func->callees)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } if (p_func->accessed_ptr_count > 0) { p_func->accessed_ptrs = (uint32_t*)calloc(p_func->accessed_ptr_count, sizeof(*(p_func->accessed_ptrs))); if (IsNull(p_func->accessed_ptrs)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } p_func->callee_count = 0; p_func->accessed_ptr_count = 0; for (size_t i = first_label_index; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->op == SpvOpFunctionEnd) { break; } switch (p_node->op) { case SpvOpFunctionCall: { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_func->callees[p_func->callee_count]); (++p_func->callee_count); } break; case SpvOpLoad: case SpvOpAccessChain: case SpvOpInBoundsAccessChain: case SpvOpPtrAccessChain: case SpvOpArrayLength: case SpvOpGenericPtrMemSemantics: case SpvOpInBoundsPtrAccessChain: case SpvOpImageTexelPointer: { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_func->accessed_ptrs[p_func->accessed_ptr_count]); (++p_func->accessed_ptr_count); } break; case SpvOpStore: { CHECKED_READU32(p_parser, p_node->word_offset + 2, p_func->accessed_ptrs[p_func->accessed_ptr_count]); (++p_func->accessed_ptr_count); } break; case SpvOpCopyMemory: case SpvOpCopyMemorySized: { CHECKED_READU32(p_parser, p_node->word_offset + 2, p_func->accessed_ptrs[p_func->accessed_ptr_count]); (++p_func->accessed_ptr_count); CHECKED_READU32(p_parser, p_node->word_offset + 3, p_func->accessed_ptrs[p_func->accessed_ptr_count]); (++p_func->accessed_ptr_count); } break; default: break; } } if (p_func->callee_count > 0) { qsort(p_func->callees, p_func->callee_count, sizeof(*(p_func->callees)), SortCompareUint32); } p_func->callee_count = (uint32_t)DedupSortedUint32(p_func->callees, p_func->callee_count); if (p_func->accessed_ptr_count > 0) { qsort(p_func->accessed_ptrs, p_func->accessed_ptr_count, sizeof(*(p_func->accessed_ptrs)), SortCompareUint32); } p_func->accessed_ptr_count = (uint32_t)DedupSortedUint32(p_func->accessed_ptrs, p_func->accessed_ptr_count); return SPV_REFLECT_RESULT_SUCCESS; } static int SortCompareFunctions( const void* a, const void* b) { const SpvReflectPrvFunction* af = (const SpvReflectPrvFunction*)a; const SpvReflectPrvFunction* bf = (const SpvReflectPrvFunction*)b; return (int)af->id - (int)bf->id; } static SpvReflectResult ParseFunctions(SpvReflectPrvParser* p_parser) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(IsNotNull(p_parser->nodes)); if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && IsNotNull(p_parser->nodes)) { if (p_parser->function_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_parser->functions = (SpvReflectPrvFunction*)calloc(p_parser->function_count, sizeof(*(p_parser->functions))); if (IsNull(p_parser->functions)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } size_t function_index = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->op != SpvOpFunction) { continue; } // Skip over function declarations that aren't definitions bool func_definition = false; // Intentionally reuse i to avoid iterating over these nodes more than // once for (; i < p_parser->node_count; ++i) { if (p_parser->nodes[i].op == SpvOpLabel) { func_definition = true; break; } if (p_parser->nodes[i].op == SpvOpFunctionEnd) { break; } } if (!func_definition) { continue; } SpvReflectPrvFunction* p_function = &(p_parser->functions[function_index]); SpvReflectResult result = ParseFunction(p_parser, p_node, p_function, i); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } ++function_index; } qsort(p_parser->functions, p_parser->function_count, sizeof(*(p_parser->functions)), SortCompareFunctions); // Once they're sorted, link the functions with pointers to improve graph // traversal efficiency for (size_t i = 0; i < p_parser->function_count; ++i) { SpvReflectPrvFunction* p_func = &(p_parser->functions[i]); if (p_func->callee_count == 0) { continue; } p_func->callee_ptrs = (SpvReflectPrvFunction**)calloc(p_func->callee_count, sizeof(*(p_func->callee_ptrs))); for (size_t j = 0, k = 0; j < p_func->callee_count; ++j) { while (p_parser->functions[k].id != p_func->callees[j]) { ++k; if (k >= p_parser->function_count) { // Invalid called function ID somewhere return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } } p_func->callee_ptrs[j] = &(p_parser->functions[k]); } } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseMemberCounts(SpvReflectPrvParser* p_parser) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(IsNotNull(p_parser->nodes)); if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && IsNotNull(p_parser->nodes)) { for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpMemberName) && (p_node->op != SpvOpMemberDecorate)) { continue; } uint32_t target_id = 0; uint32_t member_index = (uint32_t)INVALID_VALUE; CHECKED_READU32(p_parser, p_node->word_offset + 1, target_id); CHECKED_READU32(p_parser, p_node->word_offset + 2, member_index); SpvReflectPrvNode* p_target_node = FindNode(p_parser, target_id); // Not all nodes get parsed, so FindNode returning NULL is expected. if (IsNull(p_target_node)) { continue; } if (member_index == INVALID_VALUE) { return SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED; } p_target_node->member_count = Max(p_target_node->member_count, member_index + 1); } for (uint32_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->member_count == 0) { continue; } p_node->member_names = (const char **)calloc(p_node->member_count, sizeof(*(p_node->member_names))); if (IsNull(p_node->member_names)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } p_node->member_decorations = (SpvReflectPrvDecorations*)calloc(p_node->member_count, sizeof(*(p_node->member_decorations))); if (IsNull(p_node->member_decorations)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseNames(SpvReflectPrvParser* p_parser) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->spirv_code)); assert(IsNotNull(p_parser->nodes)); if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && IsNotNull(p_parser->nodes)) { for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpName) && (p_node->op != SpvOpMemberName)) { continue; } uint32_t target_id = 0; CHECKED_READU32(p_parser, p_node->word_offset + 1, target_id); SpvReflectPrvNode* p_target_node = FindNode(p_parser, target_id); // Not all nodes get parsed, so FindNode returning NULL is expected. if (IsNull(p_target_node)) { continue; } const char** pp_target_name = &(p_target_node->name); if (p_node->op == SpvOpMemberName) { uint32_t member_index = UINT32_MAX; CHECKED_READU32(p_parser, p_node->word_offset + 2, member_index); pp_target_name = &(p_target_node->member_names[member_index]); } *pp_target_name = p_node->name; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDecorations(SpvReflectPrvParser* p_parser) { for (uint32_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (((uint32_t)p_node->op != (uint32_t)SpvOpDecorate) && ((uint32_t)p_node->op != (uint32_t)SpvOpMemberDecorate) && ((uint32_t)p_node->op != (uint32_t)SpvReflectOpDecorateId) && ((uint32_t)p_node->op != (uint32_t)SpvReflectOpDecorateStringGOOGLE) && ((uint32_t)p_node->op != (uint32_t)SpvReflectOpMemberDecorateStringGOOGLE)) { continue; } // Need to adjust the read offset if this is a member decoration uint32_t member_offset = 0; if (p_node->op == SpvOpMemberDecorate) { member_offset = 1; } // Get decoration uint32_t decoration = (uint32_t)INVALID_VALUE; CHECKED_READU32(p_parser, p_node->word_offset + member_offset + 2, decoration); // Filter out the decoration that do not affect reflection, otherwise // there will be random crashes because the nodes aren't found. bool skip = false; switch (decoration) { default: { skip = true; } break; case SpvDecorationRelaxedPrecision: case SpvDecorationBlock: case SpvDecorationBufferBlock: case SpvDecorationColMajor: case SpvDecorationRowMajor: case SpvDecorationArrayStride: case SpvDecorationMatrixStride: case SpvDecorationBuiltIn: case SpvDecorationNoPerspective: case SpvDecorationFlat: case SpvDecorationNonWritable: case SpvDecorationLocation: case SpvDecorationBinding: case SpvDecorationDescriptorSet: case SpvDecorationOffset: case SpvDecorationInputAttachmentIndex: case SpvReflectDecorationHlslCounterBufferGOOGLE: case SpvReflectDecorationHlslSemanticGOOGLE: { skip = false; } break; } if (skip) { continue; } // Find target target node uint32_t target_id = 0; CHECKED_READU32(p_parser, p_node->word_offset + 1, target_id); SpvReflectPrvNode* p_target_node = FindNode(p_parser, target_id); if (IsNull(p_target_node)) { if ((p_node->op == (uint32_t)SpvOpDecorate) && (decoration == SpvDecorationRelaxedPrecision)) { // Many OPs can be decorated that we don't care about. Ignore those. // See https://github.com/KhronosGroup/SPIRV-Reflect/issues/134 continue; } return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Get decorations SpvReflectPrvDecorations* p_target_decorations = &(p_target_node->decorations); // Update pointer if this is a member member decoration if (p_node->op == SpvOpMemberDecorate) { uint32_t member_index = (uint32_t)INVALID_VALUE; CHECKED_READU32(p_parser, p_node->word_offset + 2, member_index); p_target_decorations = &(p_target_node->member_decorations[member_index]); } switch (decoration) { default: break; case SpvDecorationRelaxedPrecision: { p_target_decorations->is_relaxed_precision = true; } break; case SpvDecorationBlock: { p_target_decorations->is_block = true; } break; case SpvDecorationBufferBlock: { p_target_decorations->is_buffer_block = true; } break; case SpvDecorationColMajor: { p_target_decorations->is_column_major = true; } break; case SpvDecorationRowMajor: { p_target_decorations->is_row_major = true; } break; case SpvDecorationArrayStride: { uint32_t word_offset = p_node->word_offset + member_offset + 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->array_stride); } break; case SpvDecorationMatrixStride: { uint32_t word_offset = p_node->word_offset + member_offset + 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->matrix_stride); } break; case SpvDecorationBuiltIn: { p_target_decorations->is_built_in = true; uint32_t word_offset = p_node->word_offset + member_offset + 3; CHECKED_READU32_CAST(p_parser, word_offset, SpvBuiltIn, p_target_decorations->built_in); } break; case SpvDecorationNoPerspective: { p_target_decorations->is_noperspective = true; } break; case SpvDecorationFlat: { p_target_decorations->is_flat = true; } break; case SpvDecorationNonWritable: { p_target_decorations->is_non_writable = true; } break; case SpvDecorationLocation: { uint32_t word_offset = p_node->word_offset + member_offset + 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->location.value); p_target_decorations->location.word_offset = word_offset; } break; case SpvDecorationBinding: { uint32_t word_offset = p_node->word_offset + member_offset+ 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->binding.value); p_target_decorations->binding.word_offset = word_offset; } break; case SpvDecorationDescriptorSet: { uint32_t word_offset = p_node->word_offset + member_offset+ 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->set.value); p_target_decorations->set.word_offset = word_offset; } break; case SpvDecorationOffset: { uint32_t word_offset = p_node->word_offset + member_offset+ 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->offset.value); p_target_decorations->offset.word_offset = word_offset; } break; case SpvDecorationInputAttachmentIndex: { uint32_t word_offset = p_node->word_offset + member_offset+ 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->input_attachment_index.value); p_target_decorations->input_attachment_index.word_offset = word_offset; } break; case SpvReflectDecorationHlslCounterBufferGOOGLE: { uint32_t word_offset = p_node->word_offset + member_offset+ 3; CHECKED_READU32(p_parser, word_offset, p_target_decorations->uav_counter_buffer.value); p_target_decorations->uav_counter_buffer.word_offset = word_offset; } break; case SpvReflectDecorationHlslSemanticGOOGLE: { uint32_t word_offset = p_node->word_offset + member_offset + 3; p_target_decorations->semantic.value = (const char*)(p_parser->spirv_code + word_offset); p_target_decorations->semantic.word_offset = word_offset; } break; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult EnumerateAllUniforms( SpvReflectShaderModule* p_module, size_t* p_uniform_count, uint32_t** pp_uniforms ) { *p_uniform_count = p_module->descriptor_binding_count; if (*p_uniform_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } *pp_uniforms = (uint32_t*)calloc(*p_uniform_count, sizeof(**pp_uniforms)); if (IsNull(*pp_uniforms)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } for (size_t i = 0; i < *p_uniform_count; ++i) { (*pp_uniforms)[i] = p_module->descriptor_bindings[i].spirv_id; } qsort(*pp_uniforms, *p_uniform_count, sizeof(**pp_uniforms), SortCompareUint32); return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseType( SpvReflectPrvParser* p_parser, SpvReflectPrvNode* p_node, SpvReflectPrvDecorations* p_struct_member_decorations, SpvReflectShaderModule* p_module, SpvReflectTypeDescription* p_type ) { SpvReflectResult result = SPV_REFLECT_RESULT_SUCCESS; if (p_node->member_count > 0) { p_type->member_count = p_node->member_count; p_type->members = (SpvReflectTypeDescription*)calloc(p_type->member_count, sizeof(*(p_type->members))); if (IsNotNull(p_type->members)) { // Mark all members types with an invalid state for (size_t i = 0; i < p_type->members->member_count; ++i) { SpvReflectTypeDescription* p_member_type = &(p_type->members[i]); p_member_type->id = (uint32_t)INVALID_VALUE; p_member_type->op = (SpvOp)INVALID_VALUE; p_member_type->storage_class = (SpvStorageClass)INVALID_VALUE; } } else { result = SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } if (result == SPV_REFLECT_RESULT_SUCCESS) { // Since the parse descends on type information, these will get overwritten // if not guarded against assignment. Only assign if the id is invalid. if (p_type->id == INVALID_VALUE) { p_type->id = p_node->result_id; p_type->op = p_node->op; p_type->decoration_flags = 0; } // Top level types need to pick up decorations from all types below it. // Issue and fix here: https://github.com/chaoticbob/SPIRV-Reflect/issues/64 p_type->decoration_flags = ApplyDecorations(&p_node->decorations); switch (p_node->op) { default: break; case SpvOpTypeVoid: p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_VOID; break; case SpvOpTypeBool: p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_BOOL; break; case SpvOpTypeInt: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_INT; IF_READU32(result, p_parser, p_node->word_offset + 2, p_type->traits.numeric.scalar.width); IF_READU32(result, p_parser, p_node->word_offset + 3, p_type->traits.numeric.scalar.signedness); } break; case SpvOpTypeFloat: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_FLOAT; IF_READU32(result, p_parser, p_node->word_offset + 2, p_type->traits.numeric.scalar.width); } break; case SpvOpTypeVector: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_VECTOR; uint32_t component_type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, component_type_id); IF_READU32(result, p_parser, p_node->word_offset + 3, p_type->traits.numeric.vector.component_count); // Parse component type SpvReflectPrvNode* p_next_node = FindNode(p_parser, component_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } break; case SpvOpTypeMatrix: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_MATRIX; uint32_t column_type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, column_type_id); IF_READU32(result, p_parser, p_node->word_offset + 3, p_type->traits.numeric.matrix.column_count); SpvReflectPrvNode* p_next_node = FindNode(p_parser, column_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } p_type->traits.numeric.matrix.row_count = p_type->traits.numeric.vector.component_count; p_type->traits.numeric.matrix.stride = p_node->decorations.matrix_stride; // NOTE: Matrix stride is decorated using OpMemberDecoreate - not OpDecoreate. if (IsNotNull(p_struct_member_decorations)) { p_type->traits.numeric.matrix.stride = p_struct_member_decorations->matrix_stride; } } break; case SpvOpTypeImage: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE; uint32_t sampled_type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, sampled_type_id); SpvReflectPrvNode* p_next_node = FindNode(p_parser, sampled_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } IF_READU32_CAST(result, p_parser, p_node->word_offset + 3, SpvDim, p_type->traits.image.dim); IF_READU32(result, p_parser, p_node->word_offset + 4, p_type->traits.image.depth); IF_READU32(result, p_parser, p_node->word_offset + 5, p_type->traits.image.arrayed); IF_READU32(result, p_parser, p_node->word_offset + 6, p_type->traits.image.ms); IF_READU32(result, p_parser, p_node->word_offset + 7, p_type->traits.image.sampled); IF_READU32_CAST(result, p_parser, p_node->word_offset + 8, SpvImageFormat, p_type->traits.image.image_format); } break; case SpvOpTypeSampler: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLER; } break; case SpvOpTypeSampledImage: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLED_IMAGE; uint32_t image_type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, image_type_id); SpvReflectPrvNode* p_next_node = FindNode(p_parser, image_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } break; case SpvOpTypeArray: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_ARRAY; if (result == SPV_REFLECT_RESULT_SUCCESS) { uint32_t element_type_id = (uint32_t)INVALID_VALUE; uint32_t length_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, element_type_id); IF_READU32(result, p_parser, p_node->word_offset + 3, length_id); // NOTE: Array stride is decorated using OpDecorate instead of // OpMemberDecorate, even if the array is apart of a struct. p_type->traits.array.stride = p_node->decorations.array_stride; // Get length for current dimension SpvReflectPrvNode* p_length_node = FindNode(p_parser, length_id); if (IsNotNull(p_length_node)) { uint32_t dim_index = p_type->traits.array.dims_count; if (p_length_node->op == SpvOpSpecConstant || p_length_node->op == SpvOpSpecConstantOp) { p_type->traits.array.dims[dim_index] = 0xFFFFFFFF; p_type->traits.array.spec_constant_op_ids[dim_index] = length_id; p_type->traits.array.dims_count += 1; } else { uint32_t length = 0; IF_READU32(result, p_parser, p_length_node->word_offset + 3, length); if (result == SPV_REFLECT_RESULT_SUCCESS) { // Write the array dim and increment the count and offset p_type->traits.array.dims[dim_index] = length; p_type->traits.array.spec_constant_op_ids[dim_index] = 0xFFFFFFFF; p_type->traits.array.dims_count += 1; } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } // Parse next dimension or element type SpvReflectPrvNode* p_next_node = FindNode(p_parser, element_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } } break; case SpvOpTypeRuntimeArray: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_ARRAY; uint32_t element_type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 2, element_type_id); p_type->traits.array.stride = p_node->decorations.array_stride; uint32_t dim_index = p_type->traits.array.dims_count; p_type->traits.array.dims[dim_index] = 0; p_type->traits.array.spec_constant_op_ids[dim_index] = 0; p_type->traits.array.dims_count += 1; // Parse next dimension or element type SpvReflectPrvNode* p_next_node = FindNode(p_parser, element_type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } break; case SpvOpTypeStruct: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_STRUCT; p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_EXTERNAL_BLOCK; uint32_t word_index = 2; uint32_t member_index = 0; for (; word_index < p_node->word_count; ++word_index, ++member_index) { uint32_t member_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + word_index, member_id); // Find member node SpvReflectPrvNode* p_member_node = FindNode(p_parser, member_id); if (IsNull(p_member_node)) { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); break; } // Member decorations SpvReflectPrvDecorations* p_member_decorations = &p_node->member_decorations[member_index]; assert(member_index < p_type->member_count); // Parse member type SpvReflectTypeDescription* p_member_type = &(p_type->members[member_index]); p_member_type->id = member_id; p_member_type->op = p_member_node->op; result = ParseType(p_parser, p_member_node, p_member_decorations, p_module, p_member_type); if (result != SPV_REFLECT_RESULT_SUCCESS) { break; } // This looks wrong //p_member_type->type_name = p_member_node->name; p_member_type->struct_member_name = p_node->member_names[member_index]; } } break; case SpvOpTypeOpaque: break; case SpvOpTypePointer: { IF_READU32_CAST(result, p_parser, p_node->word_offset + 2, SpvStorageClass, p_type->storage_class); uint32_t type_id = (uint32_t)INVALID_VALUE; IF_READU32(result, p_parser, p_node->word_offset + 3, type_id); // Parse type SpvReflectPrvNode* p_next_node = FindNode(p_parser, type_id); if (IsNotNull(p_next_node)) { result = ParseType(p_parser, p_next_node, NULL, p_module, p_type); } else { result = SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; SPV_REFLECT_ASSERT(false); } } break; case SpvOpTypeAccelerationStructureKHR: { p_type->type_flags |= SPV_REFLECT_TYPE_FLAG_EXTERNAL_ACCELERATION_STRUCTURE; } break; } if (result == SPV_REFLECT_RESULT_SUCCESS) { // Names get assigned on the way down. Guard against names // get overwritten on the way up. if (IsNull(p_type->type_name)) { p_type->type_name = p_node->name; } } } return result; } static SpvReflectResult ParseTypes( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { if (p_parser->type_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_module->_internal->type_description_count = p_parser->type_count; p_module->_internal->type_descriptions = (SpvReflectTypeDescription*)calloc(p_module->_internal->type_description_count, sizeof(*(p_module->_internal->type_descriptions))); if (IsNull(p_module->_internal->type_descriptions)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Mark all types with an invalid state for (size_t i = 0; i < p_module->_internal->type_description_count; ++i) { SpvReflectTypeDescription* p_type = &(p_module->_internal->type_descriptions[i]); p_type->id = (uint32_t)INVALID_VALUE; p_type->op = (SpvOp)INVALID_VALUE; p_type->storage_class = (SpvStorageClass)INVALID_VALUE; } size_t type_index = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (! p_node->is_type) { continue; } SpvReflectTypeDescription* p_type = &(p_module->_internal->type_descriptions[type_index]); SpvReflectResult result = ParseType(p_parser, p_node, NULL, p_module, p_type); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } ++type_index; } return SPV_REFLECT_RESULT_SUCCESS; } static int SortCompareDescriptorBinding(const void* a, const void* b) { const SpvReflectDescriptorBinding* p_elem_a = (const SpvReflectDescriptorBinding*)a; const SpvReflectDescriptorBinding* p_elem_b = (const SpvReflectDescriptorBinding*)b; int value = (int)(p_elem_a->binding) - (int)(p_elem_b->binding); if (value == 0) { // use spirv-id as a tiebreaker to ensure a stable ordering, as they're guaranteed // unique. assert(p_elem_a->spirv_id != p_elem_b->spirv_id); value = (int)(p_elem_a->spirv_id) - (int)(p_elem_b->spirv_id); } return value; } static SpvReflectResult ParseDescriptorBindings( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { p_module->descriptor_binding_count = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpVariable) || ((p_node->storage_class != SpvStorageClassUniform) && (p_node->storage_class != SpvStorageClassStorageBuffer) && (p_node->storage_class != SpvStorageClassUniformConstant))) { continue; } if ((p_node->decorations.set.value == INVALID_VALUE) || (p_node->decorations.binding.value == INVALID_VALUE)) { continue; } p_module->descriptor_binding_count += 1; } if (p_module->descriptor_binding_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_module->descriptor_bindings = (SpvReflectDescriptorBinding*)calloc(p_module->descriptor_binding_count, sizeof(*(p_module->descriptor_bindings))); if (IsNull(p_module->descriptor_bindings)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Mark all types with an invalid state for (uint32_t descriptor_index = 0; descriptor_index < p_module->descriptor_binding_count; ++descriptor_index) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[descriptor_index]); p_descriptor->binding = (uint32_t)INVALID_VALUE; p_descriptor->input_attachment_index = (uint32_t)INVALID_VALUE; p_descriptor->set = (uint32_t)INVALID_VALUE; p_descriptor->descriptor_type = (SpvReflectDescriptorType)INVALID_VALUE; p_descriptor->uav_counter_id = (uint32_t)INVALID_VALUE; } size_t descriptor_index = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpVariable) || ((p_node->storage_class != SpvStorageClassUniform) && (p_node->storage_class != SpvStorageClassStorageBuffer) && (p_node->storage_class != SpvStorageClassUniformConstant))) { continue; } if ((p_node->decorations.set.value == INVALID_VALUE) || (p_node->decorations.binding.value == INVALID_VALUE)) { continue; } SpvReflectTypeDescription* p_type = FindType(p_module, p_node->type_id); if (IsNull(p_type)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // If the type is a pointer, resolve it. We need to retain the storage class // from the pointer so that we can use it to deduce deescriptor types. SpvStorageClass pointer_storage_class = SpvStorageClassMax; if (p_type->op == SpvOpTypePointer) { pointer_storage_class = p_type->storage_class; // Find the type's node SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Should be the resolved type p_type = FindType(p_module, p_type_node->type_id); if (IsNull(p_type)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } } SpvReflectDescriptorBinding* p_descriptor = &p_module->descriptor_bindings[descriptor_index]; p_descriptor->spirv_id = p_node->result_id; p_descriptor->name = p_node->name; p_descriptor->binding = p_node->decorations.binding.value; p_descriptor->input_attachment_index = p_node->decorations.input_attachment_index.value; p_descriptor->set = p_node->decorations.set.value; p_descriptor->count = 1; p_descriptor->uav_counter_id = p_node->decorations.uav_counter_buffer.value; p_descriptor->type_description = p_type; // If this is in the StorageBuffer storage class, it's for sure a storage // buffer descriptor. We need to handle this case earlier because in SPIR-V // there are two ways to indicate a storage buffer: // 1) Uniform storage class + BufferBlock decoration, or // 2) StorageBuffer storage class + Buffer decoration. // The 1) way is deprecated since SPIR-V v1.3. But the Buffer decoration is // also used together with Uniform storage class to mean uniform buffer.. // We'll handle the pre-v1.3 cases in ParseDescriptorType(). if (pointer_storage_class == SpvStorageClassStorageBuffer) { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER; } // Copy image traits if ((p_type->type_flags & SPV_REFLECT_TYPE_FLAG_EXTERNAL_MASK) == SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE) { memcpy(&p_descriptor->image, &p_type->traits.image, sizeof(p_descriptor->image)); } // This is a workaround for: https://github.com/KhronosGroup/glslang/issues/1096 { const uint32_t resource_mask = SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLED_IMAGE | SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE; if ((p_type->type_flags & resource_mask) == resource_mask) { memcpy(&p_descriptor->image, &p_type->traits.image, sizeof(p_descriptor->image)); } } // Copy array traits if (p_type->traits.array.dims_count > 0) { p_descriptor->array.dims_count = p_type->traits.array.dims_count; for (uint32_t dim_index = 0; dim_index < p_type->traits.array.dims_count; ++dim_index) { uint32_t dim_value = p_type->traits.array.dims[dim_index]; p_descriptor->array.dims[dim_index] = dim_value; p_descriptor->count *= dim_value; } } // Count p_descriptor->word_offset.binding = p_node->decorations.binding.word_offset; p_descriptor->word_offset.set = p_node->decorations.set.word_offset; ++descriptor_index; } if (p_module->descriptor_binding_count > 0) { qsort(p_module->descriptor_bindings, p_module->descriptor_binding_count, sizeof(*(p_module->descriptor_bindings)), SortCompareDescriptorBinding); } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDescriptorType(SpvReflectShaderModule* p_module) { if (p_module->descriptor_binding_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } for (uint32_t descriptor_index = 0; descriptor_index < p_module->descriptor_binding_count; ++descriptor_index) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[descriptor_index]); SpvReflectTypeDescription* p_type = p_descriptor->type_description; if ((int)p_descriptor->descriptor_type == (int)INVALID_VALUE) { switch (p_type->type_flags & SPV_REFLECT_TYPE_FLAG_EXTERNAL_MASK) { default: assert(false && "unknown type flag"); break; case SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE: { if (p_descriptor->image.dim == SpvDimBuffer) { switch (p_descriptor->image.sampled) { default: assert(false && "unknown texel buffer sampled value"); break; case IMAGE_SAMPLED: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; break; case IMAGE_STORAGE: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; break; } } else if(p_descriptor->image.dim == SpvDimSubpassData) { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT; } else { switch (p_descriptor->image.sampled) { default: assert(false && "unknown image sampled value"); break; case IMAGE_SAMPLED: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE; break; case IMAGE_STORAGE: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE; break; } } } break; case SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLER: { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER; } break; case (SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLED_IMAGE | SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE): { // This is a workaround for: https://github.com/KhronosGroup/glslang/issues/1096 if (p_descriptor->image.dim == SpvDimBuffer) { switch (p_descriptor->image.sampled) { default: assert(false && "unknown texel buffer sampled value"); break; case IMAGE_SAMPLED: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; break; case IMAGE_STORAGE: p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; break; } } else { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; } } break; case SPV_REFLECT_TYPE_FLAG_EXTERNAL_BLOCK: { if (p_type->decoration_flags & SPV_REFLECT_DECORATION_BLOCK) { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER; } else if (p_type->decoration_flags & SPV_REFLECT_DECORATION_BUFFER_BLOCK) { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER; } else { assert(false && "unknown struct"); } } break; case SPV_REFLECT_TYPE_FLAG_EXTERNAL_ACCELERATION_STRUCTURE: { p_descriptor->descriptor_type = SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; } break; } } switch (p_descriptor->descriptor_type) { case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_SAMPLER; break; case SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER : p_descriptor->resource_type = (SpvReflectResourceType)(SPV_REFLECT_RESOURCE_FLAG_SAMPLER | SPV_REFLECT_RESOURCE_FLAG_SRV); break; case SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_SRV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_UAV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_SRV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_UAV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_CBV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_CBV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_UAV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_UAV; break; case SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT : break; case SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR : p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_SRV; break; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseUAVCounterBindings(SpvReflectShaderModule* p_module) { char name[MAX_NODE_NAME_LENGTH]; const char* k_count_tag = "@count"; for (uint32_t descriptor_index = 0; descriptor_index < p_module->descriptor_binding_count; ++descriptor_index) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[descriptor_index]); if (p_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) { continue; } SpvReflectDescriptorBinding* p_counter_descriptor = NULL; // Use UAV counter buffer id if present... if (p_descriptor->uav_counter_id != UINT32_MAX) { for (uint32_t counter_descriptor_index = 0; counter_descriptor_index < p_module->descriptor_binding_count; ++counter_descriptor_index) { SpvReflectDescriptorBinding* p_test_counter_descriptor = &(p_module->descriptor_bindings[counter_descriptor_index]); if (p_test_counter_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) { continue; } if (p_descriptor->uav_counter_id == p_test_counter_descriptor->spirv_id) { p_counter_descriptor = p_test_counter_descriptor; break; } } } // ...otherwise use old @count convention. else { const size_t descriptor_name_length = p_descriptor->name? strlen(p_descriptor->name): 0; memset(name, 0, MAX_NODE_NAME_LENGTH); memcpy(name, p_descriptor->name, descriptor_name_length); #if defined(_WIN32) strcat_s(name, MAX_NODE_NAME_LENGTH, k_count_tag); #else strcat(name, k_count_tag); #endif for (uint32_t counter_descriptor_index = 0; counter_descriptor_index < p_module->descriptor_binding_count; ++counter_descriptor_index) { SpvReflectDescriptorBinding* p_test_counter_descriptor = &(p_module->descriptor_bindings[counter_descriptor_index]); if (p_test_counter_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) { continue; } if (p_test_counter_descriptor->name && strcmp(name, p_test_counter_descriptor->name) == 0) { p_counter_descriptor = p_test_counter_descriptor; break; } } } if (p_counter_descriptor != NULL) { p_descriptor->uav_counter_binding = p_counter_descriptor; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDescriptorBlockVariable( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module, SpvReflectTypeDescription* p_type, SpvReflectBlockVariable* p_var ) { bool has_non_writable = false; if (IsNotNull(p_type->members) && (p_type->member_count > 0)) { p_var->member_count = p_type->member_count; p_var->members = (SpvReflectBlockVariable*)calloc(p_var->member_count, sizeof(*p_var->members)); if (IsNull(p_var->members)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Resolve to element type if current type is array or run time array while (p_type_node->op == SpvOpTypeArray || p_type_node->op == SpvOpTypeRuntimeArray) { if (p_type_node->op == SpvOpTypeArray) { p_type_node = FindNode(p_parser, p_type_node->array_traits.element_type_id); } else { // Element type description SpvReflectTypeDescription* p_type_temp = FindType(p_module, p_type_node->array_traits.element_type_id); if (IsNull(p_type_temp)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Element type node p_type_node = FindNode(p_parser, p_type_temp->id); } if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } } // Parse members for (uint32_t member_index = 0; member_index < p_type->member_count; ++member_index) { SpvReflectTypeDescription* p_member_type = &p_type->members[member_index]; SpvReflectBlockVariable* p_member_var = &p_var->members[member_index]; bool is_struct = (p_member_type->type_flags & SPV_REFLECT_TYPE_FLAG_STRUCT) == SPV_REFLECT_TYPE_FLAG_STRUCT; if (is_struct) { SpvReflectResult result = ParseDescriptorBlockVariable(p_parser, p_module, p_member_type, p_member_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } p_member_var->name = p_type_node->member_names[member_index]; p_member_var->offset = p_type_node->member_decorations[member_index].offset.value; p_member_var->decoration_flags = ApplyDecorations(&p_type_node->member_decorations[member_index]); p_member_var->flags |= SPV_REFLECT_VARIABLE_FLAGS_UNUSED; if (!has_non_writable && (p_member_var->decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE)) { has_non_writable = true; } ApplyNumericTraits(p_member_type, &p_member_var->numeric); if (p_member_type->op == SpvOpTypeArray) { ApplyArrayTraits(p_member_type, &p_member_var->array); } p_member_var->type_description = p_member_type; } } p_var->name = p_type->type_name; p_var->type_description = p_type; if (has_non_writable) { p_var->decoration_flags |= SPV_REFLECT_DECORATION_NON_WRITABLE; } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDescriptorBlockVariableSizes( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module, bool is_parent_root, bool is_parent_aos, bool is_parent_rta, SpvReflectBlockVariable* p_var ) { if (p_var->member_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } // Absolute offsets for (uint32_t member_index = 0; member_index < p_var->member_count; ++member_index) { SpvReflectBlockVariable* p_member_var = &p_var->members[member_index]; if (is_parent_root) { p_member_var->absolute_offset = p_member_var->offset; } else { p_member_var->absolute_offset = is_parent_aos ? 0 : p_member_var->offset + p_var->absolute_offset; } } // Size for (uint32_t member_index = 0; member_index < p_var->member_count; ++member_index) { SpvReflectBlockVariable* p_member_var = &p_var->members[member_index]; SpvReflectTypeDescription* p_member_type = p_member_var->type_description; switch (p_member_type->op) { case SpvOpTypeBool: { p_member_var->size = SPIRV_WORD_SIZE; } break; case SpvOpTypeInt: case SpvOpTypeFloat: { p_member_var->size = p_member_type->traits.numeric.scalar.width / SPIRV_BYTE_WIDTH; } break; case SpvOpTypeVector: { uint32_t size = p_member_type->traits.numeric.vector.component_count * (p_member_type->traits.numeric.scalar.width / SPIRV_BYTE_WIDTH); p_member_var->size = size; } break; case SpvOpTypeMatrix: { if (p_member_var->decoration_flags & SPV_REFLECT_DECORATION_COLUMN_MAJOR) { p_member_var->size = p_member_var->numeric.matrix.column_count * p_member_var->numeric.matrix.stride; } else if (p_member_var->decoration_flags & SPV_REFLECT_DECORATION_ROW_MAJOR) { p_member_var->size = p_member_var->numeric.matrix.row_count * p_member_var->numeric.matrix.stride; } } break; case SpvOpTypeArray: { // If array of structs, parse members first... bool is_struct = (p_member_type->type_flags & SPV_REFLECT_TYPE_FLAG_STRUCT) == SPV_REFLECT_TYPE_FLAG_STRUCT; if (is_struct) { SpvReflectResult result = ParseDescriptorBlockVariableSizes(p_parser, p_module, false, true, is_parent_rta, p_member_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } // ...then array uint32_t element_count = (p_member_var->array.dims_count > 0 ? 1 : 0); for (uint32_t i = 0; i < p_member_var->array.dims_count; ++i) { element_count *= p_member_var->array.dims[i]; } p_member_var->size = element_count * p_member_var->array.stride; } break; case SpvOpTypeRuntimeArray: { bool is_struct = (p_member_type->type_flags & SPV_REFLECT_TYPE_FLAG_STRUCT) == SPV_REFLECT_TYPE_FLAG_STRUCT; if (is_struct) { SpvReflectResult result = ParseDescriptorBlockVariableSizes(p_parser, p_module, false, true, true, p_member_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } } break; case SpvOpTypeStruct: { SpvReflectResult result = ParseDescriptorBlockVariableSizes(p_parser, p_module, false, is_parent_aos, is_parent_rta, p_member_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } break; default: break; } } // Parse padded size using offset difference for all member except for the last entry... for (uint32_t member_index = 0; member_index < (p_var->member_count - 1); ++member_index) { SpvReflectBlockVariable* p_member_var = &p_var->members[member_index]; SpvReflectBlockVariable* p_next_member_var = &p_var->members[member_index + 1]; p_member_var->padded_size = p_next_member_var->offset - p_member_var->offset; if (p_member_var->size > p_member_var->padded_size) { p_member_var->size = p_member_var->padded_size; } if (is_parent_rta) { p_member_var->padded_size = p_member_var->size; } } // ...last entry just gets rounded up to near multiple of SPIRV_DATA_ALIGNMENT, which is 16 and // subtract the offset. if (p_var->member_count > 0) { SpvReflectBlockVariable* p_member_var = &p_var->members[p_var->member_count - 1]; p_member_var->padded_size = RoundUp(p_member_var->offset + p_member_var->size, SPIRV_DATA_ALIGNMENT) - p_member_var->offset; if (p_member_var->size > p_member_var->padded_size) { p_member_var->size = p_member_var->padded_size; } if (is_parent_rta) { p_member_var->padded_size = p_member_var->size; } } // @TODO validate this with assertion p_var->size = p_var->members[p_var->member_count - 1].offset + p_var->members[p_var->member_count - 1].padded_size; p_var->padded_size = p_var->size; return SPV_REFLECT_RESULT_SUCCESS; } static void MarkSelfAndAllMemberVarsAsUsed(SpvReflectBlockVariable* p_var) { // Clear the current variable's USED flag p_var->flags &= ~SPV_REFLECT_VARIABLE_FLAGS_UNUSED; SpvOp op_type = p_var->type_description->op; switch (op_type) { default: break; case SpvOpTypeArray: { } break; case SpvOpTypeStruct: { for (uint32_t i = 0; i < p_var->member_count; ++i) { SpvReflectBlockVariable* p_member_var = &p_var->members[i]; MarkSelfAndAllMemberVarsAsUsed(p_member_var); } } break; } } static SpvReflectResult ParseDescriptorBlockVariableUsage( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module, SpvReflectPrvAccessChain* p_access_chain, uint32_t index_index, SpvOp override_op_type, SpvReflectBlockVariable* p_var ) { (void)p_parser; (void)p_access_chain; (void)p_var; // Clear the current variable's UNUSED flag p_var->flags &= ~SPV_REFLECT_VARIABLE_FLAGS_UNUSED; // Parsing arrays requires overriding the op type for // for the lowest dim's element type. SpvOp op_type = p_var->type_description->op; if (override_op_type != (SpvOp)INVALID_VALUE) { op_type = override_op_type; } switch (op_type) { default: break; case SpvOpTypeArray: { // Parse through array's type hierarchy to find the actual/non-array element type SpvReflectTypeDescription* p_type = p_var->type_description; while ((p_type->op == SpvOpTypeArray) && (index_index < p_access_chain->index_count)) { // Find the array element type id SpvReflectPrvNode* p_node = FindNode(p_parser, p_type->id); if (p_node == NULL) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } uint32_t element_type_id = p_node->array_traits.element_type_id; // Get the array element type p_type = FindType(p_module, element_type_id); if (p_type == NULL) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Next access chain index index_index += 1; } // Only continue parsing if there's remaining indices in the access // chain. If the end of the access chain has been reach then all // remaining variables (including those in struct hierarchies) // are considered USED. // // See: https://github.com/KhronosGroup/SPIRV-Reflect/issues/78 // if (index_index < p_access_chain->index_count) { // Parse current var again with a type override and advanced index index SpvReflectResult result = ParseDescriptorBlockVariableUsage( p_parser, p_module, p_access_chain, index_index, p_type->op, p_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } else { // Clear UNUSED flag for remaining variables MarkSelfAndAllMemberVarsAsUsed(p_var); } } break; case SpvOpTypeStruct: { assert(p_var->member_count > 0); if (p_var->member_count == 0) { return SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_BLOCK_DATA; } // Get member variable at the access's chain current index uint32_t index = p_access_chain->indexes[index_index]; if (index >= p_var->member_count) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_BLOCK_MEMBER_REFERENCE; } SpvReflectBlockVariable* p_member_var = &p_var->members[index]; // Next access chain index index_index += 1; // Only continue parsing if there's remaining indices in the access // chain. If the end of the access chain has been reach then all // remaining variables (including those in struct hierarchies) // are considered USED. // // See: https://github.com/KhronosGroup/SPIRV-Reflect/issues/78 // if (index_index < p_access_chain->index_count) { SpvReflectResult result = ParseDescriptorBlockVariableUsage( p_parser, p_module, p_access_chain, index_index, (SpvOp)INVALID_VALUE, p_member_var); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } else { // Clear UNUSED flag for remaining variables MarkSelfAndAllMemberVarsAsUsed(p_member_var); } //SpvReflectBlockVariable* p_member_var = &p_var->members[index]; //if (index_index < p_access_chain->index_count) { // SpvReflectResult result = ParseDescriptorBlockVariableUsage( // p_parser, // p_module, // p_access_chain, // index_index + 1, // (SpvOp)INVALID_VALUE, // p_member_var); // if (result != SPV_REFLECT_RESULT_SUCCESS) { // return result; // } //} } break; } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDescriptorBlocks( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { if (p_module->descriptor_binding_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } for (uint32_t descriptor_index = 0; descriptor_index < p_module->descriptor_binding_count; ++descriptor_index) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[descriptor_index]); SpvReflectTypeDescription* p_type = p_descriptor->type_description; if ((p_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER) && (p_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) ) { continue; } // Mark UNUSED p_descriptor->block.flags |= SPV_REFLECT_VARIABLE_FLAGS_UNUSED; // Parse descriptor block SpvReflectResult result = ParseDescriptorBlockVariable(p_parser, p_module, p_type, &p_descriptor->block); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } for (uint32_t access_chain_index = 0; access_chain_index < p_parser->access_chain_count; ++access_chain_index) { SpvReflectPrvAccessChain* p_access_chain = &(p_parser->access_chains[access_chain_index]); // Skip any access chains that aren't touching this descriptor block if (p_descriptor->spirv_id != p_access_chain->base_id) { continue; } result = ParseDescriptorBlockVariableUsage( p_parser, p_module, p_access_chain, 0, (SpvOp)INVALID_VALUE, &p_descriptor->block); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } p_descriptor->block.name = p_descriptor->name; bool is_parent_rta = (p_descriptor->descriptor_type == SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER); result = ParseDescriptorBlockVariableSizes(p_parser, p_module, true, false, is_parent_rta, &p_descriptor->block); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } if (is_parent_rta) { p_descriptor->block.size = 0; p_descriptor->block.padded_size = 0; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseFormat( const SpvReflectTypeDescription* p_type, SpvReflectFormat* p_format ) { SpvReflectResult result = SPV_REFLECT_RESULT_ERROR_INTERNAL_ERROR; bool signedness = (p_type->traits.numeric.scalar.signedness != 0); uint32_t bit_width = p_type->traits.numeric.scalar.width; if (p_type->type_flags & SPV_REFLECT_TYPE_FLAG_VECTOR) { uint32_t component_count = p_type->traits.numeric.vector.component_count; if (p_type->type_flags & SPV_REFLECT_TYPE_FLAG_FLOAT) { switch (bit_width) { case 32: { switch (component_count) { case 2: *p_format = SPV_REFLECT_FORMAT_R32G32_SFLOAT; break; case 3: *p_format = SPV_REFLECT_FORMAT_R32G32B32_SFLOAT; break; case 4: *p_format = SPV_REFLECT_FORMAT_R32G32B32A32_SFLOAT; break; } } break; case 64: { switch (component_count) { case 2: *p_format = SPV_REFLECT_FORMAT_R64G64_SFLOAT; break; case 3: *p_format = SPV_REFLECT_FORMAT_R64G64B64_SFLOAT; break; case 4: *p_format = SPV_REFLECT_FORMAT_R64G64B64A64_SFLOAT; break; } } } result = SPV_REFLECT_RESULT_SUCCESS; } else if (p_type->type_flags & (SPV_REFLECT_TYPE_FLAG_INT | SPV_REFLECT_TYPE_FLAG_BOOL)) { switch (bit_width) { case 32: { switch (component_count) { case 2: *p_format = signedness ? SPV_REFLECT_FORMAT_R32G32_SINT : SPV_REFLECT_FORMAT_R32G32_UINT; break; case 3: *p_format = signedness ? SPV_REFLECT_FORMAT_R32G32B32_SINT : SPV_REFLECT_FORMAT_R32G32B32_UINT; break; case 4: *p_format = signedness ? SPV_REFLECT_FORMAT_R32G32B32A32_SINT : SPV_REFLECT_FORMAT_R32G32B32A32_UINT; break; } } break; case 64: { switch (component_count) { case 2: *p_format = signedness ? SPV_REFLECT_FORMAT_R64G64_SINT : SPV_REFLECT_FORMAT_R64G64_UINT; break; case 3: *p_format = signedness ? SPV_REFLECT_FORMAT_R64G64B64_SINT : SPV_REFLECT_FORMAT_R64G64B64_UINT; break; case 4: *p_format = signedness ? SPV_REFLECT_FORMAT_R64G64B64A64_SINT : SPV_REFLECT_FORMAT_R64G64B64A64_UINT; break; } } } result = SPV_REFLECT_RESULT_SUCCESS; } } else if (p_type->type_flags & SPV_REFLECT_TYPE_FLAG_FLOAT) { switch(bit_width) { case 32: *p_format = SPV_REFLECT_FORMAT_R32_SFLOAT; break; case 64: *p_format = SPV_REFLECT_FORMAT_R64_SFLOAT; break; } result = SPV_REFLECT_RESULT_SUCCESS; } else if (p_type->type_flags & (SPV_REFLECT_TYPE_FLAG_INT | SPV_REFLECT_TYPE_FLAG_BOOL)) { switch(bit_width) { case 32: *p_format = signedness ? SPV_REFLECT_FORMAT_R32_SINT : SPV_REFLECT_FORMAT_R32_UINT; break; break; case 64: *p_format = signedness ? SPV_REFLECT_FORMAT_R64_SINT : SPV_REFLECT_FORMAT_R64_UINT; break; } result = SPV_REFLECT_RESULT_SUCCESS; } else if (p_type->type_flags & SPV_REFLECT_TYPE_FLAG_STRUCT) { *p_format = SPV_REFLECT_FORMAT_UNDEFINED; result = SPV_REFLECT_RESULT_SUCCESS; } return result; } static SpvReflectResult ParseInterfaceVariable( SpvReflectPrvParser* p_parser, const SpvReflectPrvDecorations* p_var_node_decorations, const SpvReflectPrvDecorations* p_type_node_decorations, SpvReflectShaderModule* p_module, SpvReflectTypeDescription* p_type, SpvReflectInterfaceVariable* p_var, bool* p_has_built_in ) { SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } if (p_type->member_count > 0) { p_var->member_count = p_type->member_count; p_var->members = (SpvReflectInterfaceVariable*)calloc(p_var->member_count, sizeof(*p_var->members)); if (IsNull(p_var->members)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } for (uint32_t member_index = 0; member_index < p_type_node->member_count; ++member_index) { SpvReflectPrvDecorations* p_member_decorations = &p_type_node->member_decorations[member_index]; SpvReflectTypeDescription* p_member_type = &p_type->members[member_index]; SpvReflectInterfaceVariable* p_member_var = &p_var->members[member_index]; SpvReflectResult result = ParseInterfaceVariable(p_parser, NULL, p_member_decorations, p_module, p_member_type, p_member_var, p_has_built_in); if (result != SPV_REFLECT_RESULT_SUCCESS) { SPV_REFLECT_ASSERT(false); return result; } } } p_var->name = p_type_node->name; p_var->decoration_flags = ApplyDecorations(p_type_node_decorations); if (p_var_node_decorations != NULL) { p_var->decoration_flags |= ApplyDecorations(p_var_node_decorations); } p_var->built_in = p_type_node_decorations->built_in; ApplyNumericTraits(p_type, &p_var->numeric); if (p_type->op == SpvOpTypeArray) { ApplyArrayTraits(p_type, &p_var->array); } p_var->type_description = p_type; *p_has_built_in |= p_type_node_decorations->is_built_in; // Only parse format for interface variables that are input or output if ((p_var->storage_class == SpvStorageClassInput) || (p_var->storage_class == SpvStorageClassOutput)) { SpvReflectResult result = ParseFormat(p_var->type_description, &p_var->format); if (result != SPV_REFLECT_RESULT_SUCCESS) { SPV_REFLECT_ASSERT(false); return result; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseInterfaceVariables( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module, SpvReflectEntryPoint* p_entry, uint32_t interface_variable_count, uint32_t* p_interface_variable_ids ) { if (interface_variable_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_entry->interface_variable_count = interface_variable_count; p_entry->input_variable_count = 0; p_entry->output_variable_count = 0; for (size_t i = 0; i < interface_variable_count; ++i) { uint32_t var_result_id = *(p_interface_variable_ids + i); SpvReflectPrvNode* p_node = FindNode(p_parser, var_result_id); if (IsNull(p_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } if (p_node->storage_class == SpvStorageClassInput) { p_entry->input_variable_count += 1; } else if (p_node->storage_class == SpvStorageClassOutput) { p_entry->output_variable_count += 1; } } if (p_entry->input_variable_count > 0) { p_entry->input_variables = (SpvReflectInterfaceVariable**)calloc(p_entry->input_variable_count, sizeof(*(p_entry->input_variables))); if (IsNull(p_entry->input_variables)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } if (p_entry->output_variable_count > 0) { p_entry->output_variables = (SpvReflectInterfaceVariable**)calloc(p_entry->output_variable_count, sizeof(*(p_entry->output_variables))); if (IsNull(p_entry->output_variables)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } if (p_entry->interface_variable_count > 0) { p_entry->interface_variables = (SpvReflectInterfaceVariable*)calloc(p_entry->interface_variable_count, sizeof(*(p_entry->interface_variables))); if (IsNull(p_entry->interface_variables)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } size_t input_index = 0; size_t output_index = 0; for (size_t i = 0; i < interface_variable_count; ++i) { uint32_t var_result_id = *(p_interface_variable_ids + i); SpvReflectPrvNode* p_node = FindNode(p_parser, var_result_id); if (IsNull(p_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } SpvReflectTypeDescription* p_type = FindType(p_module, p_node->type_id); if (IsNull(p_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // If the type is a pointer, resolve it if (p_type->op == SpvOpTypePointer) { // Find the type's node SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Should be the resolved type p_type = FindType(p_module, p_type_node->type_id); if (IsNull(p_type)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } } SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } SpvReflectInterfaceVariable* p_var = &(p_entry->interface_variables[i]); p_var->storage_class = p_node->storage_class; bool has_built_in = p_node->decorations.is_built_in; SpvReflectResult result = ParseInterfaceVariable( p_parser, &p_node->decorations, &p_type_node->decorations, p_module, p_type, p_var, &has_built_in); if (result != SPV_REFLECT_RESULT_SUCCESS) { SPV_REFLECT_ASSERT(false); return result; } // Input and output variables if (p_var->storage_class == SpvStorageClassInput) { p_entry->input_variables[input_index] = p_var; ++input_index; } else if (p_node->storage_class == SpvStorageClassOutput) { p_entry->output_variables[output_index] = p_var; ++output_index; } // SPIR-V result id p_var->spirv_id = p_node->result_id; // Name p_var->name = p_node->name; // Semantic p_var->semantic = p_node->decorations.semantic.value; // Decorate with built-in if any member is built-in if (has_built_in) { p_var->decoration_flags |= SPV_REFLECT_DECORATION_BUILT_IN; } // Location is decorated on OpVariable node, not the type node. p_var->location = p_node->decorations.location.value; p_var->word_offset.location = p_node->decorations.location.word_offset; // Built in if (p_node->decorations.is_built_in) { p_var->built_in = p_node->decorations.built_in; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult EnumerateAllPushConstants( SpvReflectShaderModule* p_module, size_t* p_push_constant_count, uint32_t** p_push_constants ) { *p_push_constant_count = p_module->push_constant_block_count; if (*p_push_constant_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } *p_push_constants = (uint32_t*)calloc(*p_push_constant_count, sizeof(**p_push_constants)); if (IsNull(*p_push_constants)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } for (size_t i = 0; i < *p_push_constant_count; ++i) { (*p_push_constants)[i] = p_module->push_constant_blocks[i].spirv_id; } qsort(*p_push_constants, *p_push_constant_count, sizeof(**p_push_constants), SortCompareUint32); return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult TraverseCallGraph( SpvReflectPrvParser* p_parser, SpvReflectPrvFunction* p_func, size_t* p_func_count, uint32_t* p_func_ids, uint32_t depth ) { if (depth > p_parser->function_count) { // Vulkan does not permit recursion (Vulkan spec Appendix A): // "Recursion: The static function-call graph for an entry point must not // contain cycles." return SPV_REFLECT_RESULT_ERROR_SPIRV_RECURSION; } if (IsNotNull(p_func_ids)) { p_func_ids[(*p_func_count)++] = p_func->id; } else { ++*p_func_count; } for (size_t i = 0; i < p_func->callee_count; ++i) { SpvReflectResult result = TraverseCallGraph( p_parser, p_func->callee_ptrs[i], p_func_count, p_func_ids, depth + 1); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseStaticallyUsedResources( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module, SpvReflectEntryPoint* p_entry, size_t uniform_count, uint32_t* uniforms, size_t push_constant_count, uint32_t* push_constants ) { // Find function with the right id SpvReflectPrvFunction* p_func = NULL; for (size_t i = 0; i < p_parser->function_count; ++i) { if (p_parser->functions[i].id == p_entry->id) { p_func = &(p_parser->functions[i]); break; } } if (p_func == NULL) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } size_t called_function_count = 0; SpvReflectResult result = TraverseCallGraph( p_parser, p_func, &called_function_count, NULL, 0); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } uint32_t* p_called_functions = NULL; if (called_function_count > 0) { p_called_functions = (uint32_t*)calloc(called_function_count, sizeof(*p_called_functions)); if (IsNull(p_called_functions)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } called_function_count = 0; result = TraverseCallGraph( p_parser, p_func, &called_function_count, p_called_functions, 0); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } if (called_function_count > 0) { qsort( p_called_functions, called_function_count, sizeof(*p_called_functions), SortCompareUint32); } called_function_count = DedupSortedUint32(p_called_functions, called_function_count); uint32_t used_variable_count = 0; for (size_t i = 0, j = 0; i < called_function_count; ++i) { // No need to bounds check j because a missing ID issue would have been // found during TraverseCallGraph while (p_parser->functions[j].id != p_called_functions[i]) { ++j; } used_variable_count += p_parser->functions[j].accessed_ptr_count; } uint32_t* used_variables = NULL; if (used_variable_count > 0) { used_variables = (uint32_t*)calloc(used_variable_count, sizeof(*used_variables)); if (IsNull(used_variables)) { SafeFree(p_called_functions); return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } used_variable_count = 0; for (size_t i = 0, j = 0; i < called_function_count; ++i) { while (p_parser->functions[j].id != p_called_functions[i]) { ++j; } memcpy(&used_variables[used_variable_count], p_parser->functions[j].accessed_ptrs, p_parser->functions[j].accessed_ptr_count * sizeof(*used_variables)); used_variable_count += p_parser->functions[j].accessed_ptr_count; } SafeFree(p_called_functions); if (used_variable_count > 0) { qsort(used_variables, used_variable_count, sizeof(*used_variables), SortCompareUint32); } used_variable_count = (uint32_t)DedupSortedUint32(used_variables, used_variable_count); // Do set intersection to find the used uniform and push constants size_t used_uniform_count = 0; // SpvReflectResult result0 = IntersectSortedUint32( used_variables, used_variable_count, uniforms, uniform_count, &p_entry->used_uniforms, &used_uniform_count); size_t used_push_constant_count = 0; // SpvReflectResult result1 = IntersectSortedUint32( used_variables, used_variable_count, push_constants, push_constant_count, &p_entry->used_push_constants, &used_push_constant_count); for (uint32_t j = 0; j < p_module->descriptor_binding_count; ++j) { SpvReflectDescriptorBinding* p_binding = &p_module->descriptor_bindings[j]; bool found = SearchSortedUint32( used_variables, used_variable_count, p_binding->spirv_id); if (found) { p_binding->accessed = 1; } } SafeFree(used_variables); if (result0 != SPV_REFLECT_RESULT_SUCCESS) { return result0; } if (result1 != SPV_REFLECT_RESULT_SUCCESS) { return result1; } p_entry->used_uniform_count = (uint32_t)used_uniform_count; p_entry->used_push_constant_count = (uint32_t)used_push_constant_count; return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseEntryPoints( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { if (p_parser->entry_point_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_module->entry_point_count = p_parser->entry_point_count; p_module->entry_points = (SpvReflectEntryPoint*)calloc(p_module->entry_point_count, sizeof(*(p_module->entry_points))); if (IsNull(p_module->entry_points)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } SpvReflectResult result; size_t uniform_count = 0; uint32_t* uniforms = NULL; if ((result = EnumerateAllUniforms(p_module, &uniform_count, &uniforms)) != SPV_REFLECT_RESULT_SUCCESS) { return result; } size_t push_constant_count = 0; uint32_t* push_constants = NULL; if ((result = EnumerateAllPushConstants(p_module, &push_constant_count, &push_constants)) != SPV_REFLECT_RESULT_SUCCESS) { return result; } size_t entry_point_index = 0; for (size_t i = 0; entry_point_index < p_parser->entry_point_count && i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if (p_node->op != SpvOpEntryPoint) { continue; } SpvReflectEntryPoint* p_entry_point = &(p_module->entry_points[entry_point_index]); CHECKED_READU32_CAST(p_parser, p_node->word_offset + 1, SpvExecutionModel, p_entry_point->spirv_execution_model); CHECKED_READU32(p_parser, p_node->word_offset + 2, p_entry_point->id); switch (p_entry_point->spirv_execution_model) { default: break; case SpvExecutionModelVertex : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_VERTEX_BIT; break; case SpvExecutionModelTessellationControl : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_TESSELLATION_CONTROL_BIT; break; case SpvExecutionModelTessellationEvaluation : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_TESSELLATION_EVALUATION_BIT; break; case SpvExecutionModelGeometry : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_GEOMETRY_BIT; break; case SpvExecutionModelFragment : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_FRAGMENT_BIT; break; case SpvExecutionModelGLCompute : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_COMPUTE_BIT; break; case SpvExecutionModelTaskNV : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_TASK_BIT_NV; break; case SpvExecutionModelMeshNV : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_MESH_BIT_NV; break; case SpvExecutionModelRayGenerationKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_RAYGEN_BIT_KHR; break; case SpvExecutionModelIntersectionKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_INTERSECTION_BIT_KHR; break; case SpvExecutionModelAnyHitKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_ANY_HIT_BIT_KHR; break; case SpvExecutionModelClosestHitKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_CLOSEST_HIT_BIT_KHR; break; case SpvExecutionModelMissKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_MISS_BIT_KHR; break; case SpvExecutionModelCallableKHR : p_entry_point->shader_stage = SPV_REFLECT_SHADER_STAGE_CALLABLE_BIT_KHR; break; } ++entry_point_index; // Name length is required to calculate next operand uint32_t name_start_word_offset = 3; uint32_t name_length_with_terminator = 0; result = ReadStr(p_parser, p_node->word_offset + name_start_word_offset, 0, p_node->word_count, &name_length_with_terminator, NULL); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } p_entry_point->name = (const char*)(p_parser->spirv_code + p_node->word_offset + name_start_word_offset); uint32_t name_word_count = RoundUp(name_length_with_terminator, SPIRV_WORD_SIZE) / SPIRV_WORD_SIZE; uint32_t interface_variable_count = (p_node->word_count - (name_start_word_offset + name_word_count)); uint32_t* p_interface_variables = NULL; if (interface_variable_count > 0) { p_interface_variables = (uint32_t*)calloc(interface_variable_count, sizeof(*(p_interface_variables))); if (IsNull(p_interface_variables)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } for (uint32_t var_index = 0; var_index < interface_variable_count; ++var_index) { uint32_t var_result_id = (uint32_t)INVALID_VALUE; uint32_t offset = name_start_word_offset + name_word_count + var_index; CHECKED_READU32(p_parser, p_node->word_offset + offset, var_result_id); p_interface_variables[var_index] = var_result_id; } result = ParseInterfaceVariables( p_parser, p_module, p_entry_point, interface_variable_count, p_interface_variables); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } SafeFree(p_interface_variables); result = ParseStaticallyUsedResources( p_parser, p_module, p_entry_point, uniform_count, uniforms, push_constant_count, push_constants); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } } SafeFree(uniforms); SafeFree(push_constants); return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseExecutionModes( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { assert(IsNotNull(p_parser)); assert(IsNotNull(p_parser->nodes)); assert(IsNotNull(p_module)); if (IsNotNull(p_parser) && IsNotNull(p_parser->spirv_code) && IsNotNull(p_parser->nodes)) { for (size_t node_idx = 0; node_idx < p_parser->node_count; ++node_idx) { SpvReflectPrvNode* p_node = &(p_parser->nodes[node_idx]); if (p_node->op != SpvOpExecutionMode) { continue; } // Read entry point id uint32_t entry_point_id = 0; CHECKED_READU32(p_parser, p_node->word_offset + 1, entry_point_id); // Find entry point SpvReflectEntryPoint* p_entry_point = NULL; for (size_t entry_point_idx = 0; entry_point_idx < p_module->entry_point_count; ++entry_point_idx) { if (p_module->entry_points[entry_point_idx].id == entry_point_id) { p_entry_point = &p_module->entry_points[entry_point_idx]; break; } } // Bail if entry point is null if (IsNull(p_entry_point)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ENTRY_POINT; } // Read execution mode uint32_t execution_mode = (uint32_t)INVALID_VALUE; CHECKED_READU32(p_parser, p_node->word_offset + 2, execution_mode); // Parse execution mode switch (execution_mode) { default: { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_EXECUTION_MODE; } break; case SpvExecutionModeInvocations: { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_entry_point->invocations); } break; case SpvExecutionModeSpacingEqual: case SpvExecutionModeSpacingFractionalEven: case SpvExecutionModeSpacingFractionalOdd: case SpvExecutionModeVertexOrderCw: case SpvExecutionModeVertexOrderCcw: case SpvExecutionModePixelCenterInteger: case SpvExecutionModeOriginUpperLeft: case SpvExecutionModeOriginLowerLeft: case SpvExecutionModeEarlyFragmentTests: case SpvExecutionModePointMode: case SpvExecutionModeXfb: case SpvExecutionModeDepthReplacing: case SpvExecutionModeDepthGreater: case SpvExecutionModeDepthLess: case SpvExecutionModeDepthUnchanged: break; case SpvExecutionModeLocalSize: { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_entry_point->local_size.x); CHECKED_READU32(p_parser, p_node->word_offset + 4, p_entry_point->local_size.y); CHECKED_READU32(p_parser, p_node->word_offset + 5, p_entry_point->local_size.z); } break; case SpvExecutionModeLocalSizeHint: case SpvExecutionModeInputPoints: case SpvExecutionModeInputLines: case SpvExecutionModeInputLinesAdjacency: case SpvExecutionModeTriangles: case SpvExecutionModeInputTrianglesAdjacency: case SpvExecutionModeQuads: case SpvExecutionModeIsolines: case SpvExecutionModeOutputVertices: { CHECKED_READU32(p_parser, p_node->word_offset + 3, p_entry_point->output_vertices); } break; case SpvExecutionModeOutputPoints: case SpvExecutionModeOutputLineStrip: case SpvExecutionModeOutputTriangleStrip: case SpvExecutionModeVecTypeHint: case SpvExecutionModeContractionOff: case SpvExecutionModeInitializer: case SpvExecutionModeFinalizer: case SpvExecutionModeSubgroupSize: case SpvExecutionModeSubgroupsPerWorkgroup: case SpvExecutionModeSubgroupsPerWorkgroupId: case SpvExecutionModeLocalSizeId: case SpvExecutionModeLocalSizeHintId: case SpvExecutionModePostDepthCoverage: case SpvExecutionModeStencilRefReplacingEXT: case SpvExecutionModeOutputPrimitivesNV: case SpvExecutionModeOutputTrianglesNV: break; } } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParsePushConstantBlocks( SpvReflectPrvParser* p_parser, SpvReflectShaderModule* p_module) { for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpVariable) || (p_node->storage_class != SpvStorageClassPushConstant)) { continue; } p_module->push_constant_block_count += 1; } if (p_module->push_constant_block_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } p_module->push_constant_blocks = (SpvReflectBlockVariable*)calloc(p_module->push_constant_block_count, sizeof(*p_module->push_constant_blocks)); if (IsNull(p_module->push_constant_blocks)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } uint32_t push_constant_index = 0; for (size_t i = 0; i < p_parser->node_count; ++i) { SpvReflectPrvNode* p_node = &(p_parser->nodes[i]); if ((p_node->op != SpvOpVariable) || (p_node->storage_class != SpvStorageClassPushConstant)) { continue; } SpvReflectTypeDescription* p_type = FindType(p_module, p_node->type_id); if (IsNull(p_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // If the type is a pointer, resolve it if (p_type->op == SpvOpTypePointer) { // Find the type's node SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } // Should be the resolved type p_type = FindType(p_module, p_type_node->type_id); if (IsNull(p_type)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } } SpvReflectPrvNode* p_type_node = FindNode(p_parser, p_type->id); if (IsNull(p_type_node)) { return SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE; } SpvReflectBlockVariable* p_push_constant = &p_module->push_constant_blocks[push_constant_index]; p_push_constant->spirv_id = p_node->result_id; SpvReflectResult result = ParseDescriptorBlockVariable(p_parser, p_module, p_type, p_push_constant); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } result = ParseDescriptorBlockVariableSizes(p_parser, p_module, true, false, false, p_push_constant); if (result != SPV_REFLECT_RESULT_SUCCESS) { return result; } ++push_constant_index; } return SPV_REFLECT_RESULT_SUCCESS; } static int SortCompareDescriptorSet(const void* a, const void* b) { const SpvReflectDescriptorSet* p_elem_a = (const SpvReflectDescriptorSet*)a; const SpvReflectDescriptorSet* p_elem_b = (const SpvReflectDescriptorSet*)b; int value = (int)(p_elem_a->set) - (int)(p_elem_b->set); // We should never see duplicate descriptor set numbers in a shader; if so, a tiebreaker // would be needed here. assert(value != 0); return value; } static SpvReflectResult ParseEntrypointDescriptorSets(SpvReflectShaderModule* p_module) { // Update the entry point's sets for (uint32_t i = 0; i < p_module->entry_point_count; ++i) { SpvReflectEntryPoint* p_entry = &p_module->entry_points[i]; for (uint32_t j = 0; j < p_entry->descriptor_set_count; ++j) { SafeFree(p_entry->descriptor_sets[j].bindings); } SafeFree(p_entry->descriptor_sets); p_entry->descriptor_set_count = 0; for (uint32_t j = 0; j < p_module->descriptor_set_count; ++j) { const SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[j]; for (uint32_t k = 0; k < p_set->binding_count; ++k) { bool found = SearchSortedUint32( p_entry->used_uniforms, p_entry->used_uniform_count, p_set->bindings[k]->spirv_id); if (found) { ++p_entry->descriptor_set_count; break; } } } p_entry->descriptor_sets = NULL; if (p_entry->descriptor_set_count > 0) { p_entry->descriptor_sets = (SpvReflectDescriptorSet*)calloc(p_entry->descriptor_set_count, sizeof(*p_entry->descriptor_sets)); if (IsNull(p_entry->descriptor_sets)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } } p_entry->descriptor_set_count = 0; for (uint32_t j = 0; j < p_module->descriptor_set_count; ++j) { const SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[j]; uint32_t count = 0; for (uint32_t k = 0; k < p_set->binding_count; ++k) { bool found = SearchSortedUint32( p_entry->used_uniforms, p_entry->used_uniform_count, p_set->bindings[k]->spirv_id); if (found) { ++count; } } if (count == 0) { continue; } SpvReflectDescriptorSet* p_entry_set = &p_entry->descriptor_sets[ p_entry->descriptor_set_count++]; p_entry_set->set = p_set->set; p_entry_set->bindings = (SpvReflectDescriptorBinding**)calloc(count, sizeof(*p_entry_set->bindings)); if (IsNull(p_entry_set->bindings)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } for (uint32_t k = 0; k < p_set->binding_count; ++k) { bool found = SearchSortedUint32( p_entry->used_uniforms, p_entry->used_uniform_count, p_set->bindings[k]->spirv_id); if (found) { p_entry_set->bindings[p_entry_set->binding_count++] = p_set->bindings[k]; } } } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult ParseDescriptorSets(SpvReflectShaderModule* p_module) { // Count the descriptors in each set for (uint32_t i = 0; i < p_module->descriptor_binding_count; ++i) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[i]); // Look for a target set using the descriptor's set number SpvReflectDescriptorSet* p_target_set = NULL; for (uint32_t j = 0; j < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++j) { SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[j]; if (p_set->set == p_descriptor->set) { p_target_set = p_set; break; } } // If a target set isn't found, find the first available one. if (IsNull(p_target_set)) { for (uint32_t j = 0; j < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++j) { SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[j]; if (p_set->set == (uint32_t)INVALID_VALUE) { p_target_set = p_set; p_target_set->set = p_descriptor->set; break; } } } if (IsNull(p_target_set)) { return SPV_REFLECT_RESULT_ERROR_INTERNAL_ERROR; } p_target_set->binding_count += 1; } // Count the descriptor sets for (uint32_t i = 0; i < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++i) { const SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[i]; if (p_set->set != (uint32_t)INVALID_VALUE) { p_module->descriptor_set_count += 1; } } // Sort the descriptor sets based on numbers if (p_module->descriptor_set_count > 0) { qsort(p_module->descriptor_sets, p_module->descriptor_set_count, sizeof(*(p_module->descriptor_sets)), SortCompareDescriptorSet); } // Build descriptor pointer array for (uint32_t i = 0; i <p_module->descriptor_set_count; ++i) { SpvReflectDescriptorSet* p_set = &(p_module->descriptor_sets[i]); p_set->bindings = (SpvReflectDescriptorBinding **)calloc(p_set->binding_count, sizeof(*(p_set->bindings))); uint32_t descriptor_index = 0; for (uint32_t j = 0; j < p_module->descriptor_binding_count; ++j) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[j]); if (p_descriptor->set == p_set->set) { assert(descriptor_index < p_set->binding_count); p_set->bindings[descriptor_index] = p_descriptor; ++descriptor_index; } } } return ParseEntrypointDescriptorSets(p_module); } static SpvReflectResult DisambiguateStorageBufferSrvUav(SpvReflectShaderModule* p_module) { if (p_module->descriptor_binding_count == 0) { return SPV_REFLECT_RESULT_SUCCESS; } for (uint32_t descriptor_index = 0; descriptor_index < p_module->descriptor_binding_count; ++descriptor_index) { SpvReflectDescriptorBinding* p_descriptor = &(p_module->descriptor_bindings[descriptor_index]); // Skip everything that isn't a STORAGE_BUFFER descriptor if (p_descriptor->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) { continue; } // // Vulkan doesn't disambiguate between SRVs and UAVs so they // come back as STORAGE_BUFFER. The block parsing process will // mark a block as non-writable should any member of the block // or its descendants are non-writable. // if (p_descriptor->block.decoration_flags & SPV_REFLECT_DECORATION_NON_WRITABLE) { p_descriptor->resource_type = SPV_REFLECT_RESOURCE_FLAG_SRV; } } return SPV_REFLECT_RESULT_SUCCESS; } static SpvReflectResult SynchronizeDescriptorSets(SpvReflectShaderModule* p_module) { // Free and reset all descriptor set numbers for (uint32_t i = 0; i < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++i) { SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[i]; SafeFree(p_set->bindings); p_set->binding_count = 0; p_set->set = (uint32_t)INVALID_VALUE; } // Set descriptor set count to zero p_module->descriptor_set_count = 0; SpvReflectResult result = ParseDescriptorSets(p_module); return result; } static SpvReflectResult CreateShaderModule( uint32_t flags, size_t size, const void* p_code, SpvReflectShaderModule* p_module ) { // Initialize all module fields to zero memset(p_module, 0, sizeof(*p_module)); // Allocate module internals #ifdef __cplusplus p_module->_internal = (SpvReflectShaderModule::Internal*)calloc(1, sizeof(*(p_module->_internal))); #else p_module->_internal = calloc(1, sizeof(*(p_module->_internal))); #endif if (IsNull(p_module->_internal)) { return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Copy flags p_module->_internal->module_flags = flags; // Figure out if we need to copy the SPIR-V code or not if (flags & SPV_REFLECT_MODULE_FLAG_NO_COPY) { // Set internal size and pointer to args passed in p_module->_internal->spirv_size = size; p_module->_internal->spirv_code = (void*)p_code; // cast that const away p_module->_internal->spirv_word_count = (uint32_t)(size / SPIRV_WORD_SIZE); } else { // Allocate SPIR-V code storage p_module->_internal->spirv_size = size; p_module->_internal->spirv_code = (uint32_t*)calloc(1, p_module->_internal->spirv_size); p_module->_internal->spirv_word_count = (uint32_t)(size / SPIRV_WORD_SIZE); if (IsNull(p_module->_internal->spirv_code)) { SafeFree(p_module->_internal); return SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED; } // Copy SPIR-V to code storage memcpy(p_module->_internal->spirv_code, p_code, size); } SpvReflectPrvParser parser = { 0 }; SpvReflectResult result = CreateParser(p_module->_internal->spirv_size, p_module->_internal->spirv_code, &parser); // Generator { const uint32_t* p_ptr = (const uint32_t*)p_module->_internal->spirv_code; p_module->generator = (SpvReflectGenerator)((*(p_ptr + 2) & 0xFFFF0000) >> 16); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseNodes(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseStrings(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseSource(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseFunctions(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseMemberCounts(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseNames(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseDecorations(&parser); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } // Start of reflection data parsing if (result == SPV_REFLECT_RESULT_SUCCESS) { p_module->source_language = parser.source_language; p_module->source_language_version = parser.source_language_version; // Zero out descriptor set data p_module->descriptor_set_count = 0; memset(p_module->descriptor_sets, 0, SPV_REFLECT_MAX_DESCRIPTOR_SETS * sizeof(*p_module->descriptor_sets)); // Initialize descriptor set numbers for (uint32_t set_number = 0; set_number < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++set_number) { p_module->descriptor_sets[set_number].set = (uint32_t)INVALID_VALUE; } } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseTypes(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseDescriptorBindings(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseDescriptorType(p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseUAVCounterBindings(p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseDescriptorBlocks(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParsePushConstantBlocks(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseEntryPoints(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS && p_module->entry_point_count > 0) { SpvReflectEntryPoint* p_entry = &(p_module->entry_points[0]); p_module->entry_point_name = p_entry->name; p_module->entry_point_id = p_entry->id; p_module->spirv_execution_model = p_entry->spirv_execution_model; p_module->shader_stage = p_entry->shader_stage; p_module->input_variable_count = p_entry->input_variable_count; p_module->input_variables = p_entry->input_variables; p_module->output_variable_count = p_entry->output_variable_count; p_module->output_variables = p_entry->output_variables; p_module->interface_variable_count = p_entry->interface_variable_count; p_module->interface_variables = p_entry->interface_variables; } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = DisambiguateStorageBufferSrvUav(p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = SynchronizeDescriptorSets(p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } if (result == SPV_REFLECT_RESULT_SUCCESS) { result = ParseExecutionModes(&parser, p_module); SPV_REFLECT_ASSERT(result == SPV_REFLECT_RESULT_SUCCESS); } // Destroy module if parse was not successful if (result != SPV_REFLECT_RESULT_SUCCESS) { spvReflectDestroyShaderModule(p_module); } DestroyParser(&parser); return result; } SpvReflectResult spvReflectCreateShaderModule( size_t size, const void* p_code, SpvReflectShaderModule* p_module ) { return CreateShaderModule(0, size, p_code, p_module); } SpvReflectResult spvReflectCreateShaderModule2( uint32_t flags, size_t size, const void* p_code, SpvReflectShaderModule* p_module ) { return CreateShaderModule(flags, size, p_code, p_module); } SpvReflectResult spvReflectGetShaderModule( size_t size, const void* p_code, SpvReflectShaderModule* p_module ) { return spvReflectCreateShaderModule(size, p_code, p_module); } static void SafeFreeTypes(SpvReflectTypeDescription* p_type) { if (IsNull(p_type)) { return; } if (IsNotNull(p_type->members)) { for (size_t i = 0; i < p_type->member_count; ++i) { SpvReflectTypeDescription* p_member = &p_type->members[i]; SafeFreeTypes(p_member); } SafeFree(p_type->members); p_type->members = NULL; } } static void SafeFreeBlockVariables(SpvReflectBlockVariable* p_block) { if (IsNull(p_block)) { return; } if (IsNotNull(p_block->members)) { for (size_t i = 0; i < p_block->member_count; ++i) { SpvReflectBlockVariable* p_member = &p_block->members[i]; SafeFreeBlockVariables(p_member); } SafeFree(p_block->members); p_block->members = NULL; } } static void SafeFreeInterfaceVariable(SpvReflectInterfaceVariable* p_interface) { if (IsNull(p_interface)) { return; } if (IsNotNull(p_interface->members)) { for (size_t i = 0; i < p_interface->member_count; ++i) { SpvReflectInterfaceVariable* p_member = &p_interface->members[i]; SafeFreeInterfaceVariable(p_member); } SafeFree(p_interface->members); p_interface->members = NULL; } } void spvReflectDestroyShaderModule(SpvReflectShaderModule* p_module) { if (IsNull(p_module->_internal)) { return; } SafeFree(p_module->source_source); // Descriptor set bindings for (size_t i = 0; i < p_module->descriptor_set_count; ++i) { SpvReflectDescriptorSet* p_set = &p_module->descriptor_sets[i]; free(p_set->bindings); } // Descriptor binding blocks for (size_t i = 0; i < p_module->descriptor_binding_count; ++i) { SpvReflectDescriptorBinding* p_descriptor = &p_module->descriptor_bindings[i]; SafeFreeBlockVariables(&p_descriptor->block); } SafeFree(p_module->descriptor_bindings); // Entry points for (size_t i = 0; i < p_module->entry_point_count; ++i) { SpvReflectEntryPoint* p_entry = &p_module->entry_points[i]; for (size_t j = 0; j < p_entry->interface_variable_count; j++) { SafeFreeInterfaceVariable(&p_entry->interface_variables[j]); } for (uint32_t j = 0; j < p_entry->descriptor_set_count; ++j) { SafeFree(p_entry->descriptor_sets[j].bindings); } SafeFree(p_entry->descriptor_sets); SafeFree(p_entry->input_variables); SafeFree(p_entry->output_variables); SafeFree(p_entry->interface_variables); SafeFree(p_entry->used_uniforms); SafeFree(p_entry->used_push_constants); } SafeFree(p_module->entry_points); // Push constants for (size_t i = 0; i < p_module->push_constant_block_count; ++i) { SafeFreeBlockVariables(&p_module->push_constant_blocks[i]); } SafeFree(p_module->push_constant_blocks); // Type infos for (size_t i = 0; i < p_module->_internal->type_description_count; ++i) { SpvReflectTypeDescription* p_type = &p_module->_internal->type_descriptions[i]; if (IsNotNull(p_type->members)) { SafeFreeTypes(p_type); } SafeFree(p_type->members); } SafeFree(p_module->_internal->type_descriptions); // Free SPIR-V code if there was a copy if ((p_module->_internal->module_flags & SPV_REFLECT_MODULE_FLAG_NO_COPY) == 0) { SafeFree(p_module->_internal->spirv_code); } // Free internal SafeFree(p_module->_internal); } uint32_t spvReflectGetCodeSize(const SpvReflectShaderModule* p_module) { if (IsNull(p_module)) { return 0; } return (uint32_t)(p_module->_internal->spirv_size); } const uint32_t* spvReflectGetCode(const SpvReflectShaderModule* p_module) { if (IsNull(p_module)) { return NULL; } return p_module->_internal->spirv_code; } const SpvReflectEntryPoint* spvReflectGetEntryPoint( const SpvReflectShaderModule* p_module, const char* entry_point ) { if (IsNull(p_module) || IsNull(entry_point)) { return NULL; } for (uint32_t i = 0; i < p_module->entry_point_count; ++i) { if (strcmp(p_module->entry_points[i].name, entry_point) == 0) { return &p_module->entry_points[i]; } } return NULL; } SpvReflectResult spvReflectEnumerateDescriptorBindings( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNotNull(pp_bindings)) { if (*p_count != p_module->descriptor_binding_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectDescriptorBinding* p_bindings = (SpvReflectDescriptorBinding*)&p_module->descriptor_bindings[index]; pp_bindings[index] = p_bindings; } } else { *p_count = p_module->descriptor_binding_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateEntryPointDescriptorBindings( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } uint32_t count = 0; for (uint32_t i = 0; i < p_module->descriptor_binding_count; ++i) { bool found = SearchSortedUint32( p_entry->used_uniforms, p_entry->used_uniform_count, p_module->descriptor_bindings[i].spirv_id); if (found) { if (IsNotNull(pp_bindings)) { if (count >= *p_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } pp_bindings[count++] = (SpvReflectDescriptorBinding*)&p_module->descriptor_bindings[i]; } else { ++count; } } } if (IsNotNull(pp_bindings)) { if (count != *p_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } } else { *p_count = count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateDescriptorSets( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNotNull(pp_sets)) { if (*p_count != p_module->descriptor_set_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectDescriptorSet* p_set = (SpvReflectDescriptorSet*)&p_module->descriptor_sets[index]; pp_sets[index] = p_set; } } else { *p_count = p_module->descriptor_set_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateEntryPointDescriptorSets( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } if (IsNotNull(pp_sets)) { if (*p_count != p_entry->descriptor_set_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectDescriptorSet* p_set = (SpvReflectDescriptorSet*)&p_entry->descriptor_sets[index]; pp_sets[index] = p_set; } } else { *p_count = p_entry->descriptor_set_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateInterfaceVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNotNull(pp_variables)) { if (*p_count != p_module->interface_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = &p_module->interface_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_module->interface_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateEntryPointInterfaceVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } if (IsNotNull(pp_variables)) { if (*p_count != p_entry->interface_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = &p_entry->interface_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_entry->interface_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateInputVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNotNull(pp_variables)) { if (*p_count != p_module->input_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = p_module->input_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_module->input_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateEntryPointInputVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } if (IsNotNull(pp_variables)) { if (*p_count != p_entry->input_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = p_entry->input_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_entry->input_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateOutputVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNotNull(pp_variables)) { if (*p_count != p_module->output_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = p_module->output_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_module->output_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumerateEntryPointOutputVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } if (IsNotNull(pp_variables)) { if (*p_count != p_entry->output_variable_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectInterfaceVariable* p_var = p_entry->output_variables[index]; pp_variables[index] = p_var; } } else { *p_count = p_entry->output_variable_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumeratePushConstantBlocks( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (pp_blocks != NULL) { if (*p_count != p_module->push_constant_block_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } for (uint32_t index = 0; index < *p_count; ++index) { SpvReflectBlockVariable* p_push_constant_blocks = (SpvReflectBlockVariable*)&p_module->push_constant_blocks[index]; pp_blocks[index] = p_push_constant_blocks; } } else { *p_count = p_module->push_constant_block_count; } return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectEnumeratePushConstants( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ) { return spvReflectEnumeratePushConstantBlocks(p_module, p_count, pp_blocks); } SpvReflectResult spvReflectEnumerateEntryPointPushConstantBlocks( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_count)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } uint32_t count = 0; for (uint32_t i = 0; i < p_module->push_constant_block_count; ++i) { bool found = SearchSortedUint32(p_entry->used_push_constants, p_entry->used_push_constant_count, p_module->push_constant_blocks[i].spirv_id); if (found) { if (IsNotNull(pp_blocks)) { if (count >= *p_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } pp_blocks[count++] = (SpvReflectBlockVariable*)&p_module->push_constant_blocks[i]; } else { ++count; } } } if (IsNotNull(pp_blocks)) { if (count != *p_count) { return SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH; } } else { *p_count = count; } return SPV_REFLECT_RESULT_SUCCESS; } const SpvReflectDescriptorBinding* spvReflectGetDescriptorBinding( const SpvReflectShaderModule* p_module, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ) { const SpvReflectDescriptorBinding* p_descriptor = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->descriptor_binding_count; ++index) { const SpvReflectDescriptorBinding* p_potential = &p_module->descriptor_bindings[index]; if ((p_potential->binding == binding_number) && (p_potential->set == set_number)) { p_descriptor = p_potential; break; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_descriptor) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_descriptor; } const SpvReflectDescriptorBinding* spvReflectGetEntryPointDescriptorBinding( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectDescriptorBinding* p_descriptor = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->descriptor_binding_count; ++index) { const SpvReflectDescriptorBinding* p_potential = &p_module->descriptor_bindings[index]; bool found = SearchSortedUint32( p_entry->used_uniforms, p_entry->used_uniform_count, p_potential->spirv_id); if ((p_potential->binding == binding_number) && (p_potential->set == set_number) && found) { p_descriptor = p_potential; break; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_descriptor) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_descriptor; } const SpvReflectDescriptorSet* spvReflectGetDescriptorSet( const SpvReflectShaderModule* p_module, uint32_t set_number, SpvReflectResult* p_result ) { const SpvReflectDescriptorSet* p_set = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->descriptor_set_count; ++index) { const SpvReflectDescriptorSet* p_potential = &p_module->descriptor_sets[index]; if (p_potential->set == set_number) { p_set = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_set) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_set; } const SpvReflectDescriptorSet* spvReflectGetEntryPointDescriptorSet( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t set_number, SpvReflectResult* p_result) { const SpvReflectDescriptorSet* p_set = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t index = 0; index < p_entry->descriptor_set_count; ++index) { const SpvReflectDescriptorSet* p_potential = &p_entry->descriptor_sets[index]; if (p_potential->set == set_number) { p_set = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_set) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_set; } const SpvReflectInterfaceVariable* spvReflectGetInputVariableByLocation( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ) { if (location == INVALID_VALUE) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->input_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_module->input_variables[index]; if (p_potential->location == location) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetInputVariable( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ) { return spvReflectGetInputVariableByLocation(p_module, location, p_result); } const SpvReflectInterfaceVariable* spvReflectGetEntryPointInputVariableByLocation( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t location, SpvReflectResult* p_result ) { if (location == INVALID_VALUE) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t index = 0; index < p_entry->input_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_entry->input_variables[index]; if (p_potential->location == location) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetInputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* semantic, SpvReflectResult* p_result ) { if (IsNull(semantic)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } return NULL; } if (semantic[0] == '\0') { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->input_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_module->input_variables[index]; if (p_potential->semantic != NULL && strcmp(p_potential->semantic, semantic) == 0) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetEntryPointInputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* entry_point, const char* semantic, SpvReflectResult* p_result ) { if (IsNull(semantic)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } return NULL; } if (semantic[0] == '\0') { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t index = 0; index < p_entry->input_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_entry->input_variables[index]; if (p_potential->semantic != NULL && strcmp(p_potential->semantic, semantic) == 0) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetOutputVariableByLocation( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ) { if (location == INVALID_VALUE) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->output_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_module->output_variables[index]; if (p_potential->location == location) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetOutputVariable( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ) { return spvReflectGetOutputVariableByLocation(p_module, location, p_result); } const SpvReflectInterfaceVariable* spvReflectGetEntryPointOutputVariableByLocation( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t location, SpvReflectResult* p_result ) { if (location == INVALID_VALUE) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t index = 0; index < p_entry->output_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_entry->output_variables[index]; if (p_potential->location == location) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetOutputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* semantic, SpvReflectResult* p_result ) { if (IsNull(semantic)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } return NULL; } if (semantic[0] == '\0') { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { for (uint32_t index = 0; index < p_module->output_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_module->output_variables[index]; if (p_potential->semantic != NULL && strcmp(p_potential->semantic, semantic) == 0) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectInterfaceVariable* spvReflectGetEntryPointOutputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* entry_point, const char* semantic, SpvReflectResult* p_result) { if (IsNull(semantic)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } return NULL; } if (semantic[0] == '\0') { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } const SpvReflectInterfaceVariable* p_var = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t index = 0; index < p_entry->output_variable_count; ++index) { const SpvReflectInterfaceVariable* p_potential = p_entry->output_variables[index]; if (p_potential->semantic != NULL && strcmp(p_potential->semantic, semantic) == 0) { p_var = p_potential; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_var) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_var; } const SpvReflectBlockVariable* spvReflectGetPushConstantBlock( const SpvReflectShaderModule* p_module, uint32_t index, SpvReflectResult* p_result ) { const SpvReflectBlockVariable* p_push_constant = NULL; if (IsNotNull(p_module)) { if (index < p_module->push_constant_block_count) { p_push_constant = &p_module->push_constant_blocks[index]; } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_push_constant) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_push_constant; } const SpvReflectBlockVariable* spvReflectGetPushConstant( const SpvReflectShaderModule* p_module, uint32_t index, SpvReflectResult* p_result ) { return spvReflectGetPushConstantBlock(p_module, index, p_result); } const SpvReflectBlockVariable* spvReflectGetEntryPointPushConstantBlock( const SpvReflectShaderModule* p_module, const char* entry_point, SpvReflectResult* p_result) { const SpvReflectBlockVariable* p_push_constant = NULL; if (IsNotNull(p_module)) { const SpvReflectEntryPoint* p_entry = spvReflectGetEntryPoint(p_module, entry_point); if (IsNull(p_entry)) { if (IsNotNull(p_result)) { *p_result = SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } return NULL; } for (uint32_t i = 0; i < p_module->push_constant_block_count; ++i) { bool found = SearchSortedUint32( p_entry->used_push_constants, p_entry->used_push_constant_count, p_module->push_constant_blocks[i].spirv_id); if (found) { p_push_constant = &p_module->push_constant_blocks[i]; break; } } } if (IsNotNull(p_result)) { *p_result = IsNotNull(p_push_constant) ? SPV_REFLECT_RESULT_SUCCESS : (IsNull(p_module) ? SPV_REFLECT_RESULT_ERROR_NULL_POINTER : SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND); } return p_push_constant; } SpvReflectResult spvReflectChangeDescriptorBindingNumbers( SpvReflectShaderModule* p_module, const SpvReflectDescriptorBinding* p_binding, uint32_t new_binding_number, uint32_t new_set_binding ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_binding)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } SpvReflectDescriptorBinding* p_target_descriptor = NULL; for (uint32_t index = 0; index < p_module->descriptor_binding_count; ++index) { if(&p_module->descriptor_bindings[index] == p_binding) { p_target_descriptor = &p_module->descriptor_bindings[index]; break; } } if (IsNotNull(p_target_descriptor)) { if (p_target_descriptor->word_offset.binding > (p_module->_internal->spirv_word_count - 1)) { return SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED; } // Binding number if (new_binding_number != (uint32_t)SPV_REFLECT_BINDING_NUMBER_DONT_CHANGE) { uint32_t* p_code = p_module->_internal->spirv_code + p_target_descriptor->word_offset.binding; *p_code = new_binding_number; p_target_descriptor->binding = new_binding_number; } // Set number if (new_set_binding != (uint32_t)SPV_REFLECT_SET_NUMBER_DONT_CHANGE) { uint32_t* p_code = p_module->_internal->spirv_code + p_target_descriptor->word_offset.set; *p_code = new_set_binding; p_target_descriptor->set = new_set_binding; } } SpvReflectResult result = SPV_REFLECT_RESULT_SUCCESS; if (new_set_binding != (uint32_t)SPV_REFLECT_SET_NUMBER_DONT_CHANGE) { result = SynchronizeDescriptorSets(p_module); } return result; } SpvReflectResult spvReflectChangeDescriptorBindingNumber( SpvReflectShaderModule* p_module, const SpvReflectDescriptorBinding* p_descriptor_binding, uint32_t new_binding_number, uint32_t optional_new_set_number ) { return spvReflectChangeDescriptorBindingNumbers( p_module,p_descriptor_binding, new_binding_number, optional_new_set_number); } SpvReflectResult spvReflectChangeDescriptorSetNumber( SpvReflectShaderModule* p_module, const SpvReflectDescriptorSet* p_set, uint32_t new_set_number ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_set)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } SpvReflectDescriptorSet* p_target_set = NULL; for (uint32_t index = 0; index < SPV_REFLECT_MAX_DESCRIPTOR_SETS; ++index) { // The descriptor sets for specific entry points might not be in this set, // so just match on set index. if (p_module->descriptor_sets[index].set == p_set->set) { p_target_set = (SpvReflectDescriptorSet*)p_set; break; } } SpvReflectResult result = SPV_REFLECT_RESULT_SUCCESS; if (IsNotNull(p_target_set) && new_set_number != (uint32_t)SPV_REFLECT_SET_NUMBER_DONT_CHANGE) { for (uint32_t index = 0; index < p_target_set->binding_count; ++index) { SpvReflectDescriptorBinding* p_descriptor = p_target_set->bindings[index]; if (p_descriptor->word_offset.set > (p_module->_internal->spirv_word_count - 1)) { return SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED; } uint32_t* p_code = p_module->_internal->spirv_code + p_descriptor->word_offset.set; *p_code = new_set_number; p_descriptor->set = new_set_number; } result = SynchronizeDescriptorSets(p_module); } return result; } static SpvReflectResult ChangeVariableLocation( SpvReflectShaderModule* p_module, SpvReflectInterfaceVariable* p_variable, uint32_t new_location ) { if (p_variable->word_offset.location > (p_module->_internal->spirv_word_count - 1)) { return SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED; } uint32_t* p_code = p_module->_internal->spirv_code + p_variable->word_offset.location; *p_code = new_location; p_variable->location = new_location; return SPV_REFLECT_RESULT_SUCCESS; } SpvReflectResult spvReflectChangeInputVariableLocation( SpvReflectShaderModule* p_module, const SpvReflectInterfaceVariable* p_input_variable, uint32_t new_location ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_input_variable)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } for (uint32_t index = 0; index < p_module->input_variable_count; ++index) { if(p_module->input_variables[index] == p_input_variable) { return ChangeVariableLocation(p_module, p_module->input_variables[index], new_location); } } return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } SpvReflectResult spvReflectChangeOutputVariableLocation( SpvReflectShaderModule* p_module, const SpvReflectInterfaceVariable* p_output_variable, uint32_t new_location ) { if (IsNull(p_module)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } if (IsNull(p_output_variable)) { return SPV_REFLECT_RESULT_ERROR_NULL_POINTER; } for (uint32_t index = 0; index < p_module->output_variable_count; ++index) { if(p_module->output_variables[index] == p_output_variable) { return ChangeVariableLocation(p_module, p_module->output_variables[index], new_location); } } return SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND; } const char* spvReflectSourceLanguage(SpvSourceLanguage source_lang) { switch (source_lang) { case SpvSourceLanguageUnknown : return "Unknown"; case SpvSourceLanguageESSL : return "ESSL"; case SpvSourceLanguageGLSL : return "GLSL"; case SpvSourceLanguageOpenCL_C : return "OpenCL_C"; case SpvSourceLanguageOpenCL_CPP : return "OpenCL_CPP"; case SpvSourceLanguageHLSL : return "HLSL"; case SpvSourceLanguageCPP_for_OpenCL : return "CPP_for_OpenCL"; case SpvSourceLanguageMax: break; } return ""; } const char* spvReflectBlockVariableTypeName( const SpvReflectBlockVariable* p_var ) { if (p_var == NULL) { return NULL; } return p_var->type_description->type_name; }
whupdup/frame
real/third_party/spirv_reflect/spirv_reflect.c
C++
gpl-3.0
173,933
/* Copyright 2017-2022 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* VERSION HISTORY 1.0 (2018-03-27) Initial public release */ /*! @file spirv_reflect.h */ #ifndef SPIRV_REFLECT_H #define SPIRV_REFLECT_H #include "./include/spirv/unified1/spirv.h" #include <stdint.h> #include <string.h> #ifdef _MSC_VER #define SPV_REFLECT_DEPRECATED(msg_str) __declspec(deprecated("This symbol is deprecated. Details: " msg_str)) #elif defined(__clang__) #define SPV_REFLECT_DEPRECATED(msg_str) __attribute__((deprecated(msg_str))) #elif defined(__GNUC__) #if GCC_VERSION >= 40500 #define SPV_REFLECT_DEPRECATED(msg_str) __attribute__((deprecated(msg_str))) #else #define SPV_REFLECT_DEPRECATED(msg_str) __attribute__((deprecated)) #endif #else #define SPV_REFLECT_DEPRECATED(msg_str) #endif /*! @enum SpvReflectResult */ typedef enum SpvReflectResult { SPV_REFLECT_RESULT_SUCCESS, SPV_REFLECT_RESULT_NOT_READY, SPV_REFLECT_RESULT_ERROR_PARSE_FAILED, SPV_REFLECT_RESULT_ERROR_ALLOC_FAILED, SPV_REFLECT_RESULT_ERROR_RANGE_EXCEEDED, SPV_REFLECT_RESULT_ERROR_NULL_POINTER, SPV_REFLECT_RESULT_ERROR_INTERNAL_ERROR, SPV_REFLECT_RESULT_ERROR_COUNT_MISMATCH, SPV_REFLECT_RESULT_ERROR_ELEMENT_NOT_FOUND, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_CODE_SIZE, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_MAGIC_NUMBER, SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_EOF, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ID_REFERENCE, SPV_REFLECT_RESULT_ERROR_SPIRV_SET_NUMBER_OVERFLOW, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_STORAGE_CLASS, SPV_REFLECT_RESULT_ERROR_SPIRV_RECURSION, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_INSTRUCTION, SPV_REFLECT_RESULT_ERROR_SPIRV_UNEXPECTED_BLOCK_DATA, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_BLOCK_MEMBER_REFERENCE, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_ENTRY_POINT, SPV_REFLECT_RESULT_ERROR_SPIRV_INVALID_EXECUTION_MODE, } SpvReflectResult; /*! @enum SpvReflectModuleFlagBits SPV_REFLECT_MODULE_FLAG_NO_COPY - Disables copying of SPIR-V code when a SPIRV-Reflect shader module is created. It is the responsibility of the calling program to ensure that the pointer remains valid and the memory it's pointing to is not freed while SPIRV-Reflect operations are taking place. Freeing the backing memory will cause undefined behavior or most likely a crash. This is flag is intended for cases where the memory overhead of storing the copied SPIR-V is undesirable. */ typedef enum SpvReflectModuleFlagBits { SPV_REFLECT_MODULE_FLAG_NONE = 0x00000000, SPV_REFLECT_MODULE_FLAG_NO_COPY = 0x00000001, } SpvReflectModuleFlagBits; typedef uint32_t SpvReflectModuleFlags; /*! @enum SpvReflectTypeFlagBits */ typedef enum SpvReflectTypeFlagBits { SPV_REFLECT_TYPE_FLAG_UNDEFINED = 0x00000000, SPV_REFLECT_TYPE_FLAG_VOID = 0x00000001, SPV_REFLECT_TYPE_FLAG_BOOL = 0x00000002, SPV_REFLECT_TYPE_FLAG_INT = 0x00000004, SPV_REFLECT_TYPE_FLAG_FLOAT = 0x00000008, SPV_REFLECT_TYPE_FLAG_VECTOR = 0x00000100, SPV_REFLECT_TYPE_FLAG_MATRIX = 0x00000200, SPV_REFLECT_TYPE_FLAG_EXTERNAL_IMAGE = 0x00010000, SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLER = 0x00020000, SPV_REFLECT_TYPE_FLAG_EXTERNAL_SAMPLED_IMAGE = 0x00040000, SPV_REFLECT_TYPE_FLAG_EXTERNAL_BLOCK = 0x00080000, SPV_REFLECT_TYPE_FLAG_EXTERNAL_ACCELERATION_STRUCTURE = 0x00100000, SPV_REFLECT_TYPE_FLAG_EXTERNAL_MASK = 0x00FF0000, SPV_REFLECT_TYPE_FLAG_STRUCT = 0x10000000, SPV_REFLECT_TYPE_FLAG_ARRAY = 0x20000000, } SpvReflectTypeFlagBits; typedef uint32_t SpvReflectTypeFlags; /*! @enum SpvReflectDecorationBits NOTE: HLSL row_major and column_major decorations are reversed in SPIR-V. Meaning that matrices declrations with row_major will get reflected as column_major and vice versa. The row and column decorations get appied during the compilation. SPIRV-Reflect reads the data as is and does not make any attempt to correct it to match what's in the source. */ typedef enum SpvReflectDecorationFlagBits { SPV_REFLECT_DECORATION_NONE = 0x00000000, SPV_REFLECT_DECORATION_BLOCK = 0x00000001, SPV_REFLECT_DECORATION_BUFFER_BLOCK = 0x00000002, SPV_REFLECT_DECORATION_ROW_MAJOR = 0x00000004, SPV_REFLECT_DECORATION_COLUMN_MAJOR = 0x00000008, SPV_REFLECT_DECORATION_BUILT_IN = 0x00000010, SPV_REFLECT_DECORATION_NOPERSPECTIVE = 0x00000020, SPV_REFLECT_DECORATION_FLAT = 0x00000040, SPV_REFLECT_DECORATION_NON_WRITABLE = 0x00000080, SPV_REFLECT_DECORATION_RELAXED_PRECISION = 0x00000100, } SpvReflectDecorationFlagBits; typedef uint32_t SpvReflectDecorationFlags; /*! @enum SpvReflectResourceType */ typedef enum SpvReflectResourceType { SPV_REFLECT_RESOURCE_FLAG_UNDEFINED = 0x00000000, SPV_REFLECT_RESOURCE_FLAG_SAMPLER = 0x00000001, SPV_REFLECT_RESOURCE_FLAG_CBV = 0x00000002, SPV_REFLECT_RESOURCE_FLAG_SRV = 0x00000004, SPV_REFLECT_RESOURCE_FLAG_UAV = 0x00000008, } SpvReflectResourceType; /*! @enum SpvReflectFormat */ typedef enum SpvReflectFormat { SPV_REFLECT_FORMAT_UNDEFINED = 0, // = VK_FORMAT_UNDEFINED SPV_REFLECT_FORMAT_R32_UINT = 98, // = VK_FORMAT_R32_UINT SPV_REFLECT_FORMAT_R32_SINT = 99, // = VK_FORMAT_R32_SINT SPV_REFLECT_FORMAT_R32_SFLOAT = 100, // = VK_FORMAT_R32_SFLOAT SPV_REFLECT_FORMAT_R32G32_UINT = 101, // = VK_FORMAT_R32G32_UINT SPV_REFLECT_FORMAT_R32G32_SINT = 102, // = VK_FORMAT_R32G32_SINT SPV_REFLECT_FORMAT_R32G32_SFLOAT = 103, // = VK_FORMAT_R32G32_SFLOAT SPV_REFLECT_FORMAT_R32G32B32_UINT = 104, // = VK_FORMAT_R32G32B32_UINT SPV_REFLECT_FORMAT_R32G32B32_SINT = 105, // = VK_FORMAT_R32G32B32_SINT SPV_REFLECT_FORMAT_R32G32B32_SFLOAT = 106, // = VK_FORMAT_R32G32B32_SFLOAT SPV_REFLECT_FORMAT_R32G32B32A32_UINT = 107, // = VK_FORMAT_R32G32B32A32_UINT SPV_REFLECT_FORMAT_R32G32B32A32_SINT = 108, // = VK_FORMAT_R32G32B32A32_SINT SPV_REFLECT_FORMAT_R32G32B32A32_SFLOAT = 109, // = VK_FORMAT_R32G32B32A32_SFLOAT SPV_REFLECT_FORMAT_R64_UINT = 110, // = VK_FORMAT_R64_UINT SPV_REFLECT_FORMAT_R64_SINT = 111, // = VK_FORMAT_R64_SINT SPV_REFLECT_FORMAT_R64_SFLOAT = 112, // = VK_FORMAT_R64_SFLOAT SPV_REFLECT_FORMAT_R64G64_UINT = 113, // = VK_FORMAT_R64G64_UINT SPV_REFLECT_FORMAT_R64G64_SINT = 114, // = VK_FORMAT_R64G64_SINT SPV_REFLECT_FORMAT_R64G64_SFLOAT = 115, // = VK_FORMAT_R64G64_SFLOAT SPV_REFLECT_FORMAT_R64G64B64_UINT = 116, // = VK_FORMAT_R64G64B64_UINT SPV_REFLECT_FORMAT_R64G64B64_SINT = 117, // = VK_FORMAT_R64G64B64_SINT SPV_REFLECT_FORMAT_R64G64B64_SFLOAT = 118, // = VK_FORMAT_R64G64B64_SFLOAT SPV_REFLECT_FORMAT_R64G64B64A64_UINT = 119, // = VK_FORMAT_R64G64B64A64_UINT SPV_REFLECT_FORMAT_R64G64B64A64_SINT = 120, // = VK_FORMAT_R64G64B64A64_SINT SPV_REFLECT_FORMAT_R64G64B64A64_SFLOAT = 121, // = VK_FORMAT_R64G64B64A64_SFLOAT } SpvReflectFormat; /*! @enum SpvReflectVariableFlagBits */ enum SpvReflectVariableFlagBits{ SPV_REFLECT_VARIABLE_FLAGS_NONE = 0x00000000, SPV_REFLECT_VARIABLE_FLAGS_UNUSED = 0x00000001, }; typedef uint32_t SpvReflectVariableFlags; /*! @enum SpvReflectDescriptorType */ typedef enum SpvReflectDescriptorType { SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLER = 0, // = VK_DESCRIPTOR_TYPE_SAMPLER SPV_REFLECT_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER = 1, // = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER SPV_REFLECT_DESCRIPTOR_TYPE_SAMPLED_IMAGE = 2, // = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_IMAGE = 3, // = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER = 4, // = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER = 5, // = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER = 6, // = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER = 7, // = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER SPV_REFLECT_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC = 8, // = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC = 9, // = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC SPV_REFLECT_DESCRIPTOR_TYPE_INPUT_ATTACHMENT = 10, // = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT SPV_REFLECT_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR = 1000150000 // = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR } SpvReflectDescriptorType; /*! @enum SpvReflectShaderStageFlagBits */ typedef enum SpvReflectShaderStageFlagBits { SPV_REFLECT_SHADER_STAGE_VERTEX_BIT = 0x00000001, // = VK_SHADER_STAGE_VERTEX_BIT SPV_REFLECT_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x00000002, // = VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT SPV_REFLECT_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x00000004, // = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT SPV_REFLECT_SHADER_STAGE_GEOMETRY_BIT = 0x00000008, // = VK_SHADER_STAGE_GEOMETRY_BIT SPV_REFLECT_SHADER_STAGE_FRAGMENT_BIT = 0x00000010, // = VK_SHADER_STAGE_FRAGMENT_BIT SPV_REFLECT_SHADER_STAGE_COMPUTE_BIT = 0x00000020, // = VK_SHADER_STAGE_COMPUTE_BIT SPV_REFLECT_SHADER_STAGE_TASK_BIT_NV = 0x00000040, // = VK_SHADER_STAGE_TASK_BIT_NV SPV_REFLECT_SHADER_STAGE_MESH_BIT_NV = 0x00000080, // = VK_SHADER_STAGE_MESH_BIT_NV SPV_REFLECT_SHADER_STAGE_RAYGEN_BIT_KHR = 0x00000100, // = VK_SHADER_STAGE_RAYGEN_BIT_KHR SPV_REFLECT_SHADER_STAGE_ANY_HIT_BIT_KHR = 0x00000200, // = VK_SHADER_STAGE_ANY_HIT_BIT_KHR SPV_REFLECT_SHADER_STAGE_CLOSEST_HIT_BIT_KHR = 0x00000400, // = VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR SPV_REFLECT_SHADER_STAGE_MISS_BIT_KHR = 0x00000800, // = VK_SHADER_STAGE_MISS_BIT_KHR SPV_REFLECT_SHADER_STAGE_INTERSECTION_BIT_KHR = 0x00001000, // = VK_SHADER_STAGE_INTERSECTION_BIT_KHR SPV_REFLECT_SHADER_STAGE_CALLABLE_BIT_KHR = 0x00002000, // = VK_SHADER_STAGE_CALLABLE_BIT_KHR } SpvReflectShaderStageFlagBits; /*! @enum SpvReflectGenerator */ typedef enum SpvReflectGenerator { SPV_REFLECT_GENERATOR_KHRONOS_LLVM_SPIRV_TRANSLATOR = 6, SPV_REFLECT_GENERATOR_KHRONOS_SPIRV_TOOLS_ASSEMBLER = 7, SPV_REFLECT_GENERATOR_KHRONOS_GLSLANG_REFERENCE_FRONT_END = 8, SPV_REFLECT_GENERATOR_GOOGLE_SHADERC_OVER_GLSLANG = 13, SPV_REFLECT_GENERATOR_GOOGLE_SPIREGG = 14, SPV_REFLECT_GENERATOR_GOOGLE_RSPIRV = 15, SPV_REFLECT_GENERATOR_X_LEGEND_MESA_MESAIR_SPIRV_TRANSLATOR = 16, SPV_REFLECT_GENERATOR_KHRONOS_SPIRV_TOOLS_LINKER = 17, SPV_REFLECT_GENERATOR_WINE_VKD3D_SHADER_COMPILER = 18, SPV_REFLECT_GENERATOR_CLAY_CLAY_SHADER_COMPILER = 19, } SpvReflectGenerator; enum { SPV_REFLECT_MAX_ARRAY_DIMS = 32, SPV_REFLECT_MAX_DESCRIPTOR_SETS = 64, }; enum { SPV_REFLECT_BINDING_NUMBER_DONT_CHANGE = ~0, SPV_REFLECT_SET_NUMBER_DONT_CHANGE = ~0 }; typedef struct SpvReflectNumericTraits { struct Scalar { uint32_t width; uint32_t signedness; } scalar; struct Vector { uint32_t component_count; } vector; struct Matrix { uint32_t column_count; uint32_t row_count; uint32_t stride; // Measured in bytes } matrix; } SpvReflectNumericTraits; typedef struct SpvReflectImageTraits { SpvDim dim; uint32_t depth; uint32_t arrayed; uint32_t ms; // 0: single-sampled; 1: multisampled uint32_t sampled; SpvImageFormat image_format; } SpvReflectImageTraits; typedef struct SpvReflectArrayTraits { uint32_t dims_count; // Each entry is: 0xFFFFFFFF for a specialization constant dimension, // 0 for a runtime array dimension, and the array length otherwise. uint32_t dims[SPV_REFLECT_MAX_ARRAY_DIMS]; // Stores Ids for dimensions that are specialization constants uint32_t spec_constant_op_ids[SPV_REFLECT_MAX_ARRAY_DIMS]; uint32_t stride; // Measured in bytes } SpvReflectArrayTraits; typedef struct SpvReflectBindingArrayTraits { uint32_t dims_count; uint32_t dims[SPV_REFLECT_MAX_ARRAY_DIMS]; } SpvReflectBindingArrayTraits; /*! @struct SpvReflectTypeDescription */ typedef struct SpvReflectTypeDescription { uint32_t id; SpvOp op; const char* type_name; const char* struct_member_name; SpvStorageClass storage_class; SpvReflectTypeFlags type_flags; SpvReflectDecorationFlags decoration_flags; struct Traits { SpvReflectNumericTraits numeric; SpvReflectImageTraits image; SpvReflectArrayTraits array; } traits; uint32_t member_count; struct SpvReflectTypeDescription* members; } SpvReflectTypeDescription; /*! @struct SpvReflectInterfaceVariable */ typedef struct SpvReflectInterfaceVariable { uint32_t spirv_id; const char* name; uint32_t location; SpvStorageClass storage_class; const char* semantic; SpvReflectDecorationFlags decoration_flags; SpvBuiltIn built_in; SpvReflectNumericTraits numeric; SpvReflectArrayTraits array; uint32_t member_count; struct SpvReflectInterfaceVariable* members; SpvReflectFormat format; // NOTE: SPIR-V shares type references for variables // that have the same underlying type. This means // that the same type name will appear for multiple // variables. SpvReflectTypeDescription* type_description; struct { uint32_t location; } word_offset; } SpvReflectInterfaceVariable; /*! @struct SpvReflectBlockVariable */ typedef struct SpvReflectBlockVariable { uint32_t spirv_id; const char* name; uint32_t offset; // Measured in bytes uint32_t absolute_offset; // Measured in bytes uint32_t size; // Measured in bytes uint32_t padded_size; // Measured in bytes SpvReflectDecorationFlags decoration_flags; SpvReflectNumericTraits numeric; SpvReflectArrayTraits array; SpvReflectVariableFlags flags; uint32_t member_count; struct SpvReflectBlockVariable* members; SpvReflectTypeDescription* type_description; } SpvReflectBlockVariable; /*! @struct SpvReflectDescriptorBinding */ typedef struct SpvReflectDescriptorBinding { uint32_t spirv_id; const char* name; uint32_t binding; uint32_t input_attachment_index; uint32_t set; SpvReflectDescriptorType descriptor_type; SpvReflectResourceType resource_type; SpvReflectImageTraits image; SpvReflectBlockVariable block; SpvReflectBindingArrayTraits array; uint32_t count; uint32_t accessed; uint32_t uav_counter_id; struct SpvReflectDescriptorBinding* uav_counter_binding; SpvReflectTypeDescription* type_description; struct { uint32_t binding; uint32_t set; } word_offset; } SpvReflectDescriptorBinding; /*! @struct SpvReflectDescriptorSet */ typedef struct SpvReflectDescriptorSet { uint32_t set; uint32_t binding_count; SpvReflectDescriptorBinding** bindings; } SpvReflectDescriptorSet; /*! @struct SpvReflectEntryPoint */ typedef struct SpvReflectEntryPoint { const char* name; uint32_t id; SpvExecutionModel spirv_execution_model; SpvReflectShaderStageFlagBits shader_stage; uint32_t input_variable_count; SpvReflectInterfaceVariable** input_variables; uint32_t output_variable_count; SpvReflectInterfaceVariable** output_variables; uint32_t interface_variable_count; SpvReflectInterfaceVariable* interface_variables; uint32_t descriptor_set_count; SpvReflectDescriptorSet* descriptor_sets; uint32_t used_uniform_count; uint32_t* used_uniforms; uint32_t used_push_constant_count; uint32_t* used_push_constants; struct LocalSize { uint32_t x; uint32_t y; uint32_t z; } local_size; uint32_t invocations; // valid for geometry uint32_t output_vertices; // valid for geometry, tesselation } SpvReflectEntryPoint; /*! @struct SpvReflectShaderModule */ typedef struct SpvReflectShaderModule { SpvReflectGenerator generator; const char* entry_point_name; uint32_t entry_point_id; uint32_t entry_point_count; SpvReflectEntryPoint* entry_points; SpvSourceLanguage source_language; uint32_t source_language_version; const char* source_file; const char* source_source; SpvExecutionModel spirv_execution_model; // Uses value(s) from first entry point SpvReflectShaderStageFlagBits shader_stage; // Uses value(s) from first entry point uint32_t descriptor_binding_count; // Uses value(s) from first entry point SpvReflectDescriptorBinding* descriptor_bindings; // Uses value(s) from first entry point uint32_t descriptor_set_count; // Uses value(s) from first entry point SpvReflectDescriptorSet descriptor_sets[SPV_REFLECT_MAX_DESCRIPTOR_SETS]; // Uses value(s) from first entry point uint32_t input_variable_count; // Uses value(s) from first entry point SpvReflectInterfaceVariable** input_variables; // Uses value(s) from first entry point uint32_t output_variable_count; // Uses value(s) from first entry point SpvReflectInterfaceVariable** output_variables; // Uses value(s) from first entry point uint32_t interface_variable_count; // Uses value(s) from first entry point SpvReflectInterfaceVariable* interface_variables; // Uses value(s) from first entry point uint32_t push_constant_block_count; // Uses value(s) from first entry point SpvReflectBlockVariable* push_constant_blocks; // Uses value(s) from first entry point struct Internal { SpvReflectModuleFlags module_flags; size_t spirv_size; uint32_t* spirv_code; uint32_t spirv_word_count; size_t type_description_count; SpvReflectTypeDescription* type_descriptions; } * _internal; } SpvReflectShaderModule; #if defined(__cplusplus) extern "C" { #endif /*! @fn spvReflectCreateShaderModule @param size Size in bytes of SPIR-V code. @param p_code Pointer to SPIR-V code. @param p_module Pointer to an instance of SpvReflectShaderModule. @return SPV_REFLECT_RESULT_SUCCESS on success. */ SpvReflectResult spvReflectCreateShaderModule( size_t size, const void* p_code, SpvReflectShaderModule* p_module ); /*! @fn spvReflectCreateShaderModule2 @param flags Flags for module creations. @param size Size in bytes of SPIR-V code. @param p_code Pointer to SPIR-V code. @param p_module Pointer to an instance of SpvReflectShaderModule. @return SPV_REFLECT_RESULT_SUCCESS on success. */ SpvReflectResult spvReflectCreateShaderModule2( SpvReflectModuleFlags flags, size_t size, const void* p_code, SpvReflectShaderModule* p_module ); SPV_REFLECT_DEPRECATED("renamed to spvReflectCreateShaderModule") SpvReflectResult spvReflectGetShaderModule( size_t size, const void* p_code, SpvReflectShaderModule* p_module ); /*! @fn spvReflectDestroyShaderModule @param p_module Pointer to an instance of SpvReflectShaderModule. */ void spvReflectDestroyShaderModule(SpvReflectShaderModule* p_module); /*! @fn spvReflectGetCodeSize @param p_module Pointer to an instance of SpvReflectShaderModule. @return Returns the size of the SPIR-V in bytes */ uint32_t spvReflectGetCodeSize(const SpvReflectShaderModule* p_module); /*! @fn spvReflectGetCode @param p_module Pointer to an instance of SpvReflectShaderModule. @return Returns a const pointer to the compiled SPIR-V bytecode. */ const uint32_t* spvReflectGetCode(const SpvReflectShaderModule* p_module); /*! @fn spvReflectGetEntryPoint @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point Name of the requested entry point. @return Returns a const pointer to the requested entry point, or NULL if it's not found. */ const SpvReflectEntryPoint* spvReflectGetEntryPoint( const SpvReflectShaderModule* p_module, const char* entry_point ); /*! @fn spvReflectEnumerateDescriptorBindings @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_bindings is NULL, the module's descriptor binding count (across all descriptor sets) will be stored here. If pp_bindings is not NULL, *p_count must contain the module's descriptor binding count. @param pp_bindings If NULL, the module's total descriptor binding count will be written to *p_count. If non-NULL, pp_bindings must point to an array with *p_count entries, where pointers to the module's descriptor bindings will be written. The caller must not free the binding pointers written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateDescriptorBindings( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ); /*! @fn spvReflectEnumerateEntryPointDescriptorBindings @brief Creates a listing of all descriptor bindings that are used in the static call tree of the given entry point. @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The name of the entry point to get the descriptor bindings for. @param p_count If pp_bindings is NULL, the entry point's descriptor binding count (across all descriptor sets) will be stored here. If pp_bindings is not NULL, *p_count must contain the entry points's descriptor binding count. @param pp_bindings If NULL, the entry point's total descriptor binding count will be written to *p_count. If non-NULL, pp_bindings must point to an array with *p_count entries, where pointers to the entry point's descriptor bindings will be written. The caller must not free the binding pointers written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointDescriptorBindings( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ); /*! @fn spvReflectEnumerateDescriptorSets @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_sets is NULL, the module's descriptor set count will be stored here. If pp_sets is not NULL, *p_count must contain the module's descriptor set count. @param pp_sets If NULL, the module's total descriptor set count will be written to *p_count. If non-NULL, pp_sets must point to an array with *p_count entries, where pointers to the module's descriptor sets will be written. The caller must not free the descriptor set pointers written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateDescriptorSets( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ); /*! @fn spvReflectEnumerateEntryPointDescriptorSets @brief Creates a listing of all descriptor sets and their bindings that are used in the static call tree of a given entry point. @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The name of the entry point to get the descriptor bindings for. @param p_count If pp_sets is NULL, the module's descriptor set count will be stored here. If pp_sets is not NULL, *p_count must contain the module's descriptor set count. @param pp_sets If NULL, the module's total descriptor set count will be written to *p_count. If non-NULL, pp_sets must point to an array with *p_count entries, where pointers to the module's descriptor sets will be written. The caller must not free the descriptor set pointers written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointDescriptorSets( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ); /*! @fn spvReflectEnumerateInterfaceVariables @brief If the module contains multiple entry points, this will only get the interface variables for the first one. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_variables is NULL, the module's interface variable count will be stored here. If pp_variables is not NULL, *p_count must contain the module's interface variable count. @param pp_variables If NULL, the module's interface variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the module's interface variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateInterfaceVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumerateEntryPointInterfaceVariables @brief Enumerate the interface variables for a given entry point. @param entry_point The name of the entry point to get the interface variables for. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_variables is NULL, the entry point's interface variable count will be stored here. If pp_variables is not NULL, *p_count must contain the entry point's interface variable count. @param pp_variables If NULL, the entry point's interface variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the entry point's interface variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointInterfaceVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumerateInputVariables @brief If the module contains multiple entry points, this will only get the input variables for the first one. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_variables is NULL, the module's input variable count will be stored here. If pp_variables is not NULL, *p_count must contain the module's input variable count. @param pp_variables If NULL, the module's input variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the module's input variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateInputVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumerateEntryPointInputVariables @brief Enumerate the input variables for a given entry point. @param entry_point The name of the entry point to get the input variables for. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_variables is NULL, the entry point's input variable count will be stored here. If pp_variables is not NULL, *p_count must contain the entry point's input variable count. @param pp_variables If NULL, the entry point's input variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the entry point's input variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointInputVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumerateOutputVariables @brief Note: If the module contains multiple entry points, this will only get the output variables for the first one. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_variables is NULL, the module's output variable count will be stored here. If pp_variables is not NULL, *p_count must contain the module's output variable count. @param pp_variables If NULL, the module's output variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the module's output variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateOutputVariables( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumerateEntryPointOutputVariables @brief Enumerate the output variables for a given entry point. @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The name of the entry point to get the output variables for. @param p_count If pp_variables is NULL, the entry point's output variable count will be stored here. If pp_variables is not NULL, *p_count must contain the entry point's output variable count. @param pp_variables If NULL, the entry point's output variable count will be written to *p_count. If non-NULL, pp_variables must point to an array with *p_count entries, where pointers to the entry point's output variables will be written. The caller must not free the interface variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointOutputVariables( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ); /*! @fn spvReflectEnumeratePushConstantBlocks @brief Note: If the module contains multiple entry points, this will only get the push constant blocks for the first one. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_blocks is NULL, the module's push constant block count will be stored here. If pp_blocks is not NULL, *p_count must contain the module's push constant block count. @param pp_blocks If NULL, the module's push constant block count will be written to *p_count. If non-NULL, pp_blocks must point to an array with *p_count entries, where pointers to the module's push constant blocks will be written. The caller must not free the block variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumeratePushConstantBlocks( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ); SPV_REFLECT_DEPRECATED("renamed to spvReflectEnumeratePushConstantBlocks") SpvReflectResult spvReflectEnumeratePushConstants( const SpvReflectShaderModule* p_module, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ); /*! @fn spvReflectEnumerateEntryPointPushConstantBlocks @brief Enumerate the push constant blocks used in the static call tree of a given entry point. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_count If pp_blocks is NULL, the entry point's push constant block count will be stored here. If pp_blocks is not NULL, *p_count must contain the entry point's push constant block count. @param pp_blocks If NULL, the entry point's push constant block count will be written to *p_count. If non-NULL, pp_blocks must point to an array with *p_count entries, where pointers to the entry point's push constant blocks will be written. The caller must not free the block variables written to this array. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectEnumerateEntryPointPushConstantBlocks( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ); /*! @fn spvReflectGetDescriptorBinding @param p_module Pointer to an instance of SpvReflectShaderModule. @param binding_number The "binding" value of the requested descriptor binding. @param set_number The "set" value of the requested descriptor binding. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains a descriptor binding that matches the provided [binding_number, set_number] values, a pointer to that binding is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note If the module contains multiple desriptor bindings with the same set and binding numbers, there are no guarantees about which binding will be returned. */ const SpvReflectDescriptorBinding* spvReflectGetDescriptorBinding( const SpvReflectShaderModule* p_module, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ); /*! @fn spvReflectGetEntryPointDescriptorBinding @brief Get the descriptor binding with the given binding number and set number that is used in the static call tree of a certain entry point. @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the binding from. @param binding_number The "binding" value of the requested descriptor binding. @param set_number The "set" value of the requested descriptor binding. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains a descriptor binding that matches the provided [binding_number, set_number] values, a pointer to that binding is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note If the entry point contains multiple desriptor bindings with the same set and binding numbers, there are no guarantees about which binding will be returned. */ const SpvReflectDescriptorBinding* spvReflectGetEntryPointDescriptorBinding( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ); /*! @fn spvReflectGetDescriptorSet @param p_module Pointer to an instance of SpvReflectShaderModule. @param set_number The "set" value of the requested descriptor set. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains a descriptor set with the provided set_number, a pointer to that set is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. */ const SpvReflectDescriptorSet* spvReflectGetDescriptorSet( const SpvReflectShaderModule* p_module, uint32_t set_number, SpvReflectResult* p_result ); /*! @fn spvReflectGetEntryPointDescriptorSet @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the descriptor set from. @param set_number The "set" value of the requested descriptor set. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains a descriptor set with the provided set_number, a pointer to that set is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. */ const SpvReflectDescriptorSet* spvReflectGetEntryPointDescriptorSet( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t set_number, SpvReflectResult* p_result ); /* @fn spvReflectGetInputVariableByLocation @param p_module Pointer to an instance of SpvReflectShaderModule. @param location The "location" value of the requested input variable. A location of 0xFFFFFFFF will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains an input interface variable with the provided location value, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetInputVariableByLocation( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ); SPV_REFLECT_DEPRECATED("renamed to spvReflectGetInputVariableByLocation") const SpvReflectInterfaceVariable* spvReflectGetInputVariable( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ); /* @fn spvReflectGetEntryPointInputVariableByLocation @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the input variable from. @param location The "location" value of the requested input variable. A location of 0xFFFFFFFF will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains an input interface variable with the provided location value, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetEntryPointInputVariableByLocation( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t location, SpvReflectResult* p_result ); /* @fn spvReflectGetInputVariableBySemantic @param p_module Pointer to an instance of SpvReflectShaderModule. @param semantic The "semantic" value of the requested input variable. A semantic of NULL will return NULL. A semantic of "" will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains an input interface variable with the provided semantic, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetInputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* semantic, SpvReflectResult* p_result ); /* @fn spvReflectGetEntryPointInputVariableBySemantic @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the input variable from. @param semantic The "semantic" value of the requested input variable. A semantic of NULL will return NULL. A semantic of "" will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains an input interface variable with the provided semantic, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetEntryPointInputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* entry_point, const char* semantic, SpvReflectResult* p_result ); /* @fn spvReflectGetOutputVariableByLocation @param p_module Pointer to an instance of SpvReflectShaderModule. @param location The "location" value of the requested output variable. A location of 0xFFFFFFFF will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains an output interface variable with the provided location value, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetOutputVariableByLocation( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ); SPV_REFLECT_DEPRECATED("renamed to spvReflectGetOutputVariableByLocation") const SpvReflectInterfaceVariable* spvReflectGetOutputVariable( const SpvReflectShaderModule* p_module, uint32_t location, SpvReflectResult* p_result ); /* @fn spvReflectGetEntryPointOutputVariableByLocation @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the output variable from. @param location The "location" value of the requested output variable. A location of 0xFFFFFFFF will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains an output interface variable with the provided location value, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetEntryPointOutputVariableByLocation( const SpvReflectShaderModule* p_module, const char* entry_point, uint32_t location, SpvReflectResult* p_result ); /* @fn spvReflectGetOutputVariableBySemantic @param p_module Pointer to an instance of SpvReflectShaderModule. @param semantic The "semantic" value of the requested output variable. A semantic of NULL will return NULL. A semantic of "" will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the module contains an output interface variable with the provided semantic, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetOutputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* semantic, SpvReflectResult* p_result ); /* @fn spvReflectGetEntryPointOutputVariableBySemantic @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the output variable from. @param semantic The "semantic" value of the requested output variable. A semantic of NULL will return NULL. A semantic of "" will always return NULL with *p_result == ELEMENT_NOT_FOUND. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the entry point contains an output interface variable with the provided semantic, a pointer to that variable is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. @note */ const SpvReflectInterfaceVariable* spvReflectGetEntryPointOutputVariableBySemantic( const SpvReflectShaderModule* p_module, const char* entry_point, const char* semantic, SpvReflectResult* p_result ); /*! @fn spvReflectGetPushConstantBlock @param p_module Pointer to an instance of SpvReflectShaderModule. @param index The index of the desired block within the module's array of push constant blocks. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the provided index is within range, a pointer to the corresponding push constant block is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. */ const SpvReflectBlockVariable* spvReflectGetPushConstantBlock( const SpvReflectShaderModule* p_module, uint32_t index, SpvReflectResult* p_result ); SPV_REFLECT_DEPRECATED("renamed to spvReflectGetPushConstantBlock") const SpvReflectBlockVariable* spvReflectGetPushConstant( const SpvReflectShaderModule* p_module, uint32_t index, SpvReflectResult* p_result ); /*! @fn spvReflectGetEntryPointPushConstantBlock @brief Get the push constant block corresponding to the given entry point. As by the Vulkan specification there can be no more than one push constant block used by a given entry point, so if there is one it will be returned, otherwise NULL will be returned. @param p_module Pointer to an instance of SpvReflectShaderModule. @param entry_point The entry point to get the push constant block from. @param p_result If successful, SPV_REFLECT_RESULT_SUCCESS will be written to *p_result. Otherwise, a error code indicating the cause of the failure will be stored here. @return If the provided index is within range, a pointer to the corresponding push constant block is returned. The caller must not free this pointer. If no match can be found, or if an unrelated error occurs, the return value will be NULL. Detailed error results are written to *pResult. */ const SpvReflectBlockVariable* spvReflectGetEntryPointPushConstantBlock( const SpvReflectShaderModule* p_module, const char* entry_point, SpvReflectResult* p_result ); /*! @fn spvReflectChangeDescriptorBindingNumbers @brief Assign new set and/or binding numbers to a descriptor binding. In addition to updating the reflection data, this function modifies the underlying SPIR-V bytecode. The updated code can be retrieved with spvReflectGetCode(). If the binding is used in multiple entry points within the module, it will be changed in all of them. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_binding Pointer to the descriptor binding to modify. @param new_binding_number The new binding number to assign to the provided descriptor binding. To leave the binding number unchanged, pass SPV_REFLECT_BINDING_NUMBER_DONT_CHANGE. @param new_set_number The new set number to assign to the provided descriptor binding. Successfully changing a descriptor binding's set number invalidates all existing SpvReflectDescriptorBinding and SpvReflectDescriptorSet pointers from this module. To leave the set number unchanged, pass SPV_REFLECT_SET_NUMBER_DONT_CHANGE. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectChangeDescriptorBindingNumbers( SpvReflectShaderModule* p_module, const SpvReflectDescriptorBinding* p_binding, uint32_t new_binding_number, uint32_t new_set_number ); SPV_REFLECT_DEPRECATED("Renamed to spvReflectChangeDescriptorBindingNumbers") SpvReflectResult spvReflectChangeDescriptorBindingNumber( SpvReflectShaderModule* p_module, const SpvReflectDescriptorBinding* p_descriptor_binding, uint32_t new_binding_number, uint32_t optional_new_set_number ); /*! @fn spvReflectChangeDescriptorSetNumber @brief Assign a new set number to an entire descriptor set (including all descriptor bindings in that set). In addition to updating the reflection data, this function modifies the underlying SPIR-V bytecode. The updated code can be retrieved with spvReflectGetCode(). If the descriptor set is used in multiple entry points within the module, it will be modified in all of them. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_set Pointer to the descriptor binding to modify. @param new_set_number The new set number to assign to the provided descriptor set, and all its descriptor bindings. Successfully changing a descriptor binding's set number invalidates all existing SpvReflectDescriptorBinding and SpvReflectDescriptorSet pointers from this module. To leave the set number unchanged, pass SPV_REFLECT_SET_NUMBER_DONT_CHANGE. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectChangeDescriptorSetNumber( SpvReflectShaderModule* p_module, const SpvReflectDescriptorSet* p_set, uint32_t new_set_number ); /*! @fn spvReflectChangeInputVariableLocation @brief Assign a new location to an input interface variable. In addition to updating the reflection data, this function modifies the underlying SPIR-V bytecode. The updated code can be retrieved with spvReflectGetCode(). It is the caller's responsibility to avoid assigning the same location to multiple input variables. If the input variable is used by multiple entry points in the module, it will be changed in all of them. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_input_variable Pointer to the input variable to update. @param new_location The new location to assign to p_input_variable. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectChangeInputVariableLocation( SpvReflectShaderModule* p_module, const SpvReflectInterfaceVariable* p_input_variable, uint32_t new_location ); /*! @fn spvReflectChangeOutputVariableLocation @brief Assign a new location to an output interface variable. In addition to updating the reflection data, this function modifies the underlying SPIR-V bytecode. The updated code can be retrieved with spvReflectGetCode(). It is the caller's responsibility to avoid assigning the same location to multiple output variables. If the output variable is used by multiple entry points in the module, it will be changed in all of them. @param p_module Pointer to an instance of SpvReflectShaderModule. @param p_output_variable Pointer to the output variable to update. @param new_location The new location to assign to p_output_variable. @return If successful, returns SPV_REFLECT_RESULT_SUCCESS. Otherwise, the error code indicates the cause of the failure. */ SpvReflectResult spvReflectChangeOutputVariableLocation( SpvReflectShaderModule* p_module, const SpvReflectInterfaceVariable* p_output_variable, uint32_t new_location ); /*! @fn spvReflectSourceLanguage @param source_lang The source language code. @return Returns string of source language specified in \a source_lang. The caller must not free the memory associated with this string. */ const char* spvReflectSourceLanguage(SpvSourceLanguage source_lang); /*! @fn spvReflectBlockVariableTypeName @param p_var Pointer to block variable. @return Returns string of block variable's type description type name or NULL if p_var is NULL. */ const char* spvReflectBlockVariableTypeName( const SpvReflectBlockVariable* p_var ); #if defined(__cplusplus) }; #endif #if defined(__cplusplus) #include <cstdlib> #include <string> #include <vector> namespace spv_reflect { /*! \class ShaderModule */ class ShaderModule { public: ShaderModule(); ShaderModule(size_t size, const void* p_code, SpvReflectModuleFlags flags = SPV_REFLECT_MODULE_FLAG_NONE); ShaderModule(const std::vector<uint8_t>& code, SpvReflectModuleFlags flags = SPV_REFLECT_MODULE_FLAG_NONE); ShaderModule(const std::vector<uint32_t>& code, SpvReflectModuleFlags flags = SPV_REFLECT_MODULE_FLAG_NONE); ~ShaderModule(); ShaderModule(ShaderModule&& other); ShaderModule& operator=(ShaderModule&& other); SpvReflectResult GetResult() const; const SpvReflectShaderModule& GetShaderModule() const; uint32_t GetCodeSize() const; const uint32_t* GetCode() const; const char* GetEntryPointName() const; const char* GetSourceFile() const; uint32_t GetEntryPointCount() const; const char* GetEntryPointName(uint32_t index) const; SpvReflectShaderStageFlagBits GetEntryPointShaderStage(uint32_t index) const; SpvReflectShaderStageFlagBits GetShaderStage() const; SPV_REFLECT_DEPRECATED("Renamed to GetShaderStage") SpvReflectShaderStageFlagBits GetVulkanShaderStage() const { return GetShaderStage(); } SpvReflectResult EnumerateDescriptorBindings(uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings) const; SpvReflectResult EnumerateEntryPointDescriptorBindings(const char* entry_point, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings) const; SpvReflectResult EnumerateDescriptorSets( uint32_t* p_count, SpvReflectDescriptorSet** pp_sets) const ; SpvReflectResult EnumerateEntryPointDescriptorSets(const char* entry_point, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets) const ; SpvReflectResult EnumerateInterfaceVariables(uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumerateEntryPointInterfaceVariables(const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumerateInputVariables(uint32_t* p_count,SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumerateEntryPointInputVariables(const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumerateOutputVariables(uint32_t* p_count,SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumerateEntryPointOutputVariables(const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables) const; SpvReflectResult EnumeratePushConstantBlocks(uint32_t* p_count, SpvReflectBlockVariable** pp_blocks) const; SpvReflectResult EnumerateEntryPointPushConstantBlocks(const char* entry_point, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks) const; SPV_REFLECT_DEPRECATED("Renamed to EnumeratePushConstantBlocks") SpvReflectResult EnumeratePushConstants(uint32_t* p_count, SpvReflectBlockVariable** pp_blocks) const { return EnumeratePushConstantBlocks(p_count, pp_blocks); } const SpvReflectDescriptorBinding* GetDescriptorBinding(uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result = nullptr) const; const SpvReflectDescriptorBinding* GetEntryPointDescriptorBinding(const char* entry_point, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result = nullptr) const; const SpvReflectDescriptorSet* GetDescriptorSet(uint32_t set_number, SpvReflectResult* p_result = nullptr) const; const SpvReflectDescriptorSet* GetEntryPointDescriptorSet(const char* entry_point, uint32_t set_number, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetInputVariableByLocation(uint32_t location, SpvReflectResult* p_result = nullptr) const; SPV_REFLECT_DEPRECATED("Renamed to GetInputVariableByLocation") const SpvReflectInterfaceVariable* GetInputVariable(uint32_t location, SpvReflectResult* p_result = nullptr) const { return GetInputVariableByLocation(location, p_result); } const SpvReflectInterfaceVariable* GetEntryPointInputVariableByLocation(const char* entry_point, uint32_t location, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetInputVariableBySemantic(const char* semantic, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetEntryPointInputVariableBySemantic(const char* entry_point, const char* semantic, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetOutputVariableByLocation(uint32_t location, SpvReflectResult* p_result = nullptr) const; SPV_REFLECT_DEPRECATED("Renamed to GetOutputVariableByLocation") const SpvReflectInterfaceVariable* GetOutputVariable(uint32_t location, SpvReflectResult* p_result = nullptr) const { return GetOutputVariableByLocation(location, p_result); } const SpvReflectInterfaceVariable* GetEntryPointOutputVariableByLocation(const char* entry_point, uint32_t location, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetOutputVariableBySemantic(const char* semantic, SpvReflectResult* p_result = nullptr) const; const SpvReflectInterfaceVariable* GetEntryPointOutputVariableBySemantic(const char* entry_point, const char* semantic, SpvReflectResult* p_result = nullptr) const; const SpvReflectBlockVariable* GetPushConstantBlock(uint32_t index, SpvReflectResult* p_result = nullptr) const; SPV_REFLECT_DEPRECATED("Renamed to GetPushConstantBlock") const SpvReflectBlockVariable* GetPushConstant(uint32_t index, SpvReflectResult* p_result = nullptr) const { return GetPushConstantBlock(index, p_result); } const SpvReflectBlockVariable* GetEntryPointPushConstantBlock(const char* entry_point, SpvReflectResult* p_result = nullptr) const; SpvReflectResult ChangeDescriptorBindingNumbers(const SpvReflectDescriptorBinding* p_binding, uint32_t new_binding_number = SPV_REFLECT_BINDING_NUMBER_DONT_CHANGE, uint32_t optional_new_set_number = SPV_REFLECT_SET_NUMBER_DONT_CHANGE); SPV_REFLECT_DEPRECATED("Renamed to ChangeDescriptorBindingNumbers") SpvReflectResult ChangeDescriptorBindingNumber(const SpvReflectDescriptorBinding* p_binding, uint32_t new_binding_number = SPV_REFLECT_BINDING_NUMBER_DONT_CHANGE, uint32_t new_set_number = SPV_REFLECT_SET_NUMBER_DONT_CHANGE) { return ChangeDescriptorBindingNumbers(p_binding, new_binding_number, new_set_number); } SpvReflectResult ChangeDescriptorSetNumber(const SpvReflectDescriptorSet* p_set, uint32_t new_set_number = SPV_REFLECT_SET_NUMBER_DONT_CHANGE); SpvReflectResult ChangeInputVariableLocation(const SpvReflectInterfaceVariable* p_input_variable, uint32_t new_location); SpvReflectResult ChangeOutputVariableLocation(const SpvReflectInterfaceVariable* p_output_variable, uint32_t new_location); private: // Make noncopyable ShaderModule(const ShaderModule&); ShaderModule& operator=(const ShaderModule&); private: mutable SpvReflectResult m_result = SPV_REFLECT_RESULT_NOT_READY; SpvReflectShaderModule m_module = {}; }; // ================================================================================================= // ShaderModule // ================================================================================================= /*! @fn ShaderModule */ inline ShaderModule::ShaderModule() {} /*! @fn ShaderModule @param size @param p_code */ inline ShaderModule::ShaderModule(size_t size, const void* p_code, SpvReflectModuleFlags flags) { m_result = spvReflectCreateShaderModule2( flags, size, p_code, &m_module); } /*! @fn ShaderModule @param code */ inline ShaderModule::ShaderModule(const std::vector<uint8_t>& code, SpvReflectModuleFlags flags) { m_result = spvReflectCreateShaderModule2( flags, code.size(), code.data(), &m_module); } /*! @fn ShaderModule @param code */ inline ShaderModule::ShaderModule(const std::vector<uint32_t>& code, SpvReflectModuleFlags flags) { m_result = spvReflectCreateShaderModule2( flags, code.size() * sizeof(uint32_t), code.data(), &m_module); } /*! @fn ~ShaderModule */ inline ShaderModule::~ShaderModule() { spvReflectDestroyShaderModule(&m_module); } inline ShaderModule::ShaderModule(ShaderModule&& other) { *this = std::move(other); } inline ShaderModule& ShaderModule::operator=(ShaderModule&& other) { m_result = std::move(other.m_result); m_module = std::move(other.m_module); other.m_module = {}; return *this; } /*! @fn GetResult @return */ inline SpvReflectResult ShaderModule::GetResult() const { return m_result; } /*! @fn GetShaderModule @return */ inline const SpvReflectShaderModule& ShaderModule::GetShaderModule() const { return m_module; } /*! @fn GetCodeSize @return */ inline uint32_t ShaderModule::GetCodeSize() const { return spvReflectGetCodeSize(&m_module); } /*! @fn GetCode @return */ inline const uint32_t* ShaderModule::GetCode() const { return spvReflectGetCode(&m_module); } /*! @fn GetEntryPoint @return Returns entry point */ inline const char* ShaderModule::GetEntryPointName() const { return this->GetEntryPointName(0); } /*! @fn GetEntryPoint @return Returns entry point */ inline const char* ShaderModule::GetSourceFile() const { return m_module.source_file; } /*! @fn GetEntryPointCount @param @return */ inline uint32_t ShaderModule::GetEntryPointCount() const { return m_module.entry_point_count; } /*! @fn GetEntryPointName @param index @return */ inline const char* ShaderModule::GetEntryPointName(uint32_t index) const { return m_module.entry_points[index].name; } /*! @fn GetEntryPointShaderStage @param index @return Returns the shader stage for the entry point at \b index */ inline SpvReflectShaderStageFlagBits ShaderModule::GetEntryPointShaderStage(uint32_t index) const { return m_module.entry_points[index].shader_stage; } /*! @fn GetShaderStage @return Returns shader stage for the first entry point */ inline SpvReflectShaderStageFlagBits ShaderModule::GetShaderStage() const { return m_module.shader_stage; } /*! @fn EnumerateDescriptorBindings @param count @param p_binding_numbers @param pp_bindings @return */ inline SpvReflectResult ShaderModule::EnumerateDescriptorBindings( uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ) const { m_result = spvReflectEnumerateDescriptorBindings( &m_module, p_count, pp_bindings); return m_result; } /*! @fn EnumerateEntryPointDescriptorBindings @param entry_point @param count @param pp_bindings @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointDescriptorBindings( const char* entry_point, uint32_t* p_count, SpvReflectDescriptorBinding** pp_bindings ) const { m_result = spvReflectEnumerateEntryPointDescriptorBindings( &m_module, entry_point, p_count, pp_bindings); return m_result; } /*! @fn EnumerateDescriptorSets @param count @param pp_sets @return */ inline SpvReflectResult ShaderModule::EnumerateDescriptorSets( uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ) const { m_result = spvReflectEnumerateDescriptorSets( &m_module, p_count, pp_sets); return m_result; } /*! @fn EnumerateEntryPointDescriptorSets @param entry_point @param count @param pp_sets @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointDescriptorSets( const char* entry_point, uint32_t* p_count, SpvReflectDescriptorSet** pp_sets ) const { m_result = spvReflectEnumerateEntryPointDescriptorSets( &m_module, entry_point, p_count, pp_sets); return m_result; } /*! @fn EnumerateInterfaceVariables @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateInterfaceVariables( uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateInterfaceVariables( &m_module, p_count, pp_variables); return m_result; } /*! @fn EnumerateEntryPointInterfaceVariables @param entry_point @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointInterfaceVariables( const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateEntryPointInterfaceVariables( &m_module, entry_point, p_count, pp_variables); return m_result; } /*! @fn EnumerateInputVariables @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateInputVariables( uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateInputVariables( &m_module, p_count, pp_variables); return m_result; } /*! @fn EnumerateEntryPointInputVariables @param entry_point @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointInputVariables( const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateEntryPointInputVariables( &m_module, entry_point, p_count, pp_variables); return m_result; } /*! @fn EnumerateOutputVariables @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateOutputVariables( uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateOutputVariables( &m_module, p_count, pp_variables); return m_result; } /*! @fn EnumerateEntryPointOutputVariables @param entry_point @param count @param pp_variables @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointOutputVariables( const char* entry_point, uint32_t* p_count, SpvReflectInterfaceVariable** pp_variables ) const { m_result = spvReflectEnumerateEntryPointOutputVariables( &m_module, entry_point, p_count, pp_variables); return m_result; } /*! @fn EnumeratePushConstantBlocks @param count @param pp_blocks @return */ inline SpvReflectResult ShaderModule::EnumeratePushConstantBlocks( uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ) const { m_result = spvReflectEnumeratePushConstantBlocks( &m_module, p_count, pp_blocks); return m_result; } /*! @fn EnumerateEntryPointPushConstantBlocks @param entry_point @param count @param pp_blocks @return */ inline SpvReflectResult ShaderModule::EnumerateEntryPointPushConstantBlocks( const char* entry_point, uint32_t* p_count, SpvReflectBlockVariable** pp_blocks ) const { m_result = spvReflectEnumerateEntryPointPushConstantBlocks( &m_module, entry_point, p_count, pp_blocks); return m_result; } /*! @fn GetDescriptorBinding @param binding_number @param set_number @param p_result @return */ inline const SpvReflectDescriptorBinding* ShaderModule::GetDescriptorBinding( uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ) const { return spvReflectGetDescriptorBinding( &m_module, binding_number, set_number, p_result); } /*! @fn GetEntryPointDescriptorBinding @param entry_point @param binding_number @param set_number @param p_result @return */ inline const SpvReflectDescriptorBinding* ShaderModule::GetEntryPointDescriptorBinding( const char* entry_point, uint32_t binding_number, uint32_t set_number, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointDescriptorBinding( &m_module, entry_point, binding_number, set_number, p_result); } /*! @fn GetDescriptorSet @param set_number @param p_result @return */ inline const SpvReflectDescriptorSet* ShaderModule::GetDescriptorSet( uint32_t set_number, SpvReflectResult* p_result ) const { return spvReflectGetDescriptorSet( &m_module, set_number, p_result); } /*! @fn GetEntryPointDescriptorSet @param entry_point @param set_number @param p_result @return */ inline const SpvReflectDescriptorSet* ShaderModule::GetEntryPointDescriptorSet( const char* entry_point, uint32_t set_number, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointDescriptorSet( &m_module, entry_point, set_number, p_result); } /*! @fn GetInputVariable @param location @param p_result @return */ inline const SpvReflectInterfaceVariable* ShaderModule::GetInputVariableByLocation( uint32_t location, SpvReflectResult* p_result ) const { return spvReflectGetInputVariableByLocation( &m_module, location, p_result); } inline const SpvReflectInterfaceVariable* ShaderModule::GetInputVariableBySemantic( const char* semantic, SpvReflectResult* p_result ) const { return spvReflectGetInputVariableBySemantic( &m_module, semantic, p_result); } /*! @fn GetEntryPointInputVariable @param entry_point @param location @param p_result @return */ inline const SpvReflectInterfaceVariable* ShaderModule::GetEntryPointInputVariableByLocation( const char* entry_point, uint32_t location, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointInputVariableByLocation( &m_module, entry_point, location, p_result); } inline const SpvReflectInterfaceVariable* ShaderModule::GetEntryPointInputVariableBySemantic( const char* entry_point, const char* semantic, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointInputVariableBySemantic( &m_module, entry_point, semantic, p_result); } /*! @fn GetOutputVariable @param location @param p_result @return */ inline const SpvReflectInterfaceVariable* ShaderModule::GetOutputVariableByLocation( uint32_t location, SpvReflectResult* p_result ) const { return spvReflectGetOutputVariableByLocation( &m_module, location, p_result); } inline const SpvReflectInterfaceVariable* ShaderModule::GetOutputVariableBySemantic( const char* semantic, SpvReflectResult* p_result ) const { return spvReflectGetOutputVariableBySemantic(&m_module, semantic, p_result); } /*! @fn GetEntryPointOutputVariable @param entry_point @param location @param p_result @return */ inline const SpvReflectInterfaceVariable* ShaderModule::GetEntryPointOutputVariableByLocation( const char* entry_point, uint32_t location, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointOutputVariableByLocation( &m_module, entry_point, location, p_result); } inline const SpvReflectInterfaceVariable* ShaderModule::GetEntryPointOutputVariableBySemantic( const char* entry_point, const char* semantic, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointOutputVariableBySemantic( &m_module, entry_point, semantic, p_result); } /*! @fn GetPushConstant @param index @param p_result @return */ inline const SpvReflectBlockVariable* ShaderModule::GetPushConstantBlock( uint32_t index, SpvReflectResult* p_result ) const { return spvReflectGetPushConstantBlock( &m_module, index, p_result); } /*! @fn GetEntryPointPushConstant @param entry_point @param index @param p_result @return */ inline const SpvReflectBlockVariable* ShaderModule::GetEntryPointPushConstantBlock( const char* entry_point, SpvReflectResult* p_result ) const { return spvReflectGetEntryPointPushConstantBlock( &m_module, entry_point, p_result); } /*! @fn ChangeDescriptorBindingNumbers @param p_binding @param new_binding_number @param new_set_number @return */ inline SpvReflectResult ShaderModule::ChangeDescriptorBindingNumbers( const SpvReflectDescriptorBinding* p_binding, uint32_t new_binding_number, uint32_t new_set_number ) { return spvReflectChangeDescriptorBindingNumbers( &m_module, p_binding, new_binding_number, new_set_number); } /*! @fn ChangeDescriptorSetNumber @param p_set @param new_set_number @return */ inline SpvReflectResult ShaderModule::ChangeDescriptorSetNumber( const SpvReflectDescriptorSet* p_set, uint32_t new_set_number ) { return spvReflectChangeDescriptorSetNumber( &m_module, p_set, new_set_number); } /*! @fn ChangeInputVariableLocation @param p_input_variable @param new_location @return */ inline SpvReflectResult ShaderModule::ChangeInputVariableLocation( const SpvReflectInterfaceVariable* p_input_variable, uint32_t new_location) { return spvReflectChangeInputVariableLocation( &m_module, p_input_variable, new_location); } /*! @fn ChangeOutputVariableLocation @param p_input_variable @param new_location @return */ inline SpvReflectResult ShaderModule::ChangeOutputVariableLocation( const SpvReflectInterfaceVariable* p_output_variable, uint32_t new_location) { return spvReflectChangeOutputVariableLocation( &m_module, p_output_variable, new_location); } } // namespace spv_reflect #endif // defined(__cplusplus) #endif // SPIRV_REFLECT_H
whupdup/frame
real/third_party/spirv_reflect/spirv_reflect.h
C++
gpl-3.0
87,852
#define STB_IMAGE_IMPLEMENTATION #include "stb_image.h"
whupdup/frame
real/third_party/stb/stb_image.cpp
C++
gpl-3.0
55
/* stb_image - v2.26 - public domain image loader - http://nothings.org/stb no warranty implied; use at your own risk Do this: #define STB_IMAGE_IMPLEMENTATION before you include this file in *one* C or C++ file to create the implementation. // i.e. it should look like this: #include ... #include ... #include ... #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free QUICK NOTES: Primarily of interest to game developers and other people who can avoid problematic images and only need the trivial interface JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) PNG 1/2/4/8/16-bit-per-channel TGA (not sure what subset, if a subset) BMP non-1bpp, non-RLE PSD (composited view only, no extra channels, 8/16 bit-per-channel) GIF (*comp always reports as 4-channel) HDR (radiance rgbE format) PIC (Softimage PIC) PNM (PPM and PGM binary only) Animated GIF still needs a proper API, but here's one way to do it: http://gist.github.com/urraka/685d9a6340b26b830d49 - decode from memory or through FILE (define STBI_NO_STDIO to remove code) - decode from arbitrary I/O callbacks - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) Full documentation under "DOCUMENTATION" below. LICENSE See end of file for license information. RECENT REVISION HISTORY: 2.26 (2020-07-13) many minor fixes 2.25 (2020-02-02) fix warnings 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically 2.23 (2019-08-11) fix clang static analysis warning 2.22 (2019-03-04) gif fixes, fix warnings 2.21 (2019-02-25) fix typo in comment 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 RGB-format JPEG; remove white matting in PSD; allocate large structures on the stack; correct channel count for PNG & BMP 2.10 (2016-01-22) avoid warning introduced in 2.09 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED See end of file for full revision history. ============================ Contributors ========================= Image formats Extensions, features Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) github:urraka (animated gif) Junggon Kim (PNM comments) Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) socks-the-fox (16-bit PNG) Jeremy Sawicki (handle all ImageNet JPGs) Optimizations & bugfixes Mikhail Morozov (1-bit BMP) Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) Arseny Kapoulkine John-Mark Allen Carmelo J Fdez-Aguera Bug & warning fixes Marc LeBlanc David Woo Guillaume George Martins Mozeiko Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski Phil Jordan Dave Moore Roy Eltham Hayaki Saito Nathan Reed Won Chun Luke Graham Johan Duparc Nick Verigakis the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh Janez Zemva John Bartholomew Michal Cichon github:romigrou Jonathan Blow Ken Hamada Tero Hanninen github:svdijk Laurent Gomila Cort Stratton github:snagar Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex Cass Everitt Ryamond Barbiero github:grim210 Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus Josh Tobin Matthew Gregan github:poppolopoppo Julian Raschke Gregory Mullen Christian Floisand github:darealshinji Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 Brad Weinberger Matvey Cherevko [reserved] Luca Sas Alexander Veselov Zack Middleton [reserved] Ryan C. Gordon [reserved] [reserved] DO NOT ADD YOUR NAME HERE To add your name to the credits, pick a random blank space in the middle and fill it. 80% of merge conflicts on stb PRs are due to people adding their name at the end of the credits. */ #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H // DOCUMENTATION // // Limitations: // - no 12-bit-per-channel JPEG // - no JPEGs with arithmetic coding // - GIF always returns *comp=4 // // Basic usage (see HDR discussion below for HDR usage): // int x,y,n; // unsigned char *data = stbi_load(filename, &x, &y, &n, 0); // // ... process data if not NULL ... // // ... x = width, y = height, n = # 8-bit components per pixel ... // // ... replace '0' with '1'..'4' to force that many components per pixel // // ... but 'n' will always be the number that it would have been if you said 0 // stbi_image_free(data) // // Standard parameters: // int *x -- outputs image width in pixels // int *y -- outputs image height in pixels // int *channels_in_file -- outputs # of image components in image file // int desired_channels -- if non-zero, # of image components requested in result // // The return value from an image loader is an 'unsigned char *' which points // to the pixel data, or NULL on an allocation failure or if the image is // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, // with each pixel consisting of N interleaved 8-bit components; the first // pixel pointed to is top-left-most in the image. There is no padding between // image scanlines or between pixels, regardless of format. The number of // components N is 'desired_channels' if desired_channels is non-zero, or // *channels_in_file otherwise. If desired_channels is non-zero, // *channels_in_file has the number of components that _would_ have been // output otherwise. E.g. if you set desired_channels to 4, you will always // get RGBA output, but you can check *channels_in_file to see if it's trivially // opaque because e.g. there were only 3 channels in the source image. // // An output image with N components has the following components interleaved // in this order in each pixel: // // N=#comp components // 1 grey // 2 grey, alpha // 3 red, green, blue // 4 red, green, blue, alpha // // If image loading fails for any reason, the return value will be NULL, // and *x, *y, *channels_in_file will be unchanged. The function // stbi_failure_reason() can be queried for an extremely brief, end-user // unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS // to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly // more user-friendly ones. // // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. // // =========================================================================== // // UNICODE: // // If compiling for Windows and you wish to use Unicode filenames, compile // with // #define STBI_WINDOWS_UTF8 // and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert // Windows wchar_t filenames to utf8. // // =========================================================================== // // Philosophy // // stb libraries are designed with the following priorities: // // 1. easy to use // 2. easy to maintain // 3. good performance // // Sometimes I let "good performance" creep up in priority over "easy to maintain", // and for best performance I may provide less-easy-to-use APIs that give higher // performance, in addition to the easy-to-use ones. Nevertheless, it's important // to keep in mind that from the standpoint of you, a client of this library, // all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. // // Some secondary priorities arise directly from the first two, some of which // provide more explicit reasons why performance can't be emphasized. // // - Portable ("ease of use") // - Small source code footprint ("easy to maintain") // - No dependencies ("ease of use") // // =========================================================================== // // I/O callbacks // // I/O callbacks allow you to read from arbitrary sources, like packaged // files or some other source. Data read from callbacks are processed // through a small internal buffer (currently 128 bytes) to try to reduce // overhead. // // The three functions you must define are "read" (reads some bytes of data), // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). // // =========================================================================== // // SIMD support // // The JPEG decoder will try to automatically use SIMD kernels on x86 when // supported by the compiler. For ARM Neon support, you must explicitly // request it. // // (The old do-it-yourself SIMD API is no longer supported in the current // code.) // // On x86, SSE2 will automatically be used when available based on a run-time // test; if not, the generic C versions are used as a fall-back. On ARM targets, // the typical path is to have separate builds for NEON and non-NEON devices // (at least this is true for iOS and Android). Therefore, the NEON support is // toggled by a build flag: define STBI_NEON to get NEON loops. // // If for some reason you do not want to use any of SIMD code, or if // you have issues compiling it, you can disable it entirely by // defining STBI_NO_SIMD. // // =========================================================================== // // HDR image support (disable by defining STBI_NO_HDR) // // stb_image supports loading HDR images in general, and currently the Radiance // .HDR file format specifically. You can still load any file through the existing // interface; if you attempt to load an HDR file, it will be automatically remapped // to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; // both of these constants can be reconfigured through this interface: // // stbi_hdr_to_ldr_gamma(2.2f); // stbi_hdr_to_ldr_scale(1.0f); // // (note, do not use _inverse_ constants; stbi_image will invert them // appropriately). // // Additionally, there is a new, parallel interface for loading files as // (linear) floats to preserve the full dynamic range: // // float *data = stbi_loadf(filename, &x, &y, &n, 0); // // If you load LDR images through this interface, those images will // be promoted to floating point values, run through the inverse of // constants corresponding to the above: // // stbi_ldr_to_hdr_scale(1.0f); // stbi_ldr_to_hdr_gamma(2.2f); // // Finally, given a filename (or an open file or memory block--see header // file for details) containing image data, you can query for the "most // appropriate" interface to use (that is, whether the image is HDR or // not), using: // // stbi_is_hdr(char *filename); // // =========================================================================== // // iPhone PNG support: // // By default we convert iphone-formatted PNGs back to RGB, even though // they are internally encoded differently. You can disable this conversion // by calling stbi_convert_iphone_png_to_rgb(0), in which case // you will always just get the native iphone "format" through (which // is BGR stored in RGB). // // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per // pixel to remove any premultiplied alpha *only* if the image file explicitly // says there's premultiplied data (currently only happens in iPhone images, // and only if iPhone convert-to-rgb processing is on). // // =========================================================================== // // ADDITIONAL CONFIGURATION // // - You can suppress implementation of any of the decoders to reduce // your code footprint by #defining one or more of the following // symbols before creating the implementation. // // STBI_NO_JPEG // STBI_NO_PNG // STBI_NO_BMP // STBI_NO_PSD // STBI_NO_TGA // STBI_NO_GIF // STBI_NO_HDR // STBI_NO_PIC // STBI_NO_PNM (.ppm and .pgm) // // - You can request *only* certain decoders and suppress all other ones // (this will be more forward-compatible, as addition of new decoders // doesn't require you to disable them explicitly): // // STBI_ONLY_JPEG // STBI_ONLY_PNG // STBI_ONLY_BMP // STBI_ONLY_PSD // STBI_ONLY_TGA // STBI_ONLY_GIF // STBI_ONLY_HDR // STBI_ONLY_PIC // STBI_ONLY_PNM (.ppm and .pgm) // // - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still // want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB // // - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater // than that size (in either width or height) without further processing. // This is to let programs in the wild set an upper bound to prevent // denial-of-service attacks on untrusted data, as one could generate a // valid image of gigantic dimensions and force stb_image to allocate a // huge block of memory and spend disproportionate time decoding it. By // default this is set to (1 << 24), which is 16777216, but that's still // very big. #ifndef STBI_NO_STDIO #include <stdio.h> #endif // STBI_NO_STDIO #define STBI_VERSION 1 enum { STBI_default = 0, // only used for desired_channels STBI_grey = 1, STBI_grey_alpha = 2, STBI_rgb = 3, STBI_rgb_alpha = 4 }; #include <stdlib.h> typedef unsigned char stbi_uc; typedef unsigned short stbi_us; #ifdef __cplusplus extern "C" { #endif #ifndef STBIDEF #ifdef STB_IMAGE_STATIC #define STBIDEF static #else #define STBIDEF extern #endif #endif ////////////////////////////////////////////////////////////////////////////// // // PRIMARY API - works on images of any type // // // load image by filename, open file, or memory buffer // typedef struct { int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative int (*eof) (void *user); // returns nonzero if we are at end of file/data } stbi_io_callbacks; //////////////////////////////////// // // 8-bits-per-channel interface // STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); // for stbi_load_from_file, file pointer is left pointing immediately after image #endif #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); #endif #ifdef STBI_WINDOWS_UTF8 STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); #endif //////////////////////////////////// // // 16-bits-per-channel interface // STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif //////////////////////////////////// // // float-per-channel interface // #ifndef STBI_NO_LINEAR STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); #endif #endif #ifndef STBI_NO_HDR STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); STBIDEF void stbi_hdr_to_ldr_scale(float scale); #endif // STBI_NO_HDR #ifndef STBI_NO_LINEAR STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); STBIDEF void stbi_ldr_to_hdr_scale(float scale); #endif // STBI_NO_LINEAR // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename); STBIDEF int stbi_is_hdr_from_file(FILE *f); #endif // STBI_NO_STDIO // get a VERY brief reason for failure // on most compilers (and ALL modern mainstream compilers) this is threadsafe STBIDEF const char *stbi_failure_reason (void); // free the loaded image -- this is just free() STBIDEF void stbi_image_free (void *retval_from_stbi_load); // get image dimensions & components without fully decoding STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); #ifndef STBI_NO_STDIO STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); STBIDEF int stbi_is_16_bit (char const *filename); STBIDEF int stbi_is_16_bit_from_file(FILE *f); #endif // for image formats that explicitly notate that they have premultiplied alpha, // we just return the colors as stored in the file. set this flag to force // unpremultiplication. results are undefined if the unpremultiply overflow. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); // indicate whether we should process iphone images back to canonical format, // or just pass them through "as-is" STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); // flip the image vertically, so the first pixel in the output array is the bottom left STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); // as above, but only applies to images loaded on the thread that calls the function // this function is only available if your compiler supports thread-local variables; // calling it will fail to link if your compiler doesn't STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); // ZLIB client - used by PNG, available for other purposes STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); #ifdef __cplusplus } #endif // // //// end header file ///////////////////////////////////////////////////// #endif // STBI_INCLUDE_STB_IMAGE_H #ifdef STB_IMAGE_IMPLEMENTATION #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ || defined(STBI_ONLY_ZLIB) #ifndef STBI_ONLY_JPEG #define STBI_NO_JPEG #endif #ifndef STBI_ONLY_PNG #define STBI_NO_PNG #endif #ifndef STBI_ONLY_BMP #define STBI_NO_BMP #endif #ifndef STBI_ONLY_PSD #define STBI_NO_PSD #endif #ifndef STBI_ONLY_TGA #define STBI_NO_TGA #endif #ifndef STBI_ONLY_GIF #define STBI_NO_GIF #endif #ifndef STBI_ONLY_HDR #define STBI_NO_HDR #endif #ifndef STBI_ONLY_PIC #define STBI_NO_PIC #endif #ifndef STBI_ONLY_PNM #define STBI_NO_PNM #endif #endif #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) #define STBI_NO_ZLIB #endif #include <stdarg.h> #include <stddef.h> // ptrdiff_t on osx #include <stdlib.h> #include <string.h> #include <limits.h> #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) #include <math.h> // ldexp, pow #endif #ifndef STBI_NO_STDIO #include <stdio.h> #endif #ifndef STBI_ASSERT #include <assert.h> #define STBI_ASSERT(x) assert(x) #endif #ifdef __cplusplus #define STBI_EXTERN extern "C" #else #define STBI_EXTERN extern #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbi_inline inline #else #define stbi_inline #endif #else #define stbi_inline __forceinline #endif #ifndef STBI_NO_THREAD_LOCALS #if defined(__cplusplus) && __cplusplus >= 201103L #define STBI_THREAD_LOCAL thread_local #elif defined(__GNUC__) && __GNUC__ < 5 #define STBI_THREAD_LOCAL __thread #elif defined(_MSC_VER) #define STBI_THREAD_LOCAL __declspec(thread) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) #define STBI_THREAD_LOCAL _Thread_local #endif #ifndef STBI_THREAD_LOCAL #if defined(__GNUC__) #define STBI_THREAD_LOCAL __thread #endif #endif #endif #ifdef _MSC_VER typedef unsigned short stbi__uint16; typedef signed short stbi__int16; typedef unsigned int stbi__uint32; typedef signed int stbi__int32; #else #include <stdint.h> typedef uint16_t stbi__uint16; typedef int16_t stbi__int16; typedef uint32_t stbi__uint32; typedef int32_t stbi__int32; #endif // should produce compiler error if size is wrong typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; #ifdef _MSC_VER #define STBI_NOTUSED(v) (void)(v) #else #define STBI_NOTUSED(v) (void)sizeof(v) #endif #ifdef _MSC_VER #define STBI_HAS_LROTL #endif #ifdef STBI_HAS_LROTL #define stbi_lrot(x,y) _lrotl(x,y) #else #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) #endif #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) // ok #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) // ok #else #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." #endif #ifndef STBI_MALLOC #define STBI_MALLOC(sz) malloc(sz) #define STBI_REALLOC(p,newsz) realloc(p,newsz) #define STBI_FREE(p) free(p) #endif #ifndef STBI_REALLOC_SIZED #define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) #endif // x86/x64 detection #if defined(__x86_64__) || defined(_M_X64) #define STBI__X64_TARGET #elif defined(__i386) || defined(_M_IX86) #define STBI__X86_TARGET #endif #if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) // gcc doesn't support sse2 intrinsics unless you compile with -msse2, // which in turn means it gets to use SSE2 everywhere. This is unfortunate, // but previous attempts to provide the SSE2 functions with runtime // detection caused numerous issues. The way architecture extensions are // exposed in GCC/Clang is, sadly, not really suited for one-file libs. // New behavior: if compiled with -msse2, we use SSE2 without any // detection; if not, we don't use it at all. #define STBI_NO_SIMD #endif #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET // // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not // simultaneously enabling "-mstackrealign". // // See https://github.com/nothings/stb/issues/81 for more information. // // So default to no SSE2 on 32-bit MinGW. If you've read this far and added // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. #define STBI_NO_SIMD #endif #if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) #define STBI_SSE2 #include <emmintrin.h> #ifdef _MSC_VER #if _MSC_VER >= 1400 // not VC6 #include <intrin.h> // __cpuid static int stbi__cpuid3(void) { int info[4]; __cpuid(info,1); return info[3]; } #else static int stbi__cpuid3(void) { int res; __asm { mov eax,1 cpuid mov res,edx } return res; } #endif #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { int info3 = stbi__cpuid3(); return ((info3 >> 26) & 1) != 0; } #endif #else // assume GCC-style if not VC++ #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) static int stbi__sse2_available(void) { // If we're even attempting to compile this on GCC/Clang, that means // -msse2 is on, which means the compiler is allowed to use SSE2 // instructions at will, and so are we. return 1; } #endif #endif #endif // ARM NEON #if defined(STBI_NO_SIMD) && defined(STBI_NEON) #undef STBI_NEON #endif #ifdef STBI_NEON #include <arm_neon.h> // assume GCC or Clang on ARM targets #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) #endif #ifndef STBI_SIMD_ALIGN #define STBI_SIMD_ALIGN(type, name) type name #endif #ifndef STBI_MAX_DIMENSIONS #define STBI_MAX_DIMENSIONS (1 << 24) #endif /////////////////////////////////////////////// // // stbi__context struct and start_xxx functions // stbi__context structure is our basic context used by all images, so it // contains all the IO context, plus some basic image information typedef struct { stbi__uint32 img_x, img_y; int img_n, img_out_n; stbi_io_callbacks io; void *io_user_data; int read_from_callbacks; int buflen; stbi_uc buffer_start[128]; int callback_already_read; stbi_uc *img_buffer, *img_buffer_end; stbi_uc *img_buffer_original, *img_buffer_original_end; } stbi__context; static void stbi__refill_buffer(stbi__context *s); // initialize a memory-decode context static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) { s->io.read = NULL; s->read_from_callbacks = 0; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; } // initialize a callback-based context static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) { s->io = *c; s->io_user_data = user; s->buflen = sizeof(s->buffer_start); s->read_from_callbacks = 1; s->callback_already_read = 0; s->img_buffer = s->img_buffer_original = s->buffer_start; stbi__refill_buffer(s); s->img_buffer_original_end = s->img_buffer_end; } #ifndef STBI_NO_STDIO static int stbi__stdio_read(void *user, char *data, int size) { return (int) fread(data,1,size,(FILE*) user); } static void stbi__stdio_skip(void *user, int n) { int ch; fseek((FILE*) user, n, SEEK_CUR); ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ if (ch != EOF) { ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ } } static int stbi__stdio_eof(void *user) { return feof((FILE*) user) || ferror((FILE *) user); } static stbi_io_callbacks stbi__stdio_callbacks = { stbi__stdio_read, stbi__stdio_skip, stbi__stdio_eof, }; static void stbi__start_file(stbi__context *s, FILE *f) { stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); } //static void stop_file(stbi__context *s) { } #endif // !STBI_NO_STDIO static void stbi__rewind(stbi__context *s) { // conceptually rewind SHOULD rewind to the beginning of the stream, // but we just rewind to the beginning of the initial buffer, because // we only use it after doing 'test', which only ever looks at at most 92 bytes s->img_buffer = s->img_buffer_original; s->img_buffer_end = s->img_buffer_original_end; } enum { STBI_ORDER_RGB, STBI_ORDER_BGR }; typedef struct { int bits_per_channel; int num_channels; int channel_order; } stbi__result_info; #ifndef STBI_NO_JPEG static int stbi__jpeg_test(stbi__context *s); static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNG static int stbi__png_test(stbi__context *s); static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__png_is16(stbi__context *s); #endif #ifndef STBI_NO_BMP static int stbi__bmp_test(stbi__context *s); static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_TGA static int stbi__tga_test(stbi__context *s); static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s); static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); static int stbi__psd_is16(stbi__context *s); #endif #ifndef STBI_NO_HDR static int stbi__hdr_test(stbi__context *s); static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PIC static int stbi__pic_test(stbi__context *s); static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_GIF static int stbi__gif_test(stbi__context *s); static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); #endif #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s); static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); #endif static #ifdef STBI_THREAD_LOCAL STBI_THREAD_LOCAL #endif const char *stbi__g_failure_reason; STBIDEF const char *stbi_failure_reason(void) { return stbi__g_failure_reason; } #ifndef STBI_NO_FAILURE_STRINGS static int stbi__err(const char *str) { stbi__g_failure_reason = str; return 0; } #endif static void *stbi__malloc(size_t size) { return STBI_MALLOC(size); } // stb_image uses ints pervasively, including for offset calculations. // therefore the largest decoded image size we can support with the // current code, even on 64-bit targets, is INT_MAX. this is not a // significant limitation for the intended use case. // // we do, however, need to make sure our size calculations don't // overflow. hence a few helper functions for size calculations that // multiply integers together, making sure that they're non-negative // and no overflow occurs. // return 1 if the sum is valid, 0 on overflow. // negative terms are considered invalid. static int stbi__addsizes_valid(int a, int b) { if (b < 0) return 0; // now 0 <= b <= INT_MAX, hence also // 0 <= INT_MAX - b <= INTMAX. // And "a + b <= INT_MAX" (which might overflow) is the // same as a <= INT_MAX - b (no overflow) return a <= INT_MAX - b; } // returns 1 if the product is valid, 0 on overflow. // negative factors are considered invalid. static int stbi__mul2sizes_valid(int a, int b) { if (a < 0 || b < 0) return 0; if (b == 0) return 1; // mul-by-0 is always safe // portable way to check for no overflows in a*b return a <= INT_MAX/b; } #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow static int stbi__mad2sizes_valid(int a, int b, int add) { return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); } #endif // returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow static int stbi__mad3sizes_valid(int a, int b, int c, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__addsizes_valid(a*b*c, add); } // returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) { return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); } #endif #if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) // mallocs with size overflow checking static void *stbi__malloc_mad2(int a, int b, int add) { if (!stbi__mad2sizes_valid(a, b, add)) return NULL; return stbi__malloc(a*b + add); } #endif static void *stbi__malloc_mad3(int a, int b, int c, int add) { if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; return stbi__malloc(a*b*c + add); } #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) { if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; return stbi__malloc(a*b*c*d + add); } #endif // stbi__err - error // stbi__errpf - error returning pointer to float // stbi__errpuc - error returning pointer to unsigned char #ifdef STBI_NO_FAILURE_STRINGS #define stbi__err(x,y) 0 #elif defined(STBI_FAILURE_USERMSG) #define stbi__err(x,y) stbi__err(y) #else #define stbi__err(x,y) stbi__err(x) #endif #define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) #define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) STBIDEF void stbi_image_free(void *retval_from_stbi_load) { STBI_FREE(retval_from_stbi_load); } #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); #endif #ifndef STBI_NO_HDR static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); #endif static int stbi__vertically_flip_on_load_global = 0; STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_global = flag_true_if_should_flip; } #ifndef STBI_THREAD_LOCAL #define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global #else static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) { stbi__vertically_flip_on_load_local = flag_true_if_should_flip; stbi__vertically_flip_on_load_set = 1; } #define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ ? stbi__vertically_flip_on_load_local \ : stbi__vertically_flip_on_load_global) #endif // STBI_THREAD_LOCAL static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order ri->num_channels = 0; #ifndef STBI_NO_JPEG if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNG if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_BMP if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_GIF if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PSD if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); #else STBI_NOTUSED(bpc); #endif #ifndef STBI_NO_PIC if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_PNM if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); #endif #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); } #endif #ifndef STBI_NO_TGA // test tga last because it's a crappy test! if (stbi__tga_test(s)) return stbi__tga_load(s,x,y,comp,req_comp, ri); #endif return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); } static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi_uc *reduced; reduced = (stbi_uc *) stbi__malloc(img_len); if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling STBI_FREE(orig); return reduced; } static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) { int i; int img_len = w * h * channels; stbi__uint16 *enlarged; enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); for (i = 0; i < img_len; ++i) enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff STBI_FREE(orig); return enlarged; } static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) { int row; size_t bytes_per_row = (size_t)w * bytes_per_pixel; stbi_uc temp[2048]; stbi_uc *bytes = (stbi_uc *)image; for (row = 0; row < (h>>1); row++) { stbi_uc *row0 = bytes + row*bytes_per_row; stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; // swap row0 with row1 size_t bytes_left = bytes_per_row; while (bytes_left) { size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); memcpy(temp, row0, bytes_copy); memcpy(row0, row1, bytes_copy); memcpy(row1, temp, bytes_copy); row0 += bytes_copy; row1 += bytes_copy; bytes_left -= bytes_copy; } } } #ifndef STBI_NO_GIF static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) { int slice; int slice_size = w * h * bytes_per_pixel; stbi_uc *bytes = (stbi_uc *)image; for (slice = 0; slice < z; ++slice) { stbi__vertical_flip(bytes, w, h, bytes_per_pixel); bytes += slice_size; } } #endif static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 8) { result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 8; } // @TODO: move stbi__convert_format to here if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); } return (unsigned char *) result; } static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) { stbi__result_info ri; void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); if (result == NULL) return NULL; // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); if (ri.bits_per_channel != 16) { result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); ri.bits_per_channel = 16; } // @TODO: move stbi__convert_format16 to here // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision if (stbi__vertically_flip_on_load) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); } return (stbi__uint16 *) result; } #if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) { if (stbi__vertically_flip_on_load && result != NULL) { int channels = req_comp ? req_comp : *comp; stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); } } #endif #ifndef STBI_NO_STDIO #if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); #endif #if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) { return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); } #endif static FILE *stbi__fopen(char const *filename, char const *mode) { FILE *f; #if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8) wchar_t wMode[64]; wchar_t wFilename[1024]; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename))) return 0; if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode))) return 0; #if _MSC_VER >= 1400 if (0 != _wfopen_s(&f, wFilename, wMode)) f = 0; #else f = _wfopen(wFilename, wMode); #endif #elif defined(_MSC_VER) && _MSC_VER >= 1400 if (0 != fopen_s(&f, filename, mode)) f=0; #else f = fopen(filename, mode); #endif return f; } STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); unsigned char *result; if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__uint16 *result; stbi__context s; stbi__start_file(&s,f); result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); if (result) { // need to 'unget' all the characters in the IO buffer fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); } return result; } STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) { FILE *f = stbi__fopen(filename, "rb"); stbi__uint16 *result; if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); result = stbi_load_from_file_16(f,x,y,comp,req_comp); fclose(f); return result; } #endif //!STBI_NO_STDIO STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); } STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); } #ifndef STBI_NO_GIF STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { unsigned char *result; stbi__context s; stbi__start_mem(&s,buffer,len); result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); if (stbi__vertically_flip_on_load) { stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); } return result; } #endif #ifndef STBI_NO_LINEAR static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) { unsigned char *data; #ifndef STBI_NO_HDR if (stbi__hdr_test(s)) { stbi__result_info ri; float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); if (hdr_data) stbi__float_postprocess(hdr_data,x,y,comp,req_comp); return hdr_data; } #endif data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); if (data) return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); } STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__loadf_main(&s,x,y,comp,req_comp); } STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__loadf_main(&s,x,y,comp,req_comp); } #ifndef STBI_NO_STDIO STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) { float *result; FILE *f = stbi__fopen(filename, "rb"); if (!f) return stbi__errpf("can't fopen", "Unable to open file"); result = stbi_loadf_from_file(f,x,y,comp,req_comp); fclose(f); return result; } STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) { stbi__context s; stbi__start_file(&s,f); return stbi__loadf_main(&s,x,y,comp,req_comp); } #endif // !STBI_NO_STDIO #endif // !STBI_NO_LINEAR // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always // reports false! STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__hdr_test(&s); #else STBI_NOTUSED(buffer); STBI_NOTUSED(len); return 0; #endif } #ifndef STBI_NO_STDIO STBIDEF int stbi_is_hdr (char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result=0; if (f) { result = stbi_is_hdr_from_file(f); fclose(f); } return result; } STBIDEF int stbi_is_hdr_from_file(FILE *f) { #ifndef STBI_NO_HDR long pos = ftell(f); int res; stbi__context s; stbi__start_file(&s,f); res = stbi__hdr_test(&s); fseek(f, pos, SEEK_SET); return res; #else STBI_NOTUSED(f); return 0; #endif } #endif // !STBI_NO_STDIO STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) { #ifndef STBI_NO_HDR stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); return stbi__hdr_test(&s); #else STBI_NOTUSED(clbk); STBI_NOTUSED(user); return 0; #endif } #ifndef STBI_NO_LINEAR static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } #endif static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } ////////////////////////////////////////////////////////////////////////////// // // Common code used by all image loaders // enum { STBI__SCAN_load=0, STBI__SCAN_type, STBI__SCAN_header }; static void stbi__refill_buffer(stbi__context *s) { int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); if (n == 0) { // at end of file, treat same as if from memory, but need to handle case // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file s->read_from_callbacks = 0; s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start+1; *s->img_buffer = 0; } else { s->img_buffer = s->buffer_start; s->img_buffer_end = s->buffer_start + n; } } stbi_inline static stbi_uc stbi__get8(stbi__context *s) { if (s->img_buffer < s->img_buffer_end) return *s->img_buffer++; if (s->read_from_callbacks) { stbi__refill_buffer(s); return *s->img_buffer++; } return 0; } #if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else stbi_inline static int stbi__at_eof(stbi__context *s) { if (s->io.read) { if (!(s->io.eof)(s->io_user_data)) return 0; // if feof() is true, check if buffer = end // special case: we've only got the special 0 character at the end if (s->read_from_callbacks == 0) return 1; } return s->img_buffer >= s->img_buffer_end; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) // nothing #else static void stbi__skip(stbi__context *s, int n) { if (n == 0) return; // already there! if (n < 0) { s->img_buffer = s->img_buffer_end; return; } if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { s->img_buffer = s->img_buffer_end; (s->io.skip)(s->io_user_data, n - blen); return; } } s->img_buffer += n; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) // nothing #else static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) { if (s->io.read) { int blen = (int) (s->img_buffer_end - s->img_buffer); if (blen < n) { int res, count; memcpy(buffer, s->img_buffer, blen); count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); res = (count == (n-blen)); s->img_buffer = s->img_buffer_end; return res; } } if (s->img_buffer+n <= s->img_buffer_end) { memcpy(buffer, s->img_buffer, n); s->img_buffer += n; return 1; } else return 0; } #endif #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static int stbi__get16be(stbi__context *s) { int z = stbi__get8(s); return (z << 8) + stbi__get8(s); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) // nothing #else static stbi__uint32 stbi__get32be(stbi__context *s) { stbi__uint32 z = stbi__get16be(s); return (z << 16) + stbi__get16be(s); } #endif #if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) // nothing #else static int stbi__get16le(stbi__context *s) { int z = stbi__get8(s); return z + (stbi__get8(s) << 8); } #endif #ifndef STBI_NO_BMP static stbi__uint32 stbi__get32le(stbi__context *s) { stbi__uint32 z = stbi__get16le(s); return z + (stbi__get16le(s) << 16); } #endif #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings #if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else ////////////////////////////////////////////////////////////////////////////// // // generic converter from built-in img_n to req_comp // individual types do this automatically as much as possible (e.g. jpeg // does all cases internally since it needs to colorspace convert anyway, // and it never has alpha, so very few cases ). png can automatically // interleave an alpha=255 channel, but falls back to this for other cases // // assume data buffer is malloced, so malloc a new one and free that one // only failure mode is malloc failing static stbi_uc stbi__compute_y(int r, int g, int b) { return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) // nothing #else static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; unsigned char *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); if (good == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { unsigned char *src = data + j * x * img_n ; unsigned char *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 stbi__compute_y_16(int r, int g, int b) { return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); } #endif #if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) // nothing #else static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) { int i,j; stbi__uint16 *good; if (req_comp == img_n) return data; STBI_ASSERT(req_comp >= 1 && req_comp <= 4); good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); if (good == NULL) { STBI_FREE(data); return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); } for (j=0; j < (int) y; ++j) { stbi__uint16 *src = data + j * x * img_n ; stbi__uint16 *dest = good + j * x * req_comp; #define STBI__COMBO(a,b) ((a)*8+(b)) #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) // convert source image with img_n components to one with req_comp components; // avoid switch per pixel, so use switch per scanline and massive macros switch (STBI__COMBO(img_n, req_comp)) { STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; STBI__CASE(2,1) { dest[0]=src[0]; } break; STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); } #undef STBI__CASE } STBI_FREE(data); return good; } #endif #ifndef STBI_NO_LINEAR static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) { int i,k,n; float *output; if (!data) return NULL; output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); } } if (n < comp) { for (i=0; i < x*y; ++i) { output[i*comp + n] = data[i*comp + n]/255.0f; } } STBI_FREE(data); return output; } #endif #ifndef STBI_NO_HDR #define stbi__float2int(x) ((int) (x)) static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) { int i,k,n; stbi_uc *output; if (!data) return NULL; output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } // compute number of non-alpha components if (comp & 1) n = comp; else n = comp-1; for (i=0; i < x*y; ++i) { for (k=0; k < n; ++k) { float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } if (k < comp) { float z = data[i*comp+k] * 255 + 0.5f; if (z < 0) z = 0; if (z > 255) z = 255; output[i*comp + k] = (stbi_uc) stbi__float2int(z); } } STBI_FREE(data); return output; } #endif ////////////////////////////////////////////////////////////////////////////// // // "baseline" JPEG/JFIF decoder // // simple implementation // - doesn't support delayed output of y-dimension // - simple interface (only one output format: 8-bit interleaved RGB) // - doesn't try to recover corrupt jpegs // - doesn't allow partial loading, loading multiple at once // - still fast on x86 (copying globals into locals doesn't help x86) // - allocates lots of intermediate memory (full size of all components) // - non-interleaved case requires this anyway // - allows good upsampling (see next) // high-quality // - upsampled channels are bilinearly interpolated, even across blocks // - quality integer IDCT derived from IJG's 'slow' // performance // - fast huffman; reasonable integer IDCT // - some SIMD kernels for common paths on targets with SSE2/NEON // - uses a lot of intermediate memory, could cache poorly #ifndef STBI_NO_JPEG // huffman decoding acceleration #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache typedef struct { stbi_uc fast[1 << FAST_BITS]; // weirdly, repacking this into AoS is a 10% speed loss, instead of a win stbi__uint16 code[256]; stbi_uc values[256]; stbi_uc size[257]; unsigned int maxcode[18]; int delta[17]; // old 'firstsymbol' - old 'firstcode' } stbi__huffman; typedef struct { stbi__context *s; stbi__huffman huff_dc[4]; stbi__huffman huff_ac[4]; stbi__uint16 dequant[4][64]; stbi__int16 fast_ac[4][1 << FAST_BITS]; // sizes for components, interleaved MCUs int img_h_max, img_v_max; int img_mcu_x, img_mcu_y; int img_mcu_w, img_mcu_h; // definition of jpeg image component struct { int id; int h,v; int tq; int hd,ha; int dc_pred; int x,y,w2,h2; stbi_uc *data; void *raw_data, *raw_coeff; stbi_uc *linebuf; short *coeff; // progressive only int coeff_w, coeff_h; // number of 8x8 coefficient blocks } img_comp[4]; stbi__uint32 code_buffer; // jpeg entropy-coded buffer int code_bits; // number of valid bits unsigned char marker; // marker seen while filling entropy buffer int nomore; // flag if we saw a marker so must stop int progressive; int spec_start; int spec_end; int succ_high; int succ_low; int eob_run; int jfif; int app14_color_transform; // Adobe APP14 tag int rgb; int scan_n, order[4]; int restart_interval, todo; // kernels void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); } stbi__jpeg; static int stbi__build_huffman(stbi__huffman *h, int *count) { int i,j,k=0; unsigned int code; // build size list for each symbol (from JPEG spec) for (i=0; i < 16; ++i) for (j=0; j < count[i]; ++j) h->size[k++] = (stbi_uc) (i+1); h->size[k] = 0; // compute actual symbols (from jpeg spec) code = 0; k = 0; for(j=1; j <= 16; ++j) { // compute delta to add to code to compute symbol id h->delta[j] = k - code; if (h->size[k] == j) { while (h->size[k] == j) h->code[k++] = (stbi__uint16) (code++); if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); } // compute largest code + 1 for this size, preshifted as needed later h->maxcode[j] = code << (16-j); code <<= 1; } h->maxcode[j] = 0xffffffff; // build non-spec acceleration table; 255 is flag for not-accelerated memset(h->fast, 255, 1 << FAST_BITS); for (i=0; i < k; ++i) { int s = h->size[i]; if (s <= FAST_BITS) { int c = h->code[i] << (FAST_BITS-s); int m = 1 << (FAST_BITS-s); for (j=0; j < m; ++j) { h->fast[c+j] = (stbi_uc) i; } } } return 1; } // build a table that decodes both magnitude and value of small ACs in // one go. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) { int i; for (i=0; i < (1 << FAST_BITS); ++i) { stbi_uc fast = h->fast[i]; fast_ac[i] = 0; if (fast < 255) { int rs = h->values[fast]; int run = (rs >> 4) & 15; int magbits = rs & 15; int len = h->size[fast]; if (magbits && len + magbits <= FAST_BITS) { // magnitude code followed by receive_extend code int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); int m = 1 << (magbits - 1); if (k < m) k += (~0U << magbits) + 1; // if the result is small enough, we can fit it in fast_ac table if (k >= -128 && k <= 127) fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); } } } } static void stbi__grow_buffer_unsafe(stbi__jpeg *j) { do { unsigned int b = j->nomore ? 0 : stbi__get8(j->s); if (b == 0xff) { int c = stbi__get8(j->s); while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes if (c != 0) { j->marker = (unsigned char) c; j->nomore = 1; return; } } j->code_buffer |= b << (24 - j->code_bits); j->code_bits += 8; } while (j->code_bits <= 24); } // (1 << n) - 1 static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; // decode a jpeg huffman value from the bitstream stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) { unsigned int temp; int c,k; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); // look at the top FAST_BITS and determine what symbol ID it is, // if the code is <= FAST_BITS c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); k = h->fast[c]; if (k < 255) { int s = h->size[k]; if (s > j->code_bits) return -1; j->code_buffer <<= s; j->code_bits -= s; return h->values[k]; } // naive test is to shift the code_buffer down so k bits are // valid, then test against maxcode. To speed this up, we've // preshifted maxcode left so that it has (16-k) 0s at the // end; in other words, regardless of the number of bits, it // wants to be compared against something shifted to have 16; // that way we don't need to shift inside the loop. temp = j->code_buffer >> 16; for (k=FAST_BITS+1 ; ; ++k) if (temp < h->maxcode[k]) break; if (k == 17) { // error! code not found j->code_bits -= 16; return -1; } if (k > j->code_bits) return -1; // convert the huffman code to the symbol id c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); // convert the id to a symbol j->code_bits -= k; j->code_buffer <<= k; return h->values[c]; } // bias[n] = (-1<<n) + 1 static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767}; // combined JPEG 'receive' and JPEG 'extend', since baseline // always extends everything it receives. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n) { unsigned int k; int sgn; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB k = stbi_lrot(j->code_buffer, n); if (n < 0 || n >= (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))) return 0; j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k + (stbi__jbias[n] & ~sgn); } // get some unsigned bits stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) { unsigned int k; if (j->code_bits < n) stbi__grow_buffer_unsafe(j); k = stbi_lrot(j->code_buffer, n); j->code_buffer = k & ~stbi__bmask[n]; k &= stbi__bmask[n]; j->code_bits -= n; return k; } stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) { unsigned int k; if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); k = j->code_buffer; j->code_buffer <<= 1; --j->code_bits; return k & 0x80000000; } // given a value that's at position X in the zigzag stream, // where does it appear in the 8x8 matrix coded as row-major? static const stbi_uc stbi__jpeg_dezigzag[64+15] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, // let corrupt input sample past end 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63 }; // decode one 64-entry block-- static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) { int diff,dc,k; int t; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); t = stbi__jpeg_huff_decode(j, hdc); if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG"); // 0 all the ac values now so we can do it 32-bits at a time memset(data,0,64*sizeof(data[0])); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc * dequant[0]); // decode AC components, see JPEG spec k = 1; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) * dequant[zig]); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (rs != 0xf0) break; // end block k += 16; } else { k += r; // decode into unzigzag'd location zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); } } } while (k < 64); return 1; } static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) { int diff,dc; int t; if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); if (j->succ_high == 0) { // first scan for DC coefficient, must be first memset(data,0,64*sizeof(data[0])); // 0 all the ac values now t = stbi__jpeg_huff_decode(j, hdc); if (t == -1) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); diff = t ? stbi__extend_receive(j, t) : 0; dc = j->img_comp[b].dc_pred + diff; j->img_comp[b].dc_pred = dc; data[0] = (short) (dc << j->succ_low); } else { // refinement scan for DC coefficient if (stbi__jpeg_get_bit(j)) data[0] += (short) (1 << j->succ_low); } return 1; } // @OPTIMIZE: store non-zigzagged during the decode passes, // and only de-zigzag when dequantizing static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) { int k; if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); if (j->succ_high == 0) { int shift = j->succ_low; if (j->eob_run) { --j->eob_run; return 1; } k = j->spec_start; do { unsigned int zig; int c,r,s; if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); r = fac[c]; if (r) { // fast-AC path k += (r >> 4) & 15; // run s = r & 15; // combined length j->code_buffer <<= s; j->code_bits -= s; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) ((r >> 8) << shift); } else { int rs = stbi__jpeg_huff_decode(j, hac); if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r); if (r) j->eob_run += stbi__jpeg_get_bits(j, r); --j->eob_run; break; } k += 16; } else { k += r; zig = stbi__jpeg_dezigzag[k++]; data[zig] = (short) (stbi__extend_receive(j,s) << shift); } } } while (k <= j->spec_end); } else { // refinement scan for these AC coefficients short bit = (short) (1 << j->succ_low); if (j->eob_run) { --j->eob_run; for (k = j->spec_start; k <= j->spec_end; ++k) { short *p = &data[stbi__jpeg_dezigzag[k]]; if (*p != 0) if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } } else { k = j->spec_start; do { int r,s; int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); s = rs & 15; r = rs >> 4; if (s == 0) { if (r < 15) { j->eob_run = (1 << r) - 1; if (r) j->eob_run += stbi__jpeg_get_bits(j, r); r = 64; // force end of block } else { // r=15 s=0 should write 16 0s, so we just do // a run of 15 0s and then write s (which is 0), // so we don't have to do anything special here } } else { if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); // sign bit if (stbi__jpeg_get_bit(j)) s = bit; else s = -bit; } // advance by r while (k <= j->spec_end) { short *p = &data[stbi__jpeg_dezigzag[k++]]; if (*p != 0) { if (stbi__jpeg_get_bit(j)) if ((*p & bit)==0) { if (*p > 0) *p += bit; else *p -= bit; } } else { if (r == 0) { *p = (short) s; break; } --r; } } } while (k <= j->spec_end); } } return 1; } // take a -128..127 value and stbi__clamp it and convert to 0..255 stbi_inline static stbi_uc stbi__clamp(int x) { // trick to use a single test to catch both cases if ((unsigned int) x > 255) { if (x < 0) return 0; if (x > 255) return 255; } return (stbi_uc) x; } #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) #define stbi__fsh(x) ((x) * 4096) // derived from jidctint -- DCT_ISLOW #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ p2 = s2; \ p3 = s6; \ p1 = (p2+p3) * stbi__f2f(0.5411961f); \ t2 = p1 + p3*stbi__f2f(-1.847759065f); \ t3 = p1 + p2*stbi__f2f( 0.765366865f); \ p2 = s0; \ p3 = s4; \ t0 = stbi__fsh(p2+p3); \ t1 = stbi__fsh(p2-p3); \ x0 = t0+t3; \ x3 = t0-t3; \ x1 = t1+t2; \ x2 = t1-t2; \ t0 = s7; \ t1 = s5; \ t2 = s3; \ t3 = s1; \ p3 = t0+t2; \ p4 = t1+t3; \ p1 = t0+t3; \ p2 = t1+t2; \ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ t0 = t0*stbi__f2f( 0.298631336f); \ t1 = t1*stbi__f2f( 2.053119869f); \ t2 = t2*stbi__f2f( 3.072711026f); \ t3 = t3*stbi__f2f( 1.501321110f); \ p1 = p5 + p1*stbi__f2f(-0.899976223f); \ p2 = p5 + p2*stbi__f2f(-2.562915447f); \ p3 = p3*stbi__f2f(-1.961570560f); \ p4 = p4*stbi__f2f(-0.390180644f); \ t3 += p1+p4; \ t2 += p2+p3; \ t1 += p2+p4; \ t0 += p1+p3; static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) { int i,val[64],*v=val; stbi_uc *o; short *d = data; // columns for (i=0; i < 8; ++i,++d, ++v) { // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 && d[40]==0 && d[48]==0 && d[56]==0) { // no shortcut 0 seconds // (1|2|3|4|5|6|7)==0 0 seconds // all separate -0.047 seconds // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds int dcterm = d[0]*4; v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; } else { STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) // constants scaled things up by 1<<12; let's bring them back // down, but keep 2 extra bits of precision x0 += 512; x1 += 512; x2 += 512; x3 += 512; v[ 0] = (x0+t3) >> 10; v[56] = (x0-t3) >> 10; v[ 8] = (x1+t2) >> 10; v[48] = (x1-t2) >> 10; v[16] = (x2+t1) >> 10; v[40] = (x2-t1) >> 10; v[24] = (x3+t0) >> 10; v[32] = (x3-t0) >> 10; } } for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { // no fast case since the first 1D IDCT spread components out STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) // constants scaled things up by 1<<12, plus we had 1<<2 from first // loop, plus horizontal and vertical each scale by sqrt(8) so together // we've got an extra 1<<3, so 1<<17 total we need to remove. // so we want to round that, which means adding 0.5 * 1<<17, // aka 65536. Also, we'll end up with -128 to 127 that we want // to encode as 0..255 by adding 128, so we'll add that before the shift x0 += 65536 + (128<<17); x1 += 65536 + (128<<17); x2 += 65536 + (128<<17); x3 += 65536 + (128<<17); // tried computing the shifts into temps, or'ing the temps to see // if any were out of range, but that was slower o[0] = stbi__clamp((x0+t3) >> 17); o[7] = stbi__clamp((x0-t3) >> 17); o[1] = stbi__clamp((x1+t2) >> 17); o[6] = stbi__clamp((x1-t2) >> 17); o[2] = stbi__clamp((x2+t1) >> 17); o[5] = stbi__clamp((x2-t1) >> 17); o[3] = stbi__clamp((x3+t0) >> 17); o[4] = stbi__clamp((x3-t0) >> 17); } } #ifdef STBI_SSE2 // sse2 integer IDCT. not the fastest possible implementation but it // produces bit-identical results to the generic C version so it's // fully "transparent". static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { // This is constructed to match our regular (generic) integer IDCT exactly. __m128i row0, row1, row2, row3, row4, row5, row6, row7; __m128i tmp; // dot product constant: even elems=x, odd elems=y #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) // out(1) = c1[even]*x + c1[odd]*y #define dct_rot(out0,out1, x,y,c0,c1) \ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) // out = in << 12 (in 16-bit, out 32-bit) #define dct_widen(out, in) \ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) // wide add #define dct_wadd(out, a, b) \ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_add_epi32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) // butterfly a/b, add bias, then shift by "s" and pack #define dct_bfly32o(out0, out1, a,b,bias,s) \ { \ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ dct_wadd(sum, abiased, b); \ dct_wsub(dif, abiased, b); \ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ } // 8-bit interleave step (for transposes) #define dct_interleave8(a, b) \ tmp = a; \ a = _mm_unpacklo_epi8(a, b); \ b = _mm_unpackhi_epi8(tmp, b) // 16-bit interleave step (for transposes) #define dct_interleave16(a, b) \ tmp = a; \ a = _mm_unpacklo_epi16(a, b); \ b = _mm_unpackhi_epi16(tmp, b) #define dct_pass(bias,shift) \ { \ /* even part */ \ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ __m128i sum04 = _mm_add_epi16(row0, row4); \ __m128i dif04 = _mm_sub_epi16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ __m128i sum17 = _mm_add_epi16(row1, row7); \ __m128i sum35 = _mm_add_epi16(row3, row5); \ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ dct_wadd(x4, y0o, y4o); \ dct_wadd(x5, y1o, y5o); \ dct_wadd(x6, y2o, y5o); \ dct_wadd(x7, y3o, y4o); \ dct_bfly32o(row0,row7, x0,x7,bias,shift); \ dct_bfly32o(row1,row6, x1,x6,bias,shift); \ dct_bfly32o(row2,row5, x2,x5,bias,shift); \ dct_bfly32o(row3,row4, x3,x4,bias,shift); \ } __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); // rounding biases in column/row passes, see stbi__idct_block for explanation. __m128i bias_0 = _mm_set1_epi32(512); __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); // load row0 = _mm_load_si128((const __m128i *) (data + 0*8)); row1 = _mm_load_si128((const __m128i *) (data + 1*8)); row2 = _mm_load_si128((const __m128i *) (data + 2*8)); row3 = _mm_load_si128((const __m128i *) (data + 3*8)); row4 = _mm_load_si128((const __m128i *) (data + 4*8)); row5 = _mm_load_si128((const __m128i *) (data + 5*8)); row6 = _mm_load_si128((const __m128i *) (data + 6*8)); row7 = _mm_load_si128((const __m128i *) (data + 7*8)); // column pass dct_pass(bias_0, 10); { // 16bit 8x8 transpose pass 1 dct_interleave16(row0, row4); dct_interleave16(row1, row5); dct_interleave16(row2, row6); dct_interleave16(row3, row7); // transpose pass 2 dct_interleave16(row0, row2); dct_interleave16(row1, row3); dct_interleave16(row4, row6); dct_interleave16(row5, row7); // transpose pass 3 dct_interleave16(row0, row1); dct_interleave16(row2, row3); dct_interleave16(row4, row5); dct_interleave16(row6, row7); } // row pass dct_pass(bias_1, 17); { // pack __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 __m128i p1 = _mm_packus_epi16(row2, row3); __m128i p2 = _mm_packus_epi16(row4, row5); __m128i p3 = _mm_packus_epi16(row6, row7); // 8bit 8x8 transpose pass 1 dct_interleave8(p0, p2); // a0e0a1e1... dct_interleave8(p1, p3); // c0g0c1g1... // transpose pass 2 dct_interleave8(p0, p1); // a0c0e0g0... dct_interleave8(p2, p3); // b0d0f0h0... // transpose pass 3 dct_interleave8(p0, p2); // a0b0c0d0... dct_interleave8(p1, p3); // a4b4c4d4... // store _mm_storel_epi64((__m128i *) out, p0); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p2); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p1); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; _mm_storel_epi64((__m128i *) out, p3); out += out_stride; _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); } #undef dct_const #undef dct_rot #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_interleave8 #undef dct_interleave16 #undef dct_pass } #endif // STBI_SSE2 #ifdef STBI_NEON // NEON integer IDCT. should produce bit-identical // results to the generic C version. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) { int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); #define dct_long_mul(out, inq, coeff) \ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) #define dct_long_mac(out, acc, inq, coeff) \ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) #define dct_widen(out, inq) \ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) // wide add #define dct_wadd(out, a, b) \ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ int32x4_t out##_h = vaddq_s32(a##_h, b##_h) // wide sub #define dct_wsub(out, a, b) \ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ int32x4_t out##_h = vsubq_s32(a##_h, b##_h) // butterfly a/b, then shift using "shiftop" by "s" and pack #define dct_bfly32o(out0,out1, a,b,shiftop,s) \ { \ dct_wadd(sum, a, b); \ dct_wsub(dif, a, b); \ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ } #define dct_pass(shiftop, shift) \ { \ /* even part */ \ int16x8_t sum26 = vaddq_s16(row2, row6); \ dct_long_mul(p1e, sum26, rot0_0); \ dct_long_mac(t2e, p1e, row6, rot0_1); \ dct_long_mac(t3e, p1e, row2, rot0_2); \ int16x8_t sum04 = vaddq_s16(row0, row4); \ int16x8_t dif04 = vsubq_s16(row0, row4); \ dct_widen(t0e, sum04); \ dct_widen(t1e, dif04); \ dct_wadd(x0, t0e, t3e); \ dct_wsub(x3, t0e, t3e); \ dct_wadd(x1, t1e, t2e); \ dct_wsub(x2, t1e, t2e); \ /* odd part */ \ int16x8_t sum15 = vaddq_s16(row1, row5); \ int16x8_t sum17 = vaddq_s16(row1, row7); \ int16x8_t sum35 = vaddq_s16(row3, row5); \ int16x8_t sum37 = vaddq_s16(row3, row7); \ int16x8_t sumodd = vaddq_s16(sum17, sum35); \ dct_long_mul(p5o, sumodd, rot1_0); \ dct_long_mac(p1o, p5o, sum17, rot1_1); \ dct_long_mac(p2o, p5o, sum35, rot1_2); \ dct_long_mul(p3o, sum37, rot2_0); \ dct_long_mul(p4o, sum15, rot2_1); \ dct_wadd(sump13o, p1o, p3o); \ dct_wadd(sump24o, p2o, p4o); \ dct_wadd(sump23o, p2o, p3o); \ dct_wadd(sump14o, p1o, p4o); \ dct_long_mac(x4, sump13o, row7, rot3_0); \ dct_long_mac(x5, sump24o, row5, rot3_1); \ dct_long_mac(x6, sump23o, row3, rot3_2); \ dct_long_mac(x7, sump14o, row1, rot3_3); \ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ } // load row0 = vld1q_s16(data + 0*8); row1 = vld1q_s16(data + 1*8); row2 = vld1q_s16(data + 2*8); row3 = vld1q_s16(data + 3*8); row4 = vld1q_s16(data + 4*8); row5 = vld1q_s16(data + 5*8); row6 = vld1q_s16(data + 6*8); row7 = vld1q_s16(data + 7*8); // add DC bias row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); // column pass dct_pass(vrshrn_n_s32, 10); // 16bit 8x8 transpose { // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. // whether compilers actually get this is another story, sadly. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } // pass 1 dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 dct_trn16(row2, row3); dct_trn16(row4, row5); dct_trn16(row6, row7); // pass 2 dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 dct_trn32(row1, row3); dct_trn32(row4, row6); dct_trn32(row5, row7); // pass 3 dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 dct_trn64(row1, row5); dct_trn64(row2, row6); dct_trn64(row3, row7); #undef dct_trn16 #undef dct_trn32 #undef dct_trn64 } // row pass // vrshrn_n_s32 only supports shifts up to 16, we need // 17. so do a non-rounding shift of 16 first then follow // up with a rounding shift by 1. dct_pass(vshrn_n_s32, 16); { // pack and round uint8x8_t p0 = vqrshrun_n_s16(row0, 1); uint8x8_t p1 = vqrshrun_n_s16(row1, 1); uint8x8_t p2 = vqrshrun_n_s16(row2, 1); uint8x8_t p3 = vqrshrun_n_s16(row3, 1); uint8x8_t p4 = vqrshrun_n_s16(row4, 1); uint8x8_t p5 = vqrshrun_n_s16(row5, 1); uint8x8_t p6 = vqrshrun_n_s16(row6, 1); uint8x8_t p7 = vqrshrun_n_s16(row7, 1); // again, these can translate into one instruction, but often don't. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } // sadly can't use interleaved stores here since we only write // 8 bytes to each scan line! // 8x8 8-bit transpose pass 1 dct_trn8_8(p0, p1); dct_trn8_8(p2, p3); dct_trn8_8(p4, p5); dct_trn8_8(p6, p7); // pass 2 dct_trn8_16(p0, p2); dct_trn8_16(p1, p3); dct_trn8_16(p4, p6); dct_trn8_16(p5, p7); // pass 3 dct_trn8_32(p0, p4); dct_trn8_32(p1, p5); dct_trn8_32(p2, p6); dct_trn8_32(p3, p7); // store vst1_u8(out, p0); out += out_stride; vst1_u8(out, p1); out += out_stride; vst1_u8(out, p2); out += out_stride; vst1_u8(out, p3); out += out_stride; vst1_u8(out, p4); out += out_stride; vst1_u8(out, p5); out += out_stride; vst1_u8(out, p6); out += out_stride; vst1_u8(out, p7); #undef dct_trn8_8 #undef dct_trn8_16 #undef dct_trn8_32 } #undef dct_long_mul #undef dct_long_mac #undef dct_widen #undef dct_wadd #undef dct_wsub #undef dct_bfly32o #undef dct_pass } #endif // STBI_NEON #define STBI__MARKER_none 0xff // if there's a pending marker from the entropy stream, return that // otherwise, fetch from the stream and get a marker. if there's no // marker, return 0xff, which is never a valid marker value static stbi_uc stbi__get_marker(stbi__jpeg *j) { stbi_uc x; if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } x = stbi__get8(j->s); if (x != 0xff) return STBI__MARKER_none; while (x == 0xff) x = stbi__get8(j->s); // consume repeated 0xff fill bytes return x; } // in each scan, we'll have scan_n components, and the order // of the components is specified by order[] #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) // after a restart interval, stbi__jpeg_reset the entropy decoder and // the dc prediction static void stbi__jpeg_reset(stbi__jpeg *j) { j->code_bits = 0; j->code_buffer = 0; j->nomore = 0; j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; j->marker = STBI__MARKER_none; j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; j->eob_run = 0; // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, // since we don't even allow 1<<30 pixels } static int stbi__parse_entropy_coded_data(stbi__jpeg *z) { stbi__jpeg_reset(z); if (!z->progressive) { if (z->scan_n == 1) { int i,j; STBI_SIMD_ALIGN(short, data[64]); int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); // if it's NOT a restart, then just bail, so we get corrupt data // rather than no data if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; STBI_SIMD_ALIGN(short, data[64]); for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x)*8; int y2 = (j*z->img_comp[n].v + y)*8; int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } else { if (z->scan_n == 1) { int i,j; int n = z->order[0]; // non-interleaved data, we just need to process one block at a time, // in trivial scanline order // number of blocks to do just depends on how many actual "pixels" this // component has, independent of interleaved MCU blocking and such int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); if (z->spec_start == 0) { if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } else { int ha = z->img_comp[n].ha; if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) return 0; } // every data block is an MCU, so countdown the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } else { // interleaved int i,j,k,x,y; for (j=0; j < z->img_mcu_y; ++j) { for (i=0; i < z->img_mcu_x; ++i) { // scan an interleaved mcu... process scan_n components in order for (k=0; k < z->scan_n; ++k) { int n = z->order[k]; // scan out an mcu's worth of this component; that's just determined // by the basic H and V specified for the component for (y=0; y < z->img_comp[n].v; ++y) { for (x=0; x < z->img_comp[n].h; ++x) { int x2 = (i*z->img_comp[n].h + x); int y2 = (j*z->img_comp[n].v + y); short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) return 0; } } } // after all interleaved components, that's an interleaved MCU, // so now count down the restart interval if (--z->todo <= 0) { if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); if (!STBI__RESTART(z->marker)) return 1; stbi__jpeg_reset(z); } } } return 1; } } } static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) { int i; for (i=0; i < 64; ++i) data[i] *= dequant[i]; } static void stbi__jpeg_finish(stbi__jpeg *z) { if (z->progressive) { // dequantize and idct the data int i,j,n; for (n=0; n < z->s->img_n; ++n) { int w = (z->img_comp[n].x+7) >> 3; int h = (z->img_comp[n].y+7) >> 3; for (j=0; j < h; ++j) { for (i=0; i < w; ++i) { short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); } } } } } static int stbi__process_marker(stbi__jpeg *z, int m) { int L; switch (m) { case STBI__MARKER_none: // no marker found return stbi__err("expected marker","Corrupt JPEG"); case 0xDD: // DRI - specify restart interval if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); z->restart_interval = stbi__get16be(z->s); return 1; case 0xDB: // DQT - define quantization table L = stbi__get16be(z->s)-2; while (L > 0) { int q = stbi__get8(z->s); int p = q >> 4, sixteen = (p != 0); int t = q & 15,i; if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); for (i=0; i < 64; ++i) z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); L -= (sixteen ? 129 : 65); } return L==0; case 0xC4: // DHT - define huffman table L = stbi__get16be(z->s)-2; while (L > 0) { stbi_uc *v; int sizes[16],i,n=0; int q = stbi__get8(z->s); int tc = q >> 4; int th = q & 15; if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); for (i=0; i < 16; ++i) { sizes[i] = stbi__get8(z->s); n += sizes[i]; } L -= 17; if (tc == 0) { if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; v = z->huff_dc[th].values; } else { if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; v = z->huff_ac[th].values; } for (i=0; i < n; ++i) v[i] = stbi__get8(z->s); if (tc != 0) stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); L -= n; } return L==0; } // check for comment block or APP blocks if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { L = stbi__get16be(z->s); if (L < 2) { if (m == 0xFE) return stbi__err("bad COM len","Corrupt JPEG"); else return stbi__err("bad APP len","Corrupt JPEG"); } L -= 2; if (m == 0xE0 && L >= 5) { // JFIF APP0 segment static const unsigned char tag[5] = {'J','F','I','F','\0'}; int ok = 1; int i; for (i=0; i < 5; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 5; if (ok) z->jfif = 1; } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; int ok = 1; int i; for (i=0; i < 6; ++i) if (stbi__get8(z->s) != tag[i]) ok = 0; L -= 6; if (ok) { stbi__get8(z->s); // version stbi__get16be(z->s); // flags0 stbi__get16be(z->s); // flags1 z->app14_color_transform = stbi__get8(z->s); // color transform L -= 6; } } stbi__skip(z->s, L); return 1; } return stbi__err("unknown marker","Corrupt JPEG"); } // after we see SOS static int stbi__process_scan_header(stbi__jpeg *z) { int i; int Ls = stbi__get16be(z->s); z->scan_n = stbi__get8(z->s); if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); for (i=0; i < z->scan_n; ++i) { int id = stbi__get8(z->s), which; int q = stbi__get8(z->s); for (which = 0; which < z->s->img_n; ++which) if (z->img_comp[which].id == id) break; if (which == z->s->img_n) return 0; // no match z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); z->order[i] = which; } { int aa; z->spec_start = stbi__get8(z->s); z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 aa = stbi__get8(z->s); z->succ_high = (aa >> 4); z->succ_low = (aa & 15); if (z->progressive) { if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) return stbi__err("bad SOS", "Corrupt JPEG"); } else { if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); z->spec_end = 63; } } return 1; } static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) { int i; for (i=0; i < ncomp; ++i) { if (z->img_comp[i].raw_data) { STBI_FREE(z->img_comp[i].raw_data); z->img_comp[i].raw_data = NULL; z->img_comp[i].data = NULL; } if (z->img_comp[i].raw_coeff) { STBI_FREE(z->img_comp[i].raw_coeff); z->img_comp[i].raw_coeff = 0; z->img_comp[i].coeff = 0; } if (z->img_comp[i].linebuf) { STBI_FREE(z->img_comp[i].linebuf); z->img_comp[i].linebuf = NULL; } } return why; } static int stbi__process_frame_header(stbi__jpeg *z, int scan) { stbi__context *s = z->s; int Lf,p,i,q, h_max=1,v_max=1,c; Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); c = stbi__get8(s); if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); s->img_n = c; for (i=0; i < c; ++i) { z->img_comp[i].data = NULL; z->img_comp[i].linebuf = NULL; } if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); z->rgb = 0; for (i=0; i < s->img_n; ++i) { static const unsigned char rgb[3] = { 'R', 'G', 'B' }; z->img_comp[i].id = stbi__get8(s); if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) ++z->rgb; q = stbi__get8(s); z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); } if (scan != STBI__SCAN_load) return 1; if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); for (i=0; i < s->img_n; ++i) { if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; } // compute interleaved mcu info z->img_h_max = h_max; z->img_v_max = v_max; z->img_mcu_w = h_max * 8; z->img_mcu_h = v_max * 8; // these sizes can't be more than 17 bits z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; for (i=0; i < s->img_n; ++i) { // number of effective pixels (e.g. for non-interleaved MCU) z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; // to simplify generation, we'll allocate enough memory to decode // the bogus oversized data from using interleaved MCUs and their // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't // discard the extra data until colorspace conversion // // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) // so these muls can't overflow with 32-bit ints (which we require) z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; z->img_comp[i].coeff = 0; z->img_comp[i].raw_coeff = 0; z->img_comp[i].linebuf = NULL; z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); if (z->img_comp[i].raw_data == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); // align blocks for idct using mmx/sse z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); if (z->progressive) { // w2, h2 are multiples of 8 (see above) z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); if (z->img_comp[i].raw_coeff == NULL) return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); } } return 1; } // use comparisons since in some cases we handle more than one case (e.g. SOF) #define stbi__DNL(x) ((x) == 0xdc) #define stbi__SOI(x) ((x) == 0xd8) #define stbi__EOI(x) ((x) == 0xd9) #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) #define stbi__SOS(x) ((x) == 0xda) #define stbi__SOF_progressive(x) ((x) == 0xc2) static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) { int m; z->jfif = 0; z->app14_color_transform = -1; // valid values are 0,1,2 z->marker = STBI__MARKER_none; // initialize cached marker to empty m = stbi__get_marker(z); if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); if (scan == STBI__SCAN_type) return 1; m = stbi__get_marker(z); while (!stbi__SOF(m)) { if (!stbi__process_marker(z,m)) return 0; m = stbi__get_marker(z); while (m == STBI__MARKER_none) { // some files have extra padding after their blocks, so ok, we'll scan if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); m = stbi__get_marker(z); } } z->progressive = stbi__SOF_progressive(m); if (!stbi__process_frame_header(z, scan)) return 0; return 1; } // decode image to YCbCr format static int stbi__decode_jpeg_image(stbi__jpeg *j) { int m; for (m = 0; m < 4; m++) { j->img_comp[m].raw_data = NULL; j->img_comp[m].raw_coeff = NULL; } j->restart_interval = 0; if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; m = stbi__get_marker(j); while (!stbi__EOI(m)) { if (stbi__SOS(m)) { if (!stbi__process_scan_header(j)) return 0; if (!stbi__parse_entropy_coded_data(j)) return 0; if (j->marker == STBI__MARKER_none ) { // handle 0s at the end of image data from IP Kamera 9060 while (!stbi__at_eof(j->s)) { int x = stbi__get8(j->s); if (x == 255) { j->marker = stbi__get8(j->s); break; } } // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 } } else if (stbi__DNL(m)) { int Ld = stbi__get16be(j->s); stbi__uint32 NL = stbi__get16be(j->s); if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); } else { if (!stbi__process_marker(j, m)) return 0; } m = stbi__get_marker(j); } if (j->progressive) stbi__jpeg_finish(j); return 1; } // static jfif-centered resampling (across block boundaries) typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, int w, int hs); #define stbi__div4(x) ((stbi_uc) ((x) >> 2)) static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { STBI_NOTUSED(out); STBI_NOTUSED(in_far); STBI_NOTUSED(w); STBI_NOTUSED(hs); return in_near; } static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples vertically for every one in input int i; STBI_NOTUSED(hs); for (i=0; i < w; ++i) out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); return out; } static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate two samples horizontally for every one in input int i; stbi_uc *input = in_near; if (w == 1) { // if only one sample, can't do any interpolation out[0] = out[1] = input[0]; return out; } out[0] = input[0]; out[1] = stbi__div4(input[0]*3 + input[1] + 2); for (i=1; i < w-1; ++i) { int n = 3*input[i]+2; out[i*2+0] = stbi__div4(n+input[i-1]); out[i*2+1] = stbi__div4(n+input[i+1]); } out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); out[i*2+1] = input[w-1]; STBI_NOTUSED(in_far); STBI_NOTUSED(hs); return out; } #define stbi__div16(x) ((stbi_uc) ((x) >> 4)) static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; out[0] = stbi__div4(t1+2); for (i=1; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #if defined(STBI_SSE2) || defined(STBI_NEON) static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // need to generate 2x2 samples for every one in input int i=0,t0,t1; if (w == 1) { out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); return out; } t1 = 3*in_near[0] + in_far[0]; // process groups of 8 pixels for as long as we can. // note we can't handle the last pixel in a row in this loop // because we need to handle the filter boundary conditions. for (; i < ((w-1) & ~7); i += 8) { #if defined(STBI_SSE2) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) __m128i zero = _mm_setzero_si128(); __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); __m128i farw = _mm_unpacklo_epi8(farb, zero); __m128i nearw = _mm_unpacklo_epi8(nearb, zero); __m128i diff = _mm_sub_epi16(farw, nearw); __m128i nears = _mm_slli_epi16(nearw, 2); __m128i curr = _mm_add_epi16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. __m128i prv0 = _mm_slli_si128(curr, 2); __m128i nxt0 = _mm_srli_si128(curr, 2); __m128i prev = _mm_insert_epi16(prv0, t1, 0); __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. __m128i bias = _mm_set1_epi16(8); __m128i curs = _mm_slli_epi16(curr, 2); __m128i prvd = _mm_sub_epi16(prev, curr); __m128i nxtd = _mm_sub_epi16(next, curr); __m128i curb = _mm_add_epi16(curs, bias); __m128i even = _mm_add_epi16(prvd, curb); __m128i odd = _mm_add_epi16(nxtd, curb); // interleave even and odd pixels, then undo scaling. __m128i int0 = _mm_unpacklo_epi16(even, odd); __m128i int1 = _mm_unpackhi_epi16(even, odd); __m128i de0 = _mm_srli_epi16(int0, 4); __m128i de1 = _mm_srli_epi16(int1, 4); // pack and write output __m128i outv = _mm_packus_epi16(de0, de1); _mm_storeu_si128((__m128i *) (out + i*2), outv); #elif defined(STBI_NEON) // load and perform the vertical filtering pass // this uses 3*x + y = 4*x + (y - x) uint8x8_t farb = vld1_u8(in_far + i); uint8x8_t nearb = vld1_u8(in_near + i); int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); int16x8_t curr = vaddq_s16(nears, diff); // current row // horizontal filter works the same based on shifted vers of current // row. "prev" is current row shifted right by 1 pixel; we need to // insert the previous pixel value (from t1). // "next" is current row shifted left by 1 pixel, with first pixel // of next block of 8 pixels added in. int16x8_t prv0 = vextq_s16(curr, curr, 7); int16x8_t nxt0 = vextq_s16(curr, curr, 1); int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); // horizontal filter, polyphase implementation since it's convenient: // even pixels = 3*cur + prev = cur*4 + (prev - cur) // odd pixels = 3*cur + next = cur*4 + (next - cur) // note the shared term. int16x8_t curs = vshlq_n_s16(curr, 2); int16x8_t prvd = vsubq_s16(prev, curr); int16x8_t nxtd = vsubq_s16(next, curr); int16x8_t even = vaddq_s16(curs, prvd); int16x8_t odd = vaddq_s16(curs, nxtd); // undo scaling and round, then store with even/odd phases interleaved uint8x8x2_t o; o.val[0] = vqrshrun_n_s16(even, 4); o.val[1] = vqrshrun_n_s16(odd, 4); vst2_u8(out + i*2, o); #endif // "previous" value for next iter t1 = 3*in_near[i+7] + in_far[i+7]; } t0 = t1; t1 = 3*in_near[i] + in_far[i]; out[i*2] = stbi__div16(3*t1 + t0 + 8); for (++i; i < w; ++i) { t0 = t1; t1 = 3*in_near[i]+in_far[i]; out[i*2-1] = stbi__div16(3*t0 + t1 + 8); out[i*2 ] = stbi__div16(3*t1 + t0 + 8); } out[w*2-1] = stbi__div4(t1+2); STBI_NOTUSED(hs); return out; } #endif static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) { // resample with nearest-neighbor int i,j; STBI_NOTUSED(in_far); for (i=0; i < w; ++i) for (j=0; j < hs; ++j) out[i*hs+j] = in_near[i]; return out; } // this is a reduced-precision calculation of YCbCr-to-RGB introduced // to make sure the code produces the same results in both SIMD and scalar #define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) { int i; for (i=0; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #if defined(STBI_SSE2) || defined(STBI_NEON) static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) { int i = 0; #ifdef STBI_SSE2 // step == 3 is pretty ugly on the final interleave, and i'm not convinced // it's useful in practice (you wouldn't use it for textures, for example). // so just accelerate step == 4 case. if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. __m128i signflip = _mm_set1_epi8(-0x80); __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); __m128i xw = _mm_set1_epi16(255); // alpha channel for (; i+7 < count; i += 8) { // load __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 // unpack to short (and left-shift cr, cb by 8) __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); // color transform __m128i yws = _mm_srli_epi16(yw, 4); __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); __m128i rws = _mm_add_epi16(cr0, yws); __m128i gwt = _mm_add_epi16(cb0, yws); __m128i bws = _mm_add_epi16(yws, cb1); __m128i gws = _mm_add_epi16(gwt, cr1); // descale __m128i rw = _mm_srai_epi16(rws, 4); __m128i bw = _mm_srai_epi16(bws, 4); __m128i gw = _mm_srai_epi16(gws, 4); // back to byte, set up for transpose __m128i brb = _mm_packus_epi16(rw, bw); __m128i gxb = _mm_packus_epi16(gw, xw); // transpose to interleave channels __m128i t0 = _mm_unpacklo_epi8(brb, gxb); __m128i t1 = _mm_unpackhi_epi8(brb, gxb); __m128i o0 = _mm_unpacklo_epi16(t0, t1); __m128i o1 = _mm_unpackhi_epi16(t0, t1); // store _mm_storeu_si128((__m128i *) (out + 0), o0); _mm_storeu_si128((__m128i *) (out + 16), o1); out += 32; } } #endif #ifdef STBI_NEON // in this version, step=3 support would be easy to add. but is there demand? if (step == 4) { // this is a fairly straightforward implementation and not super-optimized. uint8x8_t signflip = vdup_n_u8(0x80); int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); for (; i+7 < count; i += 8) { // load uint8x8_t y_bytes = vld1_u8(y + i); uint8x8_t cr_bytes = vld1_u8(pcr + i); uint8x8_t cb_bytes = vld1_u8(pcb + i); int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); // expand to s16 int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); int16x8_t crw = vshll_n_s8(cr_biased, 7); int16x8_t cbw = vshll_n_s8(cb_biased, 7); // color transform int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); int16x8_t rws = vaddq_s16(yws, cr0); int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); int16x8_t bws = vaddq_s16(yws, cb1); // undo scaling, round, convert to byte uint8x8x4_t o; o.val[0] = vqrshrun_n_s16(rws, 4); o.val[1] = vqrshrun_n_s16(gws, 4); o.val[2] = vqrshrun_n_s16(bws, 4); o.val[3] = vdup_n_u8(255); // store, interleaving r/g/b/a vst4_u8(out, o); out += 8*4; } } #endif for (; i < count; ++i) { int y_fixed = (y[i] << 20) + (1<<19); // rounding int r,g,b; int cr = pcr[i] - 128; int cb = pcb[i] - 128; r = y_fixed + cr* stbi__float2fixed(1.40200f); g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); b = y_fixed + cb* stbi__float2fixed(1.77200f); r >>= 20; g >>= 20; b >>= 20; if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } out[0] = (stbi_uc)r; out[1] = (stbi_uc)g; out[2] = (stbi_uc)b; out[3] = 255; out += step; } } #endif // set up the kernels static void stbi__setup_jpeg(stbi__jpeg *j) { j->idct_block_kernel = stbi__idct_block; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; #ifdef STBI_SSE2 if (stbi__sse2_available()) { j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; } #endif #ifdef STBI_NEON j->idct_block_kernel = stbi__idct_simd; j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; #endif } // clean up the temporary component buffers static void stbi__cleanup_jpeg(stbi__jpeg *j) { stbi__free_jpeg_components(j, j->s->img_n, 0); } typedef struct { resample_row_func resample; stbi_uc *line0,*line1; int hs,vs; // expansion factor in each axis int w_lores; // horizontal pixels pre-expansion int ystep; // how far through vertical expansion we are int ypos; // which pre-expansion row we're on } stbi__resample; // fast 0..255 * 0..255 => 0..255 rounded multiplication static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) { unsigned int t = x*y + 128; return (stbi_uc) ((t + (t >>8)) >> 8); } static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) { int n, decode_n, is_rgb; z->s->img_n = 0; // make stbi__cleanup_jpeg safe // validate req_comp if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); // load a jpeg image from whichever source, but leave in YCbCr format if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } // determine actual number of components to generate n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); if (z->s->img_n == 3 && n < 3 && !is_rgb) decode_n = 1; else decode_n = z->s->img_n; // resample and color-convert { int k; unsigned int i,j; stbi_uc *output; stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; stbi__resample res_comp[4]; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; // allocate line buffer big enough for upsampling off the edges // with upsample factor of 4 z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } r->hs = z->img_h_max / z->img_comp[k].h; r->vs = z->img_v_max / z->img_comp[k].v; r->ystep = r->vs >> 1; r->w_lores = (z->s->img_x + r->hs-1) / r->hs; r->ypos = 0; r->line0 = r->line1 = z->img_comp[k].data; if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; else r->resample = stbi__resample_row_generic; } // can't error after this so, this is safe output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } // now go ahead and resample for (j=0; j < z->s->img_y; ++j) { stbi_uc *out = output + n * z->s->img_x * j; for (k=0; k < decode_n; ++k) { stbi__resample *r = &res_comp[k]; int y_bot = r->ystep >= (r->vs >> 1); coutput[k] = r->resample(z->img_comp[k].linebuf, y_bot ? r->line1 : r->line0, y_bot ? r->line0 : r->line1, r->w_lores, r->hs); if (++r->ystep >= r->vs) { r->ystep = 0; r->line0 = r->line1; if (++r->ypos < z->img_comp[k].y) r->line1 += z->img_comp[k].w2; } } if (n >= 3) { stbi_uc *y = coutput[0]; if (z->s->img_n == 3) { if (is_rgb) { for (i=0; i < z->s->img_x; ++i) { out[0] = y[i]; out[1] = coutput[1][i]; out[2] = coutput[2][i]; out[3] = 255; out += n; } } else { z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else if (z->s->img_n == 4) { if (z->app14_color_transform == 0) { // CMYK for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(coutput[0][i], m); out[1] = stbi__blinn_8x8(coutput[1][i], m); out[2] = stbi__blinn_8x8(coutput[2][i], m); out[3] = 255; out += n; } } else if (z->app14_color_transform == 2) { // YCCK z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; out[0] = stbi__blinn_8x8(255 - out[0], m); out[1] = stbi__blinn_8x8(255 - out[1], m); out[2] = stbi__blinn_8x8(255 - out[2], m); out += n; } } else { // YCbCr + alpha? Ignore the fourth channel for now z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); } } else for (i=0; i < z->s->img_x; ++i) { out[0] = out[1] = out[2] = y[i]; out[3] = 255; // not used if n==3 out += n; } } else { if (is_rgb) { if (n == 1) for (i=0; i < z->s->img_x; ++i) *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); else { for (i=0; i < z->s->img_x; ++i, out += 2) { out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); out[1] = 255; } } } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { for (i=0; i < z->s->img_x; ++i) { stbi_uc m = coutput[3][i]; stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); out[0] = stbi__compute_y(r, g, b); out[1] = 255; out += n; } } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { for (i=0; i < z->s->img_x; ++i) { out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); out[1] = 255; out += n; } } else { stbi_uc *y = coutput[0]; if (n == 1) for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; else for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } } } } stbi__cleanup_jpeg(z); *out_x = z->s->img_x; *out_y = z->s->img_y; if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output return output; } } static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { unsigned char* result; stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); STBI_NOTUSED(ri); j->s = s; stbi__setup_jpeg(j); result = load_jpeg_image(j, x,y,comp,req_comp); STBI_FREE(j); return result; } static int stbi__jpeg_test(stbi__context *s) { int r; stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); j->s = s; stbi__setup_jpeg(j); r = stbi__decode_jpeg_header(j, STBI__SCAN_type); stbi__rewind(s); STBI_FREE(j); return r; } static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) { if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { stbi__rewind( j->s ); return 0; } if (x) *x = j->s->img_x; if (y) *y = j->s->img_y; if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; return 1; } static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) { int result; stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); j->s = s; result = stbi__jpeg_info_raw(j, x, y, comp); STBI_FREE(j); return result; } #endif // public domain zlib decode v0.2 Sean Barrett 2006-11-18 // simple implementation // - all input must be provided in an upfront buffer // - all output is written to a single output buffer (can malloc/realloc) // performance // - fast huffman #ifndef STBI_NO_ZLIB // fast-way is faster to check than jpeg huffman, but slow way is slower #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) // zlib-style huffman encoding // (jpegs packs from left, zlib from right, so can't share code) typedef struct { stbi__uint16 fast[1 << STBI__ZFAST_BITS]; stbi__uint16 firstcode[16]; int maxcode[17]; stbi__uint16 firstsymbol[16]; stbi_uc size[288]; stbi__uint16 value[288]; } stbi__zhuffman; stbi_inline static int stbi__bitreverse16(int n) { n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); return n; } stbi_inline static int stbi__bit_reverse(int v, int bits) { STBI_ASSERT(bits <= 16); // to bit reverse n bits, reverse 16 and shift // e.g. 11 bits, bit reverse and shift away 5 return stbi__bitreverse16(v) >> (16-bits); } static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) { int i,k=0; int code, next_code[16], sizes[17]; // DEFLATE spec for generating codes memset(sizes, 0, sizeof(sizes)); memset(z->fast, 0, sizeof(z->fast)); for (i=0; i < num; ++i) ++sizes[sizelist[i]]; sizes[0] = 0; for (i=1; i < 16; ++i) if (sizes[i] > (1 << i)) return stbi__err("bad sizes", "Corrupt PNG"); code = 0; for (i=1; i < 16; ++i) { next_code[i] = code; z->firstcode[i] = (stbi__uint16) code; z->firstsymbol[i] = (stbi__uint16) k; code = (code + sizes[i]); if (sizes[i]) if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); z->maxcode[i] = code << (16-i); // preshift for inner loop code <<= 1; k += sizes[i]; } z->maxcode[16] = 0x10000; // sentinel for (i=0; i < num; ++i) { int s = sizelist[i]; if (s) { int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); z->size [c] = (stbi_uc ) s; z->value[c] = (stbi__uint16) i; if (s <= STBI__ZFAST_BITS) { int j = stbi__bit_reverse(next_code[s],s); while (j < (1 << STBI__ZFAST_BITS)) { z->fast[j] = fastv; j += (1 << s); } } ++next_code[s]; } } return 1; } // zlib-from-memory implementation for PNG reading // because PNG allows splitting the zlib stream arbitrarily, // and it's annoying structurally to have PNG call ZLIB call PNG, // we require PNG read all the IDATs and combine them into a single // memory buffer typedef struct { stbi_uc *zbuffer, *zbuffer_end; int num_bits; stbi__uint32 code_buffer; char *zout; char *zout_start; char *zout_end; int z_expandable; stbi__zhuffman z_length, z_distance; } stbi__zbuf; stbi_inline static int stbi__zeof(stbi__zbuf *z) { return (z->zbuffer >= z->zbuffer_end); } stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) { return stbi__zeof(z) ? 0 : *z->zbuffer++; } static void stbi__fill_bits(stbi__zbuf *z) { do { if (z->code_buffer >= (1U << z->num_bits)) { z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ return; } z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; z->num_bits += 8; } while (z->num_bits <= 24); } stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) { unsigned int k; if (z->num_bits < n) stbi__fill_bits(z); k = z->code_buffer & ((1 << n) - 1); z->code_buffer >>= n; z->num_bits -= n; return k; } static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) { int b,s,k; // not resolved by fast table, so compute it the slow way // use jpeg approach, which requires MSbits at top k = stbi__bit_reverse(a->code_buffer, 16); for (s=STBI__ZFAST_BITS+1; ; ++s) if (k < z->maxcode[s]) break; if (s >= 16) return -1; // invalid code! // code size is s, so: b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; if (b >= sizeof (z->size)) return -1; // some data was corrupt somewhere! if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. a->code_buffer >>= s; a->num_bits -= s; return z->value[b]; } stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) { int b,s; if (a->num_bits < 16) { if (stbi__zeof(a)) { return -1; /* report error for unexpected end of data. */ } stbi__fill_bits(a); } b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; if (b) { s = b >> 9; a->code_buffer >>= s; a->num_bits -= s; return b & 511; } return stbi__zhuffman_decode_slowpath(a, z); } static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes { char *q; unsigned int cur, limit, old_limit; z->zout = zout; if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); cur = (unsigned int) (z->zout - z->zout_start); limit = old_limit = (unsigned) (z->zout_end - z->zout_start); if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); while (cur + n > limit) { if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); limit *= 2; } q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); STBI_NOTUSED(old_limit); if (q == NULL) return stbi__err("outofmem", "Out of memory"); z->zout_start = q; z->zout = q + cur; z->zout_end = q + limit; return 1; } static const int stbi__zlength_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; static const int stbi__zlength_extra[31]= { 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 }; static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; static const int stbi__zdist_extra[32] = { 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}; static int stbi__parse_huffman_block(stbi__zbuf *a) { char *zout = a->zout; for(;;) { int z = stbi__zhuffman_decode(a, &a->z_length); if (z < 256) { if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes if (zout >= a->zout_end) { if (!stbi__zexpand(a, zout, 1)) return 0; zout = a->zout; } *zout++ = (char) z; } else { stbi_uc *p; int len,dist; if (z == 256) { a->zout = zout; return 1; } z -= 257; len = stbi__zlength_base[z]; if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); z = stbi__zhuffman_decode(a, &a->z_distance); if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); dist = stbi__zdist_base[z]; if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); if (zout + len > a->zout_end) { if (!stbi__zexpand(a, zout, len)) return 0; zout = a->zout; } p = (stbi_uc *) (zout - dist); if (dist == 1) { // run of one byte; common in images. stbi_uc v = *p; if (len) { do *zout++ = v; while (--len); } } else { if (len) { do *zout++ = *p++; while (--len); } } } } } static int stbi__compute_huffman_codes(stbi__zbuf *a) { static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; stbi__zhuffman z_codelength; stbi_uc lencodes[286+32+137];//padding for maximum single op stbi_uc codelength_sizes[19]; int i,n; int hlit = stbi__zreceive(a,5) + 257; int hdist = stbi__zreceive(a,5) + 1; int hclen = stbi__zreceive(a,4) + 4; int ntot = hlit + hdist; memset(codelength_sizes, 0, sizeof(codelength_sizes)); for (i=0; i < hclen; ++i) { int s = stbi__zreceive(a,3); codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; } if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; n = 0; while (n < ntot) { int c = stbi__zhuffman_decode(a, &z_codelength); if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); if (c < 16) lencodes[n++] = (stbi_uc) c; else { stbi_uc fill = 0; if (c == 16) { c = stbi__zreceive(a,2)+3; if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); fill = lencodes[n-1]; } else if (c == 17) { c = stbi__zreceive(a,3)+3; } else if (c == 18) { c = stbi__zreceive(a,7)+11; } else { return stbi__err("bad codelengths", "Corrupt PNG"); } if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); memset(lencodes+n, fill, c); n += c; } } if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; return 1; } static int stbi__parse_uncompressed_block(stbi__zbuf *a) { stbi_uc header[4]; int len,nlen,k; if (a->num_bits & 7) stbi__zreceive(a, a->num_bits & 7); // discard // drain the bit-packed data into header k = 0; while (a->num_bits > 0) { header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check a->code_buffer >>= 8; a->num_bits -= 8; } if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); // now fill header the normal way while (k < 4) header[k++] = stbi__zget8(a); len = header[1] * 256 + header[0]; nlen = header[3] * 256 + header[2]; if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, a->zout, len)) return 0; memcpy(a->zout, a->zbuffer, len); a->zbuffer += len; a->zout += len; return 1; } static int stbi__parse_zlib_header(stbi__zbuf *a) { int cmf = stbi__zget8(a); int cm = cmf & 15; /* int cinfo = cmf >> 4; */ int flg = stbi__zget8(a); if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png // window = 1 << (8 + cinfo)... but who cares, we fully buffer output return 1; } static const stbi_uc stbi__zdefault_length[288] = { 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 }; static const stbi_uc stbi__zdefault_distance[32] = { 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 }; /* Init algorithm: { int i; // use <= to match clearly with spec for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; } */ static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) { int final, type; if (parse_header) if (!stbi__parse_zlib_header(a)) return 0; a->num_bits = 0; a->code_buffer = 0; do { final = stbi__zreceive(a,1); type = stbi__zreceive(a,2); if (type == 0) { if (!stbi__parse_uncompressed_block(a)) return 0; } else if (type == 3) { return 0; } else { if (type == 1) { // use fixed code lengths if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0; if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; } else { if (!stbi__compute_huffman_codes(a)) return 0; } if (!stbi__parse_huffman_block(a)) return 0; } } while (!final); return 1; } static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) { a->zout_start = obuf; a->zout = obuf; a->zout_end = obuf + olen; a->z_expandable = exp; return stbi__parse_zlib(a, parse_header); } STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) { return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); } STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) { stbi__zbuf a; char *p = (char *) stbi__malloc(initial_size); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer + len; if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) return (int) (a.zout - a.zout_start); else return -1; } STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) { stbi__zbuf a; char *p = (char *) stbi__malloc(16384); if (p == NULL) return NULL; a.zbuffer = (stbi_uc *) buffer; a.zbuffer_end = (stbi_uc *) buffer+len; if (stbi__do_zlib(&a, p, 16384, 1, 0)) { if (outlen) *outlen = (int) (a.zout - a.zout_start); return a.zout_start; } else { STBI_FREE(a.zout_start); return NULL; } } STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) { stbi__zbuf a; a.zbuffer = (stbi_uc *) ibuffer; a.zbuffer_end = (stbi_uc *) ibuffer + ilen; if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) return (int) (a.zout - a.zout_start); else return -1; } #endif // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 // simple implementation // - only 8-bit samples // - no CRC checking // - allocates lots of intermediate memory // - avoids problem of streaming data between subsystems // - avoids explicit window management // performance // - uses stb_zlib, a PD zlib implementation with fast huffman decoding #ifndef STBI_NO_PNG typedef struct { stbi__uint32 length; stbi__uint32 type; } stbi__pngchunk; static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) { stbi__pngchunk c; c.length = stbi__get32be(s); c.type = stbi__get32be(s); return c; } static int stbi__check_png_header(stbi__context *s) { static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; int i; for (i=0; i < 8; ++i) if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); return 1; } typedef struct { stbi__context *s; stbi_uc *idata, *expanded, *out; int depth; } stbi__png; enum { STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4, // synthetic filters used for first scanline to avoid needing a dummy row of 0s STBI__F_avg_first, STBI__F_paeth_first }; static stbi_uc first_row_filter[5] = { STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first }; static int stbi__paeth(int a, int b, int c) { int p = a + b - c; int pa = abs(p-a); int pb = abs(p-b); int pc = abs(p-c); if (pa <= pb && pa <= pc) return a; if (pb <= pc) return b; return c; } static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; // create the png data from post-deflated data static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) { int bytes = (depth == 16? 2 : 1); stbi__context *s = a->s; stbi__uint32 i,j,stride = x*out_n*bytes; stbi__uint32 img_len, img_width_bytes; int k; int img_n = s->img_n; // copy it into a local for later int output_bytes = out_n*bytes; int filter_bytes = img_n*bytes; int width = x; STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into if (!a->out) return stbi__err("outofmem", "Out of memory"); if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); img_width_bytes = (((img_n * x * depth) + 7) >> 3); img_len = (img_width_bytes + 1) * y; // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), // so just check for raw_len < img_len always. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *prior; int filter = *raw++; if (filter > 4) return stbi__err("invalid filter","Corrupt PNG"); if (depth < 8) { if (img_width_bytes > x) return stbi__err("invalid width","Corrupt PNG"); cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place filter_bytes = 1; width = img_width_bytes; } prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above // if first row, use special filter that doesn't sample previous row if (j == 0) filter = first_row_filter[filter]; // handle first byte explicitly for (k=0; k < filter_bytes; ++k) { switch (filter) { case STBI__F_none : cur[k] = raw[k]; break; case STBI__F_sub : cur[k] = raw[k]; break; case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break; case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break; case STBI__F_avg_first : cur[k] = raw[k]; break; case STBI__F_paeth_first: cur[k] = raw[k]; break; } } if (depth == 8) { if (img_n != out_n) cur[img_n] = 255; // first pixel raw += img_n; cur += out_n; prior += out_n; } else if (depth == 16) { if (img_n != out_n) { cur[filter_bytes] = 255; // first pixel top byte cur[filter_bytes+1] = 255; // first pixel bottom byte } raw += filter_bytes; cur += output_bytes; prior += output_bytes; } else { raw += 1; cur += 1; prior += 1; } // this is a little gross, so that we don't switch per-pixel or per-component if (depth < 8 || img_n == out_n) { int nk = (width - 1)*filter_bytes; #define STBI__CASE(f) \ case f: \ for (k=0; k < nk; ++k) switch (filter) { // "none" filter turns into a memcpy here; make that explicit. case STBI__F_none: memcpy(cur, raw, nk); break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break; } #undef STBI__CASE raw += nk; } else { STBI_ASSERT(img_n+1 == out_n); #define STBI__CASE(f) \ case f: \ for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ for (k=0; k < filter_bytes; ++k) switch (filter) { STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break; STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break; STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break; STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break; STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break; } #undef STBI__CASE // the loop above sets the high byte of the pixels' alpha, but for // 16 bit png files we also need the low byte set. we'll do that here. if (depth == 16) { cur = a->out + stride*j; // start at the beginning of the row again for (i=0; i < x; ++i,cur+=output_bytes) { cur[filter_bytes+1] = 255; } } } } // we make a separate pass to expand bits to pixels; for performance, // this could run two scanlines behind the above code, so it won't // intefere with filtering but will still be in the cache. if (depth < 8) { for (j=0; j < y; ++j) { stbi_uc *cur = a->out + stride*j; stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range // note that the final byte might overshoot and write more data than desired. // we can allocate enough data that this never writes out of memory, but it // could also overwrite the next scanline. can it overwrite non-empty data // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. // so we need to explicitly clamp the final ones if (depth == 4) { for (k=x*img_n; k >= 2; k-=2, ++in) { *cur++ = scale * ((*in >> 4) ); *cur++ = scale * ((*in ) & 0x0f); } if (k > 0) *cur++ = scale * ((*in >> 4) ); } else if (depth == 2) { for (k=x*img_n; k >= 4; k-=4, ++in) { *cur++ = scale * ((*in >> 6) ); *cur++ = scale * ((*in >> 4) & 0x03); *cur++ = scale * ((*in >> 2) & 0x03); *cur++ = scale * ((*in ) & 0x03); } if (k > 0) *cur++ = scale * ((*in >> 6) ); if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); } else if (depth == 1) { for (k=x*img_n; k >= 8; k-=8, ++in) { *cur++ = scale * ((*in >> 7) ); *cur++ = scale * ((*in >> 6) & 0x01); *cur++ = scale * ((*in >> 5) & 0x01); *cur++ = scale * ((*in >> 4) & 0x01); *cur++ = scale * ((*in >> 3) & 0x01); *cur++ = scale * ((*in >> 2) & 0x01); *cur++ = scale * ((*in >> 1) & 0x01); *cur++ = scale * ((*in ) & 0x01); } if (k > 0) *cur++ = scale * ((*in >> 7) ); if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); } if (img_n != out_n) { int q; // insert alpha = 255 cur = a->out + stride*j; if (img_n == 1) { for (q=x-1; q >= 0; --q) { cur[q*2+1] = 255; cur[q*2+0] = cur[q]; } } else { STBI_ASSERT(img_n == 3); for (q=x-1; q >= 0; --q) { cur[q*4+3] = 255; cur[q*4+2] = cur[q*3+2]; cur[q*4+1] = cur[q*3+1]; cur[q*4+0] = cur[q*3+0]; } } } } } else if (depth == 16) { // force the image data from big-endian to platform-native. // this is done in a separate pass due to the decoding relying // on the data being untouched, but could probably be done // per-line during decode if care is taken. stbi_uc *cur = a->out; stbi__uint16 *cur16 = (stbi__uint16*)cur; for(i=0; i < x*y*out_n; ++i,cur16++,cur+=2) { *cur16 = (cur[0] << 8) | cur[1]; } } return 1; } static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) { int bytes = (depth == 16 ? 2 : 1); int out_bytes = out_n * bytes; stbi_uc *final; int p; if (!interlaced) return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); // de-interlacing final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); for (p=0; p < 7; ++p) { int xorig[] = { 0,4,0,2,0,1,0 }; int yorig[] = { 0,0,4,0,2,0,1 }; int xspc[] = { 8,8,4,4,2,2,1 }; int yspc[] = { 8,8,8,4,4,2,2 }; int i,j,x,y; // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; if (x && y) { stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { STBI_FREE(final); return 0; } for (j=0; j < y; ++j) { for (i=0; i < x; ++i) { int out_y = j*yspc[p]+yorig[p]; int out_x = i*xspc[p]+xorig[p]; memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, a->out + (j*x+i)*out_bytes, out_bytes); } } STBI_FREE(a->out); image_data += img_len; image_data_len -= img_len; } } a->out = final; return 1; } static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; // compute color-based transparency, assuming we've // already got 255 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i=0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 255); p += 2; } } else { for (i=0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi__uint16 *p = (stbi__uint16*) z->out; // compute color-based transparency, assuming we've // already got 65535 as the alpha value in the output STBI_ASSERT(out_n == 2 || out_n == 4); if (out_n == 2) { for (i = 0; i < pixel_count; ++i) { p[1] = (p[0] == tc[0] ? 0 : 65535); p += 2; } } else { for (i = 0; i < pixel_count; ++i) { if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) p[3] = 0; p += 4; } } return 1; } static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) { stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; stbi_uc *p, *temp_out, *orig = a->out; p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); if (p == NULL) return stbi__err("outofmem", "Out of memory"); // between here and free(out) below, exitting would leak temp_out = p; if (pal_img_n == 3) { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p += 3; } } else { for (i=0; i < pixel_count; ++i) { int n = orig[i]*4; p[0] = palette[n ]; p[1] = palette[n+1]; p[2] = palette[n+2]; p[3] = palette[n+3]; p += 4; } } STBI_FREE(a->out); a->out = temp_out; STBI_NOTUSED(len); return 1; } static int stbi__unpremultiply_on_load = 0; static int stbi__de_iphone_flag = 0; STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) { stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; } STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) { stbi__de_iphone_flag = flag_true_if_should_convert; } static void stbi__de_iphone(stbi__png *z) { stbi__context *s = z->s; stbi__uint32 i, pixel_count = s->img_x * s->img_y; stbi_uc *p = z->out; if (s->img_out_n == 3) { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 3; } } else { STBI_ASSERT(s->img_out_n == 4); if (stbi__unpremultiply_on_load) { // convert bgr to rgb and unpremultiply for (i=0; i < pixel_count; ++i) { stbi_uc a = p[3]; stbi_uc t = p[0]; if (a) { stbi_uc half = a / 2; p[0] = (p[2] * 255 + half) / a; p[1] = (p[1] * 255 + half) / a; p[2] = ( t * 255 + half) / a; } else { p[0] = p[2]; p[2] = t; } p += 4; } } else { // convert bgr to rgb for (i=0; i < pixel_count; ++i) { stbi_uc t = p[0]; p[0] = p[2]; p[2] = t; p += 4; } } } } #define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) { stbi_uc palette[1024], pal_img_n=0; stbi_uc has_trans=0, tc[3]={0}; stbi__uint16 tc16[3]; stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; int first=1,k,interlace=0, color=0, is_iphone=0; stbi__context *s = z->s; z->expanded = NULL; z->idata = NULL; z->out = NULL; if (!stbi__check_png_header(s)) return 0; if (scan == STBI__SCAN_type) return 1; for (;;) { stbi__pngchunk c = stbi__get_chunk_header(s); switch (c.type) { case STBI__PNG_TYPE('C','g','B','I'): is_iphone = 1; stbi__skip(s, c.length); break; case STBI__PNG_TYPE('I','H','D','R'): { int comp,filter; if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); first = 0; if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); s->img_x = stbi__get32be(s); s->img_y = stbi__get32be(s); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); if (!pal_img_n) { s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); if (scan == STBI__SCAN_header) return 1; } else { // if paletted, then pal_n is our final components, and // img_n is # components to decompress/filter. s->img_n = 1; if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); // if SCAN_header, have to scan to see if we have a tRNS } break; } case STBI__PNG_TYPE('P','L','T','E'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); pal_len = c.length / 3; if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); for (i=0; i < pal_len; ++i) { palette[i*4+0] = stbi__get8(s); palette[i*4+1] = stbi__get8(s); palette[i*4+2] = stbi__get8(s); palette[i*4+3] = 255; } break; } case STBI__PNG_TYPE('t','R','N','S'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); if (pal_img_n) { if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); pal_img_n = 4; for (i=0; i < c.length; ++i) palette[i*4+3] = stbi__get8(s); } else { if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); has_trans = 1; if (z->depth == 16) { for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is } else { for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger } } break; } case STBI__PNG_TYPE('I','D','A','T'): { if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } if ((int)(ioff + c.length) < (int)ioff) return 0; if (ioff + c.length > idata_limit) { stbi__uint32 idata_limit_old = idata_limit; stbi_uc *p; if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; while (ioff + c.length > idata_limit) idata_limit *= 2; STBI_NOTUSED(idata_limit_old); p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); z->idata = p; } if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); ioff += c.length; break; } case STBI__PNG_TYPE('I','E','N','D'): { stbi__uint32 raw_len, bpl; if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if (scan != STBI__SCAN_load) return 1; if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); // initial guess for decoded data size to avoid unnecessary reallocs bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); if (z->expanded == NULL) return 0; // zlib should set error STBI_FREE(z->idata); z->idata = NULL; if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) s->img_out_n = s->img_n+1; else s->img_out_n = s->img_n; if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; if (has_trans) { if (z->depth == 16) { if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; } else { if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; } } if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) stbi__de_iphone(z); if (pal_img_n) { // pal_img_n == 3 or 4 s->img_n = pal_img_n; // record the actual colors we had s->img_out_n = pal_img_n; if (req_comp >= 3) s->img_out_n = req_comp; if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) return 0; } else if (has_trans) { // non-paletted image with tRNS -> source image has (constant) alpha ++s->img_n; } STBI_FREE(z->expanded); z->expanded = NULL; // end of PNG chunk, read and skip CRC stbi__get32be(s); return 1; } default: // if critical, fail if (first) return stbi__err("first not IHDR", "Corrupt PNG"); if ((c.type & (1 << 29)) == 0) { #ifndef STBI_NO_FAILURE_STRINGS // not threadsafe static char invalid_chunk[] = "XXXX PNG chunk not known"; invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); #endif return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); } stbi__skip(s, c.length); break; } // end of PNG chunk, read and skip CRC stbi__get32be(s); } } static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) { void *result=NULL; if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { if (p->depth <= 8) ri->bits_per_channel = 8; else if (p->depth == 16) ri->bits_per_channel = 16; else return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); result = p->out; p->out = NULL; if (req_comp && req_comp != p->s->img_out_n) { if (ri->bits_per_channel == 8) result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); else result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); p->s->img_out_n = req_comp; if (result == NULL) return result; } *x = p->s->img_x; *y = p->s->img_y; if (n) *n = p->s->img_n; } STBI_FREE(p->out); p->out = NULL; STBI_FREE(p->expanded); p->expanded = NULL; STBI_FREE(p->idata); p->idata = NULL; return result; } static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi__png p; p.s = s; return stbi__do_png(&p, x,y,comp,req_comp, ri); } static int stbi__png_test(stbi__context *s) { int r; r = stbi__check_png_header(s); stbi__rewind(s); return r; } static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) { if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { stbi__rewind( p->s ); return 0; } if (x) *x = p->s->img_x; if (y) *y = p->s->img_y; if (comp) *comp = p->s->img_n; return 1; } static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) { stbi__png p; p.s = s; return stbi__png_info_raw(&p, x, y, comp); } static int stbi__png_is16(stbi__context *s) { stbi__png p; p.s = s; if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) return 0; if (p.depth != 16) { stbi__rewind(p.s); return 0; } return 1; } #endif // Microsoft/Windows BMP image #ifndef STBI_NO_BMP static int stbi__bmp_test_raw(stbi__context *s) { int r; int sz; if (stbi__get8(s) != 'B') return 0; if (stbi__get8(s) != 'M') return 0; stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved stbi__get32le(s); // discard data offset sz = stbi__get32le(s); r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); return r; } static int stbi__bmp_test(stbi__context *s) { int r = stbi__bmp_test_raw(s); stbi__rewind(s); return r; } // returns 0..31 for the highest set bit static int stbi__high_bit(unsigned int z) { int n=0; if (z == 0) return -1; if (z >= 0x10000) { n += 16; z >>= 16; } if (z >= 0x00100) { n += 8; z >>= 8; } if (z >= 0x00010) { n += 4; z >>= 4; } if (z >= 0x00004) { n += 2; z >>= 2; } if (z >= 0x00002) { n += 1;/* >>= 1;*/ } return n; } static int stbi__bitcount(unsigned int a) { a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits a = (a + (a >> 8)); // max 16 per 8 bits a = (a + (a >> 16)); // max 32 per 8 bits return a & 0xff; } // extract an arbitrarily-aligned N-bit value (N=bits) // from v, and then make it 8-bits long and fractionally // extend it to full full range. static int stbi__shiftsigned(unsigned int v, int shift, int bits) { static unsigned int mul_table[9] = { 0, 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, }; static unsigned int shift_table[9] = { 0, 0,0,1,0,2,4,6,0, }; if (shift < 0) v <<= -shift; else v >>= shift; STBI_ASSERT(v < 256); v >>= (8-bits); STBI_ASSERT(bits >= 0 && bits <= 8); return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; } typedef struct { int bpp, offset, hsz; unsigned int mr,mg,mb,ma, all_a; int extra_read; } stbi__bmp_data; static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) { int hsz; if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); stbi__get32le(s); // discard filesize stbi__get16le(s); // discard reserved stbi__get16le(s); // discard reserved info->offset = stbi__get32le(s); info->hsz = hsz = stbi__get32le(s); info->mr = info->mg = info->mb = info->ma = 0; info->extra_read = 14; if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); if (hsz == 12) { s->img_x = stbi__get16le(s); s->img_y = stbi__get16le(s); } else { s->img_x = stbi__get32le(s); s->img_y = stbi__get32le(s); } if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); info->bpp = stbi__get16le(s); if (hsz != 12) { int compress = stbi__get32le(s); if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); stbi__get32le(s); // discard sizeof stbi__get32le(s); // discard hres stbi__get32le(s); // discard vres stbi__get32le(s); // discard colorsused stbi__get32le(s); // discard max important if (hsz == 40 || hsz == 56) { if (hsz == 56) { stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); stbi__get32le(s); } if (info->bpp == 16 || info->bpp == 32) { if (compress == 0) { if (info->bpp == 32) { info->mr = 0xffu << 16; info->mg = 0xffu << 8; info->mb = 0xffu << 0; info->ma = 0xffu << 24; info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 } else { info->mr = 31u << 10; info->mg = 31u << 5; info->mb = 31u << 0; } } else if (compress == 3) { info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->extra_read += 12; // not documented, but generated by photoshop and handled by mspaint if (info->mr == info->mg && info->mg == info->mb) { // ?!?!? return stbi__errpuc("bad BMP", "bad BMP"); } } else return stbi__errpuc("bad BMP", "bad BMP"); } } else { int i; if (hsz != 108 && hsz != 124) return stbi__errpuc("bad BMP", "bad BMP"); info->mr = stbi__get32le(s); info->mg = stbi__get32le(s); info->mb = stbi__get32le(s); info->ma = stbi__get32le(s); stbi__get32le(s); // discard color space for (i=0; i < 12; ++i) stbi__get32le(s); // discard color space parameters if (hsz == 124) { stbi__get32le(s); // discard rendering intent stbi__get32le(s); // discard offset of profile data stbi__get32le(s); // discard size of profile data stbi__get32le(s); // discard reserved } } } return (void *) 1; } static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; unsigned int mr=0,mg=0,mb=0,ma=0, all_a; stbi_uc pal[256][4]; int psize=0,i,j,width; int flip_vertically, pad, target; stbi__bmp_data info; STBI_NOTUSED(ri); info.all_a = 255; if (stbi__bmp_parse_header(s, &info) == NULL) return NULL; // error code already set flip_vertically = ((int) s->img_y) > 0; s->img_y = abs((int) s->img_y); if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); mr = info.mr; mg = info.mg; mb = info.mb; ma = info.ma; all_a = info.all_a; if (info.hsz == 12) { if (info.bpp < 24) psize = (info.offset - info.extra_read - 24) / 3; } else { if (info.bpp < 16) psize = (info.offset - info.extra_read - info.hsz) >> 2; } if (psize == 0) { STBI_ASSERT(info.offset == s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original)); if (info.offset != s->callback_already_read + (s->img_buffer - s->buffer_start)) { return stbi__errpuc("bad offset", "Corrupt BMP"); } } if (info.bpp == 24 && ma == 0xff000000) s->img_n = 3; else s->img_n = ma ? 4 : 3; if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 target = req_comp; else target = s->img_n; // if they want monochrome, we'll post-convert // sanity-check size if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "Corrupt BMP"); out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); if (info.bpp < 16) { int z=0; if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } for (i=0; i < psize; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); if (info.hsz != 12) stbi__get8(s); pal[i][3] = 255; } stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); if (info.bpp == 1) width = (s->img_x + 7) >> 3; else if (info.bpp == 4) width = (s->img_x + 1) >> 1; else if (info.bpp == 8) width = s->img_x; else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } pad = (-width)&3; if (info.bpp == 1) { for (j=0; j < (int) s->img_y; ++j) { int bit_offset = 7, v = stbi__get8(s); for (i=0; i < (int) s->img_x; ++i) { int color = (v>>bit_offset)&0x1; out[z++] = pal[color][0]; out[z++] = pal[color][1]; out[z++] = pal[color][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; if((--bit_offset) < 0) { bit_offset = 7; v = stbi__get8(s); } } stbi__skip(s, pad); } } else { for (j=0; j < (int) s->img_y; ++j) { for (i=0; i < (int) s->img_x; i += 2) { int v=stbi__get8(s),v2=0; if (info.bpp == 4) { v2 = v & 15; v >>= 4; } out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; if (i+1 == (int) s->img_x) break; v = (info.bpp == 8) ? stbi__get8(s) : v2; out[z++] = pal[v][0]; out[z++] = pal[v][1]; out[z++] = pal[v][2]; if (target == 4) out[z++] = 255; } stbi__skip(s, pad); } } } else { int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; int z = 0; int easy=0; stbi__skip(s, info.offset - info.extra_read - info.hsz); if (info.bpp == 24) width = 3 * s->img_x; else if (info.bpp == 16) width = 2*s->img_x; else /* bpp = 32 and pad = 0 */ width=0; pad = (-width) & 3; if (info.bpp == 24) { easy = 1; } else if (info.bpp == 32) { if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) easy = 2; } if (!easy) { if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } // right shift amt to put high bit in position #7 rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } } for (j=0; j < (int) s->img_y; ++j) { if (easy) { for (i=0; i < (int) s->img_x; ++i) { unsigned char a; out[z+2] = stbi__get8(s); out[z+1] = stbi__get8(s); out[z+0] = stbi__get8(s); z += 3; a = (easy == 2 ? stbi__get8(s) : 255); all_a |= a; if (target == 4) out[z++] = a; } } else { int bpp = info.bpp; for (i=0; i < (int) s->img_x; ++i) { stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); unsigned int a; out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); all_a |= a; if (target == 4) out[z++] = STBI__BYTECAST(a); } } stbi__skip(s, pad); } } // if alpha channel is all 0s, replace with all 255s if (target == 4 && all_a == 0) for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) out[i] = 255; if (flip_vertically) { stbi_uc t; for (j=0; j < (int) s->img_y>>1; ++j) { stbi_uc *p1 = out + j *s->img_x*target; stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; for (i=0; i < (int) s->img_x*target; ++i) { t = p1[i]; p1[i] = p2[i]; p2[i] = t; } } } if (req_comp && req_comp != target) { out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; return out; } #endif // Targa Truevision - TGA // by Jonathan Dummer #ifndef STBI_NO_TGA // returns STBI_rgb or whatever, 0 on error static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) { // only RGB or RGBA (incl. 16bit) or grey allowed if (is_rgb16) *is_rgb16 = 0; switch(bits_per_pixel) { case 8: return STBI_grey; case 16: if(is_grey) return STBI_grey_alpha; // fallthrough case 15: if(is_rgb16) *is_rgb16 = 1; return STBI_rgb; case 24: // fallthrough case 32: return bits_per_pixel/8; default: return 0; } } static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) { int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; int sz, tga_colormap_type; stbi__get8(s); // discard Offset tga_colormap_type = stbi__get8(s); // colormap type if( tga_colormap_type > 1 ) { stbi__rewind(s); return 0; // only RGB or indexed allowed } tga_image_type = stbi__get8(s); // image type if ( tga_colormap_type == 1 ) { // colormapped (paletted) image if (tga_image_type != 1 && tga_image_type != 9) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { stbi__rewind(s); return 0; } stbi__skip(s,4); // skip image x and y origin tga_colormap_bpp = sz; } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { stbi__rewind(s); return 0; // only RGB or grey allowed, +/- RLE } stbi__skip(s,9); // skip colormap specification and image x/y origin tga_colormap_bpp = 0; } tga_w = stbi__get16le(s); if( tga_w < 1 ) { stbi__rewind(s); return 0; // test width } tga_h = stbi__get16le(s); if( tga_h < 1 ) { stbi__rewind(s); return 0; // test height } tga_bits_per_pixel = stbi__get8(s); // bits per pixel stbi__get8(s); // ignore alpha bits if (tga_colormap_bpp != 0) { if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { // when using a colormap, tga_bits_per_pixel is the size of the indexes // I don't think anything but 8 or 16bit indexes makes sense stbi__rewind(s); return 0; } tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); } else { tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); } if(!tga_comp) { stbi__rewind(s); return 0; } if (x) *x = tga_w; if (y) *y = tga_h; if (comp) *comp = tga_comp; return 1; // seems to have passed everything } static int stbi__tga_test(stbi__context *s) { int res = 0; int sz, tga_color_type; stbi__get8(s); // discard Offset tga_color_type = stbi__get8(s); // color type if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed sz = stbi__get8(s); // image type if ( tga_color_type == 1 ) { // colormapped (paletted) image if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 stbi__skip(s,4); // skip index of first colormap entry and number of entries sz = stbi__get8(s); // check bits per palette color entry if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; stbi__skip(s,4); // skip image x and y origin } else { // "normal" image w/o colormap if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE stbi__skip(s,9); // skip colormap specification and image x/y origin } if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height sz = stbi__get8(s); // bits per pixel if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; res = 1; // if we got this far, everything's good and we can return 1 instead of 0 errorEnd: stbi__rewind(s); return res; } // read 16bit value and convert to 24bit RGB static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) { stbi__uint16 px = (stbi__uint16)stbi__get16le(s); stbi__uint16 fiveBitMask = 31; // we have 3 channels with 5bits each int r = (px >> 10) & fiveBitMask; int g = (px >> 5) & fiveBitMask; int b = px & fiveBitMask; // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later out[0] = (stbi_uc)((r * 255)/31); out[1] = (stbi_uc)((g * 255)/31); out[2] = (stbi_uc)((b * 255)/31); // some people claim that the most significant bit might be used for alpha // (possibly if an alpha-bit is set in the "image descriptor byte") // but that only made 16bit test images completely translucent.. // so let's treat all 15 and 16bit TGAs as RGB with no alpha. } static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { // read in the TGA header stuff int tga_offset = stbi__get8(s); int tga_indexed = stbi__get8(s); int tga_image_type = stbi__get8(s); int tga_is_RLE = 0; int tga_palette_start = stbi__get16le(s); int tga_palette_len = stbi__get16le(s); int tga_palette_bits = stbi__get8(s); int tga_x_origin = stbi__get16le(s); int tga_y_origin = stbi__get16le(s); int tga_width = stbi__get16le(s); int tga_height = stbi__get16le(s); int tga_bits_per_pixel = stbi__get8(s); int tga_comp, tga_rgb16=0; int tga_inverted = stbi__get8(s); // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) // image data unsigned char *tga_data; unsigned char *tga_palette = NULL; int i, j; unsigned char raw_data[4] = {0}; int RLE_count = 0; int RLE_repeating = 0; int read_next_pixel = 1; STBI_NOTUSED(ri); STBI_NOTUSED(tga_x_origin); // @TODO STBI_NOTUSED(tga_y_origin); // @TODO if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // do a tiny bit of precessing if ( tga_image_type >= 8 ) { tga_image_type -= 8; tga_is_RLE = 1; } tga_inverted = 1 - ((tga_inverted >> 5) & 1); // If I'm paletted, then I'll use the number of bits from the palette if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); // tga info *x = tga_width; *y = tga_height; if (comp) *comp = tga_comp; if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) return stbi__errpuc("too large", "Corrupt TGA"); tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); // skip to the data's starting position (offset usually = 0) stbi__skip(s, tga_offset ); if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { for (i=0; i < tga_height; ++i) { int row = tga_inverted ? tga_height -i - 1 : i; stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; stbi__getn(s, tga_row, tga_width * tga_comp); } } else { // do I need to load a palette? if ( tga_indexed) { if (tga_palette_len == 0) { /* you have to have at least one entry! */ STBI_FREE(tga_data); return stbi__errpuc("bad palette", "Corrupt TGA"); } // any data to skip? (offset usually = 0) stbi__skip(s, tga_palette_start ); // load the palette tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); if (!tga_palette) { STBI_FREE(tga_data); return stbi__errpuc("outofmem", "Out of memory"); } if (tga_rgb16) { stbi_uc *pal_entry = tga_palette; STBI_ASSERT(tga_comp == STBI_rgb); for (i=0; i < tga_palette_len; ++i) { stbi__tga_read_rgb16(s, pal_entry); pal_entry += tga_comp; } } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { STBI_FREE(tga_data); STBI_FREE(tga_palette); return stbi__errpuc("bad palette", "Corrupt TGA"); } } // load the data for (i=0; i < tga_width * tga_height; ++i) { // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? if ( tga_is_RLE ) { if ( RLE_count == 0 ) { // yep, get the next byte as a RLE command int RLE_cmd = stbi__get8(s); RLE_count = 1 + (RLE_cmd & 127); RLE_repeating = RLE_cmd >> 7; read_next_pixel = 1; } else if ( !RLE_repeating ) { read_next_pixel = 1; } } else { read_next_pixel = 1; } // OK, if I need to read a pixel, do it now if ( read_next_pixel ) { // load however much data we did have if ( tga_indexed ) { // read in index, then perform the lookup int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); if ( pal_idx >= tga_palette_len ) { // invalid index pal_idx = 0; } pal_idx *= tga_comp; for (j = 0; j < tga_comp; ++j) { raw_data[j] = tga_palette[pal_idx+j]; } } else if(tga_rgb16) { STBI_ASSERT(tga_comp == STBI_rgb); stbi__tga_read_rgb16(s, raw_data); } else { // read in the data raw for (j = 0; j < tga_comp; ++j) { raw_data[j] = stbi__get8(s); } } // clear the reading flag for the next pixel read_next_pixel = 0; } // end of reading a pixel // copy data for (j = 0; j < tga_comp; ++j) tga_data[i*tga_comp+j] = raw_data[j]; // in case we're in RLE mode, keep counting down --RLE_count; } // do I need to invert the image? if ( tga_inverted ) { for (j = 0; j*2 < tga_height; ++j) { int index1 = j * tga_width * tga_comp; int index2 = (tga_height - 1 - j) * tga_width * tga_comp; for (i = tga_width * tga_comp; i > 0; --i) { unsigned char temp = tga_data[index1]; tga_data[index1] = tga_data[index2]; tga_data[index2] = temp; ++index1; ++index2; } } } // clear my palette, if I had one if ( tga_palette != NULL ) { STBI_FREE( tga_palette ); } } // swap RGB - if the source data was RGB16, it already is in the right order if (tga_comp >= 3 && !tga_rgb16) { unsigned char* tga_pixel = tga_data; for (i=0; i < tga_width * tga_height; ++i) { unsigned char temp = tga_pixel[0]; tga_pixel[0] = tga_pixel[2]; tga_pixel[2] = temp; tga_pixel += tga_comp; } } // convert to target component count if (req_comp && req_comp != tga_comp) tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); // the things I do to get rid of an error message, and yet keep // Microsoft's C compilers happy... [8^( tga_palette_start = tga_palette_len = tga_palette_bits = tga_x_origin = tga_y_origin = 0; STBI_NOTUSED(tga_palette_start); // OK, done return tga_data; } #endif // ************************************************************************************************* // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB #ifndef STBI_NO_PSD static int stbi__psd_test(stbi__context *s) { int r = (stbi__get32be(s) == 0x38425053); stbi__rewind(s); return r; } static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) { int count, nleft, len; count = 0; while ((nleft = pixelCount - count) > 0) { len = stbi__get8(s); if (len == 128) { // No-op. } else if (len < 128) { // Copy next len+1 bytes literally. len++; if (len > nleft) return 0; // corrupt data count += len; while (len) { *p = stbi__get8(s); p += 4; len--; } } else if (len > 128) { stbi_uc val; // Next -len+1 bytes in the dest are replicated from next source byte. // (Interpret len as a negative 8-bit int.) len = 257 - len; if (len > nleft) return 0; // corrupt data val = stbi__get8(s); count += len; while (len) { *p = val; p += 4; len--; } } } return 1; } static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) { int pixelCount; int channelCount, compression; int channel, i; int bitdepth; int w,h; stbi_uc *out; STBI_NOTUSED(ri); // Check identifier if (stbi__get32be(s) != 0x38425053) // "8BPS" return stbi__errpuc("not PSD", "Corrupt PSD image"); // Check file type version. if (stbi__get16be(s) != 1) return stbi__errpuc("wrong version", "Unsupported version of PSD image"); // Skip 6 reserved bytes. stbi__skip(s, 6 ); // Read the number of channels (R, G, B, A, etc). channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); // Read the rows and columns of the image. h = stbi__get32be(s); w = stbi__get32be(s); if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); // Make sure the depth is 8 bits. bitdepth = stbi__get16be(s); if (bitdepth != 8 && bitdepth != 16) return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); // Make sure the color mode is RGB. // Valid options are: // 0: Bitmap // 1: Grayscale // 2: Indexed color // 3: RGB color // 4: CMYK color // 7: Multichannel // 8: Duotone // 9: Lab color if (stbi__get16be(s) != 3) return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) stbi__skip(s,stbi__get32be(s) ); // Skip the image resources. (resolution, pen tool paths, etc) stbi__skip(s, stbi__get32be(s) ); // Skip the reserved data. stbi__skip(s, stbi__get32be(s) ); // Find out if the data is compressed. // Known values: // 0: no compression // 1: RLE compressed compression = stbi__get16be(s); if (compression > 1) return stbi__errpuc("bad compression", "PSD has an unknown compression format"); // Check size if (!stbi__mad3sizes_valid(4, w, h, 0)) return stbi__errpuc("too large", "Corrupt PSD"); // Create the destination image. if (!compression && bitdepth == 16 && bpc == 16) { out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); ri->bits_per_channel = 16; } else out = (stbi_uc *) stbi__malloc(4 * w*h); if (!out) return stbi__errpuc("outofmem", "Out of memory"); pixelCount = w*h; // Initialize the data to zero. //memset( out, 0, pixelCount * 4 ); // Finally, the image data. if (compression) { // RLE as used by .PSD and .TIFF // Loop until you get the number of unpacked bytes you are expecting: // Read the next source byte into n. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. // Else if n is 128, noop. // Endloop // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, // which we're going to just skip. stbi__skip(s, h * channelCount * 2 ); // Read the RLE data by channel. for (channel = 0; channel < 4; channel++) { stbi_uc *p; p = out+channel; if (channel >= channelCount) { // Fill this channel with default data. for (i = 0; i < pixelCount; i++, p += 4) *p = (channel == 3 ? 255 : 0); } else { // Read the RLE data. if (!stbi__psd_decode_rle(s, p, pixelCount)) { STBI_FREE(out); return stbi__errpuc("corrupt", "bad RLE data"); } } } } else { // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. // Read the data by channel. for (channel = 0; channel < 4; channel++) { if (channel >= channelCount) { // Fill this channel with default data. if (bitdepth == 16 && bpc == 16) { stbi__uint16 *q = ((stbi__uint16 *) out) + channel; stbi__uint16 val = channel == 3 ? 65535 : 0; for (i = 0; i < pixelCount; i++, q += 4) *q = val; } else { stbi_uc *p = out+channel; stbi_uc val = channel == 3 ? 255 : 0; for (i = 0; i < pixelCount; i++, p += 4) *p = val; } } else { if (ri->bits_per_channel == 16) { // output bpc stbi__uint16 *q = ((stbi__uint16 *) out) + channel; for (i = 0; i < pixelCount; i++, q += 4) *q = (stbi__uint16) stbi__get16be(s); } else { stbi_uc *p = out+channel; if (bitdepth == 16) { // input bpc for (i = 0; i < pixelCount; i++, p += 4) *p = (stbi_uc) (stbi__get16be(s) >> 8); } else { for (i = 0; i < pixelCount; i++, p += 4) *p = stbi__get8(s); } } } } } // remove weird white matte from PSD if (channelCount >= 4) { if (ri->bits_per_channel == 16) { for (i=0; i < w*h; ++i) { stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; if (pixel[3] != 0 && pixel[3] != 65535) { float a = pixel[3] / 65535.0f; float ra = 1.0f / a; float inv_a = 65535.0f * (1 - ra); pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); } } } else { for (i=0; i < w*h; ++i) { unsigned char *pixel = out + 4*i; if (pixel[3] != 0 && pixel[3] != 255) { float a = pixel[3] / 255.0f; float ra = 1.0f / a; float inv_a = 255.0f * (1 - ra); pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); } } } } // convert to desired output format if (req_comp && req_comp != 4) { if (ri->bits_per_channel == 16) out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); else out = stbi__convert_format(out, 4, req_comp, w, h); if (out == NULL) return out; // stbi__convert_format frees input on failure } if (comp) *comp = 4; *y = h; *x = w; return out; } #endif // ************************************************************************************************* // Softimage PIC loader // by Tom Seddon // // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ #ifndef STBI_NO_PIC static int stbi__pic_is4(stbi__context *s,const char *str) { int i; for (i=0; i<4; ++i) if (stbi__get8(s) != (stbi_uc)str[i]) return 0; return 1; } static int stbi__pic_test_core(stbi__context *s) { int i; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) return 0; for(i=0;i<84;++i) stbi__get8(s); if (!stbi__pic_is4(s,"PICT")) return 0; return 1; } typedef struct { stbi_uc size,type,channel; } stbi__pic_packet; static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) { int mask=0x80, i; for (i=0; i<4; ++i, mask>>=1) { if (channel & mask) { if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); dest[i]=stbi__get8(s); } } return dest; } static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) { int mask=0x80,i; for (i=0;i<4; ++i, mask>>=1) if (channel&mask) dest[i]=src[i]; } static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) { int act_comp=0,num_packets=0,y,chained; stbi__pic_packet packets[10]; // this will (should...) cater for even some bizarre stuff like having data // for the same channel in multiple packets. do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return stbi__errpuc("bad format","too many packets"); packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? for(y=0; y<height; ++y) { int packet_idx; for(packet_idx=0; packet_idx < num_packets; ++packet_idx) { stbi__pic_packet *packet = &packets[packet_idx]; stbi_uc *dest = result+y*width*4; switch (packet->type) { default: return stbi__errpuc("bad format","packet has bad compression type"); case 0: {//uncompressed int x; for(x=0;x<width;++x, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; break; } case 1://Pure RLE { int left=width, i; while (left>0) { stbi_uc count,value[4]; count=stbi__get8(s); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); if (count > left) count = (stbi_uc) left; if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0; i<count; ++i,dest+=4) stbi__copyval(packet->channel,dest,value); left -= count; } } break; case 2: {//Mixed RLE int left=width; while (left>0) { int count = stbi__get8(s), i; if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); if (count >= 128) { // Repeated stbi_uc value[4]; if (count==128) count = stbi__get16be(s); else count -= 127; if (count > left) return stbi__errpuc("bad file","scanline overrun"); if (!stbi__readval(s,packet->channel,value)) return 0; for(i=0;i<count;++i, dest += 4) stbi__copyval(packet->channel,dest,value); } else { // Raw ++count; if (count>left) return stbi__errpuc("bad file","scanline overrun"); for(i=0;i<count;++i, dest+=4) if (!stbi__readval(s,packet->channel,dest)) return 0; } left-=count; } break; } } } } return result; } static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) { stbi_uc *result; int i, x,y, internal_comp; STBI_NOTUSED(ri); if (!comp) comp = &internal_comp; for (i=0; i<92; ++i) stbi__get8(s); x = stbi__get16be(s); y = stbi__get16be(s); if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); stbi__get32be(s); //skip `ratio' stbi__get16be(s); //skip `fields' stbi__get16be(s); //skip `pad' // intermediate buffer is RGBA result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); memset(result, 0xff, x*y*4); if (!stbi__pic_load_core(s,x,y,comp, result)) { STBI_FREE(result); result=0; } *px = x; *py = y; if (req_comp == 0) req_comp = *comp; result=stbi__convert_format(result,4,req_comp,x,y); return result; } static int stbi__pic_test(stbi__context *s) { int r = stbi__pic_test_core(s); stbi__rewind(s); return r; } #endif // ************************************************************************************************* // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb #ifndef STBI_NO_GIF typedef struct { stbi__int16 prefix; stbi_uc first; stbi_uc suffix; } stbi__gif_lzw; typedef struct { int w,h; stbi_uc *out; // output buffer (always 4 components) stbi_uc *background; // The current "background" as far as a gif is concerned stbi_uc *history; int flags, bgindex, ratio, transparent, eflags; stbi_uc pal[256][4]; stbi_uc lpal[256][4]; stbi__gif_lzw codes[8192]; stbi_uc *color_table; int parse, step; int lflags; int start_x, start_y; int max_x, max_y; int cur_x, cur_y; int line_size; int delay; } stbi__gif; static int stbi__gif_test_raw(stbi__context *s) { int sz; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; sz = stbi__get8(s); if (sz != '9' && sz != '7') return 0; if (stbi__get8(s) != 'a') return 0; return 1; } static int stbi__gif_test(stbi__context *s) { int r = stbi__gif_test_raw(s); stbi__rewind(s); return r; } static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) { int i; for (i=0; i < num_entries; ++i) { pal[i][2] = stbi__get8(s); pal[i][1] = stbi__get8(s); pal[i][0] = stbi__get8(s); pal[i][3] = transp == i ? 0 : 255; } } static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) { stbi_uc version; if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return stbi__err("not GIF", "Corrupt GIF"); version = stbi__get8(s); if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); stbi__g_failure_reason = ""; g->w = stbi__get16le(s); g->h = stbi__get16le(s); g->flags = stbi__get8(s); g->bgindex = stbi__get8(s); g->ratio = stbi__get8(s); g->transparent = -1; if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments if (is_info) return 1; if (g->flags & 0x80) stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); return 1; } static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) { stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); if (!stbi__gif_header(s, g, comp, 1)) { STBI_FREE(g); stbi__rewind( s ); return 0; } if (x) *x = g->w; if (y) *y = g->h; STBI_FREE(g); return 1; } static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) { stbi_uc *p, *c; int idx; // recurse to decode the prefixes, since the linked-list is backwards, // and working backwards through an interleaved image would be nasty if (g->codes[code].prefix >= 0) stbi__out_gif_code(g, g->codes[code].prefix); if (g->cur_y >= g->max_y) return; idx = g->cur_x + g->cur_y; p = &g->out[idx]; g->history[idx / 4] = 1; c = &g->color_table[g->codes[code].suffix * 4]; if (c[3] > 128) { // don't render transparent pixels; p[0] = c[2]; p[1] = c[1]; p[2] = c[0]; p[3] = c[3]; } g->cur_x += 4; if (g->cur_x >= g->max_x) { g->cur_x = g->start_x; g->cur_y += g->step; while (g->cur_y >= g->max_y && g->parse > 0) { g->step = (1 << g->parse) * g->line_size; g->cur_y = g->start_y + (g->step >> 1); --g->parse; } } } static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) { stbi_uc lzw_cs; stbi__int32 len, init_code; stbi__uint32 first; stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; stbi__gif_lzw *p; lzw_cs = stbi__get8(s); if (lzw_cs > 12) return NULL; clear = 1 << lzw_cs; first = 1; codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; bits = 0; valid_bits = 0; for (init_code = 0; init_code < clear; init_code++) { g->codes[init_code].prefix = -1; g->codes[init_code].first = (stbi_uc) init_code; g->codes[init_code].suffix = (stbi_uc) init_code; } // support no starting clear code avail = clear+2; oldcode = -1; len = 0; for(;;) { if (valid_bits < codesize) { if (len == 0) { len = stbi__get8(s); // start new block if (len == 0) return g->out; } --len; bits |= (stbi__int32) stbi__get8(s) << valid_bits; valid_bits += 8; } else { stbi__int32 code = bits & codemask; bits >>= codesize; valid_bits -= codesize; // @OPTIMIZE: is there some way we can accelerate the non-clear path? if (code == clear) { // clear code codesize = lzw_cs + 1; codemask = (1 << codesize) - 1; avail = clear + 2; oldcode = -1; first = 0; } else if (code == clear + 1) { // end of stream code stbi__skip(s, len); while ((len = stbi__get8(s)) > 0) stbi__skip(s,len); return g->out; } else if (code <= avail) { if (first) { return stbi__errpuc("no clear code", "Corrupt GIF"); } if (oldcode >= 0) { p = &g->codes[avail++]; if (avail > 8192) { return stbi__errpuc("too many codes", "Corrupt GIF"); } p->prefix = (stbi__int16) oldcode; p->first = g->codes[oldcode].first; p->suffix = (code == avail) ? p->first : g->codes[code].first; } else if (code == avail) return stbi__errpuc("illegal code in raster", "Corrupt GIF"); stbi__out_gif_code(g, (stbi__uint16) code); if ((avail & codemask) == 0 && avail <= 0x0FFF) { codesize++; codemask = (1 << codesize) - 1; } oldcode = code; } else { return stbi__errpuc("illegal code in raster", "Corrupt GIF"); } } } } // this function is designed to support animated gifs, although stb_image doesn't support it // two back is the image from two frames ago, used for a very specific disposal format static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) { int dispose; int first_frame; int pi; int pcount; STBI_NOTUSED(req_comp); // on first frame, any non-written pixels get the background colour (non-transparent) first_frame = 0; if (g->out == 0) { if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) return stbi__errpuc("too large", "GIF image is too large"); pcount = g->w * g->h; g->out = (stbi_uc *) stbi__malloc(4 * pcount); g->background = (stbi_uc *) stbi__malloc(4 * pcount); g->history = (stbi_uc *) stbi__malloc(pcount); if (!g->out || !g->background || !g->history) return stbi__errpuc("outofmem", "Out of memory"); // image is treated as "transparent" at the start - ie, nothing overwrites the current background; // background colour is only used for pixels that are not rendered first frame, after that "background" // color refers to the color that was there the previous frame. memset(g->out, 0x00, 4 * pcount); memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) memset(g->history, 0x00, pcount); // pixels that were affected previous frame first_frame = 1; } else { // second frame - how do we dispose of the previous one? dispose = (g->eflags & 0x1C) >> 2; pcount = g->w * g->h; if ((dispose == 3) && (two_back == 0)) { dispose = 2; // if I don't have an image to revert back to, default to the old background } if (dispose == 3) { // use previous graphic for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); } } } else if (dispose == 2) { // restore what was changed last frame to background before that frame; for (pi = 0; pi < pcount; ++pi) { if (g->history[pi]) { memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); } } } else { // This is a non-disposal case eithe way, so just // leave the pixels as is, and they will become the new background // 1: do not dispose // 0: not specified. } // background is what out is after the undoing of the previou frame; memcpy( g->background, g->out, 4 * g->w * g->h ); } // clear my history; memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame for (;;) { int tag = stbi__get8(s); switch (tag) { case 0x2C: /* Image Descriptor */ { stbi__int32 x, y, w, h; stbi_uc *o; x = stbi__get16le(s); y = stbi__get16le(s); w = stbi__get16le(s); h = stbi__get16le(s); if (((x + w) > (g->w)) || ((y + h) > (g->h))) return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); g->line_size = g->w * 4; g->start_x = x * 4; g->start_y = y * g->line_size; g->max_x = g->start_x + w * 4; g->max_y = g->start_y + h * g->line_size; g->cur_x = g->start_x; g->cur_y = g->start_y; // if the width of the specified rectangle is 0, that means // we may not see *any* pixels or the image is malformed; // to make sure this is caught, move the current y down to // max_y (which is what out_gif_code checks). if (w == 0) g->cur_y = g->max_y; g->lflags = stbi__get8(s); if (g->lflags & 0x40) { g->step = 8 * g->line_size; // first interlaced spacing g->parse = 3; } else { g->step = g->line_size; g->parse = 0; } if (g->lflags & 0x80) { stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); g->color_table = (stbi_uc *) g->lpal; } else if (g->flags & 0x80) { g->color_table = (stbi_uc *) g->pal; } else return stbi__errpuc("missing color table", "Corrupt GIF"); o = stbi__process_gif_raster(s, g); if (!o) return NULL; // if this was the first frame, pcount = g->w * g->h; if (first_frame && (g->bgindex > 0)) { // if first frame, any pixel not drawn to gets the background color for (pi = 0; pi < pcount; ++pi) { if (g->history[pi] == 0) { g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); } } } return o; } case 0x21: // Comment Extension. { int len; int ext = stbi__get8(s); if (ext == 0xF9) { // Graphic Control Extension. len = stbi__get8(s); if (len == 4) { g->eflags = stbi__get8(s); g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. // unset old transparent if (g->transparent >= 0) { g->pal[g->transparent][3] = 255; } if (g->eflags & 0x01) { g->transparent = stbi__get8(s); if (g->transparent >= 0) { g->pal[g->transparent][3] = 0; } } else { // don't need transparent stbi__skip(s, 1); g->transparent = -1; } } else { stbi__skip(s, len); break; } } while ((len = stbi__get8(s)) != 0) { stbi__skip(s, len); } break; } case 0x3B: // gif stream termination code return (stbi_uc *) s; // using '1' causes warning on some compilers default: return stbi__errpuc("unknown code", "Corrupt GIF"); } } } static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) { if (stbi__gif_test(s)) { int layers = 0; stbi_uc *u = 0; stbi_uc *out = 0; stbi_uc *two_back = 0; stbi__gif g; int stride; int out_size = 0; int delays_size = 0; memset(&g, 0, sizeof(g)); if (delays) { *delays = 0; } do { u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; ++layers; stride = g.w * g.h * 4; if (out) { void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); if (NULL == tmp) { STBI_FREE(g.out); STBI_FREE(g.history); STBI_FREE(g.background); return stbi__errpuc("outofmem", "Out of memory"); } else { out = (stbi_uc*) tmp; out_size = layers * stride; } if (delays) { *delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); delays_size = layers * sizeof(int); } } else { out = (stbi_uc*)stbi__malloc( layers * stride ); out_size = layers * stride; if (delays) { *delays = (int*) stbi__malloc( layers * sizeof(int) ); delays_size = layers * sizeof(int); } } memcpy( out + ((layers - 1) * stride), u, stride ); if (layers >= 2) { two_back = out - 2 * stride; } if (delays) { (*delays)[layers - 1U] = g.delay; } } } while (u != 0); // free temp buffer; STBI_FREE(g.out); STBI_FREE(g.history); STBI_FREE(g.background); // do the final conversion after loading everything; if (req_comp && req_comp != 4) out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); *z = layers; return out; } else { return stbi__errpuc("not GIF", "Image was not as a gif type."); } } static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *u = 0; stbi__gif g; memset(&g, 0, sizeof(g)); STBI_NOTUSED(ri); u = stbi__gif_load_next(s, &g, comp, req_comp, 0); if (u == (stbi_uc *) s) u = 0; // end of animated gif marker if (u) { *x = g.w; *y = g.h; // moved conversion to after successful load so that the same // can be done for multiple frames. if (req_comp && req_comp != 4) u = stbi__convert_format(u, 4, req_comp, g.w, g.h); } else if (g.out) { // if there was an error and we allocated an image buffer, free it! STBI_FREE(g.out); } // free buffers needed for multiple frame loading; STBI_FREE(g.history); STBI_FREE(g.background); return u; } static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) { return stbi__gif_info_raw(s,x,y,comp); } #endif // ************************************************************************************************* // Radiance RGBE HDR loader // originally by Nicolas Schulz #ifndef STBI_NO_HDR static int stbi__hdr_test_core(stbi__context *s, const char *signature) { int i; for (i=0; signature[i]; ++i) if (stbi__get8(s) != signature[i]) return 0; stbi__rewind(s); return 1; } static int stbi__hdr_test(stbi__context* s) { int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); stbi__rewind(s); if(!r) { r = stbi__hdr_test_core(s, "#?RGBE\n"); stbi__rewind(s); } return r; } #define STBI__HDR_BUFLEN 1024 static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) { int len=0; char c = '\0'; c = (char) stbi__get8(z); while (!stbi__at_eof(z) && c != '\n') { buffer[len++] = c; if (len == STBI__HDR_BUFLEN-1) { // flush to end of line while (!stbi__at_eof(z) && stbi__get8(z) != '\n') ; break; } c = (char) stbi__get8(z); } buffer[len] = 0; return buffer; } static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) { if ( input[3] != 0 ) { float f1; // Exponent f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); if (req_comp <= 2) output[0] = (input[0] + input[1] + input[2]) * f1 / 3; else { output[0] = input[0] * f1; output[1] = input[1] * f1; output[2] = input[2] * f1; } if (req_comp == 2) output[1] = 1; if (req_comp == 4) output[3] = 1; } else { switch (req_comp) { case 4: output[3] = 1; /* fallthrough */ case 3: output[0] = output[1] = output[2] = 0; break; case 2: output[1] = 1; /* fallthrough */ case 1: output[0] = 0; break; } } } static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int width, height; stbi_uc *scanline; float *hdr_data; int len; unsigned char count, value; int i, j, k, c1,c2, z; const char *headerToken; STBI_NOTUSED(ri); // Check identifier headerToken = stbi__hdr_gettoken(s,buffer); if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) return stbi__errpf("not HDR", "Corrupt HDR image"); // Parse header for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); // Parse width and height // can't use sscanf() if we're not using stdio! token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; height = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); token += 3; width = (int) strtol(token, NULL, 10); if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); *x = width; *y = height; if (comp) *comp = 3; if (req_comp == 0) req_comp = 3; if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) return stbi__errpf("too large", "HDR image is too large"); // Read data hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); if (!hdr_data) return stbi__errpf("outofmem", "Out of memory"); // Load image data // image data is stored as some number of sca if ( width < 8 || width >= 32768) { // Read flat data for (j=0; j < height; ++j) { for (i=0; i < width; ++i) { stbi_uc rgbe[4]; main_decode_loop: stbi__getn(s, rgbe, 4); stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); } } } else { // Read RLE-encoded data scanline = NULL; for (j = 0; j < height; ++j) { c1 = stbi__get8(s); c2 = stbi__get8(s); len = stbi__get8(s); if (c1 != 2 || c2 != 2 || (len & 0x80)) { // not run-length encoded, so we have to actually use THIS data as a decoded // pixel (note this can't be a valid pixel--one of RGB must be >= 128) stbi_uc rgbe[4]; rgbe[0] = (stbi_uc) c1; rgbe[1] = (stbi_uc) c2; rgbe[2] = (stbi_uc) len; rgbe[3] = (stbi_uc) stbi__get8(s); stbi__hdr_convert(hdr_data, rgbe, req_comp); i = 1; j = 0; STBI_FREE(scanline); goto main_decode_loop; // yes, this makes no sense } len <<= 8; len |= stbi__get8(s); if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } if (scanline == NULL) { scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); if (!scanline) { STBI_FREE(hdr_data); return stbi__errpf("outofmem", "Out of memory"); } } for (k = 0; k < 4; ++k) { int nleft; i = 0; while ((nleft = width - i) > 0) { count = stbi__get8(s); if (count > 128) { // Run value = stbi__get8(s); count -= 128; if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = value; } else { // Dump if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } for (z = 0; z < count; ++z) scanline[i++ * 4 + k] = stbi__get8(s); } } } for (i=0; i < width; ++i) stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); } if (scanline) STBI_FREE(scanline); } return hdr_data; } static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) { char buffer[STBI__HDR_BUFLEN]; char *token; int valid = 0; int dummy; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__hdr_test(s) == 0) { stbi__rewind( s ); return 0; } for(;;) { token = stbi__hdr_gettoken(s,buffer); if (token[0] == 0) break; if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; } if (!valid) { stbi__rewind( s ); return 0; } token = stbi__hdr_gettoken(s,buffer); if (strncmp(token, "-Y ", 3)) { stbi__rewind( s ); return 0; } token += 3; *y = (int) strtol(token, &token, 10); while (*token == ' ') ++token; if (strncmp(token, "+X ", 3)) { stbi__rewind( s ); return 0; } token += 3; *x = (int) strtol(token, NULL, 10); *comp = 3; return 1; } #endif // STBI_NO_HDR #ifndef STBI_NO_BMP static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) { void *p; stbi__bmp_data info; info.all_a = 255; p = stbi__bmp_parse_header(s, &info); stbi__rewind( s ); if (p == NULL) return 0; if (x) *x = s->img_x; if (y) *y = s->img_y; if (comp) { if (info.bpp == 24 && info.ma == 0xff000000) *comp = 3; else *comp = info.ma ? 4 : 3; } return 1; } #endif #ifndef STBI_NO_PSD static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) { int channelCount, dummy, depth; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } *y = stbi__get32be(s); *x = stbi__get32be(s); depth = stbi__get16be(s); if (depth != 8 && depth != 16) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 3) { stbi__rewind( s ); return 0; } *comp = 4; return 1; } static int stbi__psd_is16(stbi__context *s) { int channelCount, depth; if (stbi__get32be(s) != 0x38425053) { stbi__rewind( s ); return 0; } if (stbi__get16be(s) != 1) { stbi__rewind( s ); return 0; } stbi__skip(s, 6); channelCount = stbi__get16be(s); if (channelCount < 0 || channelCount > 16) { stbi__rewind( s ); return 0; } (void) stbi__get32be(s); (void) stbi__get32be(s); depth = stbi__get16be(s); if (depth != 16) { stbi__rewind( s ); return 0; } return 1; } #endif #ifndef STBI_NO_PIC static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) { int act_comp=0,num_packets=0,chained,dummy; stbi__pic_packet packets[10]; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { stbi__rewind(s); return 0; } stbi__skip(s, 88); *x = stbi__get16be(s); *y = stbi__get16be(s); if (stbi__at_eof(s)) { stbi__rewind( s); return 0; } if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { stbi__rewind( s ); return 0; } stbi__skip(s, 8); do { stbi__pic_packet *packet; if (num_packets==sizeof(packets)/sizeof(packets[0])) return 0; packet = &packets[num_packets++]; chained = stbi__get8(s); packet->size = stbi__get8(s); packet->type = stbi__get8(s); packet->channel = stbi__get8(s); act_comp |= packet->channel; if (stbi__at_eof(s)) { stbi__rewind( s ); return 0; } if (packet->size != 8) { stbi__rewind( s ); return 0; } } while (chained); *comp = (act_comp & 0x10 ? 4 : 3); return 1; } #endif // ************************************************************************************************* // Portable Gray Map and Portable Pixel Map loader // by Ken Miller // // PGM: http://netpbm.sourceforge.net/doc/pgm.html // PPM: http://netpbm.sourceforge.net/doc/ppm.html // // Known limitations: // Does not support comments in the header section // Does not support ASCII image data (formats P2 and P3) // Does not support 16-bit-per-channel #ifndef STBI_NO_PNM static int stbi__pnm_test(stbi__context *s) { char p, t; p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind( s ); return 0; } return 1; } static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) { stbi_uc *out; STBI_NOTUSED(ri); if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) return 0; if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); *x = s->img_x; *y = s->img_y; if (comp) *comp = s->img_n; if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) return stbi__errpuc("too large", "PNM too large"); out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); if (!out) return stbi__errpuc("outofmem", "Out of memory"); stbi__getn(s, out, s->img_n * s->img_x * s->img_y); if (req_comp && req_comp != s->img_n) { out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); if (out == NULL) return out; // stbi__convert_format frees input on failure } return out; } static int stbi__pnm_isspace(char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; } static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) { for (;;) { while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) *c = (char) stbi__get8(s); if (stbi__at_eof(s) || *c != '#') break; while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) *c = (char) stbi__get8(s); } } static int stbi__pnm_isdigit(char c) { return c >= '0' && c <= '9'; } static int stbi__pnm_getinteger(stbi__context *s, char *c) { int value = 0; while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { value = value*10 + (*c - '0'); *c = (char) stbi__get8(s); } return value; } static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) { int maxv, dummy; char c, p, t; if (!x) x = &dummy; if (!y) y = &dummy; if (!comp) comp = &dummy; stbi__rewind(s); // Get identifier p = (char) stbi__get8(s); t = (char) stbi__get8(s); if (p != 'P' || (t != '5' && t != '6')) { stbi__rewind(s); return 0; } *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm c = (char) stbi__get8(s); stbi__pnm_skip_whitespace(s, &c); *x = stbi__pnm_getinteger(s, &c); // read width stbi__pnm_skip_whitespace(s, &c); *y = stbi__pnm_getinteger(s, &c); // read height stbi__pnm_skip_whitespace(s, &c); maxv = stbi__pnm_getinteger(s, &c); // read max value if (maxv > 255) return stbi__err("max value > 255", "PPM image not 8-bit"); else return 1; } #endif static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) { #ifndef STBI_NO_JPEG if (stbi__jpeg_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNG if (stbi__png_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_GIF if (stbi__gif_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_BMP if (stbi__bmp_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PIC if (stbi__pic_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_PNM if (stbi__pnm_info(s, x, y, comp)) return 1; #endif #ifndef STBI_NO_HDR if (stbi__hdr_info(s, x, y, comp)) return 1; #endif // test tga last because it's a crappy test! #ifndef STBI_NO_TGA if (stbi__tga_info(s, x, y, comp)) return 1; #endif return stbi__err("unknown image type", "Image not of any known type, or corrupt"); } static int stbi__is_16_main(stbi__context *s) { #ifndef STBI_NO_PNG if (stbi__png_is16(s)) return 1; #endif #ifndef STBI_NO_PSD if (stbi__psd_is16(s)) return 1; #endif return 0; } #ifndef STBI_NO_STDIO STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_info_from_file(f, x, y, comp); fclose(f); return result; } STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__info_main(&s,x,y,comp); fseek(f,pos,SEEK_SET); return r; } STBIDEF int stbi_is_16_bit(char const *filename) { FILE *f = stbi__fopen(filename, "rb"); int result; if (!f) return stbi__err("can't fopen", "Unable to open file"); result = stbi_is_16_bit_from_file(f); fclose(f); return result; } STBIDEF int stbi_is_16_bit_from_file(FILE *f) { int r; stbi__context s; long pos = ftell(f); stbi__start_file(&s, f); r = stbi__is_16_main(&s); fseek(f,pos,SEEK_SET); return r; } #endif // !STBI_NO_STDIO STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__info_main(&s,x,y,comp); } STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) { stbi__context s; stbi__start_mem(&s,buffer,len); return stbi__is_16_main(&s); } STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) { stbi__context s; stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); return stbi__is_16_main(&s); } #endif // STB_IMAGE_IMPLEMENTATION /* revision history: 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs 2.19 (2018-02-11) fix warning 2.18 (2018-01-30) fix warnings 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug 1-bit BMP *_is_16_bit api avoid warnings 2.16 (2017-07-23) all functions have 16-bit variants; STBI_NO_STDIO works again; compilation fixes; fix rounding in unpremultiply; optimize vertical flip; disable raw_len validation; documentation fixes 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; warning fixes; disable run-time SSE detection on gcc; uniform handling of optional "return" values; thread-safe initialization of zlib tables 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes 2.11 (2016-04-02) allocate large structures on the stack remove white matting for transparent PSD fix reported channel count for PNG & BMP re-enable SSE2 in non-gcc 64-bit support RGB-formatted JPEG read 16-bit PNGs (only as 8-bit) 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED 2.09 (2016-01-16) allow comments in PNM files 16-bit-per-pixel TGA (not bit-per-component) info() for TGA could break due to .hdr handling info() for BMP to shares code instead of sloppy parse can use STBI_REALLOC_SIZED if allocator doesn't support realloc code cleanup 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA 2.07 (2015-09-13) fix compiler warnings partial animated GIF support limited 16-bpc PSD support #ifdef unused functions bug with < 92 byte PIC,PNM,HDR,TGA 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit 2.03 (2015-04-12) extra corruption checking (mmozeiko) stbi_set_flip_vertically_on_load (nguillemot) fix NEON support; fix mingw support 2.02 (2015-01-19) fix incorrect assert, fix warning 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) progressive JPEG (stb) PGM/PPM support (Ken Miller) STBI_MALLOC,STBI_REALLOC,STBI_FREE GIF bugfix -- seemingly never worked STBI_NO_*, STBI_ONLY_* 1.48 (2014-12-14) fix incorrectly-named assert() 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) optimize PNG (ryg) fix bug in interlaced PNG with user-specified channel count (stb) 1.46 (2014-08-26) fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG 1.45 (2014-08-16) fix MSVC-ARM internal compiler error by wrapping malloc 1.44 (2014-08-07) various warning fixes from Ronny Chevalier 1.43 (2014-07-15) fix MSVC-only compiler problem in code changed in 1.42 1.42 (2014-07-09) don't define _CRT_SECURE_NO_WARNINGS (affects user code) fixes to stbi__cleanup_jpeg path added STBI_ASSERT to avoid requiring assert.h 1.41 (2014-06-25) fix search&replace from 1.36 that messed up comments/error messages 1.40 (2014-06-22) fix gcc struct-initialization warning 1.39 (2014-06-15) fix to TGA optimization when req_comp != number of components in TGA; fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) add support for BMP version 5 (more ignored fields) 1.38 (2014-06-06) suppress MSVC warnings on integer casts truncating values fix accidental rename of 'skip' field of I/O 1.37 (2014-06-04) remove duplicate typedef 1.36 (2014-06-03) convert to header file single-file library if de-iphone isn't set, load iphone images color-swapped instead of returning NULL 1.35 (2014-05-27) various warnings fix broken STBI_SIMD path fix bug where stbi_load_from_file no longer left file pointer in correct place fix broken non-easy path for 32-bit BMP (possibly never used) TGA optimization by Arseny Kapoulkine 1.34 (unknown) use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case 1.33 (2011-07-14) make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements 1.32 (2011-07-13) support for "info" function for all supported filetypes (SpartanJ) 1.31 (2011-06-20) a few more leak fixes, bug in PNG handling (SpartanJ) 1.30 (2011-06-11) added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) removed deprecated format-specific test/load functions removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) fix inefficiency in decoding 32-bit BMP (David Woo) 1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ) 1.27 (2010-08-01) cast-to-stbi_uc to fix warnings 1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ 1.25 (2010-07-17) refix trans_data warning (Won Chun) 1.24 (2010-07-12) perf improvements reading from files on platforms with lock-heavy fgetc() minor perf improvements for jpeg deprecated type-specific functions so we'll get feedback if they're needed attempt to fix trans_data warning (Won Chun) 1.23 fixed bug in iPhone support 1.22 (2010-07-10) removed image *writing* support stbi_info support from Jetro Lauha GIF support from Jean-Marc Lienher iPhone PNG-extensions from James Brown warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) 1.21 fix use of 'stbi_uc' in header (reported by jon blow) 1.20 added support for Softimage PIC, by Tom Seddon 1.19 bug in interlaced PNG corruption check (found by ryg) 1.18 (2008-08-02) fix a threading bug (local mutable static) 1.17 support interlaced PNG 1.16 major bugfix - stbi__convert_format converted one too many pixels 1.15 initialize some fields for thread safety 1.14 fix threadsafe conversion bug header-file-only version (#define STBI_HEADER_FILE_ONLY before including) 1.13 threadsafe 1.12 const qualifiers in the API 1.11 Support installable IDCT, colorspace conversion routines 1.10 Fixes for 64-bit (don't use "unsigned long") optimized upsampling by Fabian "ryg" Giesen 1.09 Fix format-conversion for PSD code (bad global variables!) 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz 1.07 attempt to fix C++ warning/errors again 1.06 attempt to fix C++ warning/errors again 1.05 fix TGA loading to return correct *comp and use good luminance calc 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR 1.02 support for (subset of) HDR files, float interface for preferred access to them 1.01 fix bug: possible bug in handling right-side up bmps... not sure fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all 1.00 interface to zlib that skips zlib header 0.99 correct handling of alpha in palette 0.98 TGA loader by lonesock; dynamically add loaders (untested) 0.97 jpeg errors on too large a file; also catch another malloc failure 0.96 fix detection of invalid v value - particleman@mollyrocket forum 0.95 during header scan, seek to markers in case of padding 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same 0.93 handle jpegtran output; verbose errors 0.92 read 4,8,16,24,32-bit BMP files of several formats 0.91 output 24-bit Windows 3.0 BMP files 0.90 fix a few more warnings; bump version number to approach 1.0 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd 0.60 fix compiling as c++ 0.59 fix warnings: merge Dave Moore's -Wall fixes 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available 0.56 fix bug: zlib uncompressed mode len vs. nlen 0.55 fix bug: restart_interval not initialized to 0 0.54 allow NULL for 'int *comp' 0.53 fix bug in png 3->4; speedup png decoding 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments 0.51 obey req_comp requests, 1-component jpegs return as 1-component, on 'test' only check type, not whether we support this variant 0.50 (2006-11-19) first released version */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
whupdup/frame
real/third_party/stb/stb_image.h
C++
gpl-3.0
273,150
#define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h"
whupdup/frame
real/third_party/stb/stb_image_resize.cpp
C++
gpl-3.0
70
/* stb_image_resize - v0.97 - public domain image resizing by Jorge L Rodriguez (@VinoBS) - 2014 http://github.com/nothings/stb Written with emphasis on usability, portability, and efficiency. (No SIMD or threads, so it be easily outperformed by libs that use those.) Only scaling and translation is supported, no rotations or shears. Easy API downsamples w/Mitchell filter, upsamples w/cubic interpolation. COMPILING & LINKING In one C/C++ file that #includes this file, do this: #define STB_IMAGE_RESIZE_IMPLEMENTATION before the #include. That will create the implementation in that file. QUICKSTART stbir_resize_uint8( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels) stbir_resize_float(...) stbir_resize_uint8_srgb( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0) stbir_resize_uint8_srgb_edgemode( input_pixels , in_w , in_h , 0, output_pixels, out_w, out_h, 0, num_channels , alpha_chan , 0, STBIR_EDGE_CLAMP) // WRAP/REFLECT/ZERO FULL API See the "header file" section of the source for API documentation. ADDITIONAL DOCUMENTATION SRGB & FLOATING POINT REPRESENTATION The sRGB functions presume IEEE floating point. If you do not have IEEE floating point, define STBIR_NON_IEEE_FLOAT. This will use a slower implementation. MEMORY ALLOCATION The resize functions here perform a single memory allocation using malloc. To control the memory allocation, before the #include that triggers the implementation, do: #define STBIR_MALLOC(size,context) ... #define STBIR_FREE(ptr,context) ... Each resize function makes exactly one call to malloc/free, so to use temp memory, store the temp memory in the context and return that. ASSERT Define STBIR_ASSERT(boolval) to override assert() and not use assert.h OPTIMIZATION Define STBIR_SATURATE_INT to compute clamp values in-range using integer operations instead of float operations. This may be faster on some platforms. DEFAULT FILTERS For functions which don't provide explicit control over what filters to use, you can change the compile-time defaults with #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_something #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_something See stbir_filter in the header-file section for the list of filters. NEW FILTERS A number of 1D filter kernels are used. For a list of supported filters see the stbir_filter enum. To add a new filter, write a filter function and add it to stbir__filter_info_table. PROGRESS For interactive use with slow resize operations, you can install a progress-report callback: #define STBIR_PROGRESS_REPORT(val) some_func(val) The parameter val is a float which goes from 0 to 1 as progress is made. For example: static void my_progress_report(float progress); #define STBIR_PROGRESS_REPORT(val) my_progress_report(val) #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize.h" static void my_progress_report(float progress) { printf("Progress: %f%%\n", progress*100); } MAX CHANNELS If your image has more than 64 channels, define STBIR_MAX_CHANNELS to the max you'll have. ALPHA CHANNEL Most of the resizing functions provide the ability to control how the alpha channel of an image is processed. The important things to know about this: 1. The best mathematically-behaved version of alpha to use is called "premultiplied alpha", in which the other color channels have had the alpha value multiplied in. If you use premultiplied alpha, linear filtering (such as image resampling done by this library, or performed in texture units on GPUs) does the "right thing". While premultiplied alpha is standard in the movie CGI industry, it is still uncommon in the videogame/real-time world. If you linearly filter non-premultiplied alpha, strange effects occur. (For example, the 50/50 average of 99% transparent bright green and 1% transparent black produces 50% transparent dark green when non-premultiplied, whereas premultiplied it produces 50% transparent near-black. The former introduces green energy that doesn't exist in the source image.) 2. Artists should not edit premultiplied-alpha images; artists want non-premultiplied alpha images. Thus, art tools generally output non-premultiplied alpha images. 3. You will get best results in most cases by converting images to premultiplied alpha before processing them mathematically. 4. If you pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, the resizer does not do anything special for the alpha channel; it is resampled identically to other channels. This produces the correct results for premultiplied-alpha images, but produces less-than-ideal results for non-premultiplied-alpha images. 5. If you do not pass the flag STBIR_FLAG_ALPHA_PREMULTIPLIED, then the resizer weights the contribution of input pixels based on their alpha values, or, equivalently, it multiplies the alpha value into the color channels, resamples, then divides by the resultant alpha value. Input pixels which have alpha=0 do not contribute at all to output pixels unless _all_ of the input pixels affecting that output pixel have alpha=0, in which case the result for that pixel is the same as it would be without STBIR_FLAG_ALPHA_PREMULTIPLIED. However, this is only true for input images in integer formats. For input images in float format, input pixels with alpha=0 have no effect, and output pixels which have alpha=0 will be 0 in all channels. (For float images, you can manually achieve the same result by adding a tiny epsilon value to the alpha channel of every image, and then subtracting or clamping it at the end.) 6. You can suppress the behavior described in #5 and make all-0-alpha pixels have 0 in all channels by #defining STBIR_NO_ALPHA_EPSILON. 7. You can separately control whether the alpha channel is interpreted as linear or affected by the colorspace. By default it is linear; you almost never want to apply the colorspace. (For example, graphics hardware does not apply sRGB conversion to the alpha channel.) CONTRIBUTORS Jorge L Rodriguez: Implementation Sean Barrett: API design, optimizations Aras Pranckevicius: bugfix Nathan Reed: warning fixes REVISIONS 0.97 (2020-02-02) fixed warning 0.96 (2019-03-04) fixed warnings 0.95 (2017-07-23) fixed warnings 0.94 (2017-03-18) fixed warnings 0.93 (2017-03-03) fixed bug with certain combinations of heights 0.92 (2017-01-02) fix integer overflow on large (>2GB) images 0.91 (2016-04-02) fix warnings; fix handling of subpixel regions 0.90 (2014-09-17) first released version LICENSE See end of file for license information. TODO Don't decode all of the image data when only processing a partial tile Don't use full-width decode buffers when only processing a partial tile When processing wide images, break processing into tiles so data fits in L1 cache Installable filters? Resize that respects alpha test coverage (Reference code: FloatImage::alphaTestCoverage and FloatImage::scaleAlphaToCoverage: https://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvimage/FloatImage.cpp ) */ #ifndef STBIR_INCLUDE_STB_IMAGE_RESIZE_H #define STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef _MSC_VER typedef unsigned char stbir_uint8; typedef unsigned short stbir_uint16; typedef unsigned int stbir_uint32; #else #include <stdint.h> typedef uint8_t stbir_uint8; typedef uint16_t stbir_uint16; typedef uint32_t stbir_uint32; #endif #ifndef STBIRDEF #ifdef STB_IMAGE_RESIZE_STATIC #define STBIRDEF static #else #ifdef __cplusplus #define STBIRDEF extern "C" #else #define STBIRDEF extern #endif #endif #endif ////////////////////////////////////////////////////////////////////////////// // // Easy-to-use API: // // * "input pixels" points to an array of image data with 'num_channels' channels (e.g. RGB=3, RGBA=4) // * input_w is input image width (x-axis), input_h is input image height (y-axis) // * stride is the offset between successive rows of image data in memory, in bytes. you can // specify 0 to mean packed continuously in memory // * alpha channel is treated identically to other channels. // * colorspace is linear or sRGB as specified by function name // * returned result is 1 for success or 0 in case of an error. // #define STBIR_ASSERT() to trigger an assert on parameter validation errors. // * Memory required grows approximately linearly with input and output size, but with // discontinuities at input_w == output_w and input_h == output_h. // * These functions use a "default" resampling filter defined at compile time. To change the filter, // you can change the compile-time defaults by #defining STBIR_DEFAULT_FILTER_UPSAMPLE // and STBIR_DEFAULT_FILTER_DOWNSAMPLE, or you can use the medium-complexity API. STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels); // The following functions interpret image data as gamma-corrected sRGB. // Specify STBIR_ALPHA_CHANNEL_NONE if you have no alpha channel, // or otherwise provide the index of the alpha channel. Flags value // of 0 will probably do the right thing if you're not sure what // the flags mean. #define STBIR_ALPHA_CHANNEL_NONE -1 // Set this flag if your texture has premultiplied alpha. Otherwise, stbir will // use alpha-weighted resampling (effectively premultiplying, resampling, // then unpremultiplying). #define STBIR_FLAG_ALPHA_PREMULTIPLIED (1 << 0) // The specified alpha channel should be handled as gamma-corrected value even // when doing sRGB operations. #define STBIR_FLAG_ALPHA_USES_COLORSPACE (1 << 1) STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags); typedef enum { STBIR_EDGE_CLAMP = 1, STBIR_EDGE_REFLECT = 2, STBIR_EDGE_WRAP = 3, STBIR_EDGE_ZERO = 4, } stbir_edge; // This function adds the ability to specify how requests to sample off the edge of the image are handled. STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode); ////////////////////////////////////////////////////////////////////////////// // // Medium-complexity API // // This extends the easy-to-use API as follows: // // * Alpha-channel can be processed separately // * If alpha_channel is not STBIR_ALPHA_CHANNEL_NONE // * Alpha channel will not be gamma corrected (unless flags&STBIR_FLAG_GAMMA_CORRECT) // * Filters will be weighted by alpha channel (unless flags&STBIR_FLAG_ALPHA_PREMULTIPLIED) // * Filter can be selected explicitly // * uint16 image type // * sRGB colorspace available for all types // * context parameter for passing to STBIR_MALLOC typedef enum { STBIR_FILTER_DEFAULT = 0, // use same filter type that easy-to-use API chooses STBIR_FILTER_BOX = 1, // A trapezoid w/1-pixel wide ramps, same result as box for integer scale ratios STBIR_FILTER_TRIANGLE = 2, // On upsampling, produces same results as bilinear texture filtering STBIR_FILTER_CUBICBSPLINE = 3, // The cubic b-spline (aka Mitchell-Netrevalli with B=1,C=0), gaussian-esque STBIR_FILTER_CATMULLROM = 4, // An interpolating cubic spline STBIR_FILTER_MITCHELL = 5, // Mitchell-Netrevalli filter with B=1/3, C=1/3 } stbir_filter; typedef enum { STBIR_COLORSPACE_LINEAR, STBIR_COLORSPACE_SRGB, STBIR_MAX_COLORSPACES, } stbir_colorspace; // The following functions are all identical except for the type of the image data STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context); ////////////////////////////////////////////////////////////////////////////// // // Full-complexity API // // This extends the medium API as follows: // // * uint32 image type // * not typesafe // * separate filter types for each axis // * separate edge modes for each axis // * can specify scale explicitly for subpixel correctness // * can specify image source tile using texture coordinates typedef enum { STBIR_TYPE_UINT8 , STBIR_TYPE_UINT16, STBIR_TYPE_UINT32, STBIR_TYPE_FLOAT , STBIR_MAX_TYPES } stbir_datatype; STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context); STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset); STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1); // (s0, t0) & (s1, t1) are the top-left and bottom right corner (uv addressing style: [0, 1]x[0, 1]) of a region of the input image to use. // // //// end header file ///////////////////////////////////////////////////// #endif // STBIR_INCLUDE_STB_IMAGE_RESIZE_H #ifdef STB_IMAGE_RESIZE_IMPLEMENTATION #ifndef STBIR_ASSERT #include <assert.h> #define STBIR_ASSERT(x) assert(x) #endif // For memset #include <string.h> #include <math.h> #ifndef STBIR_MALLOC #include <stdlib.h> // use comma operator to evaluate c, to avoid "unused parameter" warnings #define STBIR_MALLOC(size,c) ((void)(c), malloc(size)) #define STBIR_FREE(ptr,c) ((void)(c), free(ptr)) #endif #ifndef _MSC_VER #ifdef __cplusplus #define stbir__inline inline #else #define stbir__inline #endif #else #define stbir__inline __forceinline #endif // should produce compiler error if size is wrong typedef unsigned char stbir__validate_uint32[sizeof(stbir_uint32) == 4 ? 1 : -1]; #ifdef _MSC_VER #define STBIR__NOTUSED(v) (void)(v) #else #define STBIR__NOTUSED(v) (void)sizeof(v) #endif #define STBIR__ARRAY_SIZE(a) (sizeof((a))/sizeof((a)[0])) #ifndef STBIR_DEFAULT_FILTER_UPSAMPLE #define STBIR_DEFAULT_FILTER_UPSAMPLE STBIR_FILTER_CATMULLROM #endif #ifndef STBIR_DEFAULT_FILTER_DOWNSAMPLE #define STBIR_DEFAULT_FILTER_DOWNSAMPLE STBIR_FILTER_MITCHELL #endif #ifndef STBIR_PROGRESS_REPORT #define STBIR_PROGRESS_REPORT(float_0_to_1) #endif #ifndef STBIR_MAX_CHANNELS #define STBIR_MAX_CHANNELS 64 #endif #if STBIR_MAX_CHANNELS > 65536 #error "Too many channels; STBIR_MAX_CHANNELS must be no more than 65536." // because we store the indices in 16-bit variables #endif // This value is added to alpha just before premultiplication to avoid // zeroing out color values. It is equivalent to 2^-80. If you don't want // that behavior (it may interfere if you have floating point images with // very small alpha values) then you can define STBIR_NO_ALPHA_EPSILON to // disable it. #ifndef STBIR_ALPHA_EPSILON #define STBIR_ALPHA_EPSILON ((float)1 / (1 << 20) / (1 << 20) / (1 << 20) / (1 << 20)) #endif #ifdef _MSC_VER #define STBIR__UNUSED_PARAM(v) (void)(v) #else #define STBIR__UNUSED_PARAM(v) (void)sizeof(v) #endif // must match stbir_datatype static unsigned char stbir__type_size[] = { 1, // STBIR_TYPE_UINT8 2, // STBIR_TYPE_UINT16 4, // STBIR_TYPE_UINT32 4, // STBIR_TYPE_FLOAT }; // Kernel function centered at 0 typedef float (stbir__kernel_fn)(float x, float scale); typedef float (stbir__support_fn)(float scale); typedef struct { stbir__kernel_fn* kernel; stbir__support_fn* support; } stbir__filter_info; // When upsampling, the contributors are which source pixels contribute. // When downsampling, the contributors are which destination pixels are contributed to. typedef struct { int n0; // First contributing pixel int n1; // Last contributing pixel } stbir__contributors; typedef struct { const void* input_data; int input_w; int input_h; int input_stride_bytes; void* output_data; int output_w; int output_h; int output_stride_bytes; float s0, t0, s1, t1; float horizontal_shift; // Units: output pixels float vertical_shift; // Units: output pixels float horizontal_scale; float vertical_scale; int channels; int alpha_channel; stbir_uint32 flags; stbir_datatype type; stbir_filter horizontal_filter; stbir_filter vertical_filter; stbir_edge edge_horizontal; stbir_edge edge_vertical; stbir_colorspace colorspace; stbir__contributors* horizontal_contributors; float* horizontal_coefficients; stbir__contributors* vertical_contributors; float* vertical_coefficients; int decode_buffer_pixels; float* decode_buffer; float* horizontal_buffer; // cache these because ceil/floor are inexplicably showing up in profile int horizontal_coefficient_width; int vertical_coefficient_width; int horizontal_filter_pixel_width; int vertical_filter_pixel_width; int horizontal_filter_pixel_margin; int vertical_filter_pixel_margin; int horizontal_num_contributors; int vertical_num_contributors; int ring_buffer_length_bytes; // The length of an individual entry in the ring buffer. The total number of ring buffers is stbir__get_filter_pixel_width(filter) int ring_buffer_num_entries; // Total number of entries in the ring buffer. int ring_buffer_first_scanline; int ring_buffer_last_scanline; int ring_buffer_begin_index; // first_scanline is at this index in the ring buffer float* ring_buffer; float* encode_buffer; // A temporary buffer to store floats so we don't lose precision while we do multiply-adds. int horizontal_contributors_size; int horizontal_coefficients_size; int vertical_contributors_size; int vertical_coefficients_size; int decode_buffer_size; int horizontal_buffer_size; int ring_buffer_size; int encode_buffer_size; } stbir__info; static const float stbir__max_uint8_as_float = 255.0f; static const float stbir__max_uint16_as_float = 65535.0f; static const double stbir__max_uint32_as_float = 4294967295.0; static stbir__inline int stbir__min(int a, int b) { return a < b ? a : b; } static stbir__inline float stbir__saturate(float x) { if (x < 0) return 0; if (x > 1) return 1; return x; } #ifdef STBIR_SATURATE_INT static stbir__inline stbir_uint8 stbir__saturate8(int x) { if ((unsigned int) x <= 255) return x; if (x < 0) return 0; return 255; } static stbir__inline stbir_uint16 stbir__saturate16(int x) { if ((unsigned int) x <= 65535) return x; if (x < 0) return 0; return 65535; } #endif static float stbir__srgb_uchar_to_linear_float[256] = { 0.000000f, 0.000304f, 0.000607f, 0.000911f, 0.001214f, 0.001518f, 0.001821f, 0.002125f, 0.002428f, 0.002732f, 0.003035f, 0.003347f, 0.003677f, 0.004025f, 0.004391f, 0.004777f, 0.005182f, 0.005605f, 0.006049f, 0.006512f, 0.006995f, 0.007499f, 0.008023f, 0.008568f, 0.009134f, 0.009721f, 0.010330f, 0.010960f, 0.011612f, 0.012286f, 0.012983f, 0.013702f, 0.014444f, 0.015209f, 0.015996f, 0.016807f, 0.017642f, 0.018500f, 0.019382f, 0.020289f, 0.021219f, 0.022174f, 0.023153f, 0.024158f, 0.025187f, 0.026241f, 0.027321f, 0.028426f, 0.029557f, 0.030713f, 0.031896f, 0.033105f, 0.034340f, 0.035601f, 0.036889f, 0.038204f, 0.039546f, 0.040915f, 0.042311f, 0.043735f, 0.045186f, 0.046665f, 0.048172f, 0.049707f, 0.051269f, 0.052861f, 0.054480f, 0.056128f, 0.057805f, 0.059511f, 0.061246f, 0.063010f, 0.064803f, 0.066626f, 0.068478f, 0.070360f, 0.072272f, 0.074214f, 0.076185f, 0.078187f, 0.080220f, 0.082283f, 0.084376f, 0.086500f, 0.088656f, 0.090842f, 0.093059f, 0.095307f, 0.097587f, 0.099899f, 0.102242f, 0.104616f, 0.107023f, 0.109462f, 0.111932f, 0.114435f, 0.116971f, 0.119538f, 0.122139f, 0.124772f, 0.127438f, 0.130136f, 0.132868f, 0.135633f, 0.138432f, 0.141263f, 0.144128f, 0.147027f, 0.149960f, 0.152926f, 0.155926f, 0.158961f, 0.162029f, 0.165132f, 0.168269f, 0.171441f, 0.174647f, 0.177888f, 0.181164f, 0.184475f, 0.187821f, 0.191202f, 0.194618f, 0.198069f, 0.201556f, 0.205079f, 0.208637f, 0.212231f, 0.215861f, 0.219526f, 0.223228f, 0.226966f, 0.230740f, 0.234551f, 0.238398f, 0.242281f, 0.246201f, 0.250158f, 0.254152f, 0.258183f, 0.262251f, 0.266356f, 0.270498f, 0.274677f, 0.278894f, 0.283149f, 0.287441f, 0.291771f, 0.296138f, 0.300544f, 0.304987f, 0.309469f, 0.313989f, 0.318547f, 0.323143f, 0.327778f, 0.332452f, 0.337164f, 0.341914f, 0.346704f, 0.351533f, 0.356400f, 0.361307f, 0.366253f, 0.371238f, 0.376262f, 0.381326f, 0.386430f, 0.391573f, 0.396755f, 0.401978f, 0.407240f, 0.412543f, 0.417885f, 0.423268f, 0.428691f, 0.434154f, 0.439657f, 0.445201f, 0.450786f, 0.456411f, 0.462077f, 0.467784f, 0.473532f, 0.479320f, 0.485150f, 0.491021f, 0.496933f, 0.502887f, 0.508881f, 0.514918f, 0.520996f, 0.527115f, 0.533276f, 0.539480f, 0.545725f, 0.552011f, 0.558340f, 0.564712f, 0.571125f, 0.577581f, 0.584078f, 0.590619f, 0.597202f, 0.603827f, 0.610496f, 0.617207f, 0.623960f, 0.630757f, 0.637597f, 0.644480f, 0.651406f, 0.658375f, 0.665387f, 0.672443f, 0.679543f, 0.686685f, 0.693872f, 0.701102f, 0.708376f, 0.715694f, 0.723055f, 0.730461f, 0.737911f, 0.745404f, 0.752942f, 0.760525f, 0.768151f, 0.775822f, 0.783538f, 0.791298f, 0.799103f, 0.806952f, 0.814847f, 0.822786f, 0.830770f, 0.838799f, 0.846873f, 0.854993f, 0.863157f, 0.871367f, 0.879622f, 0.887923f, 0.896269f, 0.904661f, 0.913099f, 0.921582f, 0.930111f, 0.938686f, 0.947307f, 0.955974f, 0.964686f, 0.973445f, 0.982251f, 0.991102f, 1.0f }; static float stbir__srgb_to_linear(float f) { if (f <= 0.04045f) return f / 12.92f; else return (float)pow((f + 0.055f) / 1.055f, 2.4f); } static float stbir__linear_to_srgb(float f) { if (f <= 0.0031308f) return f * 12.92f; else return 1.055f * (float)pow(f, 1 / 2.4f) - 0.055f; } #ifndef STBIR_NON_IEEE_FLOAT // From https://gist.github.com/rygorous/2203834 typedef union { stbir_uint32 u; float f; } stbir__FP32; static const stbir_uint32 fp32_to_srgb8_tab4[104] = { 0x0073000d, 0x007a000d, 0x0080000d, 0x0087000d, 0x008d000d, 0x0094000d, 0x009a000d, 0x00a1000d, 0x00a7001a, 0x00b4001a, 0x00c1001a, 0x00ce001a, 0x00da001a, 0x00e7001a, 0x00f4001a, 0x0101001a, 0x010e0033, 0x01280033, 0x01410033, 0x015b0033, 0x01750033, 0x018f0033, 0x01a80033, 0x01c20033, 0x01dc0067, 0x020f0067, 0x02430067, 0x02760067, 0x02aa0067, 0x02dd0067, 0x03110067, 0x03440067, 0x037800ce, 0x03df00ce, 0x044600ce, 0x04ad00ce, 0x051400ce, 0x057b00c5, 0x05dd00bc, 0x063b00b5, 0x06970158, 0x07420142, 0x07e30130, 0x087b0120, 0x090b0112, 0x09940106, 0x0a1700fc, 0x0a9500f2, 0x0b0f01cb, 0x0bf401ae, 0x0ccb0195, 0x0d950180, 0x0e56016e, 0x0f0d015e, 0x0fbc0150, 0x10630143, 0x11070264, 0x1238023e, 0x1357021d, 0x14660201, 0x156601e9, 0x165a01d3, 0x174401c0, 0x182401af, 0x18fe0331, 0x1a9602fe, 0x1c1502d2, 0x1d7e02ad, 0x1ed4028d, 0x201a0270, 0x21520256, 0x227d0240, 0x239f0443, 0x25c003fe, 0x27bf03c4, 0x29a10392, 0x2b6a0367, 0x2d1d0341, 0x2ebe031f, 0x304d0300, 0x31d105b0, 0x34a80555, 0x37520507, 0x39d504c5, 0x3c37048b, 0x3e7c0458, 0x40a8042a, 0x42bd0401, 0x44c20798, 0x488e071e, 0x4c1c06b6, 0x4f76065d, 0x52a50610, 0x55ac05cc, 0x5892058f, 0x5b590559, 0x5e0c0a23, 0x631c0980, 0x67db08f6, 0x6c55087f, 0x70940818, 0x74a007bd, 0x787d076c, 0x7c330723, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float in) { static const stbir__FP32 almostone = { 0x3f7fffff }; // 1-eps static const stbir__FP32 minval = { (127-13) << 23 }; stbir_uint32 tab,bias,scale,t; stbir__FP32 f; // Clamp to [2^(-13), 1-eps]; these two values map to 0 and 1, respectively. // The tests are carefully written so that NaNs map to 0, same as in the reference // implementation. if (!(in > minval.f)) // written this way to catch NaNs in = minval.f; if (in > almostone.f) in = almostone.f; // Do the table lookup and unpack bias, scale f.f = in; tab = fp32_to_srgb8_tab4[(f.u - minval.u) >> 20]; bias = (tab >> 16) << 9; scale = tab & 0xffff; // Grab next-highest mantissa bits and perform linear interpolation t = (f.u >> 12) & 0xff; return (unsigned char) ((bias + scale*t) >> 16); } #else // sRGB transition values, scaled by 1<<28 static int stbir__srgb_offset_to_linear_scaled[256] = { 0, 40738, 122216, 203693, 285170, 366648, 448125, 529603, 611080, 692557, 774035, 855852, 942009, 1033024, 1128971, 1229926, 1335959, 1447142, 1563542, 1685229, 1812268, 1944725, 2082664, 2226148, 2375238, 2529996, 2690481, 2856753, 3028870, 3206888, 3390865, 3580856, 3776916, 3979100, 4187460, 4402049, 4622919, 4850123, 5083710, 5323731, 5570236, 5823273, 6082892, 6349140, 6622065, 6901714, 7188133, 7481369, 7781466, 8088471, 8402427, 8723380, 9051372, 9386448, 9728650, 10078021, 10434603, 10798439, 11169569, 11548036, 11933879, 12327139, 12727857, 13136073, 13551826, 13975156, 14406100, 14844697, 15290987, 15745007, 16206795, 16676389, 17153826, 17639142, 18132374, 18633560, 19142734, 19659934, 20185196, 20718552, 21260042, 21809696, 22367554, 22933648, 23508010, 24090680, 24681686, 25281066, 25888850, 26505076, 27129772, 27762974, 28404716, 29055026, 29713942, 30381490, 31057708, 31742624, 32436272, 33138682, 33849884, 34569912, 35298800, 36036568, 36783260, 37538896, 38303512, 39077136, 39859796, 40651528, 41452360, 42262316, 43081432, 43909732, 44747252, 45594016, 46450052, 47315392, 48190064, 49074096, 49967516, 50870356, 51782636, 52704392, 53635648, 54576432, 55526772, 56486700, 57456236, 58435408, 59424248, 60422780, 61431036, 62449032, 63476804, 64514376, 65561776, 66619028, 67686160, 68763192, 69850160, 70947088, 72053992, 73170912, 74297864, 75434880, 76581976, 77739184, 78906536, 80084040, 81271736, 82469648, 83677792, 84896192, 86124888, 87363888, 88613232, 89872928, 91143016, 92423512, 93714432, 95015816, 96327688, 97650056, 98982952, 100326408, 101680440, 103045072, 104420320, 105806224, 107202800, 108610064, 110028048, 111456776, 112896264, 114346544, 115807632, 117279552, 118762328, 120255976, 121760536, 123276016, 124802440, 126339832, 127888216, 129447616, 131018048, 132599544, 134192112, 135795792, 137410592, 139036528, 140673648, 142321952, 143981456, 145652208, 147334208, 149027488, 150732064, 152447968, 154175200, 155913792, 157663776, 159425168, 161197984, 162982240, 164777968, 166585184, 168403904, 170234160, 172075968, 173929344, 175794320, 177670896, 179559120, 181458992, 183370528, 185293776, 187228736, 189175424, 191133888, 193104112, 195086128, 197079968, 199085648, 201103184, 203132592, 205173888, 207227120, 209292272, 211369392, 213458480, 215559568, 217672656, 219797792, 221934976, 224084240, 226245600, 228419056, 230604656, 232802400, 235012320, 237234432, 239468736, 241715280, 243974080, 246245120, 248528464, 250824112, 253132064, 255452368, 257785040, 260130080, 262487520, 264857376, 267239664, }; static stbir_uint8 stbir__linear_to_srgb_uchar(float f) { int x = (int) (f * (1 << 28)); // has headroom so you don't need to clamp int v = 0; int i; // Refine the guess with a short binary search. i = v + 128; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 64; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 32; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 16; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 8; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 4; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 2; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; i = v + 1; if (x >= stbir__srgb_offset_to_linear_scaled[i]) v = i; return (stbir_uint8) v; } #endif static float stbir__filter_trapezoid(float x, float scale) { float halfscale = scale / 2; float t = 0.5f + halfscale; STBIR_ASSERT(scale <= 1); x = (float)fabs(x); if (x >= t) return 0; else { float r = 0.5f - halfscale; if (x <= r) return 1; else return (t - x) / scale; } } static float stbir__support_trapezoid(float scale) { STBIR_ASSERT(scale <= 1); return 0.5f + scale / 2; } static float stbir__filter_triangle(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x <= 1.0f) return 1 - x; else return 0; } static float stbir__filter_cubic(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (4 + x*x*(3*x - 6))/6; else if (x < 2.0f) return (8 + x*(-12 + x*(6 - x)))/6; return (0.0f); } static float stbir__filter_catmullrom(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return 1 - x*x*(2.5f - 1.5f*x); else if (x < 2.0f) return 2 - x*(4 + x*(0.5f*x - 2.5f)); return (0.0f); } static float stbir__filter_mitchell(float x, float s) { STBIR__UNUSED_PARAM(s); x = (float)fabs(x); if (x < 1.0f) return (16 + x*x*(21 * x - 36))/18; else if (x < 2.0f) return (32 + x*(-60 + x*(36 - 7*x)))/18; return (0.0f); } static float stbir__support_zero(float s) { STBIR__UNUSED_PARAM(s); return 0; } static float stbir__support_one(float s) { STBIR__UNUSED_PARAM(s); return 1; } static float stbir__support_two(float s) { STBIR__UNUSED_PARAM(s); return 2; } static stbir__filter_info stbir__filter_info_table[] = { { NULL, stbir__support_zero }, { stbir__filter_trapezoid, stbir__support_trapezoid }, { stbir__filter_triangle, stbir__support_one }, { stbir__filter_cubic, stbir__support_two }, { stbir__filter_catmullrom, stbir__support_two }, { stbir__filter_mitchell, stbir__support_two }, }; stbir__inline static int stbir__use_upsampling(float ratio) { return ratio > 1; } stbir__inline static int stbir__use_width_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->horizontal_scale); } stbir__inline static int stbir__use_height_upsampling(stbir__info* stbir_info) { return stbir__use_upsampling(stbir_info->vertical_scale); } // This is the maximum number of input samples that can affect an output sample // with the given filter static int stbir__get_filter_pixel_width(stbir_filter filter, float scale) { STBIR_ASSERT(filter != 0); STBIR_ASSERT(filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2 / scale); } // This is how much to expand buffers to account for filters seeking outside // the image boundaries. static int stbir__get_filter_pixel_margin(stbir_filter filter, float scale) { return stbir__get_filter_pixel_width(filter, scale) / 2; } static int stbir__get_coefficient_width(stbir_filter filter, float scale) { if (stbir__use_upsampling(scale)) return (int)ceil(stbir__filter_info_table[filter].support(1 / scale) * 2); else return (int)ceil(stbir__filter_info_table[filter].support(scale) * 2); } static int stbir__get_contributors(float scale, stbir_filter filter, int input_size, int output_size) { if (stbir__use_upsampling(scale)) return output_size; else return (input_size + stbir__get_filter_pixel_margin(filter, scale) * 2); } static int stbir__get_total_horizontal_coefficients(stbir__info* info) { return info->horizontal_num_contributors * stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); } static int stbir__get_total_vertical_coefficients(stbir__info* info) { return info->vertical_num_contributors * stbir__get_coefficient_width (info->vertical_filter, info->vertical_scale); } static stbir__contributors* stbir__get_contributor(stbir__contributors* contributors, int n) { return &contributors[n]; } // For perf reasons this code is duplicated in stbir__resample_horizontal_upsample/downsample, // if you change it here change it there too. static float* stbir__get_coefficient(float* coefficients, stbir_filter filter, float scale, int n, int c) { int width = stbir__get_coefficient_width(filter, scale); return &coefficients[width*n + c]; } static int stbir__edge_wrap_slow(stbir_edge edge, int n, int max) { switch (edge) { case STBIR_EDGE_ZERO: return 0; // we'll decode the wrong pixel here, and then overwrite with 0s later case STBIR_EDGE_CLAMP: if (n < 0) return 0; if (n >= max) return max - 1; return n; // NOTREACHED case STBIR_EDGE_REFLECT: { if (n < 0) { if (n < max) return -n; else return max - 1; } if (n >= max) { int max2 = max * 2; if (n >= max2) return 0; else return max2 - n - 1; } return n; // NOTREACHED } case STBIR_EDGE_WRAP: if (n >= 0) return (n % max); else { int m = (-n) % max; if (m != 0) m = max - m; return (m); } // NOTREACHED default: STBIR_ASSERT(!"Unimplemented edge type"); return 0; } } stbir__inline static int stbir__edge_wrap(stbir_edge edge, int n, int max) { // avoid per-pixel switch if (n >= 0 && n < max) return n; return stbir__edge_wrap_slow(edge, n, max); } // What input pixels contribute to this output pixel? static void stbir__calculate_sample_range_upsample(int n, float out_filter_radius, float scale_ratio, float out_shift, int* in_first_pixel, int* in_last_pixel, float* in_center_of_out) { float out_pixel_center = (float)n + 0.5f; float out_pixel_influence_lowerbound = out_pixel_center - out_filter_radius; float out_pixel_influence_upperbound = out_pixel_center + out_filter_radius; float in_pixel_influence_lowerbound = (out_pixel_influence_lowerbound + out_shift) / scale_ratio; float in_pixel_influence_upperbound = (out_pixel_influence_upperbound + out_shift) / scale_ratio; *in_center_of_out = (out_pixel_center + out_shift) / scale_ratio; *in_first_pixel = (int)(floor(in_pixel_influence_lowerbound + 0.5)); *in_last_pixel = (int)(floor(in_pixel_influence_upperbound - 0.5)); } // What output pixels does this input pixel contribute to? static void stbir__calculate_sample_range_downsample(int n, float in_pixels_radius, float scale_ratio, float out_shift, int* out_first_pixel, int* out_last_pixel, float* out_center_of_in) { float in_pixel_center = (float)n + 0.5f; float in_pixel_influence_lowerbound = in_pixel_center - in_pixels_radius; float in_pixel_influence_upperbound = in_pixel_center + in_pixels_radius; float out_pixel_influence_lowerbound = in_pixel_influence_lowerbound * scale_ratio - out_shift; float out_pixel_influence_upperbound = in_pixel_influence_upperbound * scale_ratio - out_shift; *out_center_of_in = in_pixel_center * scale_ratio - out_shift; *out_first_pixel = (int)(floor(out_pixel_influence_lowerbound + 0.5)); *out_last_pixel = (int)(floor(out_pixel_influence_upperbound - 0.5)); } static void stbir__calculate_coefficients_upsample(stbir_filter filter, float scale, int in_first_pixel, int in_last_pixel, float in_center_of_out, stbir__contributors* contributor, float* coefficient_group) { int i; float total_filter = 0; float filter_scale; STBIR_ASSERT(in_last_pixel - in_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(1/scale) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = in_first_pixel; contributor->n1 = in_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= in_last_pixel - in_first_pixel; i++) { float in_pixel_center = (float)(i + in_first_pixel) + 0.5f; coefficient_group[i] = stbir__filter_info_table[filter].kernel(in_center_of_out - in_pixel_center, 1 / scale); // If the coefficient is zero, skip it. (Don't do the <0 check here, we want the influence of those outside pixels.) if (i == 0 && !coefficient_group[i]) { contributor->n0 = ++in_first_pixel; i--; continue; } total_filter += coefficient_group[i]; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(in_last_pixel + 1) + 0.5f - in_center_of_out, 1/scale) == 0); STBIR_ASSERT(total_filter > 0.9); STBIR_ASSERT(total_filter < 1.1f); // Make sure it's not way off. // Make sure the sum of all coefficients is 1. filter_scale = 1 / total_filter; for (i = 0; i <= in_last_pixel - in_first_pixel; i++) coefficient_group[i] *= filter_scale; for (i = in_last_pixel - in_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__calculate_coefficients_downsample(stbir_filter filter, float scale_ratio, int out_first_pixel, int out_last_pixel, float out_center_of_in, stbir__contributors* contributor, float* coefficient_group) { int i; STBIR_ASSERT(out_last_pixel - out_first_pixel <= (int)ceil(stbir__filter_info_table[filter].support(scale_ratio) * 2)); // Taken directly from stbir__get_coefficient_width() which we can't call because we don't know if we're horizontal or vertical. contributor->n0 = out_first_pixel; contributor->n1 = out_last_pixel; STBIR_ASSERT(contributor->n1 >= contributor->n0); for (i = 0; i <= out_last_pixel - out_first_pixel; i++) { float out_pixel_center = (float)(i + out_first_pixel) + 0.5f; float x = out_pixel_center - out_center_of_in; coefficient_group[i] = stbir__filter_info_table[filter].kernel(x, scale_ratio) * scale_ratio; } // NOTE(fg): Not actually true in general, nor is there any reason to expect it should be. // It would be true in exact math but is at best approximately true in floating-point math, // and it would not make sense to try and put actual bounds on this here because it depends // on the image aspect ratio which can get pretty extreme. //STBIR_ASSERT(stbir__filter_info_table[filter].kernel((float)(out_last_pixel + 1) + 0.5f - out_center_of_in, scale_ratio) == 0); for (i = out_last_pixel - out_first_pixel; i >= 0; i--) { if (coefficient_group[i]) break; // This line has no weight. We can skip it. contributor->n1 = contributor->n0 + i - 1; } } static void stbir__normalize_downsample_coefficients(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, int input_size, int output_size) { int num_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); int num_coefficients = stbir__get_coefficient_width(filter, scale_ratio); int i, j; int skip; for (i = 0; i < output_size; i++) { float scale; float total = 0; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) { float coefficient = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0); total += coefficient; } else if (i < contributors[j].n0) break; } STBIR_ASSERT(total > 0.9f); STBIR_ASSERT(total < 1.1f); scale = 1 / total; for (j = 0; j < num_contributors; j++) { if (i >= contributors[j].n0 && i <= contributors[j].n1) *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i - contributors[j].n0) *= scale; else if (i < contributors[j].n0) break; } } // Optimize: Skip zero coefficients and contributions outside of image bounds. // Do this after normalizing because normalization depends on the n0/n1 values. for (j = 0; j < num_contributors; j++) { int range, max, width; skip = 0; while (*stbir__get_coefficient(coefficients, filter, scale_ratio, j, skip) == 0) skip++; contributors[j].n0 += skip; while (contributors[j].n0 < 0) { contributors[j].n0++; skip++; } range = contributors[j].n1 - contributors[j].n0 + 1; max = stbir__min(num_coefficients, range); width = stbir__get_coefficient_width(filter, scale_ratio); for (i = 0; i < max; i++) { if (i + skip >= width) break; *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i) = *stbir__get_coefficient(coefficients, filter, scale_ratio, j, i + skip); } continue; } // Using min to avoid writing into invalid pixels. for (i = 0; i < num_contributors; i++) contributors[i].n1 = stbir__min(contributors[i].n1, output_size - 1); } // Each scan line uses the same kernel values so we should calculate the kernel // values once and then we can use them for every scan line. static void stbir__calculate_filters(stbir__contributors* contributors, float* coefficients, stbir_filter filter, float scale_ratio, float shift, int input_size, int output_size) { int n; int total_contributors = stbir__get_contributors(scale_ratio, filter, input_size, output_size); if (stbir__use_upsampling(scale_ratio)) { float out_pixels_radius = stbir__filter_info_table[filter].support(1 / scale_ratio) * scale_ratio; // Looping through out pixels for (n = 0; n < total_contributors; n++) { float in_center_of_out; // Center of the current out pixel in the in pixel space int in_first_pixel, in_last_pixel; stbir__calculate_sample_range_upsample(n, out_pixels_radius, scale_ratio, shift, &in_first_pixel, &in_last_pixel, &in_center_of_out); stbir__calculate_coefficients_upsample(filter, scale_ratio, in_first_pixel, in_last_pixel, in_center_of_out, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } } else { float in_pixels_radius = stbir__filter_info_table[filter].support(scale_ratio) / scale_ratio; // Looping through in pixels for (n = 0; n < total_contributors; n++) { float out_center_of_in; // Center of the current out pixel in the in pixel space int out_first_pixel, out_last_pixel; int n_adjusted = n - stbir__get_filter_pixel_margin(filter, scale_ratio); stbir__calculate_sample_range_downsample(n_adjusted, in_pixels_radius, scale_ratio, shift, &out_first_pixel, &out_last_pixel, &out_center_of_in); stbir__calculate_coefficients_downsample(filter, scale_ratio, out_first_pixel, out_last_pixel, out_center_of_in, stbir__get_contributor(contributors, n), stbir__get_coefficient(coefficients, filter, scale_ratio, n, 0)); } stbir__normalize_downsample_coefficients(contributors, coefficients, filter, scale_ratio, input_size, output_size); } } static float* stbir__get_decode_buffer(stbir__info* stbir_info) { // The 0 index of the decode buffer starts after the margin. This makes // it okay to use negative indexes on the decode buffer. return &stbir_info->decode_buffer[stbir_info->horizontal_filter_pixel_margin * stbir_info->channels]; } #define STBIR__DECODE(type, colorspace) ((int)(type) * (STBIR_MAX_COLORSPACES) + (int)(colorspace)) static void stbir__decode_scanline(stbir__info* stbir_info, int n) { int c; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int input_w = stbir_info->input_w; size_t input_stride_bytes = stbir_info->input_stride_bytes; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir_edge edge_horizontal = stbir_info->edge_horizontal; stbir_edge edge_vertical = stbir_info->edge_vertical; size_t in_buffer_row_offset = stbir__edge_wrap(edge_vertical, n, stbir_info->input_h) * input_stride_bytes; const void* input_data = (char *) stbir_info->input_data + in_buffer_row_offset; int max_x = input_w + stbir_info->horizontal_filter_pixel_margin; int decode = STBIR__DECODE(type, colorspace); int x = -stbir_info->horizontal_filter_pixel_margin; // special handling for STBIR_EDGE_ZERO because it needs to return an item that doesn't appear in the input, // and we want to avoid paying overhead on every pixel if not STBIR_EDGE_ZERO if (edge_vertical == STBIR_EDGE_ZERO && (n < 0 || n >= stbir_info->input_h)) { for (; x < max_x; x++) for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; return; } switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned char*)input_data)[input_pixel_index + c]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_uchar_to_linear_float[((const unsigned char*)input_data)[input_pixel_index + c]]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned char*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint8_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((float)((const unsigned short*)input_data)[input_pixel_index + c]) / stbir__max_uint16_as_float); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((float)((const unsigned short*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint16_as_float; } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear((float)(((double)((const unsigned int*)input_data)[input_pixel_index + c]) / stbir__max_uint32_as_float)); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = (float)(((double)((const unsigned int*)input_data)[input_pixel_index + alpha_channel]) / stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = ((const float*)input_data)[input_pixel_index + c]; } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (; x < max_x; x++) { int decode_pixel_index = x * channels; int input_pixel_index = stbir__edge_wrap(edge_horizontal, x, input_w) * channels; for (c = 0; c < channels; c++) decode_buffer[decode_pixel_index + c] = stbir__srgb_to_linear(((const float*)input_data)[input_pixel_index + c]); if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) decode_buffer[decode_pixel_index + alpha_channel] = ((const float*)input_data)[input_pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < max_x; x++) { int decode_pixel_index = x * channels; // If the alpha value is 0 it will clobber the color values. Make sure it's not. float alpha = decode_buffer[decode_pixel_index + alpha_channel]; #ifndef STBIR_NO_ALPHA_EPSILON if (stbir_info->type != STBIR_TYPE_FLOAT) { alpha += STBIR_ALPHA_EPSILON; decode_buffer[decode_pixel_index + alpha_channel] = alpha; } #endif for (c = 0; c < channels; c++) { if (c == alpha_channel) continue; decode_buffer[decode_pixel_index + c] *= alpha; } } } if (edge_horizontal == STBIR_EDGE_ZERO) { for (x = -stbir_info->horizontal_filter_pixel_margin; x < 0; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } for (x = input_w; x < max_x; x++) { for (c = 0; c < channels; c++) decode_buffer[x*channels + c] = 0; } } } static float* stbir__get_ring_buffer_entry(float* ring_buffer, int index, int ring_buffer_length) { return &ring_buffer[index * ring_buffer_length]; } static float* stbir__add_empty_ring_buffer_entry(stbir__info* stbir_info, int n) { int ring_buffer_index; float* ring_buffer; stbir_info->ring_buffer_last_scanline = n; if (stbir_info->ring_buffer_begin_index < 0) { ring_buffer_index = stbir_info->ring_buffer_begin_index = 0; stbir_info->ring_buffer_first_scanline = n; } else { ring_buffer_index = (stbir_info->ring_buffer_begin_index + (stbir_info->ring_buffer_last_scanline - stbir_info->ring_buffer_first_scanline)) % stbir_info->ring_buffer_num_entries; STBIR_ASSERT(ring_buffer_index != stbir_info->ring_buffer_begin_index); } ring_buffer = stbir__get_ring_buffer_entry(stbir_info->ring_buffer, ring_buffer_index, stbir_info->ring_buffer_length_bytes / sizeof(float)); memset(ring_buffer, 0, stbir_info->ring_buffer_length_bytes); return ring_buffer; } static void stbir__resample_horizontal_upsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int output_w = stbir_info->output_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; for (x = 0; x < output_w; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int out_pixel_index = x * channels; int coefficient_group = coefficient_width * x; int coefficient_counter = 0; STBIR_ASSERT(n1 >= n0); STBIR_ASSERT(n0 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 >= -stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n0 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); STBIR_ASSERT(n1 < stbir_info->input_w + stbir_info->horizontal_filter_pixel_margin); switch (channels) { case 1: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (k = n0; k <= n1; k++) { int in_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; STBIR_ASSERT(coefficient != 0); output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } break; default: for (k = n0; k <= n1; k++) { int in_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + coefficient_counter++]; int c; STBIR_ASSERT(coefficient != 0); for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__resample_horizontal_downsample(stbir__info* stbir_info, float* output_buffer) { int x, k; int input_w = stbir_info->input_w; int channels = stbir_info->channels; float* decode_buffer = stbir__get_decode_buffer(stbir_info); stbir__contributors* horizontal_contributors = stbir_info->horizontal_contributors; float* horizontal_coefficients = stbir_info->horizontal_coefficients; int coefficient_width = stbir_info->horizontal_coefficient_width; int filter_pixel_margin = stbir_info->horizontal_filter_pixel_margin; int max_x = input_w + filter_pixel_margin * 2; STBIR_ASSERT(!stbir__use_width_upsampling(stbir_info)); switch (channels) { case 1: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 1; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 1; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; } } break; case 2: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 2; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 2; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; } } break; case 3: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 3; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 3; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; } } break; case 4: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * 4; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int out_pixel_index = k * 4; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; output_buffer[out_pixel_index + 0] += decode_buffer[in_pixel_index + 0] * coefficient; output_buffer[out_pixel_index + 1] += decode_buffer[in_pixel_index + 1] * coefficient; output_buffer[out_pixel_index + 2] += decode_buffer[in_pixel_index + 2] * coefficient; output_buffer[out_pixel_index + 3] += decode_buffer[in_pixel_index + 3] * coefficient; } } break; default: for (x = 0; x < max_x; x++) { int n0 = horizontal_contributors[x].n0; int n1 = horizontal_contributors[x].n1; int in_x = x - filter_pixel_margin; int in_pixel_index = in_x * channels; int max_n = n1; int coefficient_group = coefficient_width * x; for (k = n0; k <= max_n; k++) { int c; int out_pixel_index = k * channels; float coefficient = horizontal_coefficients[coefficient_group + k - n0]; for (c = 0; c < channels; c++) output_buffer[out_pixel_index + c] += decode_buffer[in_pixel_index + c] * coefficient; } } break; } } static void stbir__decode_and_resample_upsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); // Now resample it into the ring buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); else stbir__resample_horizontal_downsample(stbir_info, stbir__add_empty_ring_buffer_entry(stbir_info, n)); // Now it's sitting in the ring buffer ready to be used as source for the vertical sampling. } static void stbir__decode_and_resample_downsample(stbir__info* stbir_info, int n) { // Decode the nth scanline from the source image into the decode buffer. stbir__decode_scanline(stbir_info, n); memset(stbir_info->horizontal_buffer, 0, stbir_info->output_w * stbir_info->channels * sizeof(float)); // Now resample it into the horizontal buffer. if (stbir__use_width_upsampling(stbir_info)) stbir__resample_horizontal_upsample(stbir_info, stbir_info->horizontal_buffer); else stbir__resample_horizontal_downsample(stbir_info, stbir_info->horizontal_buffer); // Now it's sitting in the horizontal buffer ready to be distributed into the ring buffers. } // Get the specified scan line from the ring buffer. static float* stbir__get_ring_buffer_scanline(int get_scanline, float* ring_buffer, int begin_index, int first_scanline, int ring_buffer_num_entries, int ring_buffer_length) { int ring_buffer_index = (begin_index + (get_scanline - first_scanline)) % ring_buffer_num_entries; return stbir__get_ring_buffer_entry(ring_buffer, ring_buffer_index, ring_buffer_length); } static void stbir__encode_scanline(stbir__info* stbir_info, int num_pixels, void *output_buffer, float *encode_buffer, int channels, int alpha_channel, int decode) { int x; int n; int num_nonalpha; stbir_uint16 nonalpha[STBIR_MAX_CHANNELS]; if (!(stbir_info->flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; float alpha = encode_buffer[pixel_index + alpha_channel]; float reciprocal_alpha = alpha ? 1.0f / alpha : 0; // unrolling this produced a 1% slowdown upscaling a large RGBA linear-space image on my machine - stb for (n = 0; n < channels; n++) if (n != alpha_channel) encode_buffer[pixel_index + n] *= reciprocal_alpha; // We added in a small epsilon to prevent the color channel from being deleted with zero alpha. // Because we only add it for integer types, it will automatically be discarded on integer // conversion, so we don't need to subtract it back out (which would be problematic for // numeric precision reasons). } } // build a table of all channels that need colorspace correction, so // we don't perform colorspace correction on channels that don't need it. for (x = 0, num_nonalpha = 0; x < channels; ++x) { if (x != alpha_channel || (stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) { nonalpha[num_nonalpha++] = (stbir_uint16)x; } } #define STBIR__ROUND_INT(f) ((int) ((f)+0.5)) #define STBIR__ROUND_UINT(f) ((stbir_uint32) ((f)+0.5)) #ifdef STBIR__SATURATE_INT #define STBIR__ENCODE_LINEAR8(f) stbir__saturate8 (STBIR__ROUND_INT((f) * stbir__max_uint8_as_float )) #define STBIR__ENCODE_LINEAR16(f) stbir__saturate16(STBIR__ROUND_INT((f) * stbir__max_uint16_as_float)) #else #define STBIR__ENCODE_LINEAR8(f) (unsigned char ) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint8_as_float ) #define STBIR__ENCODE_LINEAR16(f) (unsigned short) STBIR__ROUND_INT(stbir__saturate(f) * stbir__max_uint16_as_float) #endif switch (decode) { case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned char*)output_buffer)[index] = STBIR__ENCODE_LINEAR8(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT8, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned char*)output_buffer)[index] = stbir__linear_to_srgb_uchar(encode_buffer[index]); } if (!(stbir_info->flags & STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned char *)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR8(encode_buffer[pixel_index+alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned short*)output_buffer)[index] = STBIR__ENCODE_LINEAR16(encode_buffer[index]); } } break; case STBIR__DECODE(STBIR_TYPE_UINT16, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned short*)output_buffer)[index] = (unsigned short)STBIR__ROUND_INT(stbir__linear_to_srgb(stbir__saturate(encode_buffer[index])) * stbir__max_uint16_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned short*)output_buffer)[pixel_index + alpha_channel] = STBIR__ENCODE_LINEAR16(encode_buffer[pixel_index + alpha_channel]); } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__saturate(encode_buffer[index])) * stbir__max_uint32_as_float); } } break; case STBIR__DECODE(STBIR_TYPE_UINT32, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((unsigned int*)output_buffer)[index] = (unsigned int)STBIR__ROUND_UINT(((double)stbir__linear_to_srgb(stbir__saturate(encode_buffer[index]))) * stbir__max_uint32_as_float); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((unsigned int*)output_buffer)[pixel_index + alpha_channel] = (unsigned int)STBIR__ROUND_INT(((double)stbir__saturate(encode_buffer[pixel_index + alpha_channel])) * stbir__max_uint32_as_float); } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_LINEAR): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < channels; n++) { int index = pixel_index + n; ((float*)output_buffer)[index] = encode_buffer[index]; } } break; case STBIR__DECODE(STBIR_TYPE_FLOAT, STBIR_COLORSPACE_SRGB): for (x=0; x < num_pixels; ++x) { int pixel_index = x*channels; for (n = 0; n < num_nonalpha; n++) { int index = pixel_index + nonalpha[n]; ((float*)output_buffer)[index] = stbir__linear_to_srgb(encode_buffer[index]); } if (!(stbir_info->flags&STBIR_FLAG_ALPHA_USES_COLORSPACE)) ((float*)output_buffer)[pixel_index + alpha_channel] = encode_buffer[pixel_index + alpha_channel]; } break; default: STBIR_ASSERT(!"Unknown type/colorspace/channels combination."); break; } } static void stbir__resample_vertical_upsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; void* output_data = stbir_info->output_data; float* encode_buffer = stbir_info->encode_buffer; int decode = STBIR__DECODE(type, colorspace); int coefficient_width = stbir_info->vertical_coefficient_width; int coefficient_counter; int contributor = n; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1, output_row_start; int coefficient_group = coefficient_width * contributor; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; output_row_start = n * stbir_info->output_stride_bytes; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); memset(encode_buffer, 0, output_w * sizeof(float) * channels); // I tried reblocking this for better cache usage of encode_buffer // (using x_outer, k, x_inner), but it lost speed. -- stb coefficient_counter = 0; switch (channels) { case 1: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 1; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; } } break; case 2: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 2; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; } } break; case 3: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 3; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; } } break; case 4: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * 4; encode_buffer[in_pixel_index + 0] += ring_buffer_entry[in_pixel_index + 0] * coefficient; encode_buffer[in_pixel_index + 1] += ring_buffer_entry[in_pixel_index + 1] * coefficient; encode_buffer[in_pixel_index + 2] += ring_buffer_entry[in_pixel_index + 2] * coefficient; encode_buffer[in_pixel_index + 3] += ring_buffer_entry[in_pixel_index + 3] * coefficient; } } break; default: for (k = n0; k <= n1; k++) { int coefficient_index = coefficient_counter++; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; for (x = 0; x < output_w; ++x) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) encode_buffer[in_pixel_index + c] += ring_buffer_entry[in_pixel_index + c] * coefficient; } } break; } stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, encode_buffer, channels, alpha_channel, decode); } static void stbir__resample_vertical_downsample(stbir__info* stbir_info, int n) { int x, k; int output_w = stbir_info->output_w; stbir__contributors* vertical_contributors = stbir_info->vertical_contributors; float* vertical_coefficients = stbir_info->vertical_coefficients; int channels = stbir_info->channels; int ring_buffer_entries = stbir_info->ring_buffer_num_entries; float* horizontal_buffer = stbir_info->horizontal_buffer; int coefficient_width = stbir_info->vertical_coefficient_width; int contributor = n + stbir_info->vertical_filter_pixel_margin; float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_begin_index = stbir_info->ring_buffer_begin_index; int ring_buffer_first_scanline = stbir_info->ring_buffer_first_scanline; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); int n0,n1; n0 = vertical_contributors[contributor].n0; n1 = vertical_contributors[contributor].n1; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (k = n0; k <= n1; k++) { int coefficient_index = k - n0; int coefficient_group = coefficient_width * contributor; float coefficient = vertical_coefficients[coefficient_group + coefficient_index]; float* ring_buffer_entry = stbir__get_ring_buffer_scanline(k, ring_buffer, ring_buffer_begin_index, ring_buffer_first_scanline, ring_buffer_entries, ring_buffer_length); switch (channels) { case 1: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 1; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; } break; case 2: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 2; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; } break; case 3: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 3; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; } break; case 4: for (x = 0; x < output_w; x++) { int in_pixel_index = x * 4; ring_buffer_entry[in_pixel_index + 0] += horizontal_buffer[in_pixel_index + 0] * coefficient; ring_buffer_entry[in_pixel_index + 1] += horizontal_buffer[in_pixel_index + 1] * coefficient; ring_buffer_entry[in_pixel_index + 2] += horizontal_buffer[in_pixel_index + 2] * coefficient; ring_buffer_entry[in_pixel_index + 3] += horizontal_buffer[in_pixel_index + 3] * coefficient; } break; default: for (x = 0; x < output_w; x++) { int in_pixel_index = x * channels; int c; for (c = 0; c < channels; c++) ring_buffer_entry[in_pixel_index + c] += horizontal_buffer[in_pixel_index + c] * coefficient; } break; } } } static void stbir__buffer_loop_upsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; float out_scanlines_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(1/scale_ratio) * scale_ratio; STBIR_ASSERT(stbir__use_height_upsampling(stbir_info)); for (y = 0; y < stbir_info->output_h; y++) { float in_center_of_out = 0; // Center of the current out scanline in the in scanline space int in_first_scanline = 0, in_last_scanline = 0; stbir__calculate_sample_range_upsample(y, out_scanlines_radius, scale_ratio, stbir_info->vertical_shift, &in_first_scanline, &in_last_scanline, &in_center_of_out); STBIR_ASSERT(in_last_scanline - in_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (in_first_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__decode_and_resample_upsample(stbir_info, in_first_scanline); while (in_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__decode_and_resample_upsample(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now all buffers should be ready to write a row of vertical sampling. stbir__resample_vertical_upsample(stbir_info, y); STBIR_PROGRESS_REPORT((float)y / stbir_info->output_h); } } static void stbir__empty_ring_buffer(stbir__info* stbir_info, int first_necessary_scanline) { int output_stride_bytes = stbir_info->output_stride_bytes; int channels = stbir_info->channels; int alpha_channel = stbir_info->alpha_channel; int type = stbir_info->type; int colorspace = stbir_info->colorspace; int output_w = stbir_info->output_w; void* output_data = stbir_info->output_data; int decode = STBIR__DECODE(type, colorspace); float* ring_buffer = stbir_info->ring_buffer; int ring_buffer_length = stbir_info->ring_buffer_length_bytes/sizeof(float); if (stbir_info->ring_buffer_begin_index >= 0) { // Get rid of whatever we don't need anymore. while (first_necessary_scanline > stbir_info->ring_buffer_first_scanline) { if (stbir_info->ring_buffer_first_scanline >= 0 && stbir_info->ring_buffer_first_scanline < stbir_info->output_h) { int output_row_start = stbir_info->ring_buffer_first_scanline * output_stride_bytes; float* ring_buffer_entry = stbir__get_ring_buffer_entry(ring_buffer, stbir_info->ring_buffer_begin_index, ring_buffer_length); stbir__encode_scanline(stbir_info, output_w, (char *) output_data + output_row_start, ring_buffer_entry, channels, alpha_channel, decode); STBIR_PROGRESS_REPORT((float)stbir_info->ring_buffer_first_scanline / stbir_info->output_h); } if (stbir_info->ring_buffer_first_scanline == stbir_info->ring_buffer_last_scanline) { // We just popped the last scanline off the ring buffer. // Reset it to the empty state. stbir_info->ring_buffer_begin_index = -1; stbir_info->ring_buffer_first_scanline = 0; stbir_info->ring_buffer_last_scanline = 0; break; } else { stbir_info->ring_buffer_first_scanline++; stbir_info->ring_buffer_begin_index = (stbir_info->ring_buffer_begin_index + 1) % stbir_info->ring_buffer_num_entries; } } } } static void stbir__buffer_loop_downsample(stbir__info* stbir_info) { int y; float scale_ratio = stbir_info->vertical_scale; int output_h = stbir_info->output_h; float in_pixels_radius = stbir__filter_info_table[stbir_info->vertical_filter].support(scale_ratio) / scale_ratio; int pixel_margin = stbir_info->vertical_filter_pixel_margin; int max_y = stbir_info->input_h + pixel_margin; STBIR_ASSERT(!stbir__use_height_upsampling(stbir_info)); for (y = -pixel_margin; y < max_y; y++) { float out_center_of_in; // Center of the current out scanline in the in scanline space int out_first_scanline, out_last_scanline; stbir__calculate_sample_range_downsample(y, in_pixels_radius, scale_ratio, stbir_info->vertical_shift, &out_first_scanline, &out_last_scanline, &out_center_of_in); STBIR_ASSERT(out_last_scanline - out_first_scanline + 1 <= stbir_info->ring_buffer_num_entries); if (out_last_scanline < 0 || out_first_scanline >= output_h) continue; stbir__empty_ring_buffer(stbir_info, out_first_scanline); stbir__decode_and_resample_downsample(stbir_info, y); // Load in new ones. if (stbir_info->ring_buffer_begin_index < 0) stbir__add_empty_ring_buffer_entry(stbir_info, out_first_scanline); while (out_last_scanline > stbir_info->ring_buffer_last_scanline) stbir__add_empty_ring_buffer_entry(stbir_info, stbir_info->ring_buffer_last_scanline + 1); // Now the horizontal buffer is ready to write to all ring buffer rows. stbir__resample_vertical_downsample(stbir_info, y); } stbir__empty_ring_buffer(stbir_info, stbir_info->output_h); } static void stbir__setup(stbir__info *info, int input_w, int input_h, int output_w, int output_h, int channels) { info->input_w = input_w; info->input_h = input_h; info->output_w = output_w; info->output_h = output_h; info->channels = channels; } static void stbir__calculate_transform(stbir__info *info, float s0, float t0, float s1, float t1, float *transform) { info->s0 = s0; info->t0 = t0; info->s1 = s1; info->t1 = t1; if (transform) { info->horizontal_scale = transform[0]; info->vertical_scale = transform[1]; info->horizontal_shift = transform[2]; info->vertical_shift = transform[3]; } else { info->horizontal_scale = ((float)info->output_w / info->input_w) / (s1 - s0); info->vertical_scale = ((float)info->output_h / info->input_h) / (t1 - t0); info->horizontal_shift = s0 * info->output_w / (s1 - s0); info->vertical_shift = t0 * info->output_h / (t1 - t0); } } static void stbir__choose_filter(stbir__info *info, stbir_filter h_filter, stbir_filter v_filter) { if (h_filter == 0) h_filter = stbir__use_upsampling(info->horizontal_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; if (v_filter == 0) v_filter = stbir__use_upsampling(info->vertical_scale) ? STBIR_DEFAULT_FILTER_UPSAMPLE : STBIR_DEFAULT_FILTER_DOWNSAMPLE; info->horizontal_filter = h_filter; info->vertical_filter = v_filter; } static stbir_uint32 stbir__calculate_memory(stbir__info *info) { int pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); int filter_height = stbir__get_filter_pixel_width(info->vertical_filter, info->vertical_scale); info->horizontal_num_contributors = stbir__get_contributors(info->horizontal_scale, info->horizontal_filter, info->input_w, info->output_w); info->vertical_num_contributors = stbir__get_contributors(info->vertical_scale , info->vertical_filter , info->input_h, info->output_h); // One extra entry because floating point precision problems sometimes cause an extra to be necessary. info->ring_buffer_num_entries = filter_height + 1; info->horizontal_contributors_size = info->horizontal_num_contributors * sizeof(stbir__contributors); info->horizontal_coefficients_size = stbir__get_total_horizontal_coefficients(info) * sizeof(float); info->vertical_contributors_size = info->vertical_num_contributors * sizeof(stbir__contributors); info->vertical_coefficients_size = stbir__get_total_vertical_coefficients(info) * sizeof(float); info->decode_buffer_size = (info->input_w + pixel_margin * 2) * info->channels * sizeof(float); info->horizontal_buffer_size = info->output_w * info->channels * sizeof(float); info->ring_buffer_size = info->output_w * info->channels * info->ring_buffer_num_entries * sizeof(float); info->encode_buffer_size = info->output_w * info->channels * sizeof(float); STBIR_ASSERT(info->horizontal_filter != 0); STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late STBIR_ASSERT(info->vertical_filter != 0); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); // this now happens too late if (stbir__use_height_upsampling(info)) // The horizontal buffer is for when we're downsampling the height and we // can't output the result of sampling the decode buffer directly into the // ring buffers. info->horizontal_buffer_size = 0; else // The encode buffer is to retain precision in the height upsampling method // and isn't used when height downsampling. info->encode_buffer_size = 0; return info->horizontal_contributors_size + info->horizontal_coefficients_size + info->vertical_contributors_size + info->vertical_coefficients_size + info->decode_buffer_size + info->horizontal_buffer_size + info->ring_buffer_size + info->encode_buffer_size; } static int stbir__resize_allocated(stbir__info *info, const void* input_data, int input_stride_in_bytes, void* output_data, int output_stride_in_bytes, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace, void* tempmem, size_t tempmem_size_in_bytes) { size_t memory_required = stbir__calculate_memory(info); int width_stride_input = input_stride_in_bytes ? input_stride_in_bytes : info->channels * info->input_w * stbir__type_size[type]; int width_stride_output = output_stride_in_bytes ? output_stride_in_bytes : info->channels * info->output_w * stbir__type_size[type]; #ifdef STBIR_DEBUG_OVERWRITE_TEST #define OVERWRITE_ARRAY_SIZE 8 unsigned char overwrite_output_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_before_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_output_after_pre[OVERWRITE_ARRAY_SIZE]; unsigned char overwrite_tempmem_after_pre[OVERWRITE_ARRAY_SIZE]; size_t begin_forbidden = width_stride_output * (info->output_h - 1) + info->output_w * info->channels * stbir__type_size[type]; memcpy(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE); memcpy(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE); #endif STBIR_ASSERT(info->channels >= 0); STBIR_ASSERT(info->channels <= STBIR_MAX_CHANNELS); if (info->channels < 0 || info->channels > STBIR_MAX_CHANNELS) return 0; STBIR_ASSERT(info->horizontal_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); STBIR_ASSERT(info->vertical_filter < STBIR__ARRAY_SIZE(stbir__filter_info_table)); if (info->horizontal_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (info->vertical_filter >= STBIR__ARRAY_SIZE(stbir__filter_info_table)) return 0; if (alpha_channel < 0) flags |= STBIR_FLAG_ALPHA_USES_COLORSPACE | STBIR_FLAG_ALPHA_PREMULTIPLIED; if (!(flags&STBIR_FLAG_ALPHA_USES_COLORSPACE) || !(flags&STBIR_FLAG_ALPHA_PREMULTIPLIED)) { STBIR_ASSERT(alpha_channel >= 0 && alpha_channel < info->channels); } if (alpha_channel >= info->channels) return 0; STBIR_ASSERT(tempmem); if (!tempmem) return 0; STBIR_ASSERT(tempmem_size_in_bytes >= memory_required); if (tempmem_size_in_bytes < memory_required) return 0; memset(tempmem, 0, tempmem_size_in_bytes); info->input_data = input_data; info->input_stride_bytes = width_stride_input; info->output_data = output_data; info->output_stride_bytes = width_stride_output; info->alpha_channel = alpha_channel; info->flags = flags; info->type = type; info->edge_horizontal = edge_horizontal; info->edge_vertical = edge_vertical; info->colorspace = colorspace; info->horizontal_coefficient_width = stbir__get_coefficient_width (info->horizontal_filter, info->horizontal_scale); info->vertical_coefficient_width = stbir__get_coefficient_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_width = stbir__get_filter_pixel_width (info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_width = stbir__get_filter_pixel_width (info->vertical_filter , info->vertical_scale ); info->horizontal_filter_pixel_margin = stbir__get_filter_pixel_margin(info->horizontal_filter, info->horizontal_scale); info->vertical_filter_pixel_margin = stbir__get_filter_pixel_margin(info->vertical_filter , info->vertical_scale ); info->ring_buffer_length_bytes = info->output_w * info->channels * sizeof(float); info->decode_buffer_pixels = info->input_w + info->horizontal_filter_pixel_margin * 2; #define STBIR__NEXT_MEMPTR(current, newtype) (newtype*)(((unsigned char*)current) + current##_size) info->horizontal_contributors = (stbir__contributors *) tempmem; info->horizontal_coefficients = STBIR__NEXT_MEMPTR(info->horizontal_contributors, float); info->vertical_contributors = STBIR__NEXT_MEMPTR(info->horizontal_coefficients, stbir__contributors); info->vertical_coefficients = STBIR__NEXT_MEMPTR(info->vertical_contributors, float); info->decode_buffer = STBIR__NEXT_MEMPTR(info->vertical_coefficients, float); if (stbir__use_height_upsampling(info)) { info->horizontal_buffer = NULL; info->ring_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->encode_buffer = STBIR__NEXT_MEMPTR(info->ring_buffer, float); STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->encode_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } else { info->horizontal_buffer = STBIR__NEXT_MEMPTR(info->decode_buffer, float); info->ring_buffer = STBIR__NEXT_MEMPTR(info->horizontal_buffer, float); info->encode_buffer = NULL; STBIR_ASSERT((size_t)STBIR__NEXT_MEMPTR(info->ring_buffer, unsigned char) == (size_t)tempmem + tempmem_size_in_bytes); } #undef STBIR__NEXT_MEMPTR // This signals that the ring buffer is empty info->ring_buffer_begin_index = -1; stbir__calculate_filters(info->horizontal_contributors, info->horizontal_coefficients, info->horizontal_filter, info->horizontal_scale, info->horizontal_shift, info->input_w, info->output_w); stbir__calculate_filters(info->vertical_contributors, info->vertical_coefficients, info->vertical_filter, info->vertical_scale, info->vertical_shift, info->input_h, info->output_h); STBIR_PROGRESS_REPORT(0); if (stbir__use_height_upsampling(info)) stbir__buffer_loop_upsample(info); else stbir__buffer_loop_downsample(info); STBIR_PROGRESS_REPORT(1); #ifdef STBIR_DEBUG_OVERWRITE_TEST STBIR_ASSERT(memcmp(overwrite_output_before_pre, &((unsigned char*)output_data)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_output_after_pre, &((unsigned char*)output_data)[begin_forbidden], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_before_pre, &((unsigned char*)tempmem)[-OVERWRITE_ARRAY_SIZE], OVERWRITE_ARRAY_SIZE) == 0); STBIR_ASSERT(memcmp(overwrite_tempmem_after_pre, &((unsigned char*)tempmem)[tempmem_size_in_bytes], OVERWRITE_ARRAY_SIZE) == 0); #endif return 1; } static int stbir__resize_arbitrary( void *alloc_context, const void* input_data, int input_w, int input_h, int input_stride_in_bytes, void* output_data, int output_w, int output_h, int output_stride_in_bytes, float s0, float t0, float s1, float t1, float *transform, int channels, int alpha_channel, stbir_uint32 flags, stbir_datatype type, stbir_filter h_filter, stbir_filter v_filter, stbir_edge edge_horizontal, stbir_edge edge_vertical, stbir_colorspace colorspace) { stbir__info info; int result; size_t memory_required; void* extra_memory; stbir__setup(&info, input_w, input_h, output_w, output_h, channels); stbir__calculate_transform(&info, s0,t0,s1,t1,transform); stbir__choose_filter(&info, h_filter, v_filter); memory_required = stbir__calculate_memory(&info); extra_memory = STBIR_MALLOC(memory_required, alloc_context); if (!extra_memory) return 0; result = stbir__resize_allocated(&info, input_data, input_stride_in_bytes, output_data, output_stride_in_bytes, alpha_channel, flags, type, edge_horizontal, edge_vertical, colorspace, extra_memory, memory_required); STBIR_FREE(extra_memory, alloc_context); return result; } STBIRDEF int stbir_resize_uint8( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_float( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,-1,0, STBIR_TYPE_FLOAT, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_LINEAR); } STBIRDEF int stbir_resize_uint8_srgb(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, STBIR_EDGE_CLAMP, STBIR_EDGE_CLAMP, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_srgb_edgemode(const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode) { return stbir__resize_arbitrary(NULL, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, STBIR_FILTER_DEFAULT, STBIR_FILTER_DEFAULT, edge_wrap_mode, edge_wrap_mode, STBIR_COLORSPACE_SRGB); } STBIRDEF int stbir_resize_uint8_generic( const unsigned char *input_pixels , int input_w , int input_h , int input_stride_in_bytes, unsigned char *output_pixels, int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT8, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_uint16_generic(const stbir_uint16 *input_pixels , int input_w , int input_h , int input_stride_in_bytes, stbir_uint16 *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_UINT16, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize_float_generic( const float *input_pixels , int input_w , int input_h , int input_stride_in_bytes, float *output_pixels , int output_w, int output_h, int output_stride_in_bytes, int num_channels, int alpha_channel, int flags, stbir_edge edge_wrap_mode, stbir_filter filter, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, STBIR_TYPE_FLOAT, filter, filter, edge_wrap_mode, edge_wrap_mode, space); } STBIRDEF int stbir_resize( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_subpixel(const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float x_scale, float y_scale, float x_offset, float y_offset) { float transform[4]; transform[0] = x_scale; transform[1] = y_scale; transform[2] = x_offset; transform[3] = y_offset; return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, 0,0,1,1,transform,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } STBIRDEF int stbir_resize_region( const void *input_pixels , int input_w , int input_h , int input_stride_in_bytes, void *output_pixels, int output_w, int output_h, int output_stride_in_bytes, stbir_datatype datatype, int num_channels, int alpha_channel, int flags, stbir_edge edge_mode_horizontal, stbir_edge edge_mode_vertical, stbir_filter filter_horizontal, stbir_filter filter_vertical, stbir_colorspace space, void *alloc_context, float s0, float t0, float s1, float t1) { return stbir__resize_arbitrary(alloc_context, input_pixels, input_w, input_h, input_stride_in_bytes, output_pixels, output_w, output_h, output_stride_in_bytes, s0,t0,s1,t1,NULL,num_channels,alpha_channel,flags, datatype, filter_horizontal, filter_vertical, edge_mode_horizontal, edge_mode_vertical, space); } #endif // STB_IMAGE_RESIZE_IMPLEMENTATION /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
whupdup/frame
real/third_party/stb/stb_image_resize.h
C++
gpl-3.0
116,516
#define TINYGLTF_IMPLEMENTATION #include <tiny_gltf.h>
whupdup/frame
real/third_party/tinygltf/tiny_gltf.cpp
C++
gpl-3.0
55
// // Header-only tiny glTF 2.0 loader and serializer. // // // The MIT License (MIT) // // Copyright (c) 2015 - Present Syoyo Fujita, Aurélien Chatelain and many // contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Version: // - v2.5.0 Add SetPreserveImageChannels() option to load image data as is. // - v2.4.3 Fix null object output when when material has all default // parameters. // - v2.4.2 Decode percent-encoded URI. // - v2.4.1 Fix some glTF object class does not have `extensions` and/or // `extras` property. // - v2.4.0 Experimental RapidJSON and C++14 support(Thanks to @jrkoone). // - v2.3.1 Set default value of minFilter and magFilter in Sampler to -1. // - v2.3.0 Modified Material representation according to glTF 2.0 schema // (and introduced TextureInfo class) // Change the behavior of `Value::IsNumber`. It return true either the // value is int or real. // - v2.2.0 Add loading 16bit PNG support. Add Sparse accessor support(Thanks // to @Ybalrid) // - v2.1.0 Add draco compression. // - v2.0.1 Add comparsion feature(Thanks to @Selmar). // - v2.0.0 glTF 2.0!. // // Tiny glTF loader is using following third party libraries: // // - jsonhpp: C++ JSON library. // - base64: base64 decode/encode library. // - stb_image: Image loading library. // #ifndef TINY_GLTF_H_ #define TINY_GLTF_H_ #include <array> #include <cassert> #include <cmath> // std::fabs #include <cstdint> #include <cstdlib> #include <cstring> #include <limits> #include <map> #include <string> #include <vector> #ifndef TINYGLTF_USE_CPP14 #include <functional> #endif #ifdef __ANDROID__ #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS #include <android/asset_manager.h> #endif #endif #ifdef __GNUC__ #if (__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ <= 8)) #define TINYGLTF_NOEXCEPT #else #define TINYGLTF_NOEXCEPT noexcept #endif #else #define TINYGLTF_NOEXCEPT noexcept #endif #define DEFAULT_METHODS(x) \ ~x() = default; \ x(const x &) = default; \ x(x &&) TINYGLTF_NOEXCEPT = default; \ x &operator=(const x &) = default; \ x &operator=(x &&) TINYGLTF_NOEXCEPT = default; namespace tinygltf { #define TINYGLTF_MODE_POINTS (0) #define TINYGLTF_MODE_LINE (1) #define TINYGLTF_MODE_LINE_LOOP (2) #define TINYGLTF_MODE_LINE_STRIP (3) #define TINYGLTF_MODE_TRIANGLES (4) #define TINYGLTF_MODE_TRIANGLE_STRIP (5) #define TINYGLTF_MODE_TRIANGLE_FAN (6) #define TINYGLTF_COMPONENT_TYPE_BYTE (5120) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_COMPONENT_TYPE_SHORT (5122) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123) #define TINYGLTF_COMPONENT_TYPE_INT (5124) #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125) #define TINYGLTF_COMPONENT_TYPE_FLOAT (5126) #define TINYGLTF_COMPONENT_TYPE_DOUBLE (5130) // OpenGL double type. Note that some of glTF 2.0 validator does not support double type even the schema seems allow any value of integer: https://github.com/KhronosGroup/glTF/blob/b9884a2fd45130b4d673dd6c8a706ee21ee5c5f7/specification/2.0/schema/accessor.schema.json#L22 #define TINYGLTF_TEXTURE_FILTER_NEAREST (9728) #define TINYGLTF_TEXTURE_FILTER_LINEAR (9729) #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984) #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985) #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986) #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987) #define TINYGLTF_TEXTURE_WRAP_REPEAT (10497) #define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071) #define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648) // Redeclarations of the above for technique.parameters. #define TINYGLTF_PARAMETER_TYPE_BYTE (5120) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_PARAMETER_TYPE_SHORT (5122) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123) #define TINYGLTF_PARAMETER_TYPE_INT (5124) #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125) #define TINYGLTF_PARAMETER_TYPE_FLOAT (5126) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665) #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666) #define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667) #define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668) #define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669) #define TINYGLTF_PARAMETER_TYPE_BOOL (35670) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672) #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675) #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676) #define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678) // End parameter types #define TINYGLTF_TYPE_VEC2 (2) #define TINYGLTF_TYPE_VEC3 (3) #define TINYGLTF_TYPE_VEC4 (4) #define TINYGLTF_TYPE_MAT2 (32 + 2) #define TINYGLTF_TYPE_MAT3 (32 + 3) #define TINYGLTF_TYPE_MAT4 (32 + 4) #define TINYGLTF_TYPE_SCALAR (64 + 1) #define TINYGLTF_TYPE_VECTOR (64 + 4) #define TINYGLTF_TYPE_MATRIX (64 + 16) #define TINYGLTF_IMAGE_FORMAT_JPEG (0) #define TINYGLTF_IMAGE_FORMAT_PNG (1) #define TINYGLTF_IMAGE_FORMAT_BMP (2) #define TINYGLTF_IMAGE_FORMAT_GIF (3) #define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406) #define TINYGLTF_TEXTURE_FORMAT_RGB (6407) #define TINYGLTF_TEXTURE_FORMAT_RGBA (6408) #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409) #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410) #define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553) #define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121) #define TINYGLTF_TARGET_ARRAY_BUFFER (34962) #define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963) #define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633) #define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632) #define TINYGLTF_DOUBLE_EPS (1.e-12) #define TINYGLTF_DOUBLE_EQUAL(a, b) (std::fabs((b) - (a)) < TINYGLTF_DOUBLE_EPS) #ifdef __ANDROID__ #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS AAssetManager *asset_manager = nullptr; #endif #endif typedef enum { NULL_TYPE, REAL_TYPE, INT_TYPE, BOOL_TYPE, STRING_TYPE, ARRAY_TYPE, BINARY_TYPE, OBJECT_TYPE } Type; static inline int32_t GetComponentSizeInBytes(uint32_t componentType) { if (componentType == TINYGLTF_COMPONENT_TYPE_BYTE) { return 1; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) { return 1; } else if (componentType == TINYGLTF_COMPONENT_TYPE_SHORT) { return 2; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) { return 2; } else if (componentType == TINYGLTF_COMPONENT_TYPE_INT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) { return 4; } else if (componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE) { return 8; } else { // Unknown componenty type return -1; } } static inline int32_t GetNumComponentsInType(uint32_t ty) { if (ty == TINYGLTF_TYPE_SCALAR) { return 1; } else if (ty == TINYGLTF_TYPE_VEC2) { return 2; } else if (ty == TINYGLTF_TYPE_VEC3) { return 3; } else if (ty == TINYGLTF_TYPE_VEC4) { return 4; } else if (ty == TINYGLTF_TYPE_MAT2) { return 4; } else if (ty == TINYGLTF_TYPE_MAT3) { return 9; } else if (ty == TINYGLTF_TYPE_MAT4) { return 16; } else { // Unknown componenty type return -1; } } // TODO(syoyo): Move these functions to TinyGLTF class bool IsDataURI(const std::string &in); bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type, const std::string &in, size_t reqBytes, bool checkSize); #ifdef __clang__ #pragma clang diagnostic push // Suppress warning for : static Value null_value #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wpadded" #endif // Simple class to represent JSON object class Value { public: typedef std::vector<Value> Array; typedef std::map<std::string, Value> Object; Value() : type_(NULL_TYPE), int_value_(0), real_value_(0.0), boolean_value_(false) {} explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; } explicit Value(int i) : type_(INT_TYPE) { int_value_ = i; real_value_ = i; } explicit Value(double n) : type_(REAL_TYPE) { real_value_ = n; } explicit Value(const std::string &s) : type_(STRING_TYPE) { string_value_ = s; } explicit Value(std::string &&s) : type_(STRING_TYPE), string_value_(std::move(s)) {} explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) { binary_value_.resize(n); memcpy(binary_value_.data(), p, n); } explicit Value(std::vector<unsigned char> &&v) noexcept : type_(BINARY_TYPE), binary_value_(std::move(v)) {} explicit Value(const Array &a) : type_(ARRAY_TYPE) { array_value_ = a; } explicit Value(Array &&a) noexcept : type_(ARRAY_TYPE), array_value_(std::move(a)) {} explicit Value(const Object &o) : type_(OBJECT_TYPE) { object_value_ = o; } explicit Value(Object &&o) noexcept : type_(OBJECT_TYPE), object_value_(std::move(o)) {} DEFAULT_METHODS(Value) char Type() const { return static_cast<char>(type_); } bool IsBool() const { return (type_ == BOOL_TYPE); } bool IsInt() const { return (type_ == INT_TYPE); } bool IsNumber() const { return (type_ == REAL_TYPE) || (type_ == INT_TYPE); } bool IsReal() const { return (type_ == REAL_TYPE); } bool IsString() const { return (type_ == STRING_TYPE); } bool IsBinary() const { return (type_ == BINARY_TYPE); } bool IsArray() const { return (type_ == ARRAY_TYPE); } bool IsObject() const { return (type_ == OBJECT_TYPE); } // Use this function if you want to have number value as double. double GetNumberAsDouble() const { if (type_ == INT_TYPE) { return double(int_value_); } else { return real_value_; } } // Use this function if you want to have number value as int. // TODO(syoyo): Support int value larger than 32 bits int GetNumberAsInt() const { if (type_ == REAL_TYPE) { return int(real_value_); } else { return int_value_; } } // Accessor template <typename T> const T &Get() const; template <typename T> T &Get(); // Lookup value from an array const Value &Get(int idx) const { static Value null_value; assert(IsArray()); assert(idx >= 0); return (static_cast<size_t>(idx) < array_value_.size()) ? array_value_[static_cast<size_t>(idx)] : null_value; } // Lookup value from a key-value pair const Value &Get(const std::string &key) const { static Value null_value; assert(IsObject()); Object::const_iterator it = object_value_.find(key); return (it != object_value_.end()) ? it->second : null_value; } size_t ArrayLen() const { if (!IsArray()) return 0; return array_value_.size(); } // Valid only for object type. bool Has(const std::string &key) const { if (!IsObject()) return false; Object::const_iterator it = object_value_.find(key); return (it != object_value_.end()) ? true : false; } // List keys std::vector<std::string> Keys() const { std::vector<std::string> keys; if (!IsObject()) return keys; // empty for (Object::const_iterator it = object_value_.begin(); it != object_value_.end(); ++it) { keys.push_back(it->first); } return keys; } size_t Size() const { return (IsArray() ? ArrayLen() : Keys().size()); } bool operator==(const tinygltf::Value &other) const; protected: int type_ = NULL_TYPE; int int_value_ = 0; double real_value_ = 0.0; std::string string_value_; std::vector<unsigned char> binary_value_; Array array_value_; Object object_value_; bool boolean_value_ = false; }; #ifdef __clang__ #pragma clang diagnostic pop #endif #define TINYGLTF_VALUE_GET(ctype, var) \ template <> \ inline const ctype &Value::Get<ctype>() const { \ return var; \ } \ template <> \ inline ctype &Value::Get<ctype>() { \ return var; \ } TINYGLTF_VALUE_GET(bool, boolean_value_) TINYGLTF_VALUE_GET(double, real_value_) TINYGLTF_VALUE_GET(int, int_value_) TINYGLTF_VALUE_GET(std::string, string_value_) TINYGLTF_VALUE_GET(std::vector<unsigned char>, binary_value_) TINYGLTF_VALUE_GET(Value::Array, array_value_) TINYGLTF_VALUE_GET(Value::Object, object_value_) #undef TINYGLTF_VALUE_GET #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #pragma clang diagnostic ignored "-Wpadded" #endif /// Agregate object for representing a color using ColorValue = std::array<double, 4>; // === legacy interface ==== // TODO(syoyo): Deprecate `Parameter` class. struct Parameter { bool bool_value = false; bool has_number_value = false; std::string string_value; std::vector<double> number_array; std::map<std::string, double> json_double_value; double number_value = 0.0; // context sensitive methods. depending the type of the Parameter you are // accessing, these are either valid or not // If this parameter represent a texture map in a material, will return the // texture index /// Return the index of a texture if this Parameter is a texture map. /// Returned value is only valid if the parameter represent a texture from a /// material int TextureIndex() const { const auto it = json_double_value.find("index"); if (it != std::end(json_double_value)) { return int(it->second); } return -1; } /// Return the index of a texture coordinate set if this Parameter is a /// texture map. Returned value is only valid if the parameter represent a /// texture from a material int TextureTexCoord() const { const auto it = json_double_value.find("texCoord"); if (it != std::end(json_double_value)) { return int(it->second); } // As per the spec, if texCoord is ommited, this parameter is 0 return 0; } /// Return the scale of a texture if this Parameter is a normal texture map. /// Returned value is only valid if the parameter represent a normal texture /// from a material double TextureScale() const { const auto it = json_double_value.find("scale"); if (it != std::end(json_double_value)) { return it->second; } // As per the spec, if scale is ommited, this paramter is 1 return 1; } /// Return the strength of a texture if this Parameter is a an occlusion map. /// Returned value is only valid if the parameter represent an occlusion map /// from a material double TextureStrength() const { const auto it = json_double_value.find("strength"); if (it != std::end(json_double_value)) { return it->second; } // As per the spec, if strenghth is ommited, this parameter is 1 return 1; } /// Material factor, like the roughness or metalness of a material /// Returned value is only valid if the parameter represent a texture from a /// material double Factor() const { return number_value; } /// Return the color of a material /// Returned value is only valid if the parameter represent a texture from a /// material ColorValue ColorFactor() const { return { {// this agregate intialize the std::array object, and uses C++11 RVO. number_array[0], number_array[1], number_array[2], (number_array.size() > 3 ? number_array[3] : 1.0)}}; } Parameter() = default; DEFAULT_METHODS(Parameter) bool operator==(const Parameter &) const; }; #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif typedef std::map<std::string, Parameter> ParameterMap; typedef std::map<std::string, Value> ExtensionMap; struct AnimationChannel { int sampler; // required int target_node; // required (index of the node to target) std::string target_path; // required in ["translation", "rotation", "scale", // "weights"] Value extras; ExtensionMap extensions; ExtensionMap target_extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; std::string target_extensions_json_string; AnimationChannel() : sampler(-1), target_node(-1) {} DEFAULT_METHODS(AnimationChannel) bool operator==(const AnimationChannel &) const; }; struct AnimationSampler { int input; // required int output; // required std::string interpolation; // "LINEAR", "STEP","CUBICSPLINE" or user defined // string. default "LINEAR" Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; AnimationSampler() : input(-1), output(-1), interpolation("LINEAR") {} DEFAULT_METHODS(AnimationSampler) bool operator==(const AnimationSampler &) const; }; struct Animation { std::string name; std::vector<AnimationChannel> channels; std::vector<AnimationSampler> samplers; Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Animation() = default; DEFAULT_METHODS(Animation) bool operator==(const Animation &) const; }; struct Skin { std::string name; int inverseBindMatrices; // required here but not in the spec int skeleton; // The index of the node used as a skeleton root std::vector<int> joints; // Indices of skeleton nodes Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Skin() { inverseBindMatrices = -1; skeleton = -1; } DEFAULT_METHODS(Skin) bool operator==(const Skin &) const; }; struct Sampler { std::string name; // glTF 2.0 spec does not define default value for `minFilter` and // `magFilter`. Set -1 in TinyGLTF(issue #186) int minFilter = -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR", // "NEAREST_MIPMAP_NEAREST", "LINEAR_MIPMAP_NEAREST", // "NEAREST_MIPMAP_LINEAR", "LINEAR_MIPMAP_LINEAR"] int magFilter = -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR"] int wrapS = TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", // "REPEAT"], default "REPEAT" int wrapT = TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", // "REPEAT"], default "REPEAT" //int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT; // TinyGLTF extension. currently not used. Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Sampler() : minFilter(-1), magFilter(-1), wrapS(TINYGLTF_TEXTURE_WRAP_REPEAT), wrapT(TINYGLTF_TEXTURE_WRAP_REPEAT) {} DEFAULT_METHODS(Sampler) bool operator==(const Sampler &) const; }; struct Image { std::string name; int width; int height; int component; int bits; // bit depth per channel. 8(byte), 16 or 32. int pixel_type; // pixel type(TINYGLTF_COMPONENT_TYPE_***). usually // UBYTE(bits = 8) or USHORT(bits = 16) std::vector<unsigned char> image; int bufferView; // (required if no uri) std::string mimeType; // (required if no uri) ["image/jpeg", "image/png", // "image/bmp", "image/gif"] std::string uri; // (required if no mimeType) uri is not decoded(e.g. // whitespace may be represented as %20) Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; // When this flag is true, data is stored to `image` in as-is format(e.g. jpeg // compressed for "image/jpeg" mime) This feature is good if you use custom // image loader function. (e.g. delayed decoding of images for faster glTF // parsing) Default parser for Image does not provide as-is loading feature at // the moment. (You can manipulate this by providing your own LoadImageData // function) bool as_is; Image() : as_is(false) { bufferView = -1; width = -1; height = -1; component = -1; bits = -1; pixel_type = -1; } DEFAULT_METHODS(Image) bool operator==(const Image &) const; }; struct Texture { std::string name; int sampler; int source; Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Texture() : sampler(-1), source(-1) {} DEFAULT_METHODS(Texture) bool operator==(const Texture &) const; }; struct TextureInfo { int index = -1; // required. int texCoord; // The set index of texture's TEXCOORD attribute used for // texture coordinate mapping. Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; TextureInfo() : index(-1), texCoord(0) {} DEFAULT_METHODS(TextureInfo) bool operator==(const TextureInfo &) const; }; struct NormalTextureInfo { int index = -1; // required int texCoord; // The set index of texture's TEXCOORD attribute used for // texture coordinate mapping. double scale; // scaledNormal = normalize((<sampled normal texture value> // * 2.0 - 1.0) * vec3(<normal scale>, <normal scale>, 1.0)) Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; NormalTextureInfo() : index(-1), texCoord(0), scale(1.0) {} DEFAULT_METHODS(NormalTextureInfo) bool operator==(const NormalTextureInfo &) const; }; struct OcclusionTextureInfo { int index = -1; // required int texCoord; // The set index of texture's TEXCOORD attribute used for // texture coordinate mapping. double strength; // occludedColor = lerp(color, color * <sampled occlusion // texture value>, <occlusion strength>) Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; OcclusionTextureInfo() : index(-1), texCoord(0), strength(1.0) {} DEFAULT_METHODS(OcclusionTextureInfo) bool operator==(const OcclusionTextureInfo &) const; }; // pbrMetallicRoughness class defined in glTF 2.0 spec. struct PbrMetallicRoughness { std::vector<double> baseColorFactor; // len = 4. default [1,1,1,1] TextureInfo baseColorTexture; double metallicFactor; // default 1 double roughnessFactor; // default 1 TextureInfo metallicRoughnessTexture; Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; PbrMetallicRoughness() : baseColorFactor(std::vector<double>{1.0, 1.0, 1.0, 1.0}), metallicFactor(1.0), roughnessFactor(1.0) {} DEFAULT_METHODS(PbrMetallicRoughness) bool operator==(const PbrMetallicRoughness &) const; }; // Each extension should be stored in a ParameterMap. // members not in the values could be included in the ParameterMap // to keep a single material model struct Material { std::string name; std::vector<double> emissiveFactor; // length 3. default [0, 0, 0] std::string alphaMode; // default "OPAQUE" double alphaCutoff; // default 0.5 bool doubleSided; // default false; PbrMetallicRoughness pbrMetallicRoughness; NormalTextureInfo normalTexture; OcclusionTextureInfo occlusionTexture; TextureInfo emissiveTexture; // For backward compatibility // TODO(syoyo): Remove `values` and `additionalValues` in the next release. ParameterMap values; ParameterMap additionalValues; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Material() : alphaMode("OPAQUE"), alphaCutoff(0.5), doubleSided(false) {} DEFAULT_METHODS(Material) bool operator==(const Material &) const; }; struct BufferView { std::string name; int buffer{-1}; // Required size_t byteOffset{0}; // minimum 0, default 0 size_t byteLength{0}; // required, minimum 1. 0 = invalid size_t byteStride{0}; // minimum 4, maximum 252 (multiple of 4), default 0 = // understood to be tightly packed int target{0}; // ["ARRAY_BUFFER", "ELEMENT_ARRAY_BUFFER"] for vertex indices // or atttribs. Could be 0 for other data Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; bool dracoDecoded{false}; // Flag indicating this has been draco decoded BufferView() : buffer(-1), byteOffset(0), byteLength(0), byteStride(0), target(0), dracoDecoded(false) {} DEFAULT_METHODS(BufferView) bool operator==(const BufferView &) const; }; struct Accessor { int bufferView; // optional in spec but required here since sparse accessor // are not supported std::string name; size_t byteOffset; bool normalized; // optional. int componentType; // (required) One of TINYGLTF_COMPONENT_TYPE_*** size_t count; // required int type; // (required) One of TINYGLTF_TYPE_*** .. Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; std::vector<double> minValues; // optional. integer value is promoted to double std::vector<double> maxValues; // optional. integer value is promoted to double struct { int count; bool isSparse; struct { int byteOffset; int bufferView; int componentType; // a TINYGLTF_COMPONENT_TYPE_ value } indices; struct { int bufferView; int byteOffset; } values; } sparse; /// /// Utility function to compute byteStride for a given bufferView object. /// Returns -1 upon invalid glTF value or parameter configuration. /// int ByteStride(const BufferView &bufferViewObject) const { if (bufferViewObject.byteStride == 0) { // Assume data is tightly packed. int componentSizeInBytes = GetComponentSizeInBytes(static_cast<uint32_t>(componentType)); if (componentSizeInBytes <= 0) { return -1; } int numComponents = GetNumComponentsInType(static_cast<uint32_t>(type)); if (numComponents <= 0) { return -1; } return componentSizeInBytes * numComponents; } else { // Check if byteStride is a mulple of the size of the accessor's component // type. int componentSizeInBytes = GetComponentSizeInBytes(static_cast<uint32_t>(componentType)); if (componentSizeInBytes <= 0) { return -1; } if ((bufferViewObject.byteStride % uint32_t(componentSizeInBytes)) != 0) { return -1; } return static_cast<int>(bufferViewObject.byteStride); } // unreachable return 0; } Accessor() : bufferView(-1), byteOffset(0), normalized(false), componentType(-1), count(0), type(-1) { sparse.isSparse = false; } DEFAULT_METHODS(Accessor) bool operator==(const tinygltf::Accessor &) const; }; struct PerspectiveCamera { double aspectRatio; // min > 0 double yfov; // required. min > 0 double zfar; // min > 0 double znear; // required. min > 0 PerspectiveCamera() : aspectRatio(0.0), yfov(0.0), zfar(0.0) // 0 = use infinite projecton matrix , znear(0.0) {} DEFAULT_METHODS(PerspectiveCamera) bool operator==(const PerspectiveCamera &) const; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; struct OrthographicCamera { double xmag; // required. must not be zero. double ymag; // required. must not be zero. double zfar; // required. `zfar` must be greater than `znear`. double znear; // required OrthographicCamera() : xmag(0.0), ymag(0.0), zfar(0.0), znear(0.0) {} DEFAULT_METHODS(OrthographicCamera) bool operator==(const OrthographicCamera &) const; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; struct Camera { std::string type; // required. "perspective" or "orthographic" std::string name; PerspectiveCamera perspective; OrthographicCamera orthographic; Camera() {} DEFAULT_METHODS(Camera) bool operator==(const Camera &) const; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; struct Primitive { std::map<std::string, int> attributes; // (required) A dictionary object of // integer, where each integer // is the index of the accessor // containing an attribute. int material; // The index of the material to apply to this primitive // when rendering. int indices; // The index of the accessor that contains the indices. int mode; // one of TINYGLTF_MODE_*** std::vector<std::map<std::string, int> > targets; // array of morph targets, // where each target is a dict with attribues in ["POSITION, "NORMAL", // "TANGENT"] pointing // to their corresponding accessors ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Primitive() { material = -1; indices = -1; mode = -1; } DEFAULT_METHODS(Primitive) bool operator==(const Primitive &) const; }; struct Mesh { std::string name; std::vector<Primitive> primitives; std::vector<double> weights; // weights to be applied to the Morph Targets ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Mesh() = default; DEFAULT_METHODS(Mesh) bool operator==(const Mesh &) const; }; class Node { public: Node() : camera(-1), skin(-1), mesh(-1) {} DEFAULT_METHODS(Node) bool operator==(const Node &) const; int camera; // the index of the camera referenced by this node std::string name; int skin; int mesh; std::vector<int> children; std::vector<double> rotation; // length must be 0 or 4 std::vector<double> scale; // length must be 0 or 3 std::vector<double> translation; // length must be 0 or 3 std::vector<double> matrix; // length must be 0 or 16 std::vector<double> weights; // The weights of the instantiated Morph Target ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; struct Buffer { std::string name; std::vector<unsigned char> data; std::string uri; // considered as required here but not in the spec (need to clarify) // uri is not decoded(e.g. whitespace may be represented as %20) Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Buffer() = default; DEFAULT_METHODS(Buffer) bool operator==(const Buffer &) const; }; struct Asset { std::string version = "2.0"; // required std::string generator; std::string minVersion; std::string copyright; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Asset() = default; DEFAULT_METHODS(Asset) bool operator==(const Asset &) const; }; struct Scene { std::string name; std::vector<int> nodes; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; Scene() = default; DEFAULT_METHODS(Scene) bool operator==(const Scene &) const; }; struct SpotLight { double innerConeAngle; double outerConeAngle; SpotLight() : innerConeAngle(0.0), outerConeAngle(0.7853981634) {} DEFAULT_METHODS(SpotLight) bool operator==(const SpotLight &) const; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; struct Light { std::string name; std::vector<double> color; double intensity{1.0}; std::string type; double range{0.0}; // 0.0 = inifinite SpotLight spot; Light() : intensity(1.0), range(0.0) {} DEFAULT_METHODS(Light) bool operator==(const Light &) const; ExtensionMap extensions; Value extras; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; class Model { public: Model() = default; DEFAULT_METHODS(Model) bool operator==(const Model &) const; std::vector<Accessor> accessors; std::vector<Animation> animations; std::vector<Buffer> buffers; std::vector<BufferView> bufferViews; std::vector<Material> materials; std::vector<Mesh> meshes; std::vector<Node> nodes; std::vector<Texture> textures; std::vector<Image> images; std::vector<Skin> skins; std::vector<Sampler> samplers; std::vector<Camera> cameras; std::vector<Scene> scenes; std::vector<Light> lights; int defaultScene = -1; std::vector<std::string> extensionsUsed; std::vector<std::string> extensionsRequired; Asset asset; Value extras; ExtensionMap extensions; // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled. std::string extras_json_string; std::string extensions_json_string; }; enum SectionCheck { NO_REQUIRE = 0x00, REQUIRE_VERSION = 0x01, REQUIRE_SCENE = 0x02, REQUIRE_SCENES = 0x04, REQUIRE_NODES = 0x08, REQUIRE_ACCESSORS = 0x10, REQUIRE_BUFFERS = 0x20, REQUIRE_BUFFER_VIEWS = 0x40, REQUIRE_ALL = 0x7f }; /// /// LoadImageDataFunction type. Signature for custom image loading callbacks. /// typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *, std::string *, int, int, const unsigned char *, int, void *user_pointer); /// /// WriteImageDataFunction type. Signature for custom image writing callbacks. /// typedef bool (*WriteImageDataFunction)(const std::string *, const std::string *, Image *, bool, void *); #ifndef TINYGLTF_NO_STB_IMAGE // Declaration of default image loader callback bool LoadImageData(Image *image, const int image_idx, std::string *err, std::string *warn, int req_width, int req_height, const unsigned char *bytes, int size, void *); #endif #ifndef TINYGLTF_NO_STB_IMAGE_WRITE // Declaration of default image writer callback bool WriteImageData(const std::string *basepath, const std::string *filename, Image *image, bool embedImages, void *); #endif /// /// FilExistsFunction type. Signature for custom filesystem callbacks. /// typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *); /// /// ExpandFilePathFunction type. Signature for custom filesystem callbacks. /// typedef std::string (*ExpandFilePathFunction)(const std::string &, void *); /// /// ReadWholeFileFunction type. Signature for custom filesystem callbacks. /// typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *, std::string *, const std::string &, void *); /// /// WriteWholeFileFunction type. Signature for custom filesystem callbacks. /// typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &, const std::vector<unsigned char> &, void *); /// /// A structure containing all required filesystem callbacks and a pointer to /// their user data. /// struct FsCallbacks { FileExistsFunction FileExists; ExpandFilePathFunction ExpandFilePath; ReadWholeFileFunction ReadWholeFile; WriteWholeFileFunction WriteWholeFile; void *user_data; // An argument that is passed to all fs callbacks }; #ifndef TINYGLTF_NO_FS // Declaration of default filesystem callbacks bool FileExists(const std::string &abs_filename, void *); /// /// Expand file path(e.g. `~` to home directory on posix, `%APPDATA%` to /// `C:\\Users\\tinygltf\\AppData`) /// /// @param[in] filepath File path string. Assume UTF-8 /// @param[in] userdata User data. Set to `nullptr` if you don't need it. /// std::string ExpandFilePath(const std::string &filepath, void *userdata); bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err, const std::string &filepath, void *); bool WriteWholeFile(std::string *err, const std::string &filepath, const std::vector<unsigned char> &contents, void *); #endif /// /// glTF Parser/Serialier context. /// class TinyGLTF { public: #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #endif TinyGLTF() : bin_data_(nullptr), bin_size_(0), is_binary_(false) {} #ifdef __clang__ #pragma clang diagnostic pop #endif ~TinyGLTF() {} /// /// Loads glTF ASCII asset from a file. /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadASCIIFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF ASCII asset from string(memory). /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadASCIIFromString(Model *model, std::string *err, std::string *warn, const char *str, const unsigned int length, const std::string &base_dir, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF binary asset from a file. /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadBinaryFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections = REQUIRE_VERSION); /// /// Loads glTF binary asset from memory. /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts. /// Returns false and set error string to `err` if there's an error. /// bool LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn, const unsigned char *bytes, const unsigned int length, const std::string &base_dir = "", unsigned int check_sections = REQUIRE_VERSION); /// /// Write glTF to stream, buffers and images will be embeded /// bool WriteGltfSceneToStream(Model *model, std::ostream &stream, bool prettyPrint, bool writeBinary); /// /// Write glTF to file. /// bool WriteGltfSceneToFile(Model *model, const std::string &filename, bool embedImages, bool embedBuffers, bool prettyPrint, bool writeBinary); /// /// Set callback to use for loading image data /// void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data); /// /// Unset(remove) callback of loading image data /// void RemoveImageLoader(); /// /// Set callback to use for writing image data /// void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data); /// /// Set callbacks to use for filesystem (fs) access and their user data /// void SetFsCallbacks(FsCallbacks callbacks); /// /// Set serializing default values(default = false). /// When true, default values are force serialized to .glTF. /// This may be helpfull if you want to serialize a full description of glTF /// data. /// /// TODO(LTE): Supply parsing option as function arguments to /// `LoadASCIIFromFile()` and others, not by a class method /// void SetSerializeDefaultValues(const bool enabled) { serialize_default_values_ = enabled; } bool GetSerializeDefaultValues() const { return serialize_default_values_; } /// /// Store original JSON string for `extras` and `extensions`. /// This feature will be useful when the user want to reconstruct custom data /// structure from JSON string. /// void SetStoreOriginalJSONForExtrasAndExtensions(const bool enabled) { store_original_json_for_extras_and_extensions_ = enabled; } bool GetStoreOriginalJSONForExtrasAndExtensions() const { return store_original_json_for_extras_and_extensions_; } /// /// Specify whether preserve image channales when loading images or not. /// (Not effective when the user suppy their own LoadImageData callbacks) /// void SetPreserveImageChannels(bool onoff) { preserve_image_channels_ = onoff; } bool GetPreserveImageChannels() const { return preserve_image_channels_; } private: /// /// Loads glTF asset from string(memory). /// `length` = strlen(str); /// Set warning message to `warn` for example it fails to load asserts /// Returns false and set error string to `err` if there's an error. /// bool LoadFromString(Model *model, std::string *err, std::string *warn, const char *str, const unsigned int length, const std::string &base_dir, unsigned int check_sections); const unsigned char *bin_data_ = nullptr; size_t bin_size_ = 0; bool is_binary_ = false; bool serialize_default_values_ = false; ///< Serialize default values? bool store_original_json_for_extras_and_extensions_ = false; bool preserve_image_channels_ = false; /// Default false(expand channels to /// RGBA) for backward compatibility. FsCallbacks fs = { #ifndef TINYGLTF_NO_FS &tinygltf::FileExists, &tinygltf::ExpandFilePath, &tinygltf::ReadWholeFile, &tinygltf::WriteWholeFile, nullptr // Fs callback user data #else nullptr, nullptr, nullptr, nullptr, nullptr // Fs callback user data #endif }; LoadImageDataFunction LoadImageData = #ifndef TINYGLTF_NO_STB_IMAGE &tinygltf::LoadImageData; #else nullptr; #endif void *load_image_user_data_{nullptr}; bool user_image_loader_{false}; WriteImageDataFunction WriteImageData = #ifndef TINYGLTF_NO_STB_IMAGE_WRITE &tinygltf::WriteImageData; #else nullptr; #endif void *write_image_user_data_{nullptr}; }; #ifdef __clang__ #pragma clang diagnostic pop // -Wpadded #endif } // namespace tinygltf #endif // TINY_GLTF_H_ #if defined(TINYGLTF_IMPLEMENTATION) || defined(__INTELLISENSE__) #include <algorithm> //#include <cassert> #ifndef TINYGLTF_NO_FS #include <cstdio> #include <fstream> #endif #include <sstream> #ifdef __clang__ // Disable some warnings for external files. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wfloat-equal" #pragma clang diagnostic ignored "-Wexit-time-destructors" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wglobal-constructors" #if __has_warning("-Wreserved-id-macro") #pragma clang diagnostic ignored "-Wreserved-id-macro" #endif #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wc++98-compat" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #pragma clang diagnostic ignored "-Wswitch-enum" #pragma clang diagnostic ignored "-Wimplicit-fallthrough" #pragma clang diagnostic ignored "-Wweak-vtables" #pragma clang diagnostic ignored "-Wcovered-switch-default" #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" #endif #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wmissing-variable-declarations") #pragma clang diagnostic ignored "-Wmissing-variable-declarations" #endif #if __has_warning("-Wmissing-prototypes") #pragma clang diagnostic ignored "-Wmissing-prototypes" #endif #if __has_warning("-Wcast-align") #pragma clang diagnostic ignored "-Wcast-align" #endif #if __has_warning("-Wnewline-eof") #pragma clang diagnostic ignored "-Wnewline-eof" #endif #if __has_warning("-Wunused-parameter") #pragma clang diagnostic ignored "-Wunused-parameter" #endif #if __has_warning("-Wmismatched-tags") #pragma clang diagnostic ignored "-Wmismatched-tags" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // Disable GCC warnigs #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" #endif // __GNUC__ #ifndef TINYGLTF_NO_INCLUDE_JSON #ifndef TINYGLTF_USE_RAPIDJSON #include "json.hpp" #else #ifndef TINYGLTF_NO_INCLUDE_RAPIDJSON #include <rapidjson/document.h> #include <rapidjson/prettywriter.h> #include <rapidjson/rapidjson.h> #include <rapidjson/stringbuffer.h> #include <rapidjson/writer.h> #endif #endif #endif #ifdef TINYGLTF_ENABLE_DRACO #include "draco/compression/decode.h" #include "draco/core/decoder_buffer.h" #endif #ifndef TINYGLTF_NO_STB_IMAGE #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE #include <stb_image.h> #endif #endif #ifndef TINYGLTF_NO_STB_IMAGE_WRITE #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE #include "stb_image_write.h" #endif #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif #ifdef _WIN32 // issue 143. // Define NOMINMAX to avoid min/max defines, // but undef it after included windows.h #ifndef NOMINMAX #define TINYGLTF_INTERNAL_NOMINMAX #define NOMINMAX #endif #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN #endif #include <windows.h> // include API for expanding a file path #ifdef TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #endif #if defined(TINYGLTF_INTERNAL_NOMINMAX) #undef NOMINMAX #endif #if defined(__GLIBCXX__) // mingw #include <fcntl.h> // _O_RDONLY #include <ext/stdio_filebuf.h> // fstream (all sorts of IO stuff) + stdio_filebuf (=streambuf) #endif #elif !defined(__ANDROID__) && !defined(__OpenBSD__) #include <wordexp.h> #endif #if defined(__sparcv9) || defined(__powerpc__) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU #define TINYGLTF_LITTLE_ENDIAN 1 #endif #endif namespace { #ifdef TINYGLTF_USE_RAPIDJSON #ifdef TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR // This uses the RapidJSON CRTAllocator. It is thread safe and multiple // documents may be active at once. using json = rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::CrtAllocator>; using json_const_iterator = json::ConstMemberIterator; using json_const_array_iterator = json const *; using JsonDocument = rapidjson::GenericDocument<rapidjson::UTF8<>, rapidjson::CrtAllocator>; rapidjson::CrtAllocator s_CrtAllocator; // stateless and thread safe rapidjson::CrtAllocator &GetAllocator() { return s_CrtAllocator; } #else // This uses the default RapidJSON MemoryPoolAllocator. It is very fast, but // not thread safe. Only a single JsonDocument may be active at any one time, // meaning only a single gltf load/save can be active any one time. using json = rapidjson::Value; using json_const_iterator = json::ConstMemberIterator; using json_const_array_iterator = json const *; rapidjson::Document *s_pActiveDocument = nullptr; rapidjson::Document::AllocatorType &GetAllocator() { assert(s_pActiveDocument); // Root json node must be JsonDocument type return s_pActiveDocument->GetAllocator(); } #ifdef __clang__ #pragma clang diagnostic push // Suppress JsonDocument(JsonDocument &&rhs) noexcept #pragma clang diagnostic ignored "-Wunused-member-function" #endif struct JsonDocument : public rapidjson::Document { JsonDocument() { assert(s_pActiveDocument == nullptr); // When using default allocator, only one document can be // active at a time, if you need multiple active at once, // define TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR s_pActiveDocument = this; } JsonDocument(const JsonDocument &) = delete; JsonDocument(JsonDocument &&rhs) noexcept : rapidjson::Document(std::move(rhs)) { s_pActiveDocument = this; rhs.isNil = true; } ~JsonDocument() { if (!isNil) { s_pActiveDocument = nullptr; } } private: bool isNil = false; }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR #else using nlohmann::json; using json_const_iterator = json::const_iterator; using json_const_array_iterator = json_const_iterator; using JsonDocument = json; #endif void JsonParse(JsonDocument &doc, const char *str, size_t length, bool throwExc = false) { #ifdef TINYGLTF_USE_RAPIDJSON (void)throwExc; doc.Parse(str, length); #else doc = json::parse(str, str + length, nullptr, throwExc); #endif } } // namespace #ifdef __APPLE__ #include "TargetConditionals.h" #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++98-compat" #endif namespace tinygltf { /// /// Internal LoadImageDataOption struct. /// This struct is passed through `user_pointer` in LoadImageData. /// The struct is not passed when the user supply their own LoadImageData /// callbacks. /// struct LoadImageDataOption { // true: preserve image channels(e.g. load as RGB image if the image has RGB // channels) default `false`(channels are expanded to RGBA for backward // compatiblity). bool preserve_channels{false}; }; // Equals function for Value, for recursivity static bool Equals(const tinygltf::Value &one, const tinygltf::Value &other) { if (one.Type() != other.Type()) return false; switch (one.Type()) { case NULL_TYPE: return true; case BOOL_TYPE: return one.Get<bool>() == other.Get<bool>(); case REAL_TYPE: return TINYGLTF_DOUBLE_EQUAL(one.Get<double>(), other.Get<double>()); case INT_TYPE: return one.Get<int>() == other.Get<int>(); case OBJECT_TYPE: { auto oneObj = one.Get<tinygltf::Value::Object>(); auto otherObj = other.Get<tinygltf::Value::Object>(); if (oneObj.size() != otherObj.size()) return false; for (auto &it : oneObj) { auto otherIt = otherObj.find(it.first); if (otherIt == otherObj.end()) return false; if (!Equals(it.second, otherIt->second)) return false; } return true; } case ARRAY_TYPE: { if (one.Size() != other.Size()) return false; for (int i = 0; i < int(one.Size()); ++i) if (!Equals(one.Get(i), other.Get(i))) return false; return true; } case STRING_TYPE: return one.Get<std::string>() == other.Get<std::string>(); case BINARY_TYPE: return one.Get<std::vector<unsigned char> >() == other.Get<std::vector<unsigned char> >(); default: { // unhandled type return false; } } } // Equals function for std::vector<double> using TINYGLTF_DOUBLE_EPSILON static bool Equals(const std::vector<double> &one, const std::vector<double> &other) { if (one.size() != other.size()) return false; for (int i = 0; i < int(one.size()); ++i) { if (!TINYGLTF_DOUBLE_EQUAL(one[size_t(i)], other[size_t(i)])) return false; } return true; } bool Accessor::operator==(const Accessor &other) const { return this->bufferView == other.bufferView && this->byteOffset == other.byteOffset && this->componentType == other.componentType && this->count == other.count && this->extensions == other.extensions && this->extras == other.extras && Equals(this->maxValues, other.maxValues) && Equals(this->minValues, other.minValues) && this->name == other.name && this->normalized == other.normalized && this->type == other.type; } bool Animation::operator==(const Animation &other) const { return this->channels == other.channels && this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->samplers == other.samplers; } bool AnimationChannel::operator==(const AnimationChannel &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->target_node == other.target_node && this->target_path == other.target_path && this->sampler == other.sampler; } bool AnimationSampler::operator==(const AnimationSampler &other) const { return this->extras == other.extras && this->extensions == other.extensions && this->input == other.input && this->interpolation == other.interpolation && this->output == other.output; } bool Asset::operator==(const Asset &other) const { return this->copyright == other.copyright && this->extensions == other.extensions && this->extras == other.extras && this->generator == other.generator && this->minVersion == other.minVersion && this->version == other.version; } bool Buffer::operator==(const Buffer &other) const { return this->data == other.data && this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->uri == other.uri; } bool BufferView::operator==(const BufferView &other) const { return this->buffer == other.buffer && this->byteLength == other.byteLength && this->byteOffset == other.byteOffset && this->byteStride == other.byteStride && this->name == other.name && this->target == other.target && this->extensions == other.extensions && this->extras == other.extras && this->dracoDecoded == other.dracoDecoded; } bool Camera::operator==(const Camera &other) const { return this->name == other.name && this->extensions == other.extensions && this->extras == other.extras && this->orthographic == other.orthographic && this->perspective == other.perspective && this->type == other.type; } bool Image::operator==(const Image &other) const { return this->bufferView == other.bufferView && this->component == other.component && this->extensions == other.extensions && this->extras == other.extras && this->height == other.height && this->image == other.image && this->mimeType == other.mimeType && this->name == other.name && this->uri == other.uri && this->width == other.width; } bool Light::operator==(const Light &other) const { return Equals(this->color, other.color) && this->name == other.name && this->type == other.type; } bool Material::operator==(const Material &other) const { return (this->pbrMetallicRoughness == other.pbrMetallicRoughness) && (this->normalTexture == other.normalTexture) && (this->occlusionTexture == other.occlusionTexture) && (this->emissiveTexture == other.emissiveTexture) && Equals(this->emissiveFactor, other.emissiveFactor) && (this->alphaMode == other.alphaMode) && TINYGLTF_DOUBLE_EQUAL(this->alphaCutoff, other.alphaCutoff) && (this->doubleSided == other.doubleSided) && (this->extensions == other.extensions) && (this->extras == other.extras) && (this->values == other.values) && (this->additionalValues == other.additionalValues) && (this->name == other.name); } bool Mesh::operator==(const Mesh &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && Equals(this->weights, other.weights) && this->primitives == other.primitives; } bool Model::operator==(const Model &other) const { return this->accessors == other.accessors && this->animations == other.animations && this->asset == other.asset && this->buffers == other.buffers && this->bufferViews == other.bufferViews && this->cameras == other.cameras && this->defaultScene == other.defaultScene && this->extensions == other.extensions && this->extensionsRequired == other.extensionsRequired && this->extensionsUsed == other.extensionsUsed && this->extras == other.extras && this->images == other.images && this->lights == other.lights && this->materials == other.materials && this->meshes == other.meshes && this->nodes == other.nodes && this->samplers == other.samplers && this->scenes == other.scenes && this->skins == other.skins && this->textures == other.textures; } bool Node::operator==(const Node &other) const { return this->camera == other.camera && this->children == other.children && this->extensions == other.extensions && this->extras == other.extras && Equals(this->matrix, other.matrix) && this->mesh == other.mesh && this->name == other.name && Equals(this->rotation, other.rotation) && Equals(this->scale, other.scale) && this->skin == other.skin && Equals(this->translation, other.translation) && Equals(this->weights, other.weights); } bool SpotLight::operator==(const SpotLight &other) const { return this->extensions == other.extensions && this->extras == other.extras && TINYGLTF_DOUBLE_EQUAL(this->innerConeAngle, other.innerConeAngle) && TINYGLTF_DOUBLE_EQUAL(this->outerConeAngle, other.outerConeAngle); } bool OrthographicCamera::operator==(const OrthographicCamera &other) const { return this->extensions == other.extensions && this->extras == other.extras && TINYGLTF_DOUBLE_EQUAL(this->xmag, other.xmag) && TINYGLTF_DOUBLE_EQUAL(this->ymag, other.ymag) && TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) && TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear); } bool Parameter::operator==(const Parameter &other) const { if (this->bool_value != other.bool_value || this->has_number_value != other.has_number_value) return false; if (!TINYGLTF_DOUBLE_EQUAL(this->number_value, other.number_value)) return false; if (this->json_double_value.size() != other.json_double_value.size()) return false; for (auto &it : this->json_double_value) { auto otherIt = other.json_double_value.find(it.first); if (otherIt == other.json_double_value.end()) return false; if (!TINYGLTF_DOUBLE_EQUAL(it.second, otherIt->second)) return false; } if (!Equals(this->number_array, other.number_array)) return false; if (this->string_value != other.string_value) return false; return true; } bool PerspectiveCamera::operator==(const PerspectiveCamera &other) const { return TINYGLTF_DOUBLE_EQUAL(this->aspectRatio, other.aspectRatio) && this->extensions == other.extensions && this->extras == other.extras && TINYGLTF_DOUBLE_EQUAL(this->yfov, other.yfov) && TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) && TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear); } bool Primitive::operator==(const Primitive &other) const { return this->attributes == other.attributes && this->extras == other.extras && this->indices == other.indices && this->material == other.material && this->mode == other.mode && this->targets == other.targets; } bool Sampler::operator==(const Sampler &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->magFilter == other.magFilter && this->minFilter == other.minFilter && this->name == other.name && this->wrapS == other.wrapS && this->wrapT == other.wrapT; //this->wrapR == other.wrapR } bool Scene::operator==(const Scene &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->nodes == other.nodes; } bool Skin::operator==(const Skin &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->inverseBindMatrices == other.inverseBindMatrices && this->joints == other.joints && this->name == other.name && this->skeleton == other.skeleton; } bool Texture::operator==(const Texture &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->name == other.name && this->sampler == other.sampler && this->source == other.source; } bool TextureInfo::operator==(const TextureInfo &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->index == other.index && this->texCoord == other.texCoord; } bool NormalTextureInfo::operator==(const NormalTextureInfo &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->index == other.index && this->texCoord == other.texCoord && TINYGLTF_DOUBLE_EQUAL(this->scale, other.scale); } bool OcclusionTextureInfo::operator==(const OcclusionTextureInfo &other) const { return this->extensions == other.extensions && this->extras == other.extras && this->index == other.index && this->texCoord == other.texCoord && TINYGLTF_DOUBLE_EQUAL(this->strength, other.strength); } bool PbrMetallicRoughness::operator==(const PbrMetallicRoughness &other) const { return this->extensions == other.extensions && this->extras == other.extras && (this->baseColorTexture == other.baseColorTexture) && (this->metallicRoughnessTexture == other.metallicRoughnessTexture) && Equals(this->baseColorFactor, other.baseColorFactor) && TINYGLTF_DOUBLE_EQUAL(this->metallicFactor, other.metallicFactor) && TINYGLTF_DOUBLE_EQUAL(this->roughnessFactor, other.roughnessFactor); } bool Value::operator==(const Value &other) const { return Equals(*this, other); } static void swap4(unsigned int *val) { #ifdef TINYGLTF_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static std::string JoinPath(const std::string &path0, const std::string &path1) { if (path0.empty()) { return path1; } else { // check '/' char lastChar = *path0.rbegin(); if (lastChar != '/') { return path0 + std::string("/") + path1; } else { return path0 + path1; } } } static std::string FindFile(const std::vector<std::string> &paths, const std::string &filepath, FsCallbacks *fs) { if (fs == nullptr || fs->ExpandFilePath == nullptr || fs->FileExists == nullptr) { // Error, fs callback[s] missing return std::string(); } for (size_t i = 0; i < paths.size(); i++) { std::string absPath = fs->ExpandFilePath(JoinPath(paths[i], filepath), fs->user_data); if (fs->FileExists(absPath, fs->user_data)) { return absPath; } } return std::string(); } static std::string GetFilePathExtension(const std::string &FileName) { if (FileName.find_last_of(".") != std::string::npos) return FileName.substr(FileName.find_last_of(".") + 1); return ""; } static std::string GetBaseDir(const std::string &filepath) { if (filepath.find_last_of("/\\") != std::string::npos) return filepath.substr(0, filepath.find_last_of("/\\")); return ""; } static std::string GetBaseFilename(const std::string &filepath) { auto idx = filepath.find_last_of("/\\"); if (idx != std::string::npos) return filepath.substr(idx + 1); return filepath; } std::string base64_encode(unsigned char const *, unsigned int len); std::string base64_decode(std::string const &s); /* base64.cpp and base64.h Copyright (C) 2004-2008 René Nyffenegger This source code is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. René Nyffenegger rene.nyffenegger@adp-gmbh.ch */ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wconversion" #endif static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; const char *base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while ((i++ < 3)) ret += '='; } return ret; } std::string base64_decode(std::string const &encoded_string) { int in_len = static_cast<int>(encoded_string.size()); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i < 4; i++) char_array_4[i] = static_cast<unsigned char>(base64_chars.find(char_array_4[i])); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j < 4; j++) char_array_4[j] = 0; for (j = 0; j < 4; j++) char_array_4[j] = static_cast<unsigned char>(base64_chars.find(char_array_4[j])); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } #ifdef __clang__ #pragma clang diagnostic pop #endif // https://github.com/syoyo/tinygltf/issues/228 // TODO(syoyo): Use uriparser https://uriparser.github.io/ for stricter Uri // decoding? // // Uri Decoding from DLIB // http://dlib.net/dlib/server/server_http.cpp.html // --- dlib begin ------------------------------------------------------------ // Copyright (C) 2003 Davis E. King (davis@dlib.net) // License: Boost Software License // Boost Software License - Version 1.0 - August 17th, 2003 // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace dlib { inline unsigned char from_hex(unsigned char ch) { if (ch <= '9' && ch >= '0') ch -= '0'; else if (ch <= 'f' && ch >= 'a') ch -= 'a' - 10; else if (ch <= 'F' && ch >= 'A') ch -= 'A' - 10; else ch = 0; return ch; } static const std::string urldecode(const std::string &str) { using namespace std; string result; string::size_type i; for (i = 0; i < str.size(); ++i) { if (str[i] == '+') { result += ' '; } else if (str[i] == '%' && str.size() > i + 2) { const unsigned char ch1 = from_hex(static_cast<unsigned char>(str[i + 1])); const unsigned char ch2 = from_hex(static_cast<unsigned char>(str[i + 2])); const unsigned char ch = static_cast<unsigned char>((ch1 << 4) | ch2); result += static_cast<char>(ch); i += 2; } else { result += str[i]; } } return result; } } // namespace dlib // --- dlib end -------------------------------------------------------------- static bool LoadExternalFile(std::vector<unsigned char> *out, std::string *err, std::string *warn, const std::string &filename, const std::string &basedir, bool required, size_t reqBytes, bool checkSize, FsCallbacks *fs) { if (fs == nullptr || fs->FileExists == nullptr || fs->ExpandFilePath == nullptr || fs->ReadWholeFile == nullptr) { // This is a developer error, assert() ? if (err) { (*err) += "FS callback[s] not set\n"; } return false; } std::string *failMsgOut = required ? err : warn; out->clear(); std::vector<std::string> paths; paths.push_back(basedir); paths.push_back("."); std::string filepath = FindFile(paths, filename, fs); if (filepath.empty() || filename.empty()) { if (failMsgOut) { (*failMsgOut) += "File not found : " + filename + "\n"; } return false; } std::vector<unsigned char> buf; std::string fileReadErr; bool fileRead = fs->ReadWholeFile(&buf, &fileReadErr, filepath, fs->user_data); if (!fileRead) { if (failMsgOut) { (*failMsgOut) += "File read error : " + filepath + " : " + fileReadErr + "\n"; } return false; } size_t sz = buf.size(); if (sz == 0) { if (failMsgOut) { (*failMsgOut) += "File is empty : " + filepath + "\n"; } return false; } if (checkSize) { if (reqBytes == sz) { out->swap(buf); return true; } else { std::stringstream ss; ss << "File size mismatch : " << filepath << ", requestedBytes " << reqBytes << ", but got " << sz << std::endl; if (failMsgOut) { (*failMsgOut) += ss.str(); } return false; } } out->swap(buf); return true; } void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) { LoadImageData = func; load_image_user_data_ = user_data; user_image_loader_ = true; } void TinyGLTF::RemoveImageLoader() { LoadImageData = #ifndef TINYGLTF_NO_STB_IMAGE &tinygltf::LoadImageData; #else nullptr; #endif load_image_user_data_ = nullptr; user_image_loader_ = false; } #ifndef TINYGLTF_NO_STB_IMAGE bool LoadImageData(Image *image, const int image_idx, std::string *err, std::string *warn, int req_width, int req_height, const unsigned char *bytes, int size, void *user_data) { (void)warn; LoadImageDataOption option; if (user_data) { option = *reinterpret_cast<LoadImageDataOption *>(user_data); } int w = 0, h = 0, comp = 0, req_comp = 0; unsigned char *data = nullptr; // preserve_channels true: Use channels stored in the image file. // false: force 32-bit textures for common Vulkan compatibility. It appears // that some GPU drivers do not support 24-bit images for Vulkan req_comp = option.preserve_channels ? 0 : 4; int bits = 8; int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE; // It is possible that the image we want to load is a 16bit per channel image // We are going to attempt to load it as 16bit per channel, and if it worked, // set the image data accodingly. We are casting the returned pointer into // unsigned char, because we are representing "bytes". But we are updating // the Image metadata to signal that this image uses 2 bytes (16bits) per // channel: if (stbi_is_16_bit_from_memory(bytes, size)) { data = reinterpret_cast<unsigned char *>( stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp)); if (data) { bits = 16; pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT; } } // at this point, if data is still NULL, it means that the image wasn't // 16bit per channel, we are going to load it as a normal 8bit per channel // mage as we used to do: // if image cannot be decoded, ignore parsing and keep it by its path // don't break in this case // FIXME we should only enter this function if the image is embedded. If // image->uri references // an image file, it should be left as it is. Image loading should not be // mandatory (to support other formats) if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp); if (!data) { // NOTE: you can use `warn` instead of `err` if (err) { (*err) += "Unknown image format. STB cannot decode image data for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\".\n"; } return false; } if ((w < 1) || (h < 1)) { stbi_image_free(data); if (err) { (*err) += "Invalid image data for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } if (req_width > 0) { if (req_width != w) { stbi_image_free(data); if (err) { (*err) += "Image width mismatch for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } } if (req_height > 0) { if (req_height != h) { stbi_image_free(data); if (err) { (*err) += "Image height mismatch. for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } } if (req_comp != 0) { // loaded data has `req_comp` channels(components) comp = req_comp; } image->width = w; image->height = h; image->component = comp; image->bits = bits; image->pixel_type = pixel_type; image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8)); std::copy(data, data + w * h * comp * (bits / 8), image->image.begin()); stbi_image_free(data); return true; } #endif void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) { WriteImageData = func; write_image_user_data_ = user_data; } #ifndef TINYGLTF_NO_STB_IMAGE_WRITE static void WriteToMemory_stbi(void *context, void *data, int size) { std::vector<unsigned char> *buffer = reinterpret_cast<std::vector<unsigned char> *>(context); unsigned char *pData = reinterpret_cast<unsigned char *>(data); buffer->insert(buffer->end(), pData, pData + size); } bool WriteImageData(const std::string *basepath, const std::string *filename, Image *image, bool embedImages, void *fsPtr) { const std::string ext = GetFilePathExtension(*filename); // Write image to temporary buffer std::string header; std::vector<unsigned char> data; if (ext == "png") { if ((image->bits != 8) || (image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) { // Unsupported pixel format return false; } if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0], 0)) { return false; } header = "data:image/png;base64,"; } else if (ext == "jpg") { if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0], 100)) { return false; } header = "data:image/jpeg;base64,"; } else if (ext == "bmp") { if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width, image->height, image->component, &image->image[0])) { return false; } header = "data:image/bmp;base64,"; } else if (!embedImages) { // Error: can't output requested format to file return false; } if (embedImages) { // Embed base64-encoded image into URI if (data.size()) { image->uri = header + base64_encode(&data[0], static_cast<unsigned int>(data.size())); } else { // Throw error? } } else { // Write image to disc FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr); if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) { const std::string imagefilepath = JoinPath(*basepath, *filename); std::string writeError; if (!fs->WriteWholeFile(&writeError, imagefilepath, data, fs->user_data)) { // Could not write image file to disc; Throw error ? return false; } } else { // Throw error? } image->uri = *filename; } return true; } #endif void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; } #ifdef _WIN32 static inline std::wstring UTF8ToWchar(const std::string &str) { int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0); std::wstring wstr(wstr_size, 0); MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0], (int)wstr.size()); return wstr; } static inline std::string WcharToUTF8(const std::wstring &wstr) { int str_size = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), nullptr, 0, NULL, NULL); std::string str(str_size, 0); WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), &str[0], (int)str.size(), NULL, NULL); return str; } #endif #ifndef TINYGLTF_NO_FS // Default implementations of filesystem functions bool FileExists(const std::string &abs_filename, void *) { bool ret; #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS if (asset_manager) { AAsset *asset = AAssetManager_open(asset_manager, abs_filename.c_str(), AASSET_MODE_STREAMING); if (!asset) { return false; } AAsset_close(asset); ret = true; } else { return false; } #else #ifdef _WIN32 #if defined(_MSC_VER) || defined(__GLIBCXX__) FILE *fp = nullptr; errno_t err = _wfopen_s(&fp, UTF8ToWchar(abs_filename).c_str(), L"rb"); if (err != 0) { return false; } #else FILE *fp = nullptr; errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb"); if (err != 0) { return false; } #endif #else FILE *fp = fopen(abs_filename.c_str(), "rb"); #endif if (fp) { ret = true; fclose(fp); } else { ret = false; } #endif return ret; } std::string ExpandFilePath(const std::string &filepath, void *) { #ifdef _WIN32 // Assume input `filepath` is encoded in UTF-8 std::wstring wfilepath = UTF8ToWchar(filepath); DWORD wlen = ExpandEnvironmentStringsW(wfilepath.c_str(), nullptr, 0); wchar_t *wstr = new wchar_t[wlen]; ExpandEnvironmentStringsW(wfilepath.c_str(), wstr, wlen); std::wstring ws(wstr); delete[] wstr; return WcharToUTF8(ws); #else #if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) || \ defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__OpenBSD__) // no expansion std::string s = filepath; #else std::string s; wordexp_t p; if (filepath.empty()) { return ""; } // Quote the string to keep any spaces in filepath intact. std::string quoted_path = "\"" + filepath + "\""; // char** w; int ret = wordexp(quoted_path.c_str(), &p, 0); if (ret) { // err s = filepath; return s; } // Use first element only. if (p.we_wordv) { s = std::string(p.we_wordv[0]); wordfree(&p); } else { s = filepath; } #endif return s; #endif } bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err, const std::string &filepath, void *) { #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS if (asset_manager) { AAsset *asset = AAssetManager_open(asset_manager, filepath.c_str(), AASSET_MODE_STREAMING); if (!asset) { if (err) { (*err) += "File open error : " + filepath + "\n"; } return false; } size_t size = AAsset_getLength(asset); if (size == 0) { if (err) { (*err) += "Invalid file size : " + filepath + " (does the path point to a directory?)"; } return false; } out->resize(size); AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size); AAsset_close(asset); return true; } else { if (err) { (*err) += "No asset manager specified : " + filepath + "\n"; } return false; } #else #ifdef _WIN32 #if defined(__GLIBCXX__) // mingw int file_descriptor = _wopen(UTF8ToWchar(filepath).c_str(), _O_RDONLY | _O_BINARY); __gnu_cxx::stdio_filebuf<char> wfile_buf(file_descriptor, std::ios_base::in); std::istream f(&wfile_buf); #elif defined(_MSC_VER) || defined(_LIBCPP_VERSION) // For libcxx, assume _LIBCPP_HAS_OPEN_WITH_WCHAR is defined to accept // `wchar_t *` std::ifstream f(UTF8ToWchar(filepath).c_str(), std::ifstream::binary); #else // Unknown compiler/runtime std::ifstream f(filepath.c_str(), std::ifstream::binary); #endif #else std::ifstream f(filepath.c_str(), std::ifstream::binary); #endif if (!f) { if (err) { (*err) += "File open error : " + filepath + "\n"; } return false; } f.seekg(0, f.end); size_t sz = static_cast<size_t>(f.tellg()); f.seekg(0, f.beg); if (int64_t(sz) < 0) { if (err) { (*err) += "Invalid file size : " + filepath + " (does the path point to a directory?)"; } return false; } else if (sz == 0) { if (err) { (*err) += "File is empty : " + filepath + "\n"; } return false; } out->resize(sz); f.read(reinterpret_cast<char *>(&out->at(0)), static_cast<std::streamsize>(sz)); return true; #endif } bool WriteWholeFile(std::string *err, const std::string &filepath, const std::vector<unsigned char> &contents, void *) { #ifdef _WIN32 #if defined(__GLIBCXX__) // mingw int file_descriptor = _wopen(UTF8ToWchar(filepath).c_str(), _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY); __gnu_cxx::stdio_filebuf<char> wfile_buf( file_descriptor, std::ios_base::out | std::ios_base::binary); std::ostream f(&wfile_buf); #elif defined(_MSC_VER) std::ofstream f(UTF8ToWchar(filepath).c_str(), std::ofstream::binary); #else // clang? std::ofstream f(filepath.c_str(), std::ofstream::binary); #endif #else std::ofstream f(filepath.c_str(), std::ofstream::binary); #endif if (!f) { if (err) { (*err) += "File open error for writing : " + filepath + "\n"; } return false; } f.write(reinterpret_cast<const char *>(&contents.at(0)), static_cast<std::streamsize>(contents.size())); if (!f) { if (err) { (*err) += "File write error: " + filepath + "\n"; } return false; } return true; } #endif // TINYGLTF_NO_FS static std::string MimeToExt(const std::string &mimeType) { if (mimeType == "image/jpeg") { return "jpg"; } else if (mimeType == "image/png") { return "png"; } else if (mimeType == "image/bmp") { return "bmp"; } else if (mimeType == "image/gif") { return "gif"; } return ""; } static void UpdateImageObject(Image &image, std::string &baseDir, int index, bool embedImages, WriteImageDataFunction *WriteImageData = nullptr, void *user_data = nullptr) { std::string filename; std::string ext; // If image has uri, use it it as a filename if (image.uri.size()) { filename = GetBaseFilename(image.uri); ext = GetFilePathExtension(filename); } else if (image.bufferView != -1) { // If there's no URI and the data exists in a buffer, // don't change properties or write images } else if (image.name.size()) { ext = MimeToExt(image.mimeType); // Otherwise use name as filename filename = image.name + "." + ext; } else { ext = MimeToExt(image.mimeType); // Fallback to index of image as filename filename = std::to_string(index) + "." + ext; } // If callback is set, modify image data object if (*WriteImageData != nullptr && !filename.empty()) { std::string uri; (*WriteImageData)(&baseDir, &filename, &image, embedImages, user_data); } } bool IsDataURI(const std::string &in) { std::string header = "data:application/octet-stream;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/jpeg;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/png;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/bmp;base64,"; if (in.find(header) == 0) { return true; } header = "data:image/gif;base64,"; if (in.find(header) == 0) { return true; } header = "data:text/plain;base64,"; if (in.find(header) == 0) { return true; } header = "data:application/gltf-buffer;base64,"; if (in.find(header) == 0) { return true; } return false; } bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type, const std::string &in, size_t reqBytes, bool checkSize) { std::string header = "data:application/octet-stream;base64,"; std::string data; if (in.find(header) == 0) { data = base64_decode(in.substr(header.size())); // cut mime string. } if (data.empty()) { header = "data:image/jpeg;base64,"; if (in.find(header) == 0) { mime_type = "image/jpeg"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/png;base64,"; if (in.find(header) == 0) { mime_type = "image/png"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/bmp;base64,"; if (in.find(header) == 0) { mime_type = "image/bmp"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:image/gif;base64,"; if (in.find(header) == 0) { mime_type = "image/gif"; data = base64_decode(in.substr(header.size())); // cut mime string. } } if (data.empty()) { header = "data:text/plain;base64,"; if (in.find(header) == 0) { mime_type = "text/plain"; data = base64_decode(in.substr(header.size())); } } if (data.empty()) { header = "data:application/gltf-buffer;base64,"; if (in.find(header) == 0) { data = base64_decode(in.substr(header.size())); } } // TODO(syoyo): Allow empty buffer? #229 if (data.empty()) { return false; } if (checkSize) { if (data.size() != reqBytes) { return false; } out->resize(reqBytes); } else { out->resize(data.size()); } std::copy(data.begin(), data.end(), out->begin()); return true; } namespace { bool GetInt(const json &o, int &val) { #ifdef TINYGLTF_USE_RAPIDJSON if (!o.IsDouble()) { if (o.IsInt()) { val = o.GetInt(); return true; } else if (o.IsUint()) { val = static_cast<int>(o.GetUint()); return true; } else if (o.IsInt64()) { val = static_cast<int>(o.GetInt64()); return true; } else if (o.IsUint64()) { val = static_cast<int>(o.GetUint64()); return true; } } return false; #else auto type = o.type(); if ((type == json::value_t::number_integer) || (type == json::value_t::number_unsigned)) { val = static_cast<int>(o.get<int64_t>()); return true; } return false; #endif } #ifdef TINYGLTF_USE_RAPIDJSON bool GetDouble(const json &o, double &val) { if (o.IsDouble()) { val = o.GetDouble(); return true; } return false; } #endif bool GetNumber(const json &o, double &val) { #ifdef TINYGLTF_USE_RAPIDJSON if (o.IsNumber()) { val = o.GetDouble(); return true; } return false; #else if (o.is_number()) { val = o.get<double>(); return true; } return false; #endif } bool GetString(const json &o, std::string &val) { #ifdef TINYGLTF_USE_RAPIDJSON if (o.IsString()) { val = o.GetString(); return true; } return false; #else if (o.type() == json::value_t::string) { val = o.get<std::string>(); return true; } return false; #endif } bool IsArray(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.IsArray(); #else return o.is_array(); #endif } json_const_array_iterator ArrayBegin(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.Begin(); #else return o.begin(); #endif } json_const_array_iterator ArrayEnd(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.End(); #else return o.end(); #endif } bool IsObject(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.IsObject(); #else return o.is_object(); #endif } json_const_iterator ObjectBegin(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.MemberBegin(); #else return o.begin(); #endif } json_const_iterator ObjectEnd(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.MemberEnd(); #else return o.end(); #endif } // Making this a const char* results in a pointer to a temporary when // TINYGLTF_USE_RAPIDJSON is off. std::string GetKey(json_const_iterator &it) { #ifdef TINYGLTF_USE_RAPIDJSON return it->name.GetString(); #else return it.key().c_str(); #endif } bool FindMember(const json &o, const char *member, json_const_iterator &it) { #ifdef TINYGLTF_USE_RAPIDJSON if (!o.IsObject()) { return false; } it = o.FindMember(member); return it != o.MemberEnd(); #else it = o.find(member); return it != o.end(); #endif } const json &GetValue(json_const_iterator &it) { #ifdef TINYGLTF_USE_RAPIDJSON return it->value; #else return it.value(); #endif } std::string JsonToString(const json &o, int spacing = -1) { #ifdef TINYGLTF_USE_RAPIDJSON using namespace rapidjson; StringBuffer buffer; if (spacing == -1) { Writer<StringBuffer> writer(buffer); o.Accept(writer); } else { PrettyWriter<StringBuffer> writer(buffer); writer.SetIndent(' ', uint32_t(spacing)); o.Accept(writer); } return buffer.GetString(); #else return o.dump(spacing); #endif } } // namespace static bool ParseJsonAsValue(Value *ret, const json &o) { Value val{}; #ifdef TINYGLTF_USE_RAPIDJSON using rapidjson::Type; switch (o.GetType()) { case Type::kObjectType: { Value::Object value_object; for (auto it = o.MemberBegin(); it != o.MemberEnd(); ++it) { Value entry; ParseJsonAsValue(&entry, it->value); if (entry.Type() != NULL_TYPE) value_object.emplace(GetKey(it), std::move(entry)); } if (value_object.size() > 0) val = Value(std::move(value_object)); } break; case Type::kArrayType: { Value::Array value_array; value_array.reserve(o.Size()); for (auto it = o.Begin(); it != o.End(); ++it) { Value entry; ParseJsonAsValue(&entry, *it); if (entry.Type() != NULL_TYPE) value_array.emplace_back(std::move(entry)); } if (value_array.size() > 0) val = Value(std::move(value_array)); } break; case Type::kStringType: val = Value(std::string(o.GetString())); break; case Type::kFalseType: case Type::kTrueType: val = Value(o.GetBool()); break; case Type::kNumberType: if (!o.IsDouble()) { int i = 0; GetInt(o, i); val = Value(i); } else { double d = 0.0; GetDouble(o, d); val = Value(d); } break; case Type::kNullType: break; // all types are covered, so no `case default` } #else switch (o.type()) { case json::value_t::object: { Value::Object value_object; for (auto it = o.begin(); it != o.end(); it++) { Value entry; ParseJsonAsValue(&entry, it.value()); if (entry.Type() != NULL_TYPE) value_object.emplace(it.key(), std::move(entry)); } if (value_object.size() > 0) val = Value(std::move(value_object)); } break; case json::value_t::array: { Value::Array value_array; value_array.reserve(o.size()); for (auto it = o.begin(); it != o.end(); it++) { Value entry; ParseJsonAsValue(&entry, it.value()); if (entry.Type() != NULL_TYPE) value_array.emplace_back(std::move(entry)); } if (value_array.size() > 0) val = Value(std::move(value_array)); } break; case json::value_t::string: val = Value(o.get<std::string>()); break; case json::value_t::boolean: val = Value(o.get<bool>()); break; case json::value_t::number_integer: case json::value_t::number_unsigned: val = Value(static_cast<int>(o.get<int64_t>())); break; case json::value_t::number_float: val = Value(o.get<double>()); break; case json::value_t::null: case json::value_t::discarded: case json::value_t::binary: // default: break; } #endif if (ret) *ret = std::move(val); return val.Type() != NULL_TYPE; } static bool ParseExtrasProperty(Value *ret, const json &o) { json_const_iterator it; if (!FindMember(o, "extras", it)) { return false; } return ParseJsonAsValue(ret, GetValue(it)); } static bool ParseBooleanProperty(bool *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } auto &value = GetValue(it); bool isBoolean; bool boolValue = false; #ifdef TINYGLTF_USE_RAPIDJSON isBoolean = value.IsBool(); if (isBoolean) { boolValue = value.GetBool(); } #else isBoolean = value.is_boolean(); if (isBoolean) { boolValue = value.get<bool>(); } #endif if (!isBoolean) { if (required) { if (err) { (*err) += "'" + property + "' property is not a bool type.\n"; } } return false; } if (ret) { (*ret) = boolValue; } return true; } static bool ParseIntegerProperty(int *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } int intValue; bool isInt = GetInt(GetValue(it), intValue); if (!isInt) { if (required) { if (err) { (*err) += "'" + property + "' property is not an integer type.\n"; } } return false; } if (ret) { (*ret) = intValue; } return true; } static bool ParseUnsignedProperty(size_t *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } auto &value = GetValue(it); size_t uValue = 0; bool isUValue; #ifdef TINYGLTF_USE_RAPIDJSON isUValue = false; if (value.IsUint()) { uValue = value.GetUint(); isUValue = true; } else if (value.IsUint64()) { uValue = value.GetUint64(); isUValue = true; } #else isUValue = value.is_number_unsigned(); if (isUValue) { uValue = value.get<size_t>(); } #endif if (!isUValue) { if (required) { if (err) { (*err) += "'" + property + "' property is not a positive integer.\n"; } } return false; } if (ret) { (*ret) = uValue; } return true; } static bool ParseNumberProperty(double *ret, std::string *err, const json &o, const std::string &property, const bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } double numberValue; bool isNumber = GetNumber(GetValue(it), numberValue); if (!isNumber) { if (required) { if (err) { (*err) += "'" + property + "' property is not a number type.\n"; } } return false; } if (ret) { (*ret) = numberValue; } return true; } static bool ParseNumberArrayProperty(std::vector<double> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!IsArray(GetValue(it))) { if (required) { if (err) { (*err) += "'" + property + "' property is not an array"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->clear(); auto end = ArrayEnd(GetValue(it)); for (auto i = ArrayBegin(GetValue(it)); i != end; ++i) { double numberValue; const bool isNumber = GetNumber(*i, numberValue); if (!isNumber) { if (required) { if (err) { (*err) += "'" + property + "' property is not a number.\n"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->push_back(numberValue); } return true; } static bool ParseIntegerArrayProperty(std::vector<int> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } if (!IsArray(GetValue(it))) { if (required) { if (err) { (*err) += "'" + property + "' property is not an array"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->clear(); auto end = ArrayEnd(GetValue(it)); for (auto i = ArrayBegin(GetValue(it)); i != end; ++i) { int numberValue; bool isNumber = GetInt(*i, numberValue); if (!isNumber) { if (required) { if (err) { (*err) += "'" + property + "' property is not an integer type.\n"; if (!parent_node.empty()) { (*err) += " in " + parent_node; } (*err) += ".\n"; } } return false; } ret->push_back(numberValue); } return true; } static bool ParseStringProperty( std::string *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent_node = std::string()) { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing"; if (parent_node.empty()) { (*err) += ".\n"; } else { (*err) += " in `" + parent_node + "'.\n"; } } } return false; } std::string strValue; if (!GetString(GetValue(it), strValue)) { if (required) { if (err) { (*err) += "'" + property + "' property is not a string type.\n"; } } return false; } if (ret) { (*ret) = std::move(strValue); } return true; } static bool ParseStringIntegerProperty(std::map<std::string, int> *ret, std::string *err, const json &o, const std::string &property, bool required, const std::string &parent = "") { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { if (!parent.empty()) { (*err) += "'" + property + "' property is missing in " + parent + ".\n"; } else { (*err) += "'" + property + "' property is missing.\n"; } } } return false; } const json &dict = GetValue(it); // Make sure we are dealing with an object / dictionary. if (!IsObject(dict)) { if (required) { if (err) { (*err) += "'" + property + "' property is not an object.\n"; } } return false; } ret->clear(); json_const_iterator dictIt(ObjectBegin(dict)); json_const_iterator dictItEnd(ObjectEnd(dict)); for (; dictIt != dictItEnd; ++dictIt) { int intVal; if (!GetInt(GetValue(dictIt), intVal)) { if (required) { if (err) { (*err) += "'" + property + "' value is not an integer type.\n"; } } return false; } // Insert into the list. (*ret)[GetKey(dictIt)] = intVal; } return true; } static bool ParseJSONProperty(std::map<std::string, double> *ret, std::string *err, const json &o, const std::string &property, bool required) { json_const_iterator it; if (!FindMember(o, property.c_str(), it)) { if (required) { if (err) { (*err) += "'" + property + "' property is missing. \n'"; } } return false; } const json &obj = GetValue(it); if (!IsObject(obj)) { if (required) { if (err) { (*err) += "'" + property + "' property is not a JSON object.\n"; } } return false; } ret->clear(); json_const_iterator it2(ObjectBegin(obj)); json_const_iterator itEnd(ObjectEnd(obj)); for (; it2 != itEnd; ++it2) { double numVal; if (GetNumber(GetValue(it2), numVal)) ret->emplace(std::string(GetKey(it2)), numVal); } return true; } static bool ParseParameterProperty(Parameter *param, std::string *err, const json &o, const std::string &prop, bool required) { // A parameter value can either be a string or an array of either a boolean or // a number. Booleans of any kind aren't supported here. Granted, it // complicates the Parameter structure and breaks it semantically in the sense // that the client probably works off the assumption that if the string is // empty the vector is used, etc. Would a tagged union work? if (ParseStringProperty(&param->string_value, err, o, prop, false)) { // Found string property. return true; } else if (ParseNumberArrayProperty(&param->number_array, err, o, prop, false)) { // Found a number array. return true; } else if (ParseNumberProperty(&param->number_value, err, o, prop, false)) { return param->has_number_value = true; } else if (ParseJSONProperty(&param->json_double_value, err, o, prop, false)) { return true; } else if (ParseBooleanProperty(&param->bool_value, err, o, prop, false)) { return true; } else { if (required) { if (err) { (*err) += "parameter must be a string or number / number array.\n"; } } return false; } } static bool ParseExtensionsProperty(ExtensionMap *ret, std::string *err, const json &o) { (void)err; json_const_iterator it; if (!FindMember(o, "extensions", it)) { return false; } auto &obj = GetValue(it); if (!IsObject(obj)) { return false; } ExtensionMap extensions; json_const_iterator extIt = ObjectBegin(obj); // it.value().begin(); json_const_iterator extEnd = ObjectEnd(obj); for (; extIt != extEnd; ++extIt) { auto &itObj = GetValue(extIt); if (!IsObject(itObj)) continue; std::string key(GetKey(extIt)); if (!ParseJsonAsValue(&extensions[key], itObj)) { if (!key.empty()) { // create empty object so that an extension object is still of type // object extensions[key] = Value{Value::Object{}}; } } } if (ret) { (*ret) = std::move(extensions); } return true; } static bool ParseAsset(Asset *asset, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&asset->version, err, o, "version", true, "Asset"); ParseStringProperty(&asset->generator, err, o, "generator", false, "Asset"); ParseStringProperty(&asset->minVersion, err, o, "minVersion", false, "Asset"); ParseStringProperty(&asset->copyright, err, o, "copyright", false, "Asset"); ParseExtensionsProperty(&asset->extensions, err, o); // Unity exporter version is added as extra here ParseExtrasProperty(&(asset->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { asset->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { asset->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseImage(Image *image, const int image_idx, std::string *err, std::string *warn, const json &o, bool store_original_json_for_extras_and_extensions, const std::string &basedir, FsCallbacks *fs, LoadImageDataFunction *LoadImageData = nullptr, void *load_image_user_data = nullptr) { // A glTF image must either reference a bufferView or an image uri // schema says oneOf [`bufferView`, `uri`] // TODO(syoyo): Check the type of each parameters. json_const_iterator it; bool hasBufferView = FindMember(o, "bufferView", it); bool hasURI = FindMember(o, "uri", it); ParseStringProperty(&image->name, err, o, "name", false); if (hasBufferView && hasURI) { // Should not both defined. if (err) { (*err) += "Only one of `bufferView` or `uri` should be defined, but both are " "defined for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } if (!hasBufferView && !hasURI) { if (err) { (*err) += "Neither required `bufferView` nor `uri` defined for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } ParseExtensionsProperty(&image->extensions, err, o); ParseExtrasProperty(&image->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator eit; if (FindMember(o, "extensions", eit)) { image->extensions_json_string = JsonToString(GetValue(eit)); } } { json_const_iterator eit; if (FindMember(o, "extras", eit)) { image->extras_json_string = JsonToString(GetValue(eit)); } } } if (hasBufferView) { int bufferView = -1; if (!ParseIntegerProperty(&bufferView, err, o, "bufferView", true)) { if (err) { (*err) += "Failed to parse `bufferView` for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\"\n"; } return false; } std::string mime_type; ParseStringProperty(&mime_type, err, o, "mimeType", false); int width = 0; ParseIntegerProperty(&width, err, o, "width", false); int height = 0; ParseIntegerProperty(&height, err, o, "height", false); // Just only save some information here. Loading actual image data from // bufferView is done after this `ParseImage` function. image->bufferView = bufferView; image->mimeType = mime_type; image->width = width; image->height = height; return true; } // Parse URI & Load image data. std::string uri; std::string tmp_err; if (!ParseStringProperty(&uri, &tmp_err, o, "uri", true)) { if (err) { (*err) += "Failed to parse `uri` for image[" + std::to_string(image_idx) + "] name = \"" + image->name + "\".\n"; } return false; } std::vector<unsigned char> img; if (IsDataURI(uri)) { if (!DecodeDataURI(&img, image->mimeType, uri, 0, false)) { if (err) { (*err) += "Failed to decode 'uri' for image[" + std::to_string(image_idx) + "] name = [" + image->name + "]\n"; } return false; } } else { // Assume external file // Keep texture path (for textures that cannot be decoded) image->uri = uri; #ifdef TINYGLTF_NO_EXTERNAL_IMAGE return true; #endif std::string decoded_uri = dlib::urldecode(uri); if (!LoadExternalFile(&img, err, warn, decoded_uri, basedir, /* required */ false, /* required bytes */ 0, /* checksize */ false, fs)) { if (warn) { (*warn) += "Failed to load external 'uri' for image[" + std::to_string(image_idx) + "] name = [" + image->name + "]\n"; } // If the image cannot be loaded, keep uri as image->uri. return true; } if (img.empty()) { if (warn) { (*warn) += "Image data is empty for image[" + std::to_string(image_idx) + "] name = [" + image->name + "] \n"; } return false; } } if (*LoadImageData == nullptr) { if (err) { (*err) += "No LoadImageData callback specified.\n"; } return false; } return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0), static_cast<int>(img.size()), load_image_user_data); } static bool ParseTexture(Texture *texture, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions, const std::string &basedir) { (void)basedir; int sampler = -1; int source = -1; ParseIntegerProperty(&sampler, err, o, "sampler", false); ParseIntegerProperty(&source, err, o, "source", false); texture->sampler = sampler; texture->source = source; ParseExtensionsProperty(&texture->extensions, err, o); ParseExtrasProperty(&texture->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { texture->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { texture->extras_json_string = JsonToString(GetValue(it)); } } } ParseStringProperty(&texture->name, err, o, "name", false); return true; } static bool ParseTextureInfo( TextureInfo *texinfo, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (texinfo == nullptr) { return false; } if (!ParseIntegerProperty(&texinfo->index, err, o, "index", /* required */ true, "TextureInfo")) { return false; } ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false); ParseExtensionsProperty(&texinfo->extensions, err, o); ParseExtrasProperty(&texinfo->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { texinfo->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { texinfo->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseNormalTextureInfo( NormalTextureInfo *texinfo, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (texinfo == nullptr) { return false; } if (!ParseIntegerProperty(&texinfo->index, err, o, "index", /* required */ true, "NormalTextureInfo")) { return false; } ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false); ParseNumberProperty(&texinfo->scale, err, o, "scale", false); ParseExtensionsProperty(&texinfo->extensions, err, o); ParseExtrasProperty(&texinfo->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { texinfo->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { texinfo->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseOcclusionTextureInfo( OcclusionTextureInfo *texinfo, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (texinfo == nullptr) { return false; } if (!ParseIntegerProperty(&texinfo->index, err, o, "index", /* required */ true, "NormalTextureInfo")) { return false; } ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false); ParseNumberProperty(&texinfo->strength, err, o, "strength", false); ParseExtensionsProperty(&texinfo->extensions, err, o); ParseExtrasProperty(&texinfo->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { texinfo->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { texinfo->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseBuffer(Buffer *buffer, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions, FsCallbacks *fs, const std::string &basedir, bool is_binary = false, const unsigned char *bin_data = nullptr, size_t bin_size = 0) { size_t byteLength; if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true, "Buffer")) { return false; } // In glTF 2.0, uri is not mandatory anymore buffer->uri.clear(); ParseStringProperty(&buffer->uri, err, o, "uri", false, "Buffer"); // having an empty uri for a non embedded image should not be valid if (!is_binary && buffer->uri.empty()) { if (err) { (*err) += "'uri' is missing from non binary glTF file buffer.\n"; } } json_const_iterator type; if (FindMember(o, "type", type)) { std::string typeStr; if (GetString(GetValue(type), typeStr)) { if (typeStr.compare("arraybuffer") == 0) { // buffer.type = "arraybuffer"; } } } if (is_binary) { // Still binary glTF accepts external dataURI. if (!buffer->uri.empty()) { // First try embedded data URI. if (IsDataURI(buffer->uri)) { std::string mime_type; if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength, true)) { if (err) { (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n"; } return false; } } else { // External .bin file. std::string decoded_uri = dlib::urldecode(buffer->uri); if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, decoded_uri, basedir, /* required */ true, byteLength, /* checkSize */ true, fs)) { return false; } } } else { // load data from (embedded) binary data if ((bin_size == 0) || (bin_data == nullptr)) { if (err) { (*err) += "Invalid binary data in `Buffer'.\n"; } return false; } if (byteLength > bin_size) { if (err) { std::stringstream ss; ss << "Invalid `byteLength'. Must be equal or less than binary size: " "`byteLength' = " << byteLength << ", binary size = " << bin_size << std::endl; (*err) += ss.str(); } return false; } // Read buffer data buffer->data.resize(static_cast<size_t>(byteLength)); memcpy(&(buffer->data.at(0)), bin_data, static_cast<size_t>(byteLength)); } } else { if (IsDataURI(buffer->uri)) { std::string mime_type; if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength, true)) { if (err) { (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n"; } return false; } } else { // Assume external .bin file. std::string decoded_uri = dlib::urldecode(buffer->uri); if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, decoded_uri, basedir, /* required */ true, byteLength, /* checkSize */ true, fs)) { return false; } } } ParseStringProperty(&buffer->name, err, o, "name", false); ParseExtensionsProperty(&buffer->extensions, err, o); ParseExtrasProperty(&buffer->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { buffer->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { buffer->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseBufferView( BufferView *bufferView, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { int buffer = -1; if (!ParseIntegerProperty(&buffer, err, o, "buffer", true, "BufferView")) { return false; } size_t byteOffset = 0; ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false); size_t byteLength = 1; if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true, "BufferView")) { return false; } size_t byteStride = 0; if (!ParseUnsignedProperty(&byteStride, err, o, "byteStride", false)) { // Spec says: When byteStride of referenced bufferView is not defined, it // means that accessor elements are tightly packed, i.e., effective stride // equals the size of the element. // We cannot determine the actual byteStride until Accessor are parsed, thus // set 0(= tightly packed) here(as done in OpenGL's VertexAttribPoiner) byteStride = 0; } if ((byteStride > 252) || ((byteStride % 4) != 0)) { if (err) { std::stringstream ss; ss << "Invalid `byteStride' value. `byteStride' must be the multiple of " "4 : " << byteStride << std::endl; (*err) += ss.str(); } return false; } int target = 0; ParseIntegerProperty(&target, err, o, "target", false); if ((target == TINYGLTF_TARGET_ARRAY_BUFFER) || (target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) { // OK } else { target = 0; } bufferView->target = target; ParseStringProperty(&bufferView->name, err, o, "name", false); ParseExtensionsProperty(&bufferView->extensions, err, o); ParseExtrasProperty(&bufferView->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { bufferView->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { bufferView->extras_json_string = JsonToString(GetValue(it)); } } } bufferView->buffer = buffer; bufferView->byteOffset = byteOffset; bufferView->byteLength = byteLength; bufferView->byteStride = byteStride; return true; } static bool ParseSparseAccessor(Accessor *accessor, std::string *err, const json &o) { accessor->sparse.isSparse = true; int count = 0; if (!ParseIntegerProperty(&count, err, o, "count", true, "SparseAccessor")) { return false; } json_const_iterator indices_iterator; json_const_iterator values_iterator; if (!FindMember(o, "indices", indices_iterator)) { (*err) = "the sparse object of this accessor doesn't have indices"; return false; } if (!FindMember(o, "values", values_iterator)) { (*err) = "the sparse object ob ths accessor doesn't have values"; return false; } const json &indices_obj = GetValue(indices_iterator); const json &values_obj = GetValue(values_iterator); int indices_buffer_view = 0, indices_byte_offset = 0, component_type = 0; if (!ParseIntegerProperty(&indices_buffer_view, err, indices_obj, "bufferView", true, "SparseAccessor")) { return false; } ParseIntegerProperty(&indices_byte_offset, err, indices_obj, "byteOffset", false); if (!ParseIntegerProperty(&component_type, err, indices_obj, "componentType", true, "SparseAccessor")) { return false; } int values_buffer_view = 0, values_byte_offset = 0; if (!ParseIntegerProperty(&values_buffer_view, err, values_obj, "bufferView", true, "SparseAccessor")) { return false; } ParseIntegerProperty(&values_byte_offset, err, values_obj, "byteOffset", false); accessor->sparse.count = count; accessor->sparse.indices.bufferView = indices_buffer_view; accessor->sparse.indices.byteOffset = indices_byte_offset; accessor->sparse.indices.componentType = component_type; accessor->sparse.values.bufferView = values_buffer_view; accessor->sparse.values.byteOffset = values_byte_offset; return true; } static bool ParseAccessor(Accessor *accessor, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { int bufferView = -1; ParseIntegerProperty(&bufferView, err, o, "bufferView", false, "Accessor"); size_t byteOffset = 0; ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false, "Accessor"); bool normalized = false; ParseBooleanProperty(&normalized, err, o, "normalized", false, "Accessor"); size_t componentType = 0; if (!ParseUnsignedProperty(&componentType, err, o, "componentType", true, "Accessor")) { return false; } size_t count = 0; if (!ParseUnsignedProperty(&count, err, o, "count", true, "Accessor")) { return false; } std::string type; if (!ParseStringProperty(&type, err, o, "type", true, "Accessor")) { return false; } if (type.compare("SCALAR") == 0) { accessor->type = TINYGLTF_TYPE_SCALAR; } else if (type.compare("VEC2") == 0) { accessor->type = TINYGLTF_TYPE_VEC2; } else if (type.compare("VEC3") == 0) { accessor->type = TINYGLTF_TYPE_VEC3; } else if (type.compare("VEC4") == 0) { accessor->type = TINYGLTF_TYPE_VEC4; } else if (type.compare("MAT2") == 0) { accessor->type = TINYGLTF_TYPE_MAT2; } else if (type.compare("MAT3") == 0) { accessor->type = TINYGLTF_TYPE_MAT3; } else if (type.compare("MAT4") == 0) { accessor->type = TINYGLTF_TYPE_MAT4; } else { std::stringstream ss; ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n"; if (err) { (*err) += ss.str(); } return false; } ParseStringProperty(&accessor->name, err, o, "name", false); accessor->minValues.clear(); accessor->maxValues.clear(); ParseNumberArrayProperty(&accessor->minValues, err, o, "min", false, "Accessor"); ParseNumberArrayProperty(&accessor->maxValues, err, o, "max", false, "Accessor"); accessor->count = count; accessor->bufferView = bufferView; accessor->byteOffset = byteOffset; accessor->normalized = normalized; { if (componentType >= TINYGLTF_COMPONENT_TYPE_BYTE && componentType <= TINYGLTF_COMPONENT_TYPE_DOUBLE) { // OK accessor->componentType = int(componentType); } else { std::stringstream ss; ss << "Invalid `componentType` in accessor. Got " << componentType << "\n"; if (err) { (*err) += ss.str(); } return false; } } ParseExtensionsProperty(&(accessor->extensions), err, o); ParseExtrasProperty(&(accessor->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { accessor->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { accessor->extras_json_string = JsonToString(GetValue(it)); } } } // check if accessor has a "sparse" object: json_const_iterator iterator; if (FindMember(o, "sparse", iterator)) { // here this accessor has a "sparse" subobject return ParseSparseAccessor(accessor, err, GetValue(iterator)); } return true; } #ifdef TINYGLTF_ENABLE_DRACO static void DecodeIndexBuffer(draco::Mesh *mesh, size_t componentSize, std::vector<uint8_t> &outBuffer) { if (componentSize == 4) { assert(sizeof(mesh->face(draco::FaceIndex(0))[0]) == componentSize); memcpy(outBuffer.data(), &mesh->face(draco::FaceIndex(0))[0], outBuffer.size()); } else { size_t faceStride = componentSize * 3; for (draco::FaceIndex f(0); f < mesh->num_faces(); ++f) { const draco::Mesh::Face &face = mesh->face(f); if (componentSize == 2) { uint16_t indices[3] = {(uint16_t)face[0].value(), (uint16_t)face[1].value(), (uint16_t)face[2].value()}; memcpy(outBuffer.data() + f.value() * faceStride, &indices[0], faceStride); } else { uint8_t indices[3] = {(uint8_t)face[0].value(), (uint8_t)face[1].value(), (uint8_t)face[2].value()}; memcpy(outBuffer.data() + f.value() * faceStride, &indices[0], faceStride); } } } } template <typename T> static bool GetAttributeForAllPoints(draco::Mesh *mesh, const draco::PointAttribute *pAttribute, std::vector<uint8_t> &outBuffer) { size_t byteOffset = 0; T values[4] = {0, 0, 0, 0}; for (draco::PointIndex i(0); i < mesh->num_points(); ++i) { const draco::AttributeValueIndex val_index = pAttribute->mapped_index(i); if (!pAttribute->ConvertValue<T>(val_index, pAttribute->num_components(), values)) return false; memcpy(outBuffer.data() + byteOffset, &values[0], sizeof(T) * pAttribute->num_components()); byteOffset += sizeof(T) * pAttribute->num_components(); } return true; } static bool GetAttributeForAllPoints(uint32_t componentType, draco::Mesh *mesh, const draco::PointAttribute *pAttribute, std::vector<uint8_t> &outBuffer) { bool decodeResult = false; switch (componentType) { case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE: decodeResult = GetAttributeForAllPoints<uint8_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_BYTE: decodeResult = GetAttributeForAllPoints<int8_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT: decodeResult = GetAttributeForAllPoints<uint16_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_SHORT: decodeResult = GetAttributeForAllPoints<int16_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_INT: decodeResult = GetAttributeForAllPoints<int32_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT: decodeResult = GetAttributeForAllPoints<uint32_t>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_FLOAT: decodeResult = GetAttributeForAllPoints<float>(mesh, pAttribute, outBuffer); break; case TINYGLTF_COMPONENT_TYPE_DOUBLE: decodeResult = GetAttributeForAllPoints<double>(mesh, pAttribute, outBuffer); break; default: return false; } return decodeResult; } static bool ParseDracoExtension(Primitive *primitive, Model *model, std::string *err, const Value &dracoExtensionValue) { (void)err; auto bufferViewValue = dracoExtensionValue.Get("bufferView"); if (!bufferViewValue.IsInt()) return false; auto attributesValue = dracoExtensionValue.Get("attributes"); if (!attributesValue.IsObject()) return false; auto attributesObject = attributesValue.Get<Value::Object>(); int bufferView = bufferViewValue.Get<int>(); BufferView &view = model->bufferViews[bufferView]; Buffer &buffer = model->buffers[view.buffer]; // BufferView has already been decoded if (view.dracoDecoded) return true; view.dracoDecoded = true; const char *bufferViewData = reinterpret_cast<const char *>(buffer.data.data() + view.byteOffset); size_t bufferViewSize = view.byteLength; // decode draco draco::DecoderBuffer decoderBuffer; decoderBuffer.Init(bufferViewData, bufferViewSize); draco::Decoder decoder; auto decodeResult = decoder.DecodeMeshFromBuffer(&decoderBuffer); if (!decodeResult.ok()) { return false; } const std::unique_ptr<draco::Mesh> &mesh = decodeResult.value(); // create new bufferView for indices if (primitive->indices >= 0) { int32_t componentSize = GetComponentSizeInBytes( model->accessors[primitive->indices].componentType); Buffer decodedIndexBuffer; decodedIndexBuffer.data.resize(mesh->num_faces() * 3 * componentSize); DecodeIndexBuffer(mesh.get(), componentSize, decodedIndexBuffer.data); model->buffers.emplace_back(std::move(decodedIndexBuffer)); BufferView decodedIndexBufferView; decodedIndexBufferView.buffer = int(model->buffers.size() - 1); decodedIndexBufferView.byteLength = int(mesh->num_faces() * 3 * componentSize); decodedIndexBufferView.byteOffset = 0; decodedIndexBufferView.byteStride = 0; decodedIndexBufferView.target = TINYGLTF_TARGET_ARRAY_BUFFER; model->bufferViews.emplace_back(std::move(decodedIndexBufferView)); model->accessors[primitive->indices].bufferView = int(model->bufferViews.size() - 1); model->accessors[primitive->indices].count = int(mesh->num_faces() * 3); } for (const auto &attribute : attributesObject) { if (!attribute.second.IsInt()) return false; auto primitiveAttribute = primitive->attributes.find(attribute.first); if (primitiveAttribute == primitive->attributes.end()) return false; int dracoAttributeIndex = attribute.second.Get<int>(); const auto pAttribute = mesh->GetAttributeByUniqueId(dracoAttributeIndex); const auto componentType = model->accessors[primitiveAttribute->second].componentType; // Create a new buffer for this decoded buffer Buffer decodedBuffer; size_t bufferSize = mesh->num_points() * pAttribute->num_components() * GetComponentSizeInBytes(componentType); decodedBuffer.data.resize(bufferSize); if (!GetAttributeForAllPoints(componentType, mesh.get(), pAttribute, decodedBuffer.data)) return false; model->buffers.emplace_back(std::move(decodedBuffer)); BufferView decodedBufferView; decodedBufferView.buffer = int(model->buffers.size() - 1); decodedBufferView.byteLength = bufferSize; decodedBufferView.byteOffset = pAttribute->byte_offset(); decodedBufferView.byteStride = pAttribute->byte_stride(); decodedBufferView.target = primitive->indices >= 0 ? TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER : TINYGLTF_TARGET_ARRAY_BUFFER; model->bufferViews.emplace_back(std::move(decodedBufferView)); model->accessors[primitiveAttribute->second].bufferView = int(model->bufferViews.size() - 1); model->accessors[primitiveAttribute->second].count = int(mesh->num_points()); } return true; } #endif static bool ParsePrimitive(Primitive *primitive, Model *model, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { int material = -1; ParseIntegerProperty(&material, err, o, "material", false); primitive->material = material; int mode = TINYGLTF_MODE_TRIANGLES; ParseIntegerProperty(&mode, err, o, "mode", false); primitive->mode = mode; // Why only triangled were supported ? int indices = -1; ParseIntegerProperty(&indices, err, o, "indices", false); primitive->indices = indices; if (!ParseStringIntegerProperty(&primitive->attributes, err, o, "attributes", true, "Primitive")) { return false; } // Look for morph targets json_const_iterator targetsObject; if (FindMember(o, "targets", targetsObject) && IsArray(GetValue(targetsObject))) { auto targetsObjectEnd = ArrayEnd(GetValue(targetsObject)); for (json_const_array_iterator i = ArrayBegin(GetValue(targetsObject)); i != targetsObjectEnd; ++i) { std::map<std::string, int> targetAttribues; const json &dict = *i; if (IsObject(dict)) { json_const_iterator dictIt(ObjectBegin(dict)); json_const_iterator dictItEnd(ObjectEnd(dict)); for (; dictIt != dictItEnd; ++dictIt) { int iVal; if (GetInt(GetValue(dictIt), iVal)) targetAttribues[GetKey(dictIt)] = iVal; } primitive->targets.emplace_back(std::move(targetAttribues)); } } } ParseExtrasProperty(&(primitive->extras), o); ParseExtensionsProperty(&primitive->extensions, err, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { primitive->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { primitive->extras_json_string = JsonToString(GetValue(it)); } } } #ifdef TINYGLTF_ENABLE_DRACO auto dracoExtension = primitive->extensions.find("KHR_draco_mesh_compression"); if (dracoExtension != primitive->extensions.end()) { ParseDracoExtension(primitive, model, err, dracoExtension->second); } #else (void)model; #endif return true; } static bool ParseMesh(Mesh *mesh, Model *model, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&mesh->name, err, o, "name", false); mesh->primitives.clear(); json_const_iterator primObject; if (FindMember(o, "primitives", primObject) && IsArray(GetValue(primObject))) { json_const_array_iterator primEnd = ArrayEnd(GetValue(primObject)); for (json_const_array_iterator i = ArrayBegin(GetValue(primObject)); i != primEnd; ++i) { Primitive primitive; if (ParsePrimitive(&primitive, model, err, *i, store_original_json_for_extras_and_extensions)) { // Only add the primitive if the parsing succeeds. mesh->primitives.emplace_back(std::move(primitive)); } } } // Should probably check if has targets and if dimensions fit ParseNumberArrayProperty(&mesh->weights, err, o, "weights", false); ParseExtensionsProperty(&mesh->extensions, err, o); ParseExtrasProperty(&(mesh->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { mesh->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { mesh->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseNode(Node *node, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&node->name, err, o, "name", false); int skin = -1; ParseIntegerProperty(&skin, err, o, "skin", false); node->skin = skin; // Matrix and T/R/S are exclusive if (!ParseNumberArrayProperty(&node->matrix, err, o, "matrix", false)) { ParseNumberArrayProperty(&node->rotation, err, o, "rotation", false); ParseNumberArrayProperty(&node->scale, err, o, "scale", false); ParseNumberArrayProperty(&node->translation, err, o, "translation", false); } int camera = -1; ParseIntegerProperty(&camera, err, o, "camera", false); node->camera = camera; int mesh = -1; ParseIntegerProperty(&mesh, err, o, "mesh", false); node->mesh = mesh; node->children.clear(); ParseIntegerArrayProperty(&node->children, err, o, "children", false); ParseNumberArrayProperty(&node->weights, err, o, "weights", false); ParseExtensionsProperty(&node->extensions, err, o); ParseExtrasProperty(&(node->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { node->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { node->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParsePbrMetallicRoughness( PbrMetallicRoughness *pbr, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (pbr == nullptr) { return false; } std::vector<double> baseColorFactor; if (ParseNumberArrayProperty(&baseColorFactor, err, o, "baseColorFactor", /* required */ false)) { if (baseColorFactor.size() != 4) { if (err) { (*err) += "Array length of `baseColorFactor` parameter in " "pbrMetallicRoughness must be 4, but got " + std::to_string(baseColorFactor.size()) + "\n"; } return false; } pbr->baseColorFactor = baseColorFactor; } { json_const_iterator it; if (FindMember(o, "baseColorTexture", it)) { ParseTextureInfo(&pbr->baseColorTexture, err, GetValue(it), store_original_json_for_extras_and_extensions); } } { json_const_iterator it; if (FindMember(o, "metallicRoughnessTexture", it)) { ParseTextureInfo(&pbr->metallicRoughnessTexture, err, GetValue(it), store_original_json_for_extras_and_extensions); } } ParseNumberProperty(&pbr->metallicFactor, err, o, "metallicFactor", false); ParseNumberProperty(&pbr->roughnessFactor, err, o, "roughnessFactor", false); ParseExtensionsProperty(&pbr->extensions, err, o); ParseExtrasProperty(&pbr->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { pbr->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { pbr->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseMaterial(Material *material, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&material->name, err, o, "name", /* required */ false); if (ParseNumberArrayProperty(&material->emissiveFactor, err, o, "emissiveFactor", /* required */ false)) { if (material->emissiveFactor.size() != 3) { if (err) { (*err) += "Array length of `emissiveFactor` parameter in " "material must be 3, but got " + std::to_string(material->emissiveFactor.size()) + "\n"; } return false; } } else { // fill with default values material->emissiveFactor = {0.0, 0.0, 0.0}; } ParseStringProperty(&material->alphaMode, err, o, "alphaMode", /* required */ false); ParseNumberProperty(&material->alphaCutoff, err, o, "alphaCutoff", /* required */ false); ParseBooleanProperty(&material->doubleSided, err, o, "doubleSided", /* required */ false); { json_const_iterator it; if (FindMember(o, "pbrMetallicRoughness", it)) { ParsePbrMetallicRoughness(&material->pbrMetallicRoughness, err, GetValue(it), store_original_json_for_extras_and_extensions); } } { json_const_iterator it; if (FindMember(o, "normalTexture", it)) { ParseNormalTextureInfo(&material->normalTexture, err, GetValue(it), store_original_json_for_extras_and_extensions); } } { json_const_iterator it; if (FindMember(o, "occlusionTexture", it)) { ParseOcclusionTextureInfo(&material->occlusionTexture, err, GetValue(it), store_original_json_for_extras_and_extensions); } } { json_const_iterator it; if (FindMember(o, "emissiveTexture", it)) { ParseTextureInfo(&material->emissiveTexture, err, GetValue(it), store_original_json_for_extras_and_extensions); } } // Old code path. For backward compatibility, we still store material values // as Parameter. This will create duplicated information for // example(pbrMetallicRoughness), but should be neglible in terms of memory // consumption. // TODO(syoyo): Remove in the next major release. material->values.clear(); material->additionalValues.clear(); json_const_iterator it(ObjectBegin(o)); json_const_iterator itEnd(ObjectEnd(o)); for (; it != itEnd; ++it) { std::string key(GetKey(it)); if (key == "pbrMetallicRoughness") { if (IsObject(GetValue(it))) { const json &values_object = GetValue(it); json_const_iterator itVal(ObjectBegin(values_object)); json_const_iterator itValEnd(ObjectEnd(values_object)); for (; itVal != itValEnd; ++itVal) { Parameter param; if (ParseParameterProperty(&param, err, values_object, GetKey(itVal), false)) { material->values.emplace(GetKey(itVal), std::move(param)); } } } } else if (key == "extensions" || key == "extras") { // done later, skip, otherwise poorly parsed contents will be saved in the // parametermap and serialized again later } else { Parameter param; if (ParseParameterProperty(&param, err, o, key, false)) { // names of materials have already been parsed. Putting it in this map // doesn't correctly reflext the glTF specification if (key != "name") material->additionalValues.emplace(std::move(key), std::move(param)); } } } material->extensions.clear(); ParseExtensionsProperty(&material->extensions, err, o); ParseExtrasProperty(&(material->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator eit; if (FindMember(o, "extensions", eit)) { material->extensions_json_string = JsonToString(GetValue(eit)); } } { json_const_iterator eit; if (FindMember(o, "extras", eit)) { material->extras_json_string = JsonToString(GetValue(eit)); } } } return true; } static bool ParseAnimationChannel( AnimationChannel *channel, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { int samplerIndex = -1; int targetIndex = -1; if (!ParseIntegerProperty(&samplerIndex, err, o, "sampler", true, "AnimationChannel")) { if (err) { (*err) += "`sampler` field is missing in animation channels\n"; } return false; } json_const_iterator targetIt; if (FindMember(o, "target", targetIt) && IsObject(GetValue(targetIt))) { const json &target_object = GetValue(targetIt); if (!ParseIntegerProperty(&targetIndex, err, target_object, "node", true)) { if (err) { (*err) += "`node` field is missing in animation.channels.target\n"; } return false; } if (!ParseStringProperty(&channel->target_path, err, target_object, "path", true)) { if (err) { (*err) += "`path` field is missing in animation.channels.target\n"; } return false; } ParseExtensionsProperty(&channel->target_extensions, err, target_object); if (store_original_json_for_extras_and_extensions) { json_const_iterator it; if (FindMember(target_object, "extensions", it)) { channel->target_extensions_json_string = JsonToString(GetValue(it)); } } } channel->sampler = samplerIndex; channel->target_node = targetIndex; ParseExtensionsProperty(&channel->extensions, err, o); ParseExtrasProperty(&(channel->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { channel->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { channel->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseAnimation(Animation *animation, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { { json_const_iterator channelsIt; if (FindMember(o, "channels", channelsIt) && IsArray(GetValue(channelsIt))) { json_const_array_iterator channelEnd = ArrayEnd(GetValue(channelsIt)); for (json_const_array_iterator i = ArrayBegin(GetValue(channelsIt)); i != channelEnd; ++i) { AnimationChannel channel; if (ParseAnimationChannel( &channel, err, *i, store_original_json_for_extras_and_extensions)) { // Only add the channel if the parsing succeeds. animation->channels.emplace_back(std::move(channel)); } } } } { json_const_iterator samplerIt; if (FindMember(o, "samplers", samplerIt) && IsArray(GetValue(samplerIt))) { const json &sampler_array = GetValue(samplerIt); json_const_array_iterator it = ArrayBegin(sampler_array); json_const_array_iterator itEnd = ArrayEnd(sampler_array); for (; it != itEnd; ++it) { const json &s = *it; AnimationSampler sampler; int inputIndex = -1; int outputIndex = -1; if (!ParseIntegerProperty(&inputIndex, err, s, "input", true)) { if (err) { (*err) += "`input` field is missing in animation.sampler\n"; } return false; } ParseStringProperty(&sampler.interpolation, err, s, "interpolation", false); if (!ParseIntegerProperty(&outputIndex, err, s, "output", true)) { if (err) { (*err) += "`output` field is missing in animation.sampler\n"; } return false; } sampler.input = inputIndex; sampler.output = outputIndex; ParseExtensionsProperty(&(sampler.extensions), err, o); ParseExtrasProperty(&(sampler.extras), s); if (store_original_json_for_extras_and_extensions) { { json_const_iterator eit; if (FindMember(o, "extensions", eit)) { sampler.extensions_json_string = JsonToString(GetValue(eit)); } } { json_const_iterator eit; if (FindMember(o, "extras", eit)) { sampler.extras_json_string = JsonToString(GetValue(eit)); } } } animation->samplers.emplace_back(std::move(sampler)); } } } ParseStringProperty(&animation->name, err, o, "name", false); ParseExtensionsProperty(&animation->extensions, err, o); ParseExtrasProperty(&(animation->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { animation->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { animation->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseSampler(Sampler *sampler, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&sampler->name, err, o, "name", false); int minFilter = -1; int magFilter = -1; int wrapS = TINYGLTF_TEXTURE_WRAP_REPEAT; int wrapT = TINYGLTF_TEXTURE_WRAP_REPEAT; //int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT; ParseIntegerProperty(&minFilter, err, o, "minFilter", false); ParseIntegerProperty(&magFilter, err, o, "magFilter", false); ParseIntegerProperty(&wrapS, err, o, "wrapS", false); ParseIntegerProperty(&wrapT, err, o, "wrapT", false); //ParseIntegerProperty(&wrapR, err, o, "wrapR", false); // tinygltf extension // TODO(syoyo): Check the value is alloed one. // (e.g. we allow 9728(NEAREST), but don't allow 9727) sampler->minFilter = minFilter; sampler->magFilter = magFilter; sampler->wrapS = wrapS; sampler->wrapT = wrapT; //sampler->wrapR = wrapR; ParseExtensionsProperty(&(sampler->extensions), err, o); ParseExtrasProperty(&(sampler->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { sampler->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { sampler->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseSkin(Skin *skin, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseStringProperty(&skin->name, err, o, "name", false, "Skin"); std::vector<int> joints; if (!ParseIntegerArrayProperty(&joints, err, o, "joints", false, "Skin")) { return false; } skin->joints = std::move(joints); int skeleton = -1; ParseIntegerProperty(&skeleton, err, o, "skeleton", false, "Skin"); skin->skeleton = skeleton; int invBind = -1; ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin"); skin->inverseBindMatrices = invBind; ParseExtensionsProperty(&(skin->extensions), err, o); ParseExtrasProperty(&(skin->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { skin->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { skin->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParsePerspectiveCamera( PerspectiveCamera *camera, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { double yfov = 0.0; if (!ParseNumberProperty(&yfov, err, o, "yfov", true, "OrthographicCamera")) { return false; } double znear = 0.0; if (!ParseNumberProperty(&znear, err, o, "znear", true, "PerspectiveCamera")) { return false; } double aspectRatio = 0.0; // = invalid ParseNumberProperty(&aspectRatio, err, o, "aspectRatio", false, "PerspectiveCamera"); double zfar = 0.0; // = invalid ParseNumberProperty(&zfar, err, o, "zfar", false, "PerspectiveCamera"); camera->aspectRatio = aspectRatio; camera->zfar = zfar; camera->yfov = yfov; camera->znear = znear; ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { camera->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { camera->extras_json_string = JsonToString(GetValue(it)); } } } // TODO(syoyo): Validate parameter values. return true; } static bool ParseSpotLight(SpotLight *light, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { ParseNumberProperty(&light->innerConeAngle, err, o, "innerConeAngle", false); ParseNumberProperty(&light->outerConeAngle, err, o, "outerConeAngle", false); ParseExtensionsProperty(&light->extensions, err, o); ParseExtrasProperty(&light->extras, o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { light->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { light->extras_json_string = JsonToString(GetValue(it)); } } } // TODO(syoyo): Validate parameter values. return true; } static bool ParseOrthographicCamera( OrthographicCamera *camera, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { double xmag = 0.0; if (!ParseNumberProperty(&xmag, err, o, "xmag", true, "OrthographicCamera")) { return false; } double ymag = 0.0; if (!ParseNumberProperty(&ymag, err, o, "ymag", true, "OrthographicCamera")) { return false; } double zfar = 0.0; if (!ParseNumberProperty(&zfar, err, o, "zfar", true, "OrthographicCamera")) { return false; } double znear = 0.0; if (!ParseNumberProperty(&znear, err, o, "znear", true, "OrthographicCamera")) { return false; } ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { camera->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { camera->extras_json_string = JsonToString(GetValue(it)); } } } camera->xmag = xmag; camera->ymag = ymag; camera->zfar = zfar; camera->znear = znear; // TODO(syoyo): Validate parameter values. return true; } static bool ParseCamera(Camera *camera, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (!ParseStringProperty(&camera->type, err, o, "type", true, "Camera")) { return false; } if (camera->type.compare("orthographic") == 0) { json_const_iterator orthoIt; if (!FindMember(o, "orthographic", orthoIt)) { if (err) { std::stringstream ss; ss << "Orhographic camera description not found." << std::endl; (*err) += ss.str(); } return false; } const json &v = GetValue(orthoIt); if (!IsObject(v)) { if (err) { std::stringstream ss; ss << "\"orthographic\" is not a JSON object." << std::endl; (*err) += ss.str(); } return false; } if (!ParseOrthographicCamera( &camera->orthographic, err, v, store_original_json_for_extras_and_extensions)) { return false; } } else if (camera->type.compare("perspective") == 0) { json_const_iterator perspIt; if (!FindMember(o, "perspective", perspIt)) { if (err) { std::stringstream ss; ss << "Perspective camera description not found." << std::endl; (*err) += ss.str(); } return false; } const json &v = GetValue(perspIt); if (!IsObject(v)) { if (err) { std::stringstream ss; ss << "\"perspective\" is not a JSON object." << std::endl; (*err) += ss.str(); } return false; } if (!ParsePerspectiveCamera( &camera->perspective, err, v, store_original_json_for_extras_and_extensions)) { return false; } } else { if (err) { std::stringstream ss; ss << "Invalid camera type: \"" << camera->type << "\". Must be \"perspective\" or \"orthographic\"" << std::endl; (*err) += ss.str(); } return false; } ParseStringProperty(&camera->name, err, o, "name", false); ParseExtensionsProperty(&camera->extensions, err, o); ParseExtrasProperty(&(camera->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { camera->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { camera->extras_json_string = JsonToString(GetValue(it)); } } } return true; } static bool ParseLight(Light *light, std::string *err, const json &o, bool store_original_json_for_extras_and_extensions) { if (!ParseStringProperty(&light->type, err, o, "type", true)) { return false; } if (light->type == "spot") { json_const_iterator spotIt; if (!FindMember(o, "spot", spotIt)) { if (err) { std::stringstream ss; ss << "Spot light description not found." << std::endl; (*err) += ss.str(); } return false; } const json &v = GetValue(spotIt); if (!IsObject(v)) { if (err) { std::stringstream ss; ss << "\"spot\" is not a JSON object." << std::endl; (*err) += ss.str(); } return false; } if (!ParseSpotLight(&light->spot, err, v, store_original_json_for_extras_and_extensions)) { return false; } } ParseStringProperty(&light->name, err, o, "name", false); ParseNumberArrayProperty(&light->color, err, o, "color", false); ParseNumberProperty(&light->range, err, o, "range", false); ParseNumberProperty(&light->intensity, err, o, "intensity", false); ParseExtensionsProperty(&light->extensions, err, o); ParseExtrasProperty(&(light->extras), o); if (store_original_json_for_extras_and_extensions) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { light->extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { light->extras_json_string = JsonToString(GetValue(it)); } } } return true; } bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn, const char *json_str, unsigned int json_str_length, const std::string &base_dir, unsigned int check_sections) { if (json_str_length < 4) { if (err) { (*err) = "JSON string too short.\n"; } return false; } JsonDocument v; #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || \ defined(_CPPUNWIND)) && \ !defined(TINYGLTF_NOEXCEPTION) try { JsonParse(v, json_str, json_str_length, true); } catch (const std::exception &e) { if (err) { (*err) = e.what(); } return false; } #else { JsonParse(v, json_str, json_str_length); if (!IsObject(v)) { // Assume parsing was failed. if (err) { (*err) = "Failed to parse JSON object\n"; } return false; } } #endif if (!IsObject(v)) { // root is not an object. if (err) { (*err) = "Root element is not a JSON object\n"; } return false; } { bool version_found = false; json_const_iterator it; if (FindMember(v, "asset", it) && IsObject(GetValue(it))) { auto &itObj = GetValue(it); json_const_iterator version_it; std::string versionStr; if (FindMember(itObj, "version", version_it) && GetString(GetValue(version_it), versionStr)) { version_found = true; } } if (version_found) { // OK } else if (check_sections & REQUIRE_VERSION) { if (err) { (*err) += "\"asset\" object not found in .gltf or not an object type\n"; } return false; } } // scene is not mandatory. // FIXME Maybe a better way to handle it than removing the code auto IsArrayMemberPresent = [](const json &_v, const char *name) -> bool { json_const_iterator it; return FindMember(_v, name, it) && IsArray(GetValue(it)); }; { if ((check_sections & REQUIRE_SCENES) && !IsArrayMemberPresent(v, "scenes")) { if (err) { (*err) += "\"scenes\" object not found in .gltf or not an array type\n"; } return false; } } { if ((check_sections & REQUIRE_NODES) && !IsArrayMemberPresent(v, "nodes")) { if (err) { (*err) += "\"nodes\" object not found in .gltf\n"; } return false; } } { if ((check_sections & REQUIRE_ACCESSORS) && !IsArrayMemberPresent(v, "accessors")) { if (err) { (*err) += "\"accessors\" object not found in .gltf\n"; } return false; } } { if ((check_sections & REQUIRE_BUFFERS) && !IsArrayMemberPresent(v, "buffers")) { if (err) { (*err) += "\"buffers\" object not found in .gltf\n"; } return false; } } { if ((check_sections & REQUIRE_BUFFER_VIEWS) && !IsArrayMemberPresent(v, "bufferViews")) { if (err) { (*err) += "\"bufferViews\" object not found in .gltf\n"; } return false; } } model->buffers.clear(); model->bufferViews.clear(); model->accessors.clear(); model->meshes.clear(); model->cameras.clear(); model->nodes.clear(); model->extensionsUsed.clear(); model->extensionsRequired.clear(); model->extensions.clear(); model->defaultScene = -1; // 1. Parse Asset { json_const_iterator it; if (FindMember(v, "asset", it) && IsObject(GetValue(it))) { const json &root = GetValue(it); ParseAsset(&model->asset, err, root, store_original_json_for_extras_and_extensions_); } } #ifdef TINYGLTF_USE_CPP14 auto ForEachInArray = [](const json &_v, const char *member, const auto &cb) -> bool #else // The std::function<> implementation can be less efficient because it will // allocate heap when the size of the captured lambda is above 16 bytes with // clang and gcc, but it does not require C++14. auto ForEachInArray = [](const json &_v, const char *member, const std::function<bool(const json &)> &cb) -> bool #endif { json_const_iterator itm; if (FindMember(_v, member, itm) && IsArray(GetValue(itm))) { const json &root = GetValue(itm); auto it = ArrayBegin(root); auto end = ArrayEnd(root); for (; it != end; ++it) { if (!cb(*it)) return false; } } return true; }; // 2. Parse extensionUsed { ForEachInArray(v, "extensionsUsed", [&](const json &o) { std::string str; GetString(o, str); model->extensionsUsed.emplace_back(std::move(str)); return true; }); } { ForEachInArray(v, "extensionsRequired", [&](const json &o) { std::string str; GetString(o, str); model->extensionsRequired.emplace_back(std::move(str)); return true; }); } // 3. Parse Buffer { bool success = ForEachInArray(v, "buffers", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`buffers' does not contain an JSON object."; } return false; } Buffer buffer; if (!ParseBuffer(&buffer, err, o, store_original_json_for_extras_and_extensions_, &fs, base_dir, is_binary_, bin_data_, bin_size_)) { return false; } model->buffers.emplace_back(std::move(buffer)); return true; }); if (!success) { return false; } } // 4. Parse BufferView { bool success = ForEachInArray(v, "bufferViews", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`bufferViews' does not contain an JSON object."; } return false; } BufferView bufferView; if (!ParseBufferView(&bufferView, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->bufferViews.emplace_back(std::move(bufferView)); return true; }); if (!success) { return false; } } // 5. Parse Accessor { bool success = ForEachInArray(v, "accessors", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`accessors' does not contain an JSON object."; } return false; } Accessor accessor; if (!ParseAccessor(&accessor, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->accessors.emplace_back(std::move(accessor)); return true; }); if (!success) { return false; } } // 6. Parse Mesh { bool success = ForEachInArray(v, "meshes", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`meshes' does not contain an JSON object."; } return false; } Mesh mesh; if (!ParseMesh(&mesh, model, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->meshes.emplace_back(std::move(mesh)); return true; }); if (!success) { return false; } } // Assign missing bufferView target types // - Look for missing Mesh indices // - Look for missing Mesh attributes for (auto &mesh : model->meshes) { for (auto &primitive : mesh.primitives) { if (primitive.indices > -1) // has indices from parsing step, must be Element Array Buffer { if (size_t(primitive.indices) >= model->accessors.size()) { if (err) { (*err) += "primitive indices accessor out of bounds"; } return false; } auto bufferView = model->accessors[size_t(primitive.indices)].bufferView; if (bufferView < 0 || size_t(bufferView) >= model->bufferViews.size()) { if (err) { (*err) += "accessor[" + std::to_string(primitive.indices) + "] invalid bufferView"; } return false; } model->bufferViews[size_t(bufferView)].target = TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER; // we could optionally check if acessors' bufferView type is Scalar, as // it should be } for (auto &attribute : primitive.attributes) { model ->bufferViews[size_t( model->accessors[size_t(attribute.second)].bufferView)] .target = TINYGLTF_TARGET_ARRAY_BUFFER; } for (auto &target : primitive.targets) { for (auto &attribute : target) { auto bufferView = model->accessors[size_t(attribute.second)].bufferView; // bufferView could be null(-1) for sparse morph target if (bufferView >= 0) { model->bufferViews[size_t(bufferView)].target = TINYGLTF_TARGET_ARRAY_BUFFER; } } } } } // 7. Parse Node { bool success = ForEachInArray(v, "nodes", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`nodes' does not contain an JSON object."; } return false; } Node node; if (!ParseNode(&node, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->nodes.emplace_back(std::move(node)); return true; }); if (!success) { return false; } } // 8. Parse scenes. { bool success = ForEachInArray(v, "scenes", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`scenes' does not contain an JSON object."; } return false; } std::vector<int> nodes; ParseIntegerArrayProperty(&nodes, err, o, "nodes", false); Scene scene; scene.nodes = std::move(nodes); ParseStringProperty(&scene.name, err, o, "name", false); ParseExtensionsProperty(&scene.extensions, err, o); ParseExtrasProperty(&scene.extras, o); if (store_original_json_for_extras_and_extensions_) { { json_const_iterator it; if (FindMember(o, "extensions", it)) { scene.extensions_json_string = JsonToString(GetValue(it)); } } { json_const_iterator it; if (FindMember(o, "extras", it)) { scene.extras_json_string = JsonToString(GetValue(it)); } } } model->scenes.emplace_back(std::move(scene)); return true; }); if (!success) { return false; } } // 9. Parse default scenes. { json_const_iterator rootIt; int iVal; if (FindMember(v, "scene", rootIt) && GetInt(GetValue(rootIt), iVal)) { model->defaultScene = iVal; } } // 10. Parse Material { bool success = ForEachInArray(v, "materials", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`materials' does not contain an JSON object."; } return false; } Material material; ParseStringProperty(&material.name, err, o, "name", false); if (!ParseMaterial(&material, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->materials.emplace_back(std::move(material)); return true; }); if (!success) { return false; } } // 11. Parse Image void *load_image_user_data{nullptr}; LoadImageDataOption load_image_option; if (user_image_loader_) { // Use user supplied pointer load_image_user_data = load_image_user_data_; } else { load_image_option.preserve_channels = preserve_image_channels_; load_image_user_data = reinterpret_cast<void *>(&load_image_option); } { int idx = 0; bool success = ForEachInArray(v, "images", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "image[" + std::to_string(idx) + "] is not a JSON object."; } return false; } Image image; if (!ParseImage(&image, idx, err, warn, o, store_original_json_for_extras_and_extensions_, base_dir, &fs, &this->LoadImageData, load_image_user_data)) { return false; } if (image.bufferView != -1) { // Load image from the buffer view. if (size_t(image.bufferView) >= model->bufferViews.size()) { if (err) { std::stringstream ss; ss << "image[" << idx << "] bufferView \"" << image.bufferView << "\" not found in the scene." << std::endl; (*err) += ss.str(); } return false; } const BufferView &bufferView = model->bufferViews[size_t(image.bufferView)]; if (size_t(bufferView.buffer) >= model->buffers.size()) { if (err) { std::stringstream ss; ss << "image[" << idx << "] buffer \"" << bufferView.buffer << "\" not found in the scene." << std::endl; (*err) += ss.str(); } return false; } const Buffer &buffer = model->buffers[size_t(bufferView.buffer)]; if (*LoadImageData == nullptr) { if (err) { (*err) += "No LoadImageData callback specified.\n"; } return false; } bool ret = LoadImageData( &image, idx, err, warn, image.width, image.height, &buffer.data[bufferView.byteOffset], static_cast<int>(bufferView.byteLength), load_image_user_data); if (!ret) { return false; } } model->images.emplace_back(std::move(image)); ++idx; return true; }); if (!success) { return false; } } // 12. Parse Texture { bool success = ForEachInArray(v, "textures", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`textures' does not contain an JSON object."; } return false; } Texture texture; if (!ParseTexture(&texture, err, o, store_original_json_for_extras_and_extensions_, base_dir)) { return false; } model->textures.emplace_back(std::move(texture)); return true; }); if (!success) { return false; } } // 13. Parse Animation { bool success = ForEachInArray(v, "animations", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`animations' does not contain an JSON object."; } return false; } Animation animation; if (!ParseAnimation(&animation, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->animations.emplace_back(std::move(animation)); return true; }); if (!success) { return false; } } // 14. Parse Skin { bool success = ForEachInArray(v, "skins", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`skins' does not contain an JSON object."; } return false; } Skin skin; if (!ParseSkin(&skin, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->skins.emplace_back(std::move(skin)); return true; }); if (!success) { return false; } } // 15. Parse Sampler { bool success = ForEachInArray(v, "samplers", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`samplers' does not contain an JSON object."; } return false; } Sampler sampler; if (!ParseSampler(&sampler, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->samplers.emplace_back(std::move(sampler)); return true; }); if (!success) { return false; } } // 16. Parse Camera { bool success = ForEachInArray(v, "cameras", [&](const json &o) { if (!IsObject(o)) { if (err) { (*err) += "`cameras' does not contain an JSON object."; } return false; } Camera camera; if (!ParseCamera(&camera, err, o, store_original_json_for_extras_and_extensions_)) { return false; } model->cameras.emplace_back(std::move(camera)); return true; }); if (!success) { return false; } } // 17. Parse Extensions ParseExtensionsProperty(&model->extensions, err, v); // 18. Specific extension implementations { json_const_iterator rootIt; if (FindMember(v, "extensions", rootIt) && IsObject(GetValue(rootIt))) { const json &root = GetValue(rootIt); json_const_iterator it(ObjectBegin(root)); json_const_iterator itEnd(ObjectEnd(root)); for (; it != itEnd; ++it) { // parse KHR_lights_punctual extension std::string key(GetKey(it)); if ((key == "KHR_lights_punctual") && IsObject(GetValue(it))) { const json &object = GetValue(it); json_const_iterator itLight; if (FindMember(object, "lights", itLight)) { const json &lights = GetValue(itLight); if (!IsArray(lights)) { continue; } auto arrayIt(ArrayBegin(lights)); auto arrayItEnd(ArrayEnd(lights)); for (; arrayIt != arrayItEnd; ++arrayIt) { Light light; if (!ParseLight(&light, err, *arrayIt, store_original_json_for_extras_and_extensions_)) { return false; } model->lights.emplace_back(std::move(light)); } } } } } } // 19. Parse Extras ParseExtrasProperty(&model->extras, v); if (store_original_json_for_extras_and_extensions_) { model->extras_json_string = JsonToString(v["extras"]); model->extensions_json_string = JsonToString(v["extensions"]); } return true; } bool TinyGLTF::LoadASCIIFromString(Model *model, std::string *err, std::string *warn, const char *str, unsigned int length, const std::string &base_dir, unsigned int check_sections) { is_binary_ = false; bin_data_ = nullptr; bin_size_ = 0; return LoadFromString(model, err, warn, str, length, base_dir, check_sections); } bool TinyGLTF::LoadASCIIFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections) { std::stringstream ss; if (fs.ReadWholeFile == nullptr) { // Programmer error, assert() ? ss << "Failed to read file: " << filename << ": one or more FS callback not set" << std::endl; if (err) { (*err) = ss.str(); } return false; } std::vector<unsigned char> data; std::string fileerr; bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data); if (!fileread) { ss << "Failed to read file: " << filename << ": " << fileerr << std::endl; if (err) { (*err) = ss.str(); } return false; } size_t sz = data.size(); if (sz == 0) { if (err) { (*err) = "Empty file."; } return false; } std::string basedir = GetBaseDir(filename); bool ret = LoadASCIIFromString( model, err, warn, reinterpret_cast<const char *>(&data.at(0)), static_cast<unsigned int>(data.size()), basedir, check_sections); return ret; } bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn, const unsigned char *bytes, unsigned int size, const std::string &base_dir, unsigned int check_sections) { if (size < 20) { if (err) { (*err) = "Too short data size for glTF Binary."; } return false; } if (bytes[0] == 'g' && bytes[1] == 'l' && bytes[2] == 'T' && bytes[3] == 'F') { // ok } else { if (err) { (*err) = "Invalid magic."; } return false; } unsigned int version; // 4 bytes unsigned int length; // 4 bytes unsigned int model_length; // 4 bytes unsigned int model_format; // 4 bytes; // @todo { Endian swap for big endian machine. } memcpy(&version, bytes + 4, 4); swap4(&version); memcpy(&length, bytes + 8, 4); swap4(&length); memcpy(&model_length, bytes + 12, 4); swap4(&model_length); memcpy(&model_format, bytes + 16, 4); swap4(&model_format); // In case the Bin buffer is not present, the size is exactly 20 + size of // JSON contents, // so use "greater than" operator. if ((20 + model_length > size) || (model_length < 1) || (length > size) || (20 + model_length > length) || (model_format != 0x4E4F534A)) { // 0x4E4F534A = JSON format. if (err) { (*err) = "Invalid glTF binary."; } return false; } // Extract JSON string. std::string jsonString(reinterpret_cast<const char *>(&bytes[20]), model_length); is_binary_ = true; bin_data_ = bytes + 20 + model_length + 8; // 4 bytes (buffer_length) + 4 bytes(buffer_format) bin_size_ = length - (20 + model_length); // extract header + JSON scene data. bool ret = LoadFromString(model, err, warn, reinterpret_cast<const char *>(&bytes[20]), model_length, base_dir, check_sections); if (!ret) { return ret; } return true; } bool TinyGLTF::LoadBinaryFromFile(Model *model, std::string *err, std::string *warn, const std::string &filename, unsigned int check_sections) { std::stringstream ss; if (fs.ReadWholeFile == nullptr) { // Programmer error, assert() ? ss << "Failed to read file: " << filename << ": one or more FS callback not set" << std::endl; if (err) { (*err) = ss.str(); } return false; } std::vector<unsigned char> data; std::string fileerr; bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data); if (!fileread) { ss << "Failed to read file: " << filename << ": " << fileerr << std::endl; if (err) { (*err) = ss.str(); } return false; } std::string basedir = GetBaseDir(filename); bool ret = LoadBinaryFromMemory(model, err, warn, &data.at(0), static_cast<unsigned int>(data.size()), basedir, check_sections); return ret; } /////////////////////// // GLTF Serialization /////////////////////// namespace { json JsonFromString(const char *s) { #ifdef TINYGLTF_USE_RAPIDJSON return json(s, GetAllocator()); #else return json(s); #endif } void JsonAssign(json &dest, const json &src) { #ifdef TINYGLTF_USE_RAPIDJSON dest.CopyFrom(src, GetAllocator()); #else dest = src; #endif } void JsonAddMember(json &o, const char *key, json &&value) { #ifdef TINYGLTF_USE_RAPIDJSON if (!o.IsObject()) { o.SetObject(); } o.AddMember(json(key, GetAllocator()), std::move(value), GetAllocator()); #else o[key] = std::move(value); #endif } void JsonPushBack(json &o, json &&value) { #ifdef TINYGLTF_USE_RAPIDJSON o.PushBack(std::move(value), GetAllocator()); #else o.push_back(std::move(value)); #endif } bool JsonIsNull(const json &o) { #ifdef TINYGLTF_USE_RAPIDJSON return o.IsNull(); #else return o.is_null(); #endif } void JsonSetObject(json &o) { #ifdef TINYGLTF_USE_RAPIDJSON o.SetObject(); #else o = o.object({}); #endif } void JsonReserveArray(json &o, size_t s) { #ifdef TINYGLTF_USE_RAPIDJSON o.SetArray(); o.Reserve(static_cast<rapidjson::SizeType>(s), GetAllocator()); #endif (void)(o); (void)(s); } } // namespace // typedef std::pair<std::string, json> json_object_pair; template <typename T> static void SerializeNumberProperty(const std::string &key, T number, json &obj) { // obj.insert( // json_object_pair(key, json(static_cast<double>(number)))); // obj[key] = static_cast<double>(number); JsonAddMember(obj, key.c_str(), json(number)); } #ifdef TINYGLTF_USE_RAPIDJSON template <> void SerializeNumberProperty(const std::string &key, size_t number, json &obj) { JsonAddMember(obj, key.c_str(), json(static_cast<uint64_t>(number))); } #endif template <typename T> static void SerializeNumberArrayProperty(const std::string &key, const std::vector<T> &value, json &obj) { if (value.empty()) return; json ary; JsonReserveArray(ary, value.size()); for (const auto &s : value) { JsonPushBack(ary, json(s)); } JsonAddMember(obj, key.c_str(), std::move(ary)); } static void SerializeStringProperty(const std::string &key, const std::string &value, json &obj) { JsonAddMember(obj, key.c_str(), JsonFromString(value.c_str())); } static void SerializeStringArrayProperty(const std::string &key, const std::vector<std::string> &value, json &obj) { json ary; JsonReserveArray(ary, value.size()); for (auto &s : value) { JsonPushBack(ary, JsonFromString(s.c_str())); } JsonAddMember(obj, key.c_str(), std::move(ary)); } static bool ValueToJson(const Value &value, json *ret) { json obj; #ifdef TINYGLTF_USE_RAPIDJSON switch (value.Type()) { case REAL_TYPE: obj.SetDouble(value.Get<double>()); break; case INT_TYPE: obj.SetInt(value.Get<int>()); break; case BOOL_TYPE: obj.SetBool(value.Get<bool>()); break; case STRING_TYPE: obj.SetString(value.Get<std::string>().c_str(), GetAllocator()); break; case ARRAY_TYPE: { obj.SetArray(); obj.Reserve(static_cast<rapidjson::SizeType>(value.ArrayLen()), GetAllocator()); for (unsigned int i = 0; i < value.ArrayLen(); ++i) { Value elementValue = value.Get(int(i)); json elementJson; if (ValueToJson(value.Get(int(i)), &elementJson)) obj.PushBack(std::move(elementJson), GetAllocator()); } break; } case BINARY_TYPE: // TODO // obj = json(value.Get<std::vector<unsigned char>>()); return false; break; case OBJECT_TYPE: { obj.SetObject(); Value::Object objMap = value.Get<Value::Object>(); for (auto &it : objMap) { json elementJson; if (ValueToJson(it.second, &elementJson)) { obj.AddMember(json(it.first.c_str(), GetAllocator()), std::move(elementJson), GetAllocator()); } } break; } case NULL_TYPE: default: return false; } #else switch (value.Type()) { case REAL_TYPE: obj = json(value.Get<double>()); break; case INT_TYPE: obj = json(value.Get<int>()); break; case BOOL_TYPE: obj = json(value.Get<bool>()); break; case STRING_TYPE: obj = json(value.Get<std::string>()); break; case ARRAY_TYPE: { for (unsigned int i = 0; i < value.ArrayLen(); ++i) { Value elementValue = value.Get(int(i)); json elementJson; if (ValueToJson(value.Get(int(i)), &elementJson)) obj.push_back(elementJson); } break; } case BINARY_TYPE: // TODO // obj = json(value.Get<std::vector<unsigned char>>()); return false; break; case OBJECT_TYPE: { Value::Object objMap = value.Get<Value::Object>(); for (auto &it : objMap) { json elementJson; if (ValueToJson(it.second, &elementJson)) obj[it.first] = elementJson; } break; } case NULL_TYPE: default: return false; } #endif if (ret) *ret = std::move(obj); return true; } static void SerializeValue(const std::string &key, const Value &value, json &obj) { json ret; if (ValueToJson(value, &ret)) { JsonAddMember(obj, key.c_str(), std::move(ret)); } } static void SerializeGltfBufferData(const std::vector<unsigned char> &data, json &o) { std::string header = "data:application/octet-stream;base64,"; if (data.size() > 0) { std::string encodedData = base64_encode(&data[0], static_cast<unsigned int>(data.size())); SerializeStringProperty("uri", header + encodedData, o); } else { // Issue #229 // size 0 is allowd. Just emit mime header. SerializeStringProperty("uri", header, o); } } static bool SerializeGltfBufferData(const std::vector<unsigned char> &data, const std::string &binFilename) { #ifdef _WIN32 #if defined(__GLIBCXX__) // mingw int file_descriptor = _wopen(UTF8ToWchar(binFilename).c_str(), _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY); __gnu_cxx::stdio_filebuf<char> wfile_buf( file_descriptor, std::ios_base::out | std::ios_base::binary); std::ostream output(&wfile_buf); if (!wfile_buf.is_open()) return false; #elif defined(_MSC_VER) std::ofstream output(UTF8ToWchar(binFilename).c_str(), std::ofstream::binary); if (!output.is_open()) return false; #else std::ofstream output(binFilename.c_str(), std::ofstream::binary); if (!output.is_open()) return false; #endif #else std::ofstream output(binFilename.c_str(), std::ofstream::binary); if (!output.is_open()) return false; #endif if (data.size() > 0) { output.write(reinterpret_cast<const char *>(&data[0]), std::streamsize(data.size())); } else { // Issue #229 // size 0 will be still valid buffer data. // write empty file. } return true; } #if 0 // FIXME(syoyo): not used. will be removed in the future release. static void SerializeParameterMap(ParameterMap &param, json &o) { for (ParameterMap::iterator paramIt = param.begin(); paramIt != param.end(); ++paramIt) { if (paramIt->second.number_array.size()) { SerializeNumberArrayProperty<double>(paramIt->first, paramIt->second.number_array, o); } else if (paramIt->second.json_double_value.size()) { json json_double_value; for (std::map<std::string, double>::iterator it = paramIt->second.json_double_value.begin(); it != paramIt->second.json_double_value.end(); ++it) { if (it->first == "index") { json_double_value[it->first] = paramIt->second.TextureIndex(); } else { json_double_value[it->first] = it->second; } } o[paramIt->first] = json_double_value; } else if (!paramIt->second.string_value.empty()) { SerializeStringProperty(paramIt->first, paramIt->second.string_value, o); } else if (paramIt->second.has_number_value) { o[paramIt->first] = paramIt->second.number_value; } else { o[paramIt->first] = paramIt->second.bool_value; } } } #endif static void SerializeExtensionMap(const ExtensionMap &extensions, json &o) { if (!extensions.size()) return; json extMap; for (ExtensionMap::const_iterator extIt = extensions.begin(); extIt != extensions.end(); ++extIt) { // Allow an empty object for extension(#97) json ret; bool isNull = true; if (ValueToJson(extIt->second, &ret)) { isNull = JsonIsNull(ret); JsonAddMember(extMap, extIt->first.c_str(), std::move(ret)); } if (isNull) { if (!(extIt->first.empty())) { // name should not be empty, but for sure // create empty object so that an extension name is still included in // json. json empty; JsonSetObject(empty); JsonAddMember(extMap, extIt->first.c_str(), std::move(empty)); } } } JsonAddMember(o, "extensions", std::move(extMap)); } static void SerializeGltfAccessor(Accessor &accessor, json &o) { if (accessor.bufferView >= 0) SerializeNumberProperty<int>("bufferView", accessor.bufferView, o); if (accessor.byteOffset != 0) SerializeNumberProperty<int>("byteOffset", int(accessor.byteOffset), o); SerializeNumberProperty<int>("componentType", accessor.componentType, o); SerializeNumberProperty<size_t>("count", accessor.count, o); if ((accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) || (accessor.componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE)) { SerializeNumberArrayProperty<double>("min", accessor.minValues, o); SerializeNumberArrayProperty<double>("max", accessor.maxValues, o); } else { // Issue #301. Serialize as integer. // Assume int value is within [-2**31-1, 2**31-1] { std::vector<int> values; std::transform(accessor.minValues.begin(), accessor.minValues.end(), std::back_inserter(values), [](double v) { return static_cast<int>(v); }); SerializeNumberArrayProperty<int>("min", values, o); } { std::vector<int> values; std::transform(accessor.maxValues.begin(), accessor.maxValues.end(), std::back_inserter(values), [](double v) { return static_cast<int>(v); }); SerializeNumberArrayProperty<int>("max", values, o); } } if (accessor.normalized) SerializeValue("normalized", Value(accessor.normalized), o); std::string type; switch (accessor.type) { case TINYGLTF_TYPE_SCALAR: type = "SCALAR"; break; case TINYGLTF_TYPE_VEC2: type = "VEC2"; break; case TINYGLTF_TYPE_VEC3: type = "VEC3"; break; case TINYGLTF_TYPE_VEC4: type = "VEC4"; break; case TINYGLTF_TYPE_MAT2: type = "MAT2"; break; case TINYGLTF_TYPE_MAT3: type = "MAT3"; break; case TINYGLTF_TYPE_MAT4: type = "MAT4"; break; } SerializeStringProperty("type", type, o); if (!accessor.name.empty()) SerializeStringProperty("name", accessor.name, o); if (accessor.extras.Type() != NULL_TYPE) { SerializeValue("extras", accessor.extras, o); } } static void SerializeGltfAnimationChannel(AnimationChannel &channel, json &o) { SerializeNumberProperty("sampler", channel.sampler, o); { json target; SerializeNumberProperty("node", channel.target_node, target); SerializeStringProperty("path", channel.target_path, target); SerializeExtensionMap(channel.target_extensions, target); JsonAddMember(o, "target", std::move(target)); } if (channel.extras.Type() != NULL_TYPE) { SerializeValue("extras", channel.extras, o); } SerializeExtensionMap(channel.extensions, o); } static void SerializeGltfAnimationSampler(AnimationSampler &sampler, json &o) { SerializeNumberProperty("input", sampler.input, o); SerializeNumberProperty("output", sampler.output, o); SerializeStringProperty("interpolation", sampler.interpolation, o); if (sampler.extras.Type() != NULL_TYPE) { SerializeValue("extras", sampler.extras, o); } } static void SerializeGltfAnimation(Animation &animation, json &o) { if (!animation.name.empty()) SerializeStringProperty("name", animation.name, o); { json channels; JsonReserveArray(channels, animation.channels.size()); for (unsigned int i = 0; i < animation.channels.size(); ++i) { json channel; AnimationChannel gltfChannel = animation.channels[i]; SerializeGltfAnimationChannel(gltfChannel, channel); JsonPushBack(channels, std::move(channel)); } JsonAddMember(o, "channels", std::move(channels)); } { json samplers; JsonReserveArray(samplers, animation.samplers.size()); for (unsigned int i = 0; i < animation.samplers.size(); ++i) { json sampler; AnimationSampler gltfSampler = animation.samplers[i]; SerializeGltfAnimationSampler(gltfSampler, sampler); JsonPushBack(samplers, std::move(sampler)); } JsonAddMember(o, "samplers", std::move(samplers)); } if (animation.extras.Type() != NULL_TYPE) { SerializeValue("extras", animation.extras, o); } SerializeExtensionMap(animation.extensions, o); } static void SerializeGltfAsset(Asset &asset, json &o) { if (!asset.generator.empty()) { SerializeStringProperty("generator", asset.generator, o); } if (!asset.copyright.empty()) { SerializeStringProperty("copyright", asset.copyright, o); } if (asset.version.empty()) { // Just in case // `version` must be defined asset.version = "2.0"; } // TODO(syoyo): Do we need to check if `version` is greater or equal to 2.0? SerializeStringProperty("version", asset.version, o); if (asset.extras.Keys().size()) { SerializeValue("extras", asset.extras, o); } SerializeExtensionMap(asset.extensions, o); } static void SerializeGltfBufferBin(Buffer &buffer, json &o, std::vector<unsigned char> &binBuffer) { SerializeNumberProperty("byteLength", buffer.data.size(), o); binBuffer = buffer.data; if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o); if (buffer.extras.Type() != NULL_TYPE) { SerializeValue("extras", buffer.extras, o); } } static void SerializeGltfBuffer(Buffer &buffer, json &o) { SerializeNumberProperty("byteLength", buffer.data.size(), o); SerializeGltfBufferData(buffer.data, o); if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o); if (buffer.extras.Type() != NULL_TYPE) { SerializeValue("extras", buffer.extras, o); } } static bool SerializeGltfBuffer(Buffer &buffer, json &o, const std::string &binFilename, const std::string &binBaseFilename) { if (!SerializeGltfBufferData(buffer.data, binFilename)) return false; SerializeNumberProperty("byteLength", buffer.data.size(), o); SerializeStringProperty("uri", binBaseFilename, o); if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o); if (buffer.extras.Type() != NULL_TYPE) { SerializeValue("extras", buffer.extras, o); } return true; } static void SerializeGltfBufferView(BufferView &bufferView, json &o) { SerializeNumberProperty("buffer", bufferView.buffer, o); SerializeNumberProperty<size_t>("byteLength", bufferView.byteLength, o); // byteStride is optional, minimum allowed is 4 if (bufferView.byteStride >= 4) { SerializeNumberProperty<size_t>("byteStride", bufferView.byteStride, o); } // byteOffset is optional, default is 0 if (bufferView.byteOffset > 0) { SerializeNumberProperty<size_t>("byteOffset", bufferView.byteOffset, o); } // Target is optional, check if it contains a valid value if (bufferView.target == TINYGLTF_TARGET_ARRAY_BUFFER || bufferView.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER) { SerializeNumberProperty("target", bufferView.target, o); } if (bufferView.name.size()) { SerializeStringProperty("name", bufferView.name, o); } if (bufferView.extras.Type() != NULL_TYPE) { SerializeValue("extras", bufferView.extras, o); } } static void SerializeGltfImage(Image &image, json &o) { // if uri empty, the mimeType and bufferview should be set if (image.uri.empty()) { SerializeStringProperty("mimeType", image.mimeType, o); SerializeNumberProperty<int>("bufferView", image.bufferView, o); } else { // TODO(syoyo): dlib::urilencode? SerializeStringProperty("uri", image.uri, o); } if (image.name.size()) { SerializeStringProperty("name", image.name, o); } if (image.extras.Type() != NULL_TYPE) { SerializeValue("extras", image.extras, o); } SerializeExtensionMap(image.extensions, o); } static void SerializeGltfTextureInfo(TextureInfo &texinfo, json &o) { SerializeNumberProperty("index", texinfo.index, o); if (texinfo.texCoord != 0) { SerializeNumberProperty("texCoord", texinfo.texCoord, o); } if (texinfo.extras.Type() != NULL_TYPE) { SerializeValue("extras", texinfo.extras, o); } SerializeExtensionMap(texinfo.extensions, o); } static void SerializeGltfNormalTextureInfo(NormalTextureInfo &texinfo, json &o) { SerializeNumberProperty("index", texinfo.index, o); if (texinfo.texCoord != 0) { SerializeNumberProperty("texCoord", texinfo.texCoord, o); } if (!TINYGLTF_DOUBLE_EQUAL(texinfo.scale, 1.0)) { SerializeNumberProperty("scale", texinfo.scale, o); } if (texinfo.extras.Type() != NULL_TYPE) { SerializeValue("extras", texinfo.extras, o); } SerializeExtensionMap(texinfo.extensions, o); } static void SerializeGltfOcclusionTextureInfo(OcclusionTextureInfo &texinfo, json &o) { SerializeNumberProperty("index", texinfo.index, o); if (texinfo.texCoord != 0) { SerializeNumberProperty("texCoord", texinfo.texCoord, o); } if (!TINYGLTF_DOUBLE_EQUAL(texinfo.strength, 1.0)) { SerializeNumberProperty("strength", texinfo.strength, o); } if (texinfo.extras.Type() != NULL_TYPE) { SerializeValue("extras", texinfo.extras, o); } SerializeExtensionMap(texinfo.extensions, o); } static void SerializeGltfPbrMetallicRoughness(PbrMetallicRoughness &pbr, json &o) { std::vector<double> default_baseColorFactor = {1.0, 1.0, 1.0, 1.0}; if (!Equals(pbr.baseColorFactor, default_baseColorFactor)) { SerializeNumberArrayProperty<double>("baseColorFactor", pbr.baseColorFactor, o); } if (!TINYGLTF_DOUBLE_EQUAL(pbr.metallicFactor, 1.0)) { SerializeNumberProperty("metallicFactor", pbr.metallicFactor, o); } if (!TINYGLTF_DOUBLE_EQUAL(pbr.roughnessFactor, 1.0)) { SerializeNumberProperty("roughnessFactor", pbr.roughnessFactor, o); } if (pbr.baseColorTexture.index > -1) { json texinfo; SerializeGltfTextureInfo(pbr.baseColorTexture, texinfo); JsonAddMember(o, "baseColorTexture", std::move(texinfo)); } if (pbr.metallicRoughnessTexture.index > -1) { json texinfo; SerializeGltfTextureInfo(pbr.metallicRoughnessTexture, texinfo); JsonAddMember(o, "metallicRoughnessTexture", std::move(texinfo)); } SerializeExtensionMap(pbr.extensions, o); if (pbr.extras.Type() != NULL_TYPE) { SerializeValue("extras", pbr.extras, o); } } static void SerializeGltfMaterial(Material &material, json &o) { if (material.name.size()) { SerializeStringProperty("name", material.name, o); } // QUESTION(syoyo): Write material parameters regardless of its default value? if (!TINYGLTF_DOUBLE_EQUAL(material.alphaCutoff, 0.5)) { SerializeNumberProperty("alphaCutoff", material.alphaCutoff, o); } if (material.alphaMode.compare("OPAQUE") != 0) { SerializeStringProperty("alphaMode", material.alphaMode, o); } if (material.doubleSided != false) JsonAddMember(o, "doubleSided", json(material.doubleSided)); if (material.normalTexture.index > -1) { json texinfo; SerializeGltfNormalTextureInfo(material.normalTexture, texinfo); JsonAddMember(o, "normalTexture", std::move(texinfo)); } if (material.occlusionTexture.index > -1) { json texinfo; SerializeGltfOcclusionTextureInfo(material.occlusionTexture, texinfo); JsonAddMember(o, "occlusionTexture", std::move(texinfo)); } if (material.emissiveTexture.index > -1) { json texinfo; SerializeGltfTextureInfo(material.emissiveTexture, texinfo); JsonAddMember(o, "emissiveTexture", std::move(texinfo)); } std::vector<double> default_emissiveFactor = {0.0, 0.0, 0.0}; if (!Equals(material.emissiveFactor, default_emissiveFactor)) { SerializeNumberArrayProperty<double>("emissiveFactor", material.emissiveFactor, o); } { json pbrMetallicRoughness; SerializeGltfPbrMetallicRoughness(material.pbrMetallicRoughness, pbrMetallicRoughness); // Issue 204 // Do not serialize `pbrMetallicRoughness` if pbrMetallicRoughness has all // default values(json is null). Otherwise it will serialize to // `pbrMetallicRoughness : null`, which cannot be read by other glTF // importers(and validators). // if (!JsonIsNull(pbrMetallicRoughness)) { JsonAddMember(o, "pbrMetallicRoughness", std::move(pbrMetallicRoughness)); } } #if 0 // legacy way. just for the record. if (material.values.size()) { json pbrMetallicRoughness; SerializeParameterMap(material.values, pbrMetallicRoughness); JsonAddMember(o, "pbrMetallicRoughness", std::move(pbrMetallicRoughness)); } SerializeParameterMap(material.additionalValues, o); #else #endif SerializeExtensionMap(material.extensions, o); if (material.extras.Type() != NULL_TYPE) { SerializeValue("extras", material.extras, o); } } static void SerializeGltfMesh(Mesh &mesh, json &o) { json primitives; JsonReserveArray(primitives, mesh.primitives.size()); for (unsigned int i = 0; i < mesh.primitives.size(); ++i) { json primitive; const Primitive &gltfPrimitive = mesh.primitives[i]; // don't make a copy { json attributes; for (auto attrIt = gltfPrimitive.attributes.begin(); attrIt != gltfPrimitive.attributes.end(); ++attrIt) { SerializeNumberProperty<int>(attrIt->first, attrIt->second, attributes); } JsonAddMember(primitive, "attributes", std::move(attributes)); } // Indicies is optional if (gltfPrimitive.indices > -1) { SerializeNumberProperty<int>("indices", gltfPrimitive.indices, primitive); } // Material is optional if (gltfPrimitive.material > -1) { SerializeNumberProperty<int>("material", gltfPrimitive.material, primitive); } SerializeNumberProperty<int>("mode", gltfPrimitive.mode, primitive); // Morph targets if (gltfPrimitive.targets.size()) { json targets; JsonReserveArray(targets, gltfPrimitive.targets.size()); for (unsigned int k = 0; k < gltfPrimitive.targets.size(); ++k) { json targetAttributes; std::map<std::string, int> targetData = gltfPrimitive.targets[k]; for (std::map<std::string, int>::iterator attrIt = targetData.begin(); attrIt != targetData.end(); ++attrIt) { SerializeNumberProperty<int>(attrIt->first, attrIt->second, targetAttributes); } JsonPushBack(targets, std::move(targetAttributes)); } JsonAddMember(primitive, "targets", std::move(targets)); } SerializeExtensionMap(gltfPrimitive.extensions, primitive); if (gltfPrimitive.extras.Type() != NULL_TYPE) { SerializeValue("extras", gltfPrimitive.extras, primitive); } JsonPushBack(primitives, std::move(primitive)); } JsonAddMember(o, "primitives", std::move(primitives)); if (mesh.weights.size()) { SerializeNumberArrayProperty<double>("weights", mesh.weights, o); } if (mesh.name.size()) { SerializeStringProperty("name", mesh.name, o); } SerializeExtensionMap(mesh.extensions, o); if (mesh.extras.Type() != NULL_TYPE) { SerializeValue("extras", mesh.extras, o); } } static void SerializeSpotLight(SpotLight &spot, json &o) { SerializeNumberProperty("innerConeAngle", spot.innerConeAngle, o); SerializeNumberProperty("outerConeAngle", spot.outerConeAngle, o); SerializeExtensionMap(spot.extensions, o); if (spot.extras.Type() != NULL_TYPE) { SerializeValue("extras", spot.extras, o); } } static void SerializeGltfLight(Light &light, json &o) { if (!light.name.empty()) SerializeStringProperty("name", light.name, o); SerializeNumberProperty("intensity", light.intensity, o); if (light.range > 0.0) { SerializeNumberProperty("range", light.range, o); } SerializeNumberArrayProperty("color", light.color, o); SerializeStringProperty("type", light.type, o); if (light.type == "spot") { json spot; SerializeSpotLight(light.spot, spot); JsonAddMember(o, "spot", std::move(spot)); } SerializeExtensionMap(light.extensions, o); if (light.extras.Type() != NULL_TYPE) { SerializeValue("extras", light.extras, o); } } static void SerializeGltfNode(Node &node, json &o) { if (node.translation.size() > 0) { SerializeNumberArrayProperty<double>("translation", node.translation, o); } if (node.rotation.size() > 0) { SerializeNumberArrayProperty<double>("rotation", node.rotation, o); } if (node.scale.size() > 0) { SerializeNumberArrayProperty<double>("scale", node.scale, o); } if (node.matrix.size() > 0) { SerializeNumberArrayProperty<double>("matrix", node.matrix, o); } if (node.mesh != -1) { SerializeNumberProperty<int>("mesh", node.mesh, o); } if (node.skin != -1) { SerializeNumberProperty<int>("skin", node.skin, o); } if (node.camera != -1) { SerializeNumberProperty<int>("camera", node.camera, o); } if (node.weights.size() > 0) { SerializeNumberArrayProperty<double>("weights", node.weights, o); } if (node.extras.Type() != NULL_TYPE) { SerializeValue("extras", node.extras, o); } SerializeExtensionMap(node.extensions, o); if (!node.name.empty()) SerializeStringProperty("name", node.name, o); SerializeNumberArrayProperty<int>("children", node.children, o); } static void SerializeGltfSampler(Sampler &sampler, json &o) { if (sampler.magFilter != -1) { SerializeNumberProperty("magFilter", sampler.magFilter, o); } if (sampler.minFilter != -1) { SerializeNumberProperty("minFilter", sampler.minFilter, o); } //SerializeNumberProperty("wrapR", sampler.wrapR, o); SerializeNumberProperty("wrapS", sampler.wrapS, o); SerializeNumberProperty("wrapT", sampler.wrapT, o); if (sampler.extras.Type() != NULL_TYPE) { SerializeValue("extras", sampler.extras, o); } } static void SerializeGltfOrthographicCamera(const OrthographicCamera &camera, json &o) { SerializeNumberProperty("zfar", camera.zfar, o); SerializeNumberProperty("znear", camera.znear, o); SerializeNumberProperty("xmag", camera.xmag, o); SerializeNumberProperty("ymag", camera.ymag, o); if (camera.extras.Type() != NULL_TYPE) { SerializeValue("extras", camera.extras, o); } } static void SerializeGltfPerspectiveCamera(const PerspectiveCamera &camera, json &o) { SerializeNumberProperty("zfar", camera.zfar, o); SerializeNumberProperty("znear", camera.znear, o); if (camera.aspectRatio > 0) { SerializeNumberProperty("aspectRatio", camera.aspectRatio, o); } if (camera.yfov > 0) { SerializeNumberProperty("yfov", camera.yfov, o); } if (camera.extras.Type() != NULL_TYPE) { SerializeValue("extras", camera.extras, o); } } static void SerializeGltfCamera(const Camera &camera, json &o) { SerializeStringProperty("type", camera.type, o); if (!camera.name.empty()) { SerializeStringProperty("name", camera.name, o); } if (camera.type.compare("orthographic") == 0) { json orthographic; SerializeGltfOrthographicCamera(camera.orthographic, orthographic); JsonAddMember(o, "orthographic", std::move(orthographic)); } else if (camera.type.compare("perspective") == 0) { json perspective; SerializeGltfPerspectiveCamera(camera.perspective, perspective); JsonAddMember(o, "perspective", std::move(perspective)); } else { // ??? } if (camera.extras.Type() != NULL_TYPE) { SerializeValue("extras", camera.extras, o); } SerializeExtensionMap(camera.extensions, o); } static void SerializeGltfScene(Scene &scene, json &o) { SerializeNumberArrayProperty<int>("nodes", scene.nodes, o); if (scene.name.size()) { SerializeStringProperty("name", scene.name, o); } if (scene.extras.Type() != NULL_TYPE) { SerializeValue("extras", scene.extras, o); } SerializeExtensionMap(scene.extensions, o); } static void SerializeGltfSkin(Skin &skin, json &o) { // required SerializeNumberArrayProperty<int>("joints", skin.joints, o); if (skin.inverseBindMatrices >= 0) { SerializeNumberProperty("inverseBindMatrices", skin.inverseBindMatrices, o); } if (skin.skeleton >= 0) { SerializeNumberProperty("skeleton", skin.skeleton, o); } if (skin.name.size()) { SerializeStringProperty("name", skin.name, o); } } static void SerializeGltfTexture(Texture &texture, json &o) { if (texture.sampler > -1) { SerializeNumberProperty("sampler", texture.sampler, o); } if (texture.source > -1) { SerializeNumberProperty("source", texture.source, o); } if (texture.name.size()) { SerializeStringProperty("name", texture.name, o); } if (texture.extras.Type() != NULL_TYPE) { SerializeValue("extras", texture.extras, o); } SerializeExtensionMap(texture.extensions, o); } /// /// Serialize all properties except buffers and images. /// static void SerializeGltfModel(Model *model, json &o) { // ACCESSORS if (model->accessors.size()) { json accessors; JsonReserveArray(accessors, model->accessors.size()); for (unsigned int i = 0; i < model->accessors.size(); ++i) { json accessor; SerializeGltfAccessor(model->accessors[i], accessor); JsonPushBack(accessors, std::move(accessor)); } JsonAddMember(o, "accessors", std::move(accessors)); } // ANIMATIONS if (model->animations.size()) { json animations; JsonReserveArray(animations, model->animations.size()); for (unsigned int i = 0; i < model->animations.size(); ++i) { if (model->animations[i].channels.size()) { json animation; SerializeGltfAnimation(model->animations[i], animation); JsonPushBack(animations, std::move(animation)); } } JsonAddMember(o, "animations", std::move(animations)); } // ASSET json asset; SerializeGltfAsset(model->asset, asset); JsonAddMember(o, "asset", std::move(asset)); // BUFFERVIEWS if (model->bufferViews.size()) { json bufferViews; JsonReserveArray(bufferViews, model->bufferViews.size()); for (unsigned int i = 0; i < model->bufferViews.size(); ++i) { json bufferView; SerializeGltfBufferView(model->bufferViews[i], bufferView); JsonPushBack(bufferViews, std::move(bufferView)); } JsonAddMember(o, "bufferViews", std::move(bufferViews)); } // Extensions required if (model->extensionsRequired.size()) { SerializeStringArrayProperty("extensionsRequired", model->extensionsRequired, o); } // MATERIALS if (model->materials.size()) { json materials; JsonReserveArray(materials, model->materials.size()); for (unsigned int i = 0; i < model->materials.size(); ++i) { json material; SerializeGltfMaterial(model->materials[i], material); if (JsonIsNull(material)) { // Issue 294. // `material` does not have any required parameters // so the result may be null(unmodified) when all material parameters // have default value. // // null is not allowed thus we create an empty JSON object. JsonSetObject(material); } JsonPushBack(materials, std::move(material)); } JsonAddMember(o, "materials", std::move(materials)); } // MESHES if (model->meshes.size()) { json meshes; JsonReserveArray(meshes, model->meshes.size()); for (unsigned int i = 0; i < model->meshes.size(); ++i) { json mesh; SerializeGltfMesh(model->meshes[i], mesh); JsonPushBack(meshes, std::move(mesh)); } JsonAddMember(o, "meshes", std::move(meshes)); } // NODES if (model->nodes.size()) { json nodes; JsonReserveArray(nodes, model->nodes.size()); for (unsigned int i = 0; i < model->nodes.size(); ++i) { json node; SerializeGltfNode(model->nodes[i], node); JsonPushBack(nodes, std::move(node)); } JsonAddMember(o, "nodes", std::move(nodes)); } // SCENE if (model->defaultScene > -1) { SerializeNumberProperty<int>("scene", model->defaultScene, o); } // SCENES if (model->scenes.size()) { json scenes; JsonReserveArray(scenes, model->scenes.size()); for (unsigned int i = 0; i < model->scenes.size(); ++i) { json currentScene; SerializeGltfScene(model->scenes[i], currentScene); JsonPushBack(scenes, std::move(currentScene)); } JsonAddMember(o, "scenes", std::move(scenes)); } // SKINS if (model->skins.size()) { json skins; JsonReserveArray(skins, model->skins.size()); for (unsigned int i = 0; i < model->skins.size(); ++i) { json skin; SerializeGltfSkin(model->skins[i], skin); JsonPushBack(skins, std::move(skin)); } JsonAddMember(o, "skins", std::move(skins)); } // TEXTURES if (model->textures.size()) { json textures; JsonReserveArray(textures, model->textures.size()); for (unsigned int i = 0; i < model->textures.size(); ++i) { json texture; SerializeGltfTexture(model->textures[i], texture); JsonPushBack(textures, std::move(texture)); } JsonAddMember(o, "textures", std::move(textures)); } // SAMPLERS if (model->samplers.size()) { json samplers; JsonReserveArray(samplers, model->samplers.size()); for (unsigned int i = 0; i < model->samplers.size(); ++i) { json sampler; SerializeGltfSampler(model->samplers[i], sampler); JsonPushBack(samplers, std::move(sampler)); } JsonAddMember(o, "samplers", std::move(samplers)); } // CAMERAS if (model->cameras.size()) { json cameras; JsonReserveArray(cameras, model->cameras.size()); for (unsigned int i = 0; i < model->cameras.size(); ++i) { json camera; SerializeGltfCamera(model->cameras[i], camera); JsonPushBack(cameras, std::move(camera)); } JsonAddMember(o, "cameras", std::move(cameras)); } // EXTENSIONS SerializeExtensionMap(model->extensions, o); auto extensionsUsed = model->extensionsUsed; // LIGHTS as KHR_lights_punctual if (model->lights.size()) { json lights; JsonReserveArray(lights, model->lights.size()); for (unsigned int i = 0; i < model->lights.size(); ++i) { json light; SerializeGltfLight(model->lights[i], light); JsonPushBack(lights, std::move(light)); } json khr_lights_cmn; JsonAddMember(khr_lights_cmn, "lights", std::move(lights)); json ext_j; { json_const_iterator it; if (FindMember(o, "extensions", it)) { JsonAssign(ext_j, GetValue(it)); } } JsonAddMember(ext_j, "KHR_lights_punctual", std::move(khr_lights_cmn)); JsonAddMember(o, "extensions", std::move(ext_j)); // Also add "KHR_lights_punctual" to `extensionsUsed` { auto has_khr_lights_punctual = std::find_if(extensionsUsed.begin(), extensionsUsed.end(), [](const std::string &s) { return (s.compare("KHR_lights_punctual") == 0); }); if (has_khr_lights_punctual == extensionsUsed.end()) { extensionsUsed.push_back("KHR_lights_punctual"); } } } // Extensions used if (extensionsUsed.size()) { SerializeStringArrayProperty("extensionsUsed", extensionsUsed, o); } // EXTRAS if (model->extras.Type() != NULL_TYPE) { SerializeValue("extras", model->extras, o); } } static bool WriteGltfStream(std::ostream &stream, const std::string &content) { stream << content << std::endl; return true; } static bool WriteGltfFile(const std::string &output, const std::string &content) { #ifdef _WIN32 #if defined(_MSC_VER) std::ofstream gltfFile(UTF8ToWchar(output).c_str()); #elif defined(__GLIBCXX__) int file_descriptor = _wopen(UTF8ToWchar(output).c_str(), _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY); __gnu_cxx::stdio_filebuf<char> wfile_buf( file_descriptor, std::ios_base::out | std::ios_base::binary); std::ostream gltfFile(&wfile_buf); if (!wfile_buf.is_open()) return false; #else std::ofstream gltfFile(output.c_str()); if (!gltfFile.is_open()) return false; #endif #else std::ofstream gltfFile(output.c_str()); if (!gltfFile.is_open()) return false; #endif return WriteGltfStream(gltfFile, content); } static void WriteBinaryGltfStream(std::ostream &stream, const std::string &content, const std::vector<unsigned char> &binBuffer) { const std::string header = "glTF"; const int version = 2; const uint32_t content_size = uint32_t(content.size()); const uint32_t binBuffer_size = uint32_t(binBuffer.size()); // determine number of padding bytes required to ensure 4 byte alignment const uint32_t content_padding_size = content_size % 4 == 0 ? 0 : 4 - content_size % 4; const uint32_t bin_padding_size = binBuffer_size % 4 == 0 ? 0 : 4 - binBuffer_size % 4; // 12 bytes for header, JSON content length, 8 bytes for JSON chunk info. // Chunk data must be located at 4-byte boundary, which may require padding const uint32_t length = 12 + 8 + content_size + content_padding_size + (binBuffer_size ? (8 + binBuffer_size + bin_padding_size) : 0); stream.write(header.c_str(), std::streamsize(header.size())); stream.write(reinterpret_cast<const char *>(&version), sizeof(version)); stream.write(reinterpret_cast<const char *>(&length), sizeof(length)); // JSON chunk info, then JSON data const uint32_t model_length = uint32_t(content.size()) + content_padding_size; const uint32_t model_format = 0x4E4F534A; stream.write(reinterpret_cast<const char *>(&model_length), sizeof(model_length)); stream.write(reinterpret_cast<const char *>(&model_format), sizeof(model_format)); stream.write(content.c_str(), std::streamsize(content.size())); // Chunk must be multiplies of 4, so pad with spaces if (content_padding_size > 0) { const std::string padding = std::string(size_t(content_padding_size), ' '); stream.write(padding.c_str(), std::streamsize(padding.size())); } if (binBuffer.size() > 0) { // BIN chunk info, then BIN data const uint32_t bin_length = uint32_t(binBuffer.size()) + bin_padding_size; const uint32_t bin_format = 0x004e4942; stream.write(reinterpret_cast<const char *>(&bin_length), sizeof(bin_length)); stream.write(reinterpret_cast<const char *>(&bin_format), sizeof(bin_format)); stream.write(reinterpret_cast<const char *>(binBuffer.data()), std::streamsize(binBuffer.size())); // Chunksize must be multiplies of 4, so pad with zeroes if (bin_padding_size > 0) { const std::vector<unsigned char> padding = std::vector<unsigned char>(size_t(bin_padding_size), 0); stream.write(reinterpret_cast<const char *>(padding.data()), std::streamsize(padding.size())); } } } static void WriteBinaryGltfFile(const std::string &output, const std::string &content, const std::vector<unsigned char> &binBuffer) { #ifdef _WIN32 #if defined(_MSC_VER) std::ofstream gltfFile(UTF8ToWchar(output).c_str(), std::ios::binary); #elif defined(__GLIBCXX__) int file_descriptor = _wopen(UTF8ToWchar(output).c_str(), _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY); __gnu_cxx::stdio_filebuf<char> wfile_buf( file_descriptor, std::ios_base::out | std::ios_base::binary); std::ostream gltfFile(&wfile_buf); #else std::ofstream gltfFile(output.c_str(), std::ios::binary); #endif #else std::ofstream gltfFile(output.c_str(), std::ios::binary); #endif WriteBinaryGltfStream(gltfFile, content, binBuffer); } bool TinyGLTF::WriteGltfSceneToStream(Model *model, std::ostream &stream, bool prettyPrint = true, bool writeBinary = false) { JsonDocument output; /// Serialize all properties except buffers and images. SerializeGltfModel(model, output); // BUFFERS std::vector<unsigned char> binBuffer; if (model->buffers.size()) { json buffers; JsonReserveArray(buffers, model->buffers.size()); for (unsigned int i = 0; i < model->buffers.size(); ++i) { json buffer; if (writeBinary && i == 0 && model->buffers[i].uri.empty()) { SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer); } else { SerializeGltfBuffer(model->buffers[i], buffer); } JsonPushBack(buffers, std::move(buffer)); } JsonAddMember(output, "buffers", std::move(buffers)); } // IMAGES if (model->images.size()) { json images; JsonReserveArray(images, model->images.size()); for (unsigned int i = 0; i < model->images.size(); ++i) { json image; std::string dummystring = ""; // UpdateImageObject need baseDir but only uses it if embeddedImages is // enabled, since we won't write separate images when writing to a stream // we UpdateImageObject(model->images[i], dummystring, int(i), false, &this->WriteImageData, this->write_image_user_data_); SerializeGltfImage(model->images[i], image); JsonPushBack(images, std::move(image)); } JsonAddMember(output, "images", std::move(images)); } if (writeBinary) { WriteBinaryGltfStream(stream, JsonToString(output), binBuffer); } else { WriteGltfStream(stream, JsonToString(output, prettyPrint ? 2 : -1)); } return true; } bool TinyGLTF::WriteGltfSceneToFile(Model *model, const std::string &filename, bool embedImages = false, bool embedBuffers = false, bool prettyPrint = true, bool writeBinary = false) { JsonDocument output; std::string defaultBinFilename = GetBaseFilename(filename); std::string defaultBinFileExt = ".bin"; std::string::size_type pos = defaultBinFilename.rfind('.', defaultBinFilename.length()); if (pos != std::string::npos) { defaultBinFilename = defaultBinFilename.substr(0, pos); } std::string baseDir = GetBaseDir(filename); if (baseDir.empty()) { baseDir = "./"; } /// Serialize all properties except buffers and images. SerializeGltfModel(model, output); // BUFFERS std::vector<std::string> usedUris; std::vector<unsigned char> binBuffer; if (model->buffers.size()) { json buffers; JsonReserveArray(buffers, model->buffers.size()); for (unsigned int i = 0; i < model->buffers.size(); ++i) { json buffer; if (writeBinary && i == 0 && model->buffers[i].uri.empty()) { SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer); } else if (embedBuffers) { SerializeGltfBuffer(model->buffers[i], buffer); } else { std::string binSavePath; std::string binUri; if (!model->buffers[i].uri.empty() && !IsDataURI(model->buffers[i].uri)) { binUri = model->buffers[i].uri; } else { binUri = defaultBinFilename + defaultBinFileExt; bool inUse = true; int numUsed = 0; while (inUse) { inUse = false; for (const std::string &usedName : usedUris) { if (binUri.compare(usedName) != 0) continue; inUse = true; binUri = defaultBinFilename + std::to_string(numUsed++) + defaultBinFileExt; break; } } } usedUris.push_back(binUri); binSavePath = JoinPath(baseDir, binUri); if (!SerializeGltfBuffer(model->buffers[i], buffer, binSavePath, binUri)) { return false; } } JsonPushBack(buffers, std::move(buffer)); } JsonAddMember(output, "buffers", std::move(buffers)); } // IMAGES if (model->images.size()) { json images; JsonReserveArray(images, model->images.size()); for (unsigned int i = 0; i < model->images.size(); ++i) { json image; UpdateImageObject(model->images[i], baseDir, int(i), embedImages, &this->WriteImageData, this->write_image_user_data_); SerializeGltfImage(model->images[i], image); JsonPushBack(images, std::move(image)); } JsonAddMember(output, "images", std::move(images)); } if (writeBinary) { WriteBinaryGltfFile(filename, JsonToString(output), binBuffer); } else { WriteGltfFile(filename, JsonToString(output, (prettyPrint ? 2 : -1))); } return true; } } // namespace tinygltf #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TINYGLTF_IMPLEMENTATION
whupdup/frame
real/third_party/tinygltf/tiny_gltf.h
C++
gpl-3.0
236,841
github: wolfpld
whupdup/frame
real/third_party/tracy/.github/FUNDING.yml
YAML
gpl-3.0
16
name: gcc on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-22.04, macOS-latest] steps: - uses: actions/checkout@v2 - name: Install linux libraries if: ${{ matrix.os == 'ubuntu-22.04' }} run: sudo apt-get update && sudo apt-get -y install libglfw3-dev libdbus-1-dev libcapstone-dev libtbb-dev libdebuginfod-dev - name: Install macos libraries if: ${{ matrix.os == 'macOS-latest' }} run: brew install capstone tbb pkg-config glfw - name: Profiler GUI run: make -j -C profiler/build/unix debug release - name: Update utility run: make -j -C update/build/unix debug release - name: Capture utility run: make -j -C capture/build/unix debug release - name: Csvexport utility run: make -j -C csvexport/build/unix debug release - name: Import-chrome utility run: make -j -C import-chrome/build/unix debug release - name: Library run: make -j -C library/unix debug release - name: Test application run: | make -j -C test make -j -C test clean make -j -C test TRACYFLAGS=-DTRACY_ON_DEMAND make -j -C test clean make -j -C test TRACYFLAGS="-DTRACY_DELAYED_INIT -DTRACY_MANUAL_LIFETIME"
whupdup/frame
real/third_party/tracy/.github/workflows/gcc.yml
YAML
gpl-3.0
1,374
name: Manual on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Fix stupidity run: | cp AUTHORS AUTHORS. cp LICENSE LICENSE. - name: Compile LaTeX uses: xu-cheng/latex-action@v2 with: working_directory: manual root_file: tracy.tex - uses: actions/upload-artifact@v2 with: name: manual path: manual/tracy.pdf
whupdup/frame
real/third_party/tracy/.github/workflows/latex.yml
YAML
gpl-3.0
516
name: MSVC on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build-with-vcpkg-integration: runs-on: windows-2022 steps: - uses: actions/checkout@v2 - uses: microsoft/setup-msbuild@v1.0.2 - name: Integrate vcpkg run: vcpkg integrate install - name: Profiler GUI Debug run: msbuild .\profiler\build\win32\Tracy.vcxproj /property:Configuration=Debug /property:Platform=x64 - name: Profiler GUI Release run: msbuild .\profiler\build\win32\Tracy.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Update utility Debug run: msbuild .\update\build\win32\update.vcxproj /property:Configuration=Debug /property:Platform=x64 - name: Update utility Release run: msbuild .\update\build\win32\update.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Capture utility Debug run: msbuild .\capture\build\win32\capture.vcxproj /property:Configuration=Debug /property:Platform=x64 - name: Capture utility Release run: msbuild .\capture\build\win32\capture.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Csvexport utility Debug run: msbuild .\csvexport\build\win32\csvexport.vcxproj /property:Configuration=Debug /property:Platform=x64 - name: Csvexport utility Release run: msbuild .\csvexport\build\win32\csvexport.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Import-chrome utility Debug run: msbuild .\import-chrome\build\win32\import-chrome.vcxproj /property:Configuration=Debug /property:Platform=x64 - name: Import-chrome utility Release run: msbuild .\import-chrome\build\win32\import-chrome.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Library run: msbuild .\library\win32\TracyProfiler.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Package binaries run: | mkdir bin mkdir bin\dev copy profiler\build\win32\x64\Release\Tracy.exe bin copy update\build\win32\x64\Release\update.exe bin copy capture\build\win32\x64\Release\capture.exe bin copy import-chrome\build\win32\x64\Release\import-chrome.exe bin copy csvexport\build\win32\x64\Release\csvexport.exe bin copy library\win32\x64\Release\TracyProfiler.dll bin\dev copy library\win32\x64\Release\TracyProfiler.lib bin\dev 7z a Tracy.7z bin - uses: actions/upload-artifact@v2 with: path: Tracy.7z build-without-vcpkg-integration: runs-on: windows-2022 env: VCPKG_ROOT: '' steps: - uses: actions/checkout@v2 - uses: microsoft/setup-msbuild@v1.0.2 - name: Install vcpkg dependencies run: vcpkg/install_vcpkg_dependencies.bat - name: Profiler GUI Release run: msbuild .\profiler\build\win32\Tracy.vcxproj /property:Configuration=Release /property:Platform=x64 - name: Capture utility Release run: msbuild .\capture\build\win32\capture.vcxproj /property:Configuration=Release /property:Platform=x64
whupdup/frame
real/third_party/tracy/.github/workflows/msvc.yml
YAML
gpl-3.0
3,122
.vs *.opendb *.db *.vcxproj.user x64 Release Debug _build _compiler tools/* *.d *.o *.so *.swp imgui.ini test/tracy_test test/tracy_test.exe */build/unix/*-* manual/t*.aux manual/t*.log manual/t*.out manual/t*.pdf manual/t*.synctex.gz manual/t*.toc manual/t*.bbl manual/t*.blg profiler/build/win32/packages profiler/build/win32/Tracy.aps # include the vcpkg install script but not the files it produces vcpkg/* !vcpkg/install_vcpkg_dependencies.bat /vcpkg_installed .deps/ .dirstamp .vscode/ /_*/** /**/__pycache__/** extra/vswhere.exe extra/tracy-build /.cache compile_commands.json
whupdup/frame
real/third_party/tracy/.gitignore
Git
gpl-3.0
585
Bartosz Taudul <wolf@nereid.pl> Kamil Klimek <kamil.klimek@sharkbits.com> (initial find zone implementation) Bartosz Szreder <zgredder@gmail.com> (view/worker split) Arvid Gerstmann <dev@arvid-g.de> (compatibility fixes) Rokas Kupstys <rokups@zoho.com> (compatibility fixes, initial CI work, MingW support) Till Rathmann <till.rathmann@gmx.de> (DLL support) Sherief Farouk <sherief.personal@gmail.com> (compatibility fixes) Dedmen Miller <dedmen@dedmen.de> (find zone bug fixes, improvements) Michał Cichoń <michcic@gmail.com> (OSX call stack decoding backport) Thales Sabino <thales@codeplay.com> (OpenCL support) Andrew Depke <andrewdepke@gmail.com> (Direct3D 12 support) Simonas Kazlauskas <git@kazlauskas.me> (OSX CI, external bindings) Jakub Žádník <kubouch@gmail.com> (csvexport utility) Andrey Voroshilov <andrew.voroshilov@gmail.com> (multi-DLL fixes) Benoit Jacob <benoitjacob@google.com> (Android improvements) David Farrel <dafarrel@adobe.com> (Direct3D 11 support) Terence Rokop <rokopt@sharpears.net> (Non-reentrant zones) Lukas Berbuer <lukas.berbuer@gmail.com> (CMake integration) Xavier Bouchoux <xavierb@gmail.com> (sample data in find zone) Balazs Kovacsics <kovab93@gmail.com> (Universal Windows Platform)
whupdup/frame
real/third_party/tracy/AUTHORS
none
gpl-3.0
1,511
cmake_minimum_required(VERSION 3.10) project(Tracy LANGUAGES CXX) find_package(Threads REQUIRED) add_library(TracyClient TracyClient.cpp) target_compile_features(TracyClient PUBLIC cxx_std_11) target_include_directories(TracyClient SYSTEM PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}> $<INSTALL_INTERFACE:include>) target_link_libraries( TracyClient PUBLIC Threads::Threads ${CMAKE_DL_LIBS} ) # Public dependency on some libraries required when using Mingw if(WIN32 AND ${CMAKE_CXX_COMPILER_ID} MATCHES "GNU") target_link_libraries(TracyClient PUBLIC ws2_32 dbghelp) endif() if(CMAKE_SYSTEM_NAME MATCHES "FreeBSD") find_library(EXECINFO_LIBRARY NAMES execinfo REQUIRED) target_link_libraries(TracyClient PUBLIC ${EXECINFO_LIBRARY}) endif() add_library(Tracy::TracyClient ALIAS TracyClient) macro(set_option option help value) option(${option} ${help} ${value}) if(${option}) message(STATUS "${option}: ON") target_compile_definitions(TracyClient PUBLIC ${option}) else() message(STATUS "${option}: OFF") endif() endmacro() set_option(TRACY_ENABLE "Enable profiling" ON) set_option(TRACY_ON_DEMAND "On-demand profiling" OFF) set_option(TRACY_CALLSTACK "Enfore callstack collection for tracy regions" OFF) set_option(TRACY_NO_CALLSTACK "Disable all callstack related functionality" OFF) set_option(TRACY_NO_CALLSTACK_INLINES "Disables the inline functions in callstacks" OFF) set_option(TRACY_ONLY_LOCALHOST "Only listen on the localhost interface" OFF) set_option(TRACY_NO_BROADCAST "Disable client discovery by broadcast to local network" OFF) set_option(TRACY_ONLY_IPV4 "Tracy will only accept connections on IPv4 addresses (disable IPv6)" OFF) set_option(TRACY_NO_CODE_TRANSFER "Disable collection of source code" OFF) set_option(TRACY_NO_CONTEXT_SWITCH "Disable capture of context switches" OFF) set_option(TRACY_NO_EXIT "Client executable does not exit until all profile data is sent to server" OFF) set_option(TRACY_NO_SAMPLING "Disable call stack sampling" OFF) set_option(TRACY_NO_VERIFY "Disable zone validation for C API" OFF) set_option(TRACY_NO_VSYNC_CAPTURE "Disable capture of hardware Vsync events" OFF) set_option(TRACY_NO_FRAME_IMAGE "Disable the frame image support and its thread" OFF) set_option(TRACY_NO_SYSTEM_TRACING "Disable systrace sampling" OFF) set_option(TRACY_DELAYED_INIT "Enable delayed initialization of the library (init on first call)" OFF) set_option(TRACY_MANUAL_LIFETIME "Enable the manual lifetime management of the profile" OFF) set_option(TRACY_FIBERS "Enable fibers support" OFF) set_option(TRACY_NO_CRASH_HANDLER "Disable crash handling" OFF) set_option(TRACY_TIMER_FALLBACK "Use lower resolution timers" OFF) if(BUILD_SHARED_LIBS) target_compile_definitions(TracyClient PRIVATE TRACY_EXPORTS) target_compile_definitions(TracyClient PUBLIC TRACY_IMPORTS) endif() include(CMakePackageConfigHelpers) include(GNUInstallDirs) set(includes ${CMAKE_CURRENT_LIST_DIR}/TracyC.h ${CMAKE_CURRENT_LIST_DIR}/Tracy.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyD3D11.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyD3D12.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyLua.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyOpenCL.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyOpenGL.hpp ${CMAKE_CURRENT_LIST_DIR}/TracyVulkan.hpp) set(client_includes ${CMAKE_CURRENT_LIST_DIR}/client/tracy_concurrentqueue.h ${CMAKE_CURRENT_LIST_DIR}/client/tracy_rpmalloc.hpp ${CMAKE_CURRENT_LIST_DIR}/client/tracy_SPSCQueue.h ${CMAKE_CURRENT_LIST_DIR}/client/TracyArmCpuTable.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyCallstack.h ${CMAKE_CURRENT_LIST_DIR}/client/TracyCallstack.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyDebug.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyDxt1.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyFastVector.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyLock.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyProfiler.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyRingBuffer.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyScoped.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyStringHelpers.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracySysTime.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracySysTrace.hpp ${CMAKE_CURRENT_LIST_DIR}/client/TracyThread.hpp) set(common_includes ${CMAKE_CURRENT_LIST_DIR}/common/tracy_lz4.hpp ${CMAKE_CURRENT_LIST_DIR}/common/tracy_lz4hc.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyAlign.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyAlign.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyAlloc.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyApi.h ${CMAKE_CURRENT_LIST_DIR}/common/TracyColor.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyForceInline.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyMutex.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyProtocol.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyQueue.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracySocket.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyStackFrames.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracySystem.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyUwp.hpp ${CMAKE_CURRENT_LIST_DIR}/common/TracyYield.hpp) install(TARGETS TracyClient EXPORT TracyConfig RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(FILES ${includes} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(FILES ${client_includes} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/client) install(FILES ${common_includes} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/common) install(EXPORT TracyConfig NAMESPACE Tracy:: FILE TracyConfig.cmake DESTINATION share/Tracy)
whupdup/frame
real/third_party/tracy/CMakeLists.txt
Text
gpl-3.0
5,754
Note: There is no guarantee that version mismatched client and server will be able to talk with each other. Network protocol breakages won't be listed here. v0.8.2 (2022-06-28) ------------------- - Added support for debuginfod debug information services. Note that since this depends on proper system configuration, vendors providing the debug information, and network retrieval, it is disabled by default. To enable, compile the profiled application with the TRACY_DEBUGINFOD define and link with libdebuginfod. - When Tracy server-side utilities are build with MSVC, the required libraries will be now automatically retrieved and built with vcpkg. - Added microarchitecture data for: Bonnell, Airmont, Goldmont, Goldmont Plus, Tremont. - Recognize additional CPUIDs of Zen 3, Alder Lake, Ice Lake microarchitectures. - Assembly line width will be now extended, if needed. Previously the line width was calculated for the initial layout and changing amount of displayed data (especially listing the read/written registers) didn't affect this, which may have made some lines partially unreadable. - Added ability to filter call stacks in memory tab by inactive allocations. Filtering by inactive allocations helps to pinpoint wasteful allocations in the program. - Plot graph will no longer display min/max values interpolated for animation, but rather true values. - The CPU topology tree structure was replaced by a CPU schematic showing the same thing in a more concise way. v0.8.1 (2022-04-21) ------------------- - Support for pre-0.7 traces has been dropped. - Update utility can now scan for source files missing in the trace cache, if the '-c' parameter is given. Found files will be added to the cache. - Added high-priority queue for fast queries to bypass slow symbol queries. - Fixed Android documentation to show how to enable context switch tracing. - Workaround MSVC 2015 stupidity which prevented compilation as C++11. - Added support for showing branch cost data for CPUs that don't report branch retirement events (but do report branch misses). - The right-click context menu available for jump arrows in the symbol view window will now additionally display jump context, i.e. jump sources and jump target source code fragments. - Added freedesktop.org compliant desktop entry and MIME type definition. - The call stack column in list of messages will now be only displayed when at least one message on the list has call stack data. - File dialogs on Unix will be now native to the desktop environment you are using. Note that this relies on xdg-desktop-portal and dbus. v0.8.0 (2022-03-28) ------------------- - Support for Cygwin has been dropped. It was not working for a very long time and nobody had complained about it. - Mingw is deprecated due to lack of interest. - Added TRACY_NO_CALLSTACK_INLINES macro to disable inline functions resolution in call stacks on Windows. - Improved function matching algorithm in compare traces view. - Added CMake integration. - Reworked rpmalloc initialization. - Fixed display of messages with newlines on messages list. - Excluded some uninteresting wrapper functions from call stacks (for example SIMD pass-through intrinsics to the compiler built-ins). - Adjusted coloring of instruction hotness in symbol view. - Properly handle rare cases when sampling on Linux is momentary not able to resolve time stamps. - Added Rocket Lake microarchitectural data. - Updated CPU identifier lists. - Implemented GPU timer overflow handling heuristics. - Assembly instructions are now assigned to inline symbols. - You can not only see the assembly source file and line, but also the originating function. - If symbol view is restricted to a single inline function, all assembly instructions not in this context will be dimmed out. - Likewise, the navigation in assembly code will be limited just to the inline context, if a single function is selected. - Kernel call stacks will be now properly captured and displayed in the profiler. Kernel functions are marked with the red color. - The CPU hardware performance counters can be now sampled on Linux. - Three inferred statistics are displayed for lines in both source and assembly code in the symbol view window: - Instructions executed per cycle. - Branch miss rate. - Cache miss rate. - Instruction cost estimation method is no longer tied to software call stack sampling. - The image name filter entry field is now providing a list of available images. - Reentrant function calls may be now excluded from calculations in the statistics view. - Crash handler is now properly removed during profiler destruction. - Repeatedly right-clicking on the same source line in the symbol view window will now cycle through assembly blocks associated with this source line. - Vulkan headers must be now explicitly included before including TracyVulkan.hpp. - The capture utility may now limit capture time to a specified number of seconds. - Fixed message thread assignment in the import-chrome utility. - Sampling data can be now also found in the find zone menu. - Instrumentation failures may now display their context, e.g. the zone text that was to be set. - A warning is now displayed when sampling data is out-of-order. - Average value for plots can be now viewed. - Moved symbol resolution to a separate thread. Profiling will no longer be stuck when there is a large number of symbols to resolve. This not only improves user experience, but also prevents buildup of data (and memory consumption) on the client side. - Android device name will be now reported. - Added support for capturing fibers. - Fibers require additional processing, which has to be enabled by adding the TRACY_FIBERS define on the client side. - Client code requires additional instrumentation using the new macros TracyFiberEnter and TracyFiberLeave (or the corresponding C API variants). - Fibers are represented in traces as separate threads, and are distinguished by green color. Faux context switch regions are used to indicate when a fiber is being run by the worker thread. - Continuous frame marks no longer need to be issued from a single thread. - Context switch call stacks are now captured on Windows and Linux. - Hovering the context switch wait region will now display wait stack, which may provide additional insight into why the switch happened. - Wait stacks inspection can be performed in a new view. - Stacks can be limited to certain threads and to a selected time range. - Stacks are presented either as a sorted list, or as a bottom-up and top-down trees. - Entry call stacks can be now also viewed as a bottom-up and top-down trees. - Updated project build files to MSVC 2022. - Call stack tooltips now also show the executable image name. - Playback frames can be now changed by interacting with the frame image slider using the mouse wheel. - Signal used to handle crashes on Linux can be now redefined. - Various DPI scaling improvements. - User interface can be now scaled in run time. - Symbol code retrieval now also supports kernel on Windows. - Added low-level C API interface for GPU zones. - Symbol child calls can be now listed. - Replaced "restrict time" in memory window with a proper time range limit. - Added Alder Lake microarchitectural data. - Added GPU zone statistics. - Universal Windows Platform support. - All call stack related functionality can be now disabled with the TRACY_NO_CALLSTACK macro. - Added ability to add full-view annotations from the annotations list window. v0.7.8 (2021-05-19) ------------------- - Updated Zen 3 and added Tiger Lake microarchitectural data. - Manually disconnecting from the server will no longer display erroneous warning message. - Added ability to display sample time spent in child function calls. - Fixed issue which may have prevented sampling on ARM64. - Added TRACY_NO_FRAME_IMAGE macro to disable frame image compression thread. - Ctrl and shift keys will now modify mouse wheel zoom speed. - Improved user experience in the symbol view window. - Added support for Direct3D 11 instrumentation. - Vulkan contexts can be now calibrated on Linux. - Support loading zstd-compressed chrome traces. - Chrome traces with multiple PID entries (and possibly conflicting TIDs) can be now imported. - Added support for custom source location tag ("loc") in chrome traces. - Sampling frequency can be now controlled using TRACY_SAMPLING_HZ macro. - Trace compression can be now selected when saving a trace. - If a trace cannot be saved, a failure dialog will be displayed. - Run-time memory usage of frame images can be reduced by calculating a compression dictionary. This can be only performed when a trace is saved or through the update utility. v0.7.7 (2021-04-01) ------------------- - Linux crash handler will now also catch SIGABRT. - Fixed invalid name assignment to source files discovered client-side. - Added ability to check if a zone is active (which may be used to avoid preparing zone text, etc., as it wouldn't be used anyway). - Improved sorting behavior of internal vectors. - Some data will now be always properly displayed during live capture. This was not particularly visible before, as it mainly concerns edge cases. - Sorting is performed only as needed. - In case of plots the performance during live capture may be decreased, as these were sorted with at least 0.25 second intervals before. Now the sorting is performed every frame. - Some other data, which previously was not sorted, is sorted now. - In headless capture mode sorting will be only performed when the trace is saved to disk. - Fixed some typos in macros. - Fixed handling of non-ANSI file names on Windows. You can now name your traces 'ęśąćż.tracy' and it should work as intended. This is supported on Windows 10 release 1903 and newer. - Fixed sending GPU context name in on-demand mode. - Fixed color channel order in ZoneColor() macro. - Handle failure state when a memory pointer allocation is reported twice, without an intermediate free. - Renamed "call stack parents" to "entry call stacks". - Display number of entry call stacks in assembly line sample count tooltip. - Added tooltips with preview of source code in various places in the UI. v0.7.6 (2021-02-06) ------------------- - Various fixes in build scripts. - Fixed a faulty rpmalloc initialization path when the first thing the thread did was sending a message with call stack. - Added fallback timer define for various virtualized environments, which may not be able to access the hardware timer registers. This will result in usage of timer provided by the standard library, with reduced resolution. - Further OpenCL improvements. - Updated libbacktrace. - Adds Mach-O 64-bit FAT support. - Fixes memory corruption when processing Mach-O data. - Fixes missing matching entries during binary search. - Adds support for MiniDebugInfo. - Adds fallback to ELF symbol table if no debug info is available. - Various other fixes. - Store build time of profiled program in captures. - GPU contexts can be now named. - Implemented client -> server source code transfer. v0.7.5 (2021-01-23) ------------------- - More robust handling of system tracing on Android. - Added warning dialog when the connection is lost before all needed data can be retrieved. - Fixed handling of NaN plot entries (by skipping them). - Dynamic zone colors are now supported through the ZoneColor() macro. - Fixed Arm machine code printout to match the one printed by objdump. - Fixed client memory corruption when using colored messages. - Switched to the next-gen ImGui table UI. - Table columns can have their order rearranged, can be hidden, can be sorted both in ascending and descending order (where appropriate). - Table columns state is now preserved between runs. - Various fixes related to restricting listening to localhost. - Improved compatibility of ETW tracing with non-MSVC compilers. - Fixed Vulkan call stack transfer. - Added support for transient GPU zones (OpenGL, Vulkan, Direct3D 12). - OpenCL fixes for assert-less builds and non-active zones. - Added support for thread names and title bar description in traces imported from chrome tracing format. v0.7.4 (2020-11-15) ------------------- - Added support for user-provided locks to keep dbghelp calls thread-safe. - Call stacks can be now copied to clipboard. - Allow more control over which automated captures are performed. - Added textual descriptions for some assembly instructions. - Profiler memory usage is now also displayed as a percentage of available physical memory. - Microarchitecture mismatch is now clearly displayed in the source view window. - Added Zen 3 and Cascade Lake microarchitectural data. - Ghost zones are now supporting all zone coloring modes and namespace shortening. - Extend C API to support memory pools. - Frame rate targets can be now visually represented on the timeline view. v0.7.3 (2020-10-06) ------------------- - Properly support DPI scaling on Linux (requires GLFW 3.3). - Added early checks for output file validity in the capture utility. - Improvements to presence broadcast handling. - Custom zone colors can be optionally ignored. - Added support for tracking multiple memory pools. - Memory free failure dialog can now show call stack pointing to the failure location. - Added support for Wayland on Linux. - If during the first 5 seconds of the trace there are no frames being reported, the profiler will switch to following last 5 seconds of the trace, instead of displaying three last frames. v0.7.2 (2020-09-14) ------------------- - Note: the bitbucket repository is obsolete and will soon stop receiving updates. Migrate to https://github.com/wolfpld/tracy, if you haven't already. - The "waiting for connection" dialog no longer has "cancel" button. To abort connection attempt just use the "close window" button. - Added update notification. - The most recent traced events can be now viewed regardless of timeline zoom level. - Fixed going-to-line in source view (again). - Crash handling on client is now not performed, if there is no active connection. - Added ability to listen only on IPv4 interfaces. v0.7.1 (2020-08-24) ------------------- - Dropped support for pre-v0.6 traces. - Fixed regression on non-AVX2 CPUs. - Fixed incorrect calculation of some ghost zones. - Added list of cached source files. - Added import of plot data. - Secure versions of alloc/free macros. - Automated tracing of vertical synchronization on Windows. - Fixed attachment of postponed frame images. - Source location data can be now copied to clipboard from zone info window. - Zones in find zones menu can be now grouped by zone name. - Vulkan and D3D12 GPU contexts can be now calibrated. - Added CSV export utility. - "Go to frame" popup no longer has a dedicated button. To show it, click on the frame counter. - Added macro for checking if profiler is connected. - Implemented optional data removal from traces in the update utility. - Allow manual management of profiler lifetime. - Adjusted priority of ETW threads to time critical. - Annotations can be now freely adjusted on the timeline. - Limiting time range for find zone functionality has been significantly improved. - Added time range limits for statistics and symbol view. - Implemented call stack sampling on Linux (including Android). - Exact time from start of profiling session can be now viewed by hovering the mouse over the time scale. - Code transfer can be now compiled-out. - Added support for zone markup in unloadable modules. - Added image name filter to sampling statistics results window. v0.7 (2020-06-11) ----------------- This is the last release which will be able to load pre-v0.6 traces. Use the update utility to convert your old traces now! - chrome:tracing importer now imports zone metadata from "args" key. - Added display of statistical mode to find zone menu. - Automatic stack sampling is now available on windows. - Properly handle tracing on long-running systems. - Message list entries can now show associated frame image. - Call stack window will now display module names. - Symbol location in call stack window may now also display symbol address. - Statistics menu can now be used to display call stack sampling data or list available symbols. - All call paths leading to the sampled instruction in a call stack can be now displayed. - Frame image compression ratio (lossless in-memory compression, not taking into account DXT compression) is displayed in playback window. - Allow reconnection straight from the discard data dialog. - Added ability to set custom names for locks. - Improved handling of network ports. - Added time percentage display to instrumentation statistics. - Display of ghost zones (generated from automated call stack sampling). - Notify when empty labels display is enabled. - Small fragments of executable code will be now sent from client to server. - Added notification about query backlog. - Fixed performance problem with query backlog. - Display number of in-flight queries, in addition to query backlog. - Improved failure reports. - The capture utility will connect to localhost by default. - Added optional support for QPC timer on windows. - Complete rewrite of source file viewer. It is now 100% reliable when going to a source location. - Symbol source view was added. - Extension of source file viewer. - Can display source file, assembly view, or both at the same time. - May include display of statistical profiling data. - Ability to switch between source files which were used to build the symbol. - Ability to switch between inlined functions which are incorporated into the symbol. - Graphical representation of control flow in program. - Display of micro-architectural data for each assembly instruction. - Tracking register dependencies between assembly instructions. - Disassembly may be saved to a file, in order to be processed by external tools. - If the default listening port is occupied, profiler will now try listening on other ports. - Added possibility to perform source file names substitution. - Profiler windows can be now docked. - CPU usage tooltip now displays a list of running threads. - Added possibility to filter discovered clients list. - Source files are now cached during capture. - Profiler will now display a popup when application crashes. - Added ability to send simple integral values as extra payload for zones. - Per-frame zone times on the frames plot can now display self time. - Ability to bind only on localhost interface. - OpenCL profiling. - Direct3D 12 profiling. v0.6.3 (2020-02-13) ------------------- - Fixed performance issues with loading saved traces on Ryzen CPUs. - Profiler window contents are now properly updated during window resize. - Improved tid to pid mapping on windows. - Zero length and unfinished zones are no longer taken into account for statistics. - Build files for shared library are now available (experimental). - GPU zones now also have "active" parameter. - Further reduction of memory usage and on-disk trace size. - Replaced ska::flat_hash_map with robin-hood-hashing. - Speed-up rendering of long lists of items. - Exact event time is displayed in some places in the UI. - Memory allocation lists can now be sorted. - Added display of trace file compression ratio. - Optional Zstd compression of trace files. - Frame images are now internally compressed using Zstd (instead of LZ4). - Fix display of continuous frame set tooltips. v0.6.2 (2019-12-30) ------------------- - Improved call stack decoding on OSX. - Collection of CPU topology data. - C API now supports allocated source locations. - Added chrome:tracing importer. - Allow merging of ZoneText() strings. - Time distribution can now show both exclusive and inclusive times. - Display proper value of selection time in find zone menu. - Implemented limiting find zone search to a specified time range. - Highlight hovered zone from find zone menu zone list on the histogram. - Allow copying user data directory location to the clipboard. v0.6.1 (2019-11-28) ------------------- - Dropped support for pre-v0.5 traces. - Improve BSD support. - GPU zone CPU thread highlight will now highlight whole thread, not only the thread name. - Added CPU thread highlight for CPU data items. - Client parameters may be now set from the server. - Minor UI fixes. v0.6 (2019-11-17) ----------------- This is the last release which will be able to load pre-v0.5 traces. Use the update utility to convert your old traces now! - Dropped support for pre-v0.4 traces. - Major memory usage decrease. - Significant network bandwidth decrease. - Implemented context switch capture on selected platforms. - Zone timings in various UI places can now take into account only the time when the thread was executing. - Zone information window can now display regions in which thread was suspended by the operating system. - CPUs on which the zone was running are enumerated. - Thread activity regions can be graphed on the timeline. - API breakage: SetThreadName() now only works on current thread. - Fixed thread name retrieval after thread is destroyed. - Added number of CPU cores to host info. - Limited number of possible source locations to 64K. - Limited supported capture length to 1.6 days. - CPU cores are now displayed on the timeline. - Thread execution workload is displayed, including threads from external programs. - Thread migrations across CPU cores can be graphed. - System-wide workload distribution is now plotted on the timeline. - Added "CPU data" window showing programs competing for CPU during the capture. - Switched to using native thread identifiers (relatively small numbers), as opposed to pthreads identifiers, which in reality were pointers. - Improved thread name discovery if context switch capture is enabled. - Per-trace state is now preserved between profiling sessions: - Timeline view position. - Item categories draw/hide settings. - Timeline zones will be highlighted using a different color, when a matching time range is selected on histogram. - Per-frame zone times are now displayed on the frames plot when a zone is selected in the find zone menu. - Zone color is now displayed in zone information window. - Zone colors can now be determined basing on depth and thread or source location. - Thread colors are displayed across the profiler application. - Frame times can be now compared. - Expose more lock handling functionality. - Network port can be now specified by the user. - Proper handling of multithreaded Vulkan code. - Added extreme compression level in update utility. - Added time distribution data in the zone information window. - Trace file name is now displayed in trace information window. - Annotations can be now added to the timeline. - Server now performs network data retrieval and decompression on a dedicated thread. - Added examples of Tracy integration. - Allow grouping of zones in the find zone menu by zone parent or with no grouping. - Zone list in the statistics window can be now filtered. - Implemented configuration of plots. - Messages can now collect call stacks. v0.5 (2019-08-10) ----------------- This is the last release which will be able to load pre-v0.4 traces. Use the update utility to convert your old traces now! - Major decrease of trace dump file size. - Major optimizations across the board. - Vcpkg is now used for library management on Windows. - Display dump file size change in the update utility. - Added notification area. - Display trace loading time. - Display background processing tasks after trace is loaded. - Display trace save notification. - Show crash icon, if there was a crash. - Added C API. - Profiling session may now gracefully terminate, due to incorrect instrumentation. A popup with termination reason will be displayed. - Call stack improvements. - Call stack frames now have a proper source file and file line information on Linux. - Single call stack frame may now have multiple entries, representing inlined function calls. - Call stack grouping in the find zone menu now has a special display mode. - Call stack memory allocations tree improvements: - Add top-down variant to complement the previously available bottom-up one. - Add ability to group tree nodes by function name. - Allow restricting tree to display only active allocations. - Added support for Lua call stack capture. - Self time of zones may be now displayed in the find zone menu. - Added ability to disconnect from a client. - Find zone groups can now be sorted by mean time per call. - Zones displayed in the find zone menu can be now grouped by order of appearance, execution time or name. - Time is now displayed without trailing fractional zeros (e.g. "2.5 ms" instead of "2.50 ms"). - Child zones displayed in zone info window can be now grouped by source location. - Selected or hovered lock is now highlighted on the timeline. - Locks are now grouped into single and multithreaded (contended and uncontended) in the options menu locks list. - On broken platforms the profiler can now be initialized as needed (and possible), taking a performance and functionality hit. - User experience improvements in the graphical profiler. - Thread position and height is now animated, to eliminate flickering that was happening when depth of displayed zones was changing. - Zooming in/out using the mouse wheel is now animated. - Plot range adjustment is now animated. - Various other UI improvements. - System CPU usage is now being monitored. - Threads that have nothing to display in the current view are now hidden by default. - Dimmed-out the timeline outside the profiling area. - Source file view can now be opened also from statistics menu. - Display standard deviation in find zone and compare traces menus. - Display zone messages in zone information window. - Display order of threads can be changed in the options menu. - Prevent deadlocks by querying socket send buffer size. - Frame set statistics can be now limited to frames visible on the screen. - Messages can be now colored. - Zone selection in compare traces menu can be now linked to the other trace. - Added support for frame image (screen shot) storage. - Implemented ability to cut off outliers on histograms. - Zone or frame that is currently hovered by the mouse cursor will be highlighted on the histogram. - Server now displays available clients in the local network. - Source code whitespace visibility can now be enabled or disabled. - Profiler will now check if proper timer readings can be performed on x86/x64. - Application can now log app-specific information, similarly to how the host info reports system information. - Message list will automatically scroll down to the most recent message. - Feature will disable when the list is scrolled by user. - To re-enable, scroll to the bottom of the list. - Message list can be now filtered. - A notification popup will be displayed during trace cleanup. - Source file view won't be available if a source file is newer than the capture. - Added ability to set custom trace descriptions. - Added frame time target lines. - FPS counts are now displayed next to frame times. - GPU drift value can be now automatically measured. - Connection window is now a popup hidden under a dedicated button. v0.4.1 (2018-12-30) ------------------- - Active frame set can be now switched by clicking on a frame set on the timeline. - Add ability to go to a specified frame. - Most commonly used addresses can be now selected from the drop-down menu. - Fixed corner case problem with profiler initialization on Windows. - Added third state (stopped) to the pause/resume button. It will be used after the connection to the client is terminated. - Active trace can be discarded. - Call stack capture may be forced through TRACY_CALLSTACK define. - Lock info window has been added. - Time of lock creation and termination is now being tracked. - Menu bar buttons are now toggles that can also close their corresponding windows. - Find zone and compare menu improvements. - Ability to ignore case during search. - Pressing enter key will now start search, just like pressing the "find" button. - Using the ^F keyboard shortcut will open the find zone menu and focus the input box. - Added ability to automatically connect to an IP address in the graphical profiler application (use "-a address" argument to enable). - Pressing enter key after entering client address in the welcome dialog will now automatically begin connection process. v0.4 (2018-10-09) ----------------- - Renamed "standalone" utility to "profiler". - Added trace update utility, which will convert files saved in previous versions of tracy to be up-to-date. - Optional high compression (--hc) mode is available that will increase the compression level, at the cost of considerably longer compression time. - Fix regression causing varying size of profiler window for different captures. - Added support for on-demand tracing. - If a client application is compiled with the TRACY_ON_DEMAND macro defined, tracing will not begin until a connection to server is established. - Since data is not fully captured in this mode, the resulting trace will be less precise, until application state is appropriately reset. For example, locks need to be fully released, zone stacks need to be flushed. This is an automatic process. - All tracing macros are able to work in the on-demand mode. - Improved compatibility with various system setups. - Aside from using TRACY_NO_EXIT define you can also set the same-named environmental variable to 1 to get the same effect. - Added ability to show/hide all threads and plots. - Performance improvements. - Improvements to memory data presentation. - Added memory allocation info window. - Selecting memory allocation on a plot will draw time range of the allocation. - Middle clicking on an memory allocation address (or on a button in memory allocation info window) will zoom the view to the allocation range. - Find zone menu improvements: - Zones can be now also grouped by call stacks. - Zone groups can be now also sorted by time spend in each zone. - Zone groups list now displays group times. - Average and median zone times are now displayed on the histogram. - Selected zones will be highlighted on the timeline view. - Added named versions of tracing macros that allow specifying scoped variable name. - The main profiler window is now kept at the bottom of windows stack. - The "profiler" utility will now use a custom embedded font. - Microseconds are now displayed using correct symbol ('μ' instead of 'u'). - Unix builds of the "profiler" utility will now ask for a file name when saving a trace. - Progress popup is now displayed when a trace file is loading. - Zones that share source location with a zone that is hovered over are now highlighted. - Added ability to zoom-in to a selection range made using middle mouse button. - Holding the ctrl key will switch to zoom-out mode. - The "profiler" utility will use less resources when its window is out-of-focus or minimized. - Added support for cross-DLL profiling. - Items in options menu (locks, threads, etc.) are now described with number of events. - Source location of lock declaration is also provided. - Created an extensive user manual for the profiler. - Added ability to capture multiple frame sets. - Viewer will display multiple frame ranges at once. - Only one frame set can be active at once. The selected one is used for the frame navigation graph, frame navigation buttons and drawing frame separators. - The active frame set will be highlighted, and the rest will be dimmed out. - Frames can now also be discontinuous. - Frames and zones too small to be displayed will be marked with a zig-zag pattern. - General improvements to message list and message markers. - Hovering over message on a list will highlight its marker (previously it only worked the other way). - Left clicking on a message marker will focus the message list on the selected message. - Middle clicking on a message marker will center it on screen. - Added trace information window. - This includes frame time statistics and histogram. - Displayed memory sizes are now properly formatted. - Added call stack tree for memory allocations. - You can display allocations list for each call stack tree entry. - The source code of the profiled application may now be viewed in the profiler. - BIG FAT WARNING: The actual profiled program source code is not known to the profiler. It only checks if there is a file on your disk that matches the file name of the captured source location. Even if the file is displayed, it may be out of date. - CPU and GPU zones will have "Source" button, if source file can be opened. - Source files for call stack traces can be opened by right-clicking on the file name. Since in this case there is no button that can be hidden, a small animation will be played to notify user if the source cannot be opened. - The main profiler view will now occupy the whole window. Previous behavior is still available for embedded use cases. - Many button labels are now accompanied by icons. - Fonts should now be less blurry. - "Go to parent" button in zone info window won't be displayed if there is no parent to go to. - Improvements to the compare traces menu. - There are now colored markers to make it easier to distinguish "this" and "external" traces. - The amount of saved time is now displayed (a difference between total run times of both traces). - Tracy will now collect host information, like CPU name, amount of system memory, etc. - Windows builds of the "profiler" utility will perform a check of supported CPU instruction set and match it against the one required by the binary (by default AVX2 is used). If the program cannot be executed on the processor, a message dialog with workaround instructions will be displayed. - Tracy can intercept crashes and finish sending data from a dying process. - Currently this is only implemented on Windows, Linux and Android. - Call stack window may now display addresses of the frames, instead of source file locations. - Memory events will now properly register their thread. - Profiler settings are now stored in a persistent location. - On Windows settings are stored in %APPDATA%/tracy. - On other platforms settings are stored in $XDG_CONFIG_HOME/tracy or $HOME/.config/tracy, if the variable is not set. - The main profiler window position, size and maximized state are saved and restored. - The size and position of internal windows now doesn't depend on the runtime directory of the profiler executable. - Added connection handshake. - Server won't be able to connect to client if there's a protocol version mismatch. - Client not in on-demand mode will refuse connections after the first connection was made and the initial event buffers were cleared. - A single server will no longer try to connect to multiple clients. - The capture utility will now display time span of the ongoing capture. v0.3 (2018-07-03) ----------------- - Breaking change: the format of trace files has changed. - Previous tracy version will crash when trying to open new traces. - Loading of traces saved by previous version is supported. - Tracy will no longer crash when trying to load traces saved by future versions. Instead, a dialog advising to update will be displayed. - Tracy will no longer crash in most cases when trying to open files that are not traces. Some crashes are still possible, due to support of old, header-less traces. - Ability to track every memory allocation in profiled program. - Allocation event queuing must be done in order, which requires exclusive access to the serialized queue on the client side. This has no effect on the rest of events, which are stored in a concurrent queue, as before. - You can search for a memory address and see where it was allocated, for how long, etc. This lists all matching allocations since the program was started. - All active (non-freed) allocations may be listed. This shows the current memory state by default, but can go back to any point in time. - Graphical representation of process memory map may be displayed. New allocations/frees are displayed in a bright color and fade out with time. This feature also can look back in time. - Memory usage plot is automatically generated. - Basic allocation information is displayed in memory plot tooltips. - A summary of memory events within a zone (and its children) is now printed in zone info window. - Support loading profile dumps with no memory allocation data (generated by v0.2). - Added ability to display global statistics of a selected zone from the zone info window. - Fixed regression with lock announce processing that appeared during worker/viewer split. - Allow selecting/unselecting all locks for display. - Performance improvements. - Don't save unneeded lock information in trace file. - Don't save thrash in message list data. - Allow expanding view span up to one hour, instead of one minute. - Added trace comparison window. - An external trace has to be loaded first. - Zone query in both traces (current and external). - Both results are overlaid on the same histogram. - Graphs can be adjusted as-if there was the same number of zones collected. - Read time directly from a hardware register on ARM/ARM64, if possible. - User-space access to the timer needs to be enabled in the kernel, so tracy will perform run-time checks and fallback to the old method if the check fails. - Prevent connections in a TIME-WAIT state from blocking new listen connections. - Display y-range of plots. - Added ability to unload traces loaded from files. To do so close the main profiler window. You will return to the connect/open selection dialog. Live captures cannot be terminated this way. - Zones previously displayed in zone info window are remembered and you can go back to them. Closing the zone info window or switching between CPU and GPU zones will clear the memory. - Improved message list window. - Messages are now displayed in columns. - Originating thread of each message is now included in the list. - Messages can be filtered by the originating thread. - You can now navigate to next and previous frame. - Zone statistics can be now displayed using only self times. - Support for tracing GPU events using Vulkan. - Timeline will now display "OpenGL context" or "Vulkan context" instead of "GPU context". - Fixed regression causing invalid display of GPU context appearance time. - Fixed regression causing invalid reporting of an active CPU in zone end events, if MSVC rdtscp optimization was not enabled. - Ability to collect true call stacks. - Supported on Windows, Linux, Android. - The following events can collect call stacks: - Memory alloc/free. - Zone begin. - GPU zone begin. - Zone stack trace now also displays frames from a real call trace. - On Linux call stack frame name resolution requires a call to dladdr, which in turn requires linking with libdl. - Allow manual entry of GPU time drift value. - Unix build system no longer shares object files between different build units. - Fixes inability to build debug and release versions of a single utility without "make clean". - Fixes incompatibility between "standalone" and "capture" utilities due to different set of used feature flags. - On Windows "standalone" utility now adapts to system DPI setting. - Optional per-call zone naming. v0.2 (2018-04-05) ----------------- - Fixed broken TRACY_NO_EXIT behavior. - Visual refresh (new color scheme). - Added optional support for live in-depth zone analysis. - Ability to search for zones matching a query. - Histogram of zone time spans. - List occurrences of a zone, grouped by thread, or by user text. - Zone groups can be selected and highlighted on histogram graph. - Support for linear and logarithmic display of time and values. - Histogram bins can show zone counts or total execution time. - Listed zones can be narrowed down by data range selection on histogram. - Separation of server data handling code from the visualisation. - Implementation of a command line capture utility. - Support libraries have been updated. - Fixed an issue that prevented de-duplication of source location payloads. - Fixed an issue that prevented the ability to disable threads in settings menu, if two threads had the same name. - Performance optimizations. - Visual clean up of the settings menu. - Zone info windows improvements. - Visual improvements to zone info window child list. - Zone info windows now show zone thread. - Display zone stack trace. - Hide pause/resume button if there's no data connection (i.e. trace was loaded from file). - Source location statistics view has been added. - Fixed crash when a saved trace was opened, but no trace capture session was performed before. - Standalone server will now open trace files passed as an argument to the executable. - Fix possible crash in SetThreadName, that could happen if TLS init was delayed until first use of thread local variable. - Store full thread name if pthreads (with 15 character name limit) are used. - Properly handle unaligned memory access (no performance impact). - Fixed broken lock identifiers in try_lock(). v0.1 (2017-12-18) ----------------- - Initial release.
whupdup/frame
real/third_party/tracy/NEWS
none
gpl-3.0
42,256
# Tracy Profiler [![Sponsor](.github/sponsor.png)](https://github.com/sponsors/wolfpld/) ### A real time, nanosecond resolution, remote telemetry, hybrid frame and sampling profiler for games and other applications. Tracy supports profiling CPU (Direct support is provided for C, C++, and Lua integration. At the same time, third-party bindings to many other languages exist on the internet, such as Rust, Zig, OCaml, Odin, etc.), GPU (All major graphic APIs: OpenGL, Vulkan, Direct3D 11/12, OpenCL.), memory allocations, locks, context switches, automatically attribute screenshots to captured frames, and much more. - [Documentation](https://github.com/wolfpld/tracy/releases/latest/download/tracy.pdf) for usage and build process instructions - [Releases](https://github.com/wolfpld/tracy/releases) containing the documentation (`tracy.pdf`) and compiled Windows x64 binaries (`Tracy-<version>.7z`) as assets - [Changelog](NEWS) ![](doc/profiler.png) ![](doc/profiler2.png) ![](doc/profiler3.png) [Introduction to Tracy Profiler v0.2](https://www.youtube.com/watch?v=fB5B46lbapc) [New features in Tracy Profiler v0.3](https://www.youtube.com/watch?v=3SXpDpDh2Uo) [New features in Tracy Profiler v0.4](https://www.youtube.com/watch?v=eAkgkaO8B9o) [New features in Tracy Profiler v0.5](https://www.youtube.com/watch?v=P6E7qLMmzTQ) [New features in Tracy Profiler v0.6](https://www.youtube.com/watch?v=uJkrFgriuOo) [New features in Tracy Profiler v0.7](https://www.youtube.com/watch?v=_hU7vw00MZ4) [New features in Tracy Profiler v0.8](https://www.youtube.com/watch?v=30wpRpHTTag)
whupdup/frame
real/third_party/tracy/README.md
Markdown
gpl-3.0
1,601
"Would be nice to have" list for 1.0 release: ============================================= * Pack queue items tightly in the queues. * Use level-of-detail system for plots. * Use per-thread lock data structures. * Use DTrace for BSD/OSX context switch capture.
whupdup/frame
real/third_party/tracy/TODO
none
gpl-3.0
263
#ifndef __TRACY_HPP__ #define __TRACY_HPP__ #include "common/TracyColor.hpp" #include "common/TracySystem.hpp" #ifndef TRACY_ENABLE #define ZoneNamed(x,y) #define ZoneNamedN(x,y,z) #define ZoneNamedC(x,y,z) #define ZoneNamedNC(x,y,z,w) #define ZoneTransient(x,y) #define ZoneTransientN(x,y,z) #define ZoneScoped #define ZoneScopedN(x) #define ZoneScopedC(x) #define ZoneScopedNC(x,y) #define ZoneText(x,y) #define ZoneTextV(x,y,z) #define ZoneName(x,y) #define ZoneNameV(x,y,z) #define ZoneColor(x) #define ZoneColorV(x,y) #define ZoneValue(x) #define ZoneValueV(x,y) #define ZoneIsActive false #define ZoneIsActiveV(x) false #define FrameMark #define FrameMarkNamed(x) #define FrameMarkStart(x) #define FrameMarkEnd(x) #define FrameImage(x,y,z,w,a) #define TracyLockable( type, varname ) type varname; #define TracyLockableN( type, varname, desc ) type varname; #define TracySharedLockable( type, varname ) type varname; #define TracySharedLockableN( type, varname, desc ) type varname; #define LockableBase( type ) type #define SharedLockableBase( type ) type #define LockMark(x) (void)x; #define LockableName(x,y,z); #define TracyPlot(x,y) #define TracyPlotConfig(x,y) #define TracyMessage(x,y) #define TracyMessageL(x) #define TracyMessageC(x,y,z) #define TracyMessageLC(x,y) #define TracyAppInfo(x,y) #define TracyAlloc(x,y) #define TracyFree(x) #define TracySecureAlloc(x,y) #define TracySecureFree(x) #define TracyAllocN(x,y,z) #define TracyFreeN(x,y) #define TracySecureAllocN(x,y,z) #define TracySecureFreeN(x,y) #define ZoneNamedS(x,y,z) #define ZoneNamedNS(x,y,z,w) #define ZoneNamedCS(x,y,z,w) #define ZoneNamedNCS(x,y,z,w,a) #define ZoneTransientS(x,y,z) #define ZoneTransientNS(x,y,z,w) #define ZoneScopedS(x) #define ZoneScopedNS(x,y) #define ZoneScopedCS(x,y) #define ZoneScopedNCS(x,y,z) #define TracyAllocS(x,y,z) #define TracyFreeS(x,y) #define TracySecureAllocS(x,y,z) #define TracySecureFreeS(x,y) #define TracyAllocNS(x,y,z,w) #define TracyFreeNS(x,y,z) #define TracySecureAllocNS(x,y,z,w) #define TracySecureFreeNS(x,y,z) #define TracyMessageS(x,y,z) #define TracyMessageLS(x,y) #define TracyMessageCS(x,y,z,w) #define TracyMessageLCS(x,y,z) #define TracyParameterRegister(x) #define TracyParameterSetup(x,y,z,w) #define TracyIsConnected false #define TracyFiberEnter(x) #define TracyFiberLeave #else #include <string.h> #include "client/TracyLock.hpp" #include "client/TracyProfiler.hpp" #include "client/TracyScoped.hpp" #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define ZoneNamed( varname, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define ZoneNamedN( varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define ZoneNamedC( varname, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define ZoneNamedNC( varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define ZoneTransient( varname, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), nullptr, 0, TRACY_CALLSTACK, active ); # define ZoneTransientN( varname, name, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), TRACY_CALLSTACK, active ); #else # define ZoneNamed( varname, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), active ); # define ZoneNamedN( varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), active ); # define ZoneNamedC( varname, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), active ); # define ZoneNamedNC( varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), active ); # define ZoneTransient( varname, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), nullptr, 0, active ); # define ZoneTransientN( varname, name, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), active ); #endif #define ZoneScoped ZoneNamed( ___tracy_scoped_zone, true ) #define ZoneScopedN( name ) ZoneNamedN( ___tracy_scoped_zone, name, true ) #define ZoneScopedC( color ) ZoneNamedC( ___tracy_scoped_zone, color, true ) #define ZoneScopedNC( name, color ) ZoneNamedNC( ___tracy_scoped_zone, name, color, true ) #define ZoneText( txt, size ) ___tracy_scoped_zone.Text( txt, size ); #define ZoneTextV( varname, txt, size ) varname.Text( txt, size ); #define ZoneName( txt, size ) ___tracy_scoped_zone.Name( txt, size ); #define ZoneNameV( varname, txt, size ) varname.Name( txt, size ); #define ZoneColor( color ) ___tracy_scoped_zone.Color( color ); #define ZoneColorV( varname, color ) varname.Color( color ); #define ZoneValue( value ) ___tracy_scoped_zone.Value( value ); #define ZoneValueV( varname, value ) varname.Value( value ); #define ZoneIsActive ___tracy_scoped_zone.IsActive() #define ZoneIsActiveV( varname ) varname.IsActive() #define FrameMark tracy::Profiler::SendFrameMark( nullptr ); #define FrameMarkNamed( name ) tracy::Profiler::SendFrameMark( name ); #define FrameMarkStart( name ) tracy::Profiler::SendFrameMark( name, tracy::QueueType::FrameMarkMsgStart ); #define FrameMarkEnd( name ) tracy::Profiler::SendFrameMark( name, tracy::QueueType::FrameMarkMsgEnd ); #define FrameImage( image, width, height, offset, flip ) tracy::Profiler::SendFrameImage( image, width, height, offset, flip ); #define TracyLockable( type, varname ) tracy::Lockable<type> varname { [] () -> const tracy::SourceLocationData* { static constexpr tracy::SourceLocationData srcloc { nullptr, #type " " #varname, __FILE__, __LINE__, 0 }; return &srcloc; }() }; #define TracyLockableN( type, varname, desc ) tracy::Lockable<type> varname { [] () -> const tracy::SourceLocationData* { static constexpr tracy::SourceLocationData srcloc { nullptr, desc, __FILE__, __LINE__, 0 }; return &srcloc; }() }; #define TracySharedLockable( type, varname ) tracy::SharedLockable<type> varname { [] () -> const tracy::SourceLocationData* { static constexpr tracy::SourceLocationData srcloc { nullptr, #type " " #varname, __FILE__, __LINE__, 0 }; return &srcloc; }() }; #define TracySharedLockableN( type, varname, desc ) tracy::SharedLockable<type> varname { [] () -> const tracy::SourceLocationData* { static constexpr tracy::SourceLocationData srcloc { nullptr, desc, __FILE__, __LINE__, 0 }; return &srcloc; }() }; #define LockableBase( type ) tracy::Lockable<type> #define SharedLockableBase( type ) tracy::SharedLockable<type> #define LockMark( varname ) static constexpr tracy::SourceLocationData __tracy_lock_location_##varname { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; varname.Mark( &__tracy_lock_location_##varname ); #define LockableName( varname, txt, size ) varname.CustomName( txt, size ); #define TracyPlot( name, val ) tracy::Profiler::PlotData( name, val ); #define TracyPlotConfig( name, type ) tracy::Profiler::ConfigurePlot( name, type ); #define TracyAppInfo( txt, size ) tracy::Profiler::MessageAppInfo( txt, size ); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyMessage( txt, size ) tracy::Profiler::Message( txt, size, TRACY_CALLSTACK ); # define TracyMessageL( txt ) tracy::Profiler::Message( txt, TRACY_CALLSTACK ); # define TracyMessageC( txt, size, color ) tracy::Profiler::MessageColor( txt, size, color, TRACY_CALLSTACK ); # define TracyMessageLC( txt, color ) tracy::Profiler::MessageColor( txt, color, TRACY_CALLSTACK ); # define TracyAlloc( ptr, size ) tracy::Profiler::MemAllocCallstack( ptr, size, TRACY_CALLSTACK, false ); # define TracyFree( ptr ) tracy::Profiler::MemFreeCallstack( ptr, TRACY_CALLSTACK, false ); # define TracySecureAlloc( ptr, size ) tracy::Profiler::MemAllocCallstack( ptr, size, TRACY_CALLSTACK, true ); # define TracySecureFree( ptr ) tracy::Profiler::MemFreeCallstack( ptr, TRACY_CALLSTACK, true ); # define TracyAllocN( ptr, size, name ) tracy::Profiler::MemAllocCallstackNamed( ptr, size, TRACY_CALLSTACK, false, name ); # define TracyFreeN( ptr, name ) tracy::Profiler::MemFreeCallstackNamed( ptr, TRACY_CALLSTACK, false, name ); # define TracySecureAllocN( ptr, size, name ) tracy::Profiler::MemAllocCallstackNamed( ptr, size, TRACY_CALLSTACK, true, name ); # define TracySecureFreeN( ptr, name ) tracy::Profiler::MemFreeCallstackNamed( ptr, TRACY_CALLSTACK, true, name ); #else # define TracyMessage( txt, size ) tracy::Profiler::Message( txt, size, 0 ); # define TracyMessageL( txt ) tracy::Profiler::Message( txt, 0 ); # define TracyMessageC( txt, size, color ) tracy::Profiler::MessageColor( txt, size, color, 0 ); # define TracyMessageLC( txt, color ) tracy::Profiler::MessageColor( txt, color, 0 ); # define TracyAlloc( ptr, size ) tracy::Profiler::MemAlloc( ptr, size, false ); # define TracyFree( ptr ) tracy::Profiler::MemFree( ptr, false ); # define TracySecureAlloc( ptr, size ) tracy::Profiler::MemAlloc( ptr, size, true ); # define TracySecureFree( ptr ) tracy::Profiler::MemFree( ptr, true ); # define TracyAllocN( ptr, size, name ) tracy::Profiler::MemAllocNamed( ptr, size, false, name ); # define TracyFreeN( ptr, name ) tracy::Profiler::MemFreeNamed( ptr, false, name ); # define TracySecureAllocN( ptr, size, name ) tracy::Profiler::MemAllocNamed( ptr, size, true, name ); # define TracySecureFreeN( ptr, name ) tracy::Profiler::MemFreeNamed( ptr, true, name ); #endif #ifdef TRACY_HAS_CALLSTACK # define ZoneNamedS( varname, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define ZoneNamedNS( varname, name, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define ZoneNamedCS( varname, color, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { nullptr, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define ZoneNamedNCS( varname, name, color, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::ScopedZone varname( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define ZoneTransientS( varname, depth, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), nullptr, 0, depth, active ); # define ZoneTransientNS( varname, name, depth, active ) tracy::ScopedZone varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), depth, active ); # define ZoneScopedS( depth ) ZoneNamedS( ___tracy_scoped_zone, depth, true ) # define ZoneScopedNS( name, depth ) ZoneNamedNS( ___tracy_scoped_zone, name, depth, true ) # define ZoneScopedCS( color, depth ) ZoneNamedCS( ___tracy_scoped_zone, color, depth, true ) # define ZoneScopedNCS( name, color, depth ) ZoneNamedNCS( ___tracy_scoped_zone, name, color, depth, true ) # define TracyAllocS( ptr, size, depth ) tracy::Profiler::MemAllocCallstack( ptr, size, depth, false ); # define TracyFreeS( ptr, depth ) tracy::Profiler::MemFreeCallstack( ptr, depth, false ); # define TracySecureAllocS( ptr, size, depth ) tracy::Profiler::MemAllocCallstack( ptr, size, depth, true ); # define TracySecureFreeS( ptr, depth ) tracy::Profiler::MemFreeCallstack( ptr, depth, true ); # define TracyAllocNS( ptr, size, depth, name ) tracy::Profiler::MemAllocCallstackNamed( ptr, size, depth, false, name ); # define TracyFreeNS( ptr, depth, name ) tracy::Profiler::MemFreeCallstackNamed( ptr, depth, false, name ); # define TracySecureAllocNS( ptr, size, depth, name ) tracy::Profiler::MemAllocCallstackNamed( ptr, size, depth, true, name ); # define TracySecureFreeNS( ptr, depth, name ) tracy::Profiler::MemFreeCallstackNamed( ptr, depth, true, name ); # define TracyMessageS( txt, size, depth ) tracy::Profiler::Message( txt, size, depth ); # define TracyMessageLS( txt, depth ) tracy::Profiler::Message( txt, depth ); # define TracyMessageCS( txt, size, color, depth ) tracy::Profiler::MessageColor( txt, size, color, depth ); # define TracyMessageLCS( txt, color, depth ) tracy::Profiler::MessageColor( txt, color, depth ); #else # define ZoneNamedS( varname, depth, active ) ZoneNamed( varname, active ) # define ZoneNamedNS( varname, name, depth, active ) ZoneNamedN( varname, name, active ) # define ZoneNamedCS( varname, color, depth, active ) ZoneNamedC( varname, color, active ) # define ZoneNamedNCS( varname, name, color, depth, active ) ZoneNamedNC( varname, name, color, active ) # define ZoneTransientS( varname, depth, active ) ZoneTransient( varname, active ) # define ZoneTransientNS( varname, name, depth, active ) ZoneTransientN( varname, name, active ) # define ZoneScopedS( depth ) ZoneScoped # define ZoneScopedNS( name, depth ) ZoneScopedN( name ) # define ZoneScopedCS( color, depth ) ZoneScopedC( color ) # define ZoneScopedNCS( name, color, depth ) ZoneScopedNC( name, color ) # define TracyAllocS( ptr, size, depth ) TracyAlloc( ptr, size ) # define TracyFreeS( ptr, depth ) TracyFree( ptr ) # define TracySecureAllocS( ptr, size, depth ) TracySecureAlloc( ptr, size ) # define TracySecureFreeS( ptr, depth ) TracySecureFree( ptr ) # define TracyAllocNS( ptr, size, depth, name ) TracyAlloc( ptr, size, name ) # define TracyFreeNS( ptr, depth, name ) TracyFree( ptr, name ) # define TracySecureAllocNS( ptr, size, depth, name ) TracySecureAlloc( ptr, size, name ) # define TracySecureFreeNS( ptr, depth, name ) TracySecureFree( ptr, name ) # define TracyMessageS( txt, size, depth ) TracyMessage( txt, size ) # define TracyMessageLS( txt, depth ) TracyMessageL( txt ) # define TracyMessageCS( txt, size, color, depth ) TracyMessageC( txt, size, color ) # define TracyMessageLCS( txt, color, depth ) TracyMessageLC( txt, color ) #endif #define TracyParameterRegister( cb ) tracy::Profiler::ParameterRegister( cb ); #define TracyParameterSetup( idx, name, isBool, val ) tracy::Profiler::ParameterSetup( idx, name, isBool, val ); #define TracyIsConnected tracy::GetProfiler().IsConnected() #ifdef TRACY_FIBERS # define TracyFiberEnter( fiber ) tracy::Profiler::EnterFiber( fiber ); # define TracyFiberLeave tracy::Profiler::LeaveFiber(); #endif #endif #endif
whupdup/frame
real/third_party/tracy/Tracy.hpp
C++
gpl-3.0
16,348
#ifndef __TRACYC_HPP__ #define __TRACYC_HPP__ #include <stddef.h> #include <stdint.h> #include "client/TracyCallstack.h" #include "common/TracyApi.h" #ifdef __cplusplus extern "C" { #endif TRACY_API void ___tracy_set_thread_name( const char* name ); #define TracyCSetThreadName( name ) ___tracy_set_thread_name( name ); #ifndef TRACY_ENABLE typedef const void* TracyCZoneCtx; #define TracyCZone(c,x) #define TracyCZoneN(c,x,y) #define TracyCZoneC(c,x,y) #define TracyCZoneNC(c,x,y,z) #define TracyCZoneEnd(c) #define TracyCZoneText(c,x,y) #define TracyCZoneName(c,x,y) #define TracyCZoneColor(c,x) #define TracyCZoneValue(c,x) #define TracyCAlloc(x,y) #define TracyCFree(x) #define TracyCSecureAlloc(x,y) #define TracyCSecureFree(x) #define TracyCAllocN(x,y,z) #define TracyCFreeN(x,y) #define TracyCSecureAllocN(x,y,z) #define TracyCSecureFreeN(x,y) #define TracyCFrameMark #define TracyCFrameMarkNamed(x) #define TracyCFrameMarkStart(x) #define TracyCFrameMarkEnd(x) #define TracyCFrameImage(x,y,z,w,a) #define TracyCPlot(x,y) #define TracyCMessage(x,y) #define TracyCMessageL(x) #define TracyCMessageC(x,y,z) #define TracyCMessageLC(x,y) #define TracyCAppInfo(x,y) #define TracyCZoneS(x,y,z) #define TracyCZoneNS(x,y,z,w) #define TracyCZoneCS(x,y,z,w) #define TracyCZoneNCS(x,y,z,w,a) #define TracyCAllocS(x,y,z) #define TracyCFreeS(x,y) #define TracyCSecureAllocS(x,y,z) #define TracyCSecureFreeS(x,y) #define TracyCAllocNS(x,y,z,w) #define TracyCFreeNS(x,y,z) #define TracyCSecureAllocNS(x,y,z,w) #define TracyCSecureFreeNS(x,y,z) #define TracyCMessageS(x,y,z) #define TracyCMessageLS(x,y) #define TracyCMessageCS(x,y,z,w) #define TracyCMessageLCS(x,y,z) #define TracyCIsConnected 0 #ifdef TRACY_FIBERS # define TracyCFiberEnter(fiber) # define TracyCFiberLeave #endif #else #ifndef TracyConcat # define TracyConcat(x,y) TracyConcatIndirect(x,y) #endif #ifndef TracyConcatIndirect # define TracyConcatIndirect(x,y) x##y #endif struct ___tracy_source_location_data { const char* name; const char* function; const char* file; uint32_t line; uint32_t color; }; struct ___tracy_c_zone_context { uint32_t id; int active; }; struct ___tracy_gpu_time_data { int64_t gpuTime; uint16_t queryId; uint8_t context; }; struct ___tracy_gpu_zone_begin_data { uint64_t srcloc; uint16_t queryId; uint8_t context; }; struct ___tracy_gpu_zone_end_data { uint16_t queryId; uint8_t context; }; struct ___tracy_gpu_new_context_data { int64_t gpuTime; float period; uint8_t context; uint8_t flags; uint8_t type; }; struct ___tracy_gpu_context_name_data { uint8_t context; const char* name; uint16_t len; }; // Some containers don't support storing const types. // This struct, as visible to user, is immutable, so treat it as if const was declared here. typedef /*const*/ struct ___tracy_c_zone_context TracyCZoneCtx; #ifdef TRACY_MANUAL_LIFETIME TRACY_API void ___tracy_startup_profiler(void); TRACY_API void ___tracy_shutdown_profiler(void); #endif TRACY_API uint64_t ___tracy_alloc_srcloc( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz ); TRACY_API uint64_t ___tracy_alloc_srcloc_name( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz ); TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin( const struct ___tracy_source_location_data* srcloc, int active ); TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_callstack( const struct ___tracy_source_location_data* srcloc, int depth, int active ); TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_alloc( uint64_t srcloc, int active ); TRACY_API TracyCZoneCtx ___tracy_emit_zone_begin_alloc_callstack( uint64_t srcloc, int depth, int active ); TRACY_API void ___tracy_emit_zone_end( TracyCZoneCtx ctx ); TRACY_API void ___tracy_emit_zone_text( TracyCZoneCtx ctx, const char* txt, size_t size ); TRACY_API void ___tracy_emit_zone_name( TracyCZoneCtx ctx, const char* txt, size_t size ); TRACY_API void ___tracy_emit_zone_color( TracyCZoneCtx ctx, uint32_t color ); TRACY_API void ___tracy_emit_zone_value( TracyCZoneCtx ctx, uint64_t value ); TRACY_API void ___tracy_emit_gpu_zone_begin_alloc( const struct ___tracy_gpu_zone_begin_data ); TRACY_API void ___tracy_emit_gpu_zone_end( const struct ___tracy_gpu_zone_end_data data ); TRACY_API void ___tracy_emit_gpu_time( const struct ___tracy_gpu_time_data ); TRACY_API void ___tracy_emit_gpu_new_context( const struct ___tracy_gpu_new_context_data ); TRACY_API void ___tracy_emit_gpu_context_name( const struct ___tracy_gpu_context_name_data ); TRACY_API void ___tracy_emit_gpu_zone_begin_alloc_serial( const struct ___tracy_gpu_zone_begin_data ); TRACY_API void ___tracy_emit_gpu_zone_end_serial( const struct ___tracy_gpu_zone_end_data data ); TRACY_API void ___tracy_emit_gpu_time_serial( const struct ___tracy_gpu_time_data ); TRACY_API void ___tracy_emit_gpu_new_context_serial( const struct ___tracy_gpu_new_context_data ); TRACY_API void ___tracy_emit_gpu_context_name_serial( const struct ___tracy_gpu_context_name_data ); TRACY_API int ___tracy_connected(void); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyCZone( ctx, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyCZoneN( ctx, name, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyCZoneC( ctx, color, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyCZoneNC( ctx, name, color, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), TRACY_CALLSTACK, active ); #else # define TracyCZone( ctx, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin( &TracyConcat(__tracy_source_location,__LINE__), active ); # define TracyCZoneN( ctx, name, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin( &TracyConcat(__tracy_source_location,__LINE__), active ); # define TracyCZoneC( ctx, color, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin( &TracyConcat(__tracy_source_location,__LINE__), active ); # define TracyCZoneNC( ctx, name, color, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin( &TracyConcat(__tracy_source_location,__LINE__), active ); #endif #define TracyCZoneEnd( ctx ) ___tracy_emit_zone_end( ctx ); #define TracyCZoneText( ctx, txt, size ) ___tracy_emit_zone_text( ctx, txt, size ); #define TracyCZoneName( ctx, txt, size ) ___tracy_emit_zone_name( ctx, txt, size ); #define TracyCZoneColor( ctx, color ) ___tracy_emit_zone_color( ctx, color ); #define TracyCZoneValue( ctx, value ) ___tracy_emit_zone_value( ctx, value ); TRACY_API void ___tracy_emit_memory_alloc( const void* ptr, size_t size, int secure ); TRACY_API void ___tracy_emit_memory_alloc_callstack( const void* ptr, size_t size, int depth, int secure ); TRACY_API void ___tracy_emit_memory_free( const void* ptr, int secure ); TRACY_API void ___tracy_emit_memory_free_callstack( const void* ptr, int depth, int secure ); TRACY_API void ___tracy_emit_memory_alloc_named( const void* ptr, size_t size, int secure, const char* name ); TRACY_API void ___tracy_emit_memory_alloc_callstack_named( const void* ptr, size_t size, int depth, int secure, const char* name ); TRACY_API void ___tracy_emit_memory_free_named( const void* ptr, int secure, const char* name ); TRACY_API void ___tracy_emit_memory_free_callstack_named( const void* ptr, int depth, int secure, const char* name ); TRACY_API void ___tracy_emit_message( const char* txt, size_t size, int callstack ); TRACY_API void ___tracy_emit_messageL( const char* txt, int callstack ); TRACY_API void ___tracy_emit_messageC( const char* txt, size_t size, uint32_t color, int callstack ); TRACY_API void ___tracy_emit_messageLC( const char* txt, uint32_t color, int callstack ); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyCAlloc( ptr, size ) ___tracy_emit_memory_alloc_callstack( ptr, size, TRACY_CALLSTACK, 0 ) # define TracyCFree( ptr ) ___tracy_emit_memory_free_callstack( ptr, TRACY_CALLSTACK, 0 ) # define TracyCSecureAlloc( ptr, size ) ___tracy_emit_memory_alloc_callstack( ptr, size, TRACY_CALLSTACK, 1 ) # define TracyCSecureFree( ptr ) ___tracy_emit_memory_free_callstack( ptr, TRACY_CALLSTACK, 1 ) # define TracyCAllocN( ptr, size, name ) ___tracy_emit_memory_alloc_callstack_named( ptr, size, TRACY_CALLSTACK, 0, name ) # define TracyCFreeN( ptr, name ) ___tracy_emit_memory_free_callstack_named( ptr, TRACY_CALLSTACK, 0, name ) # define TracyCSecureAllocN( ptr, size, name ) ___tracy_emit_memory_alloc_callstack_named( ptr, size, TRACY_CALLSTACK, 1, name ) # define TracyCSecureFreeN( ptr, name ) ___tracy_emit_memory_free_callstack_named( ptr, TRACY_CALLSTACK, 1, name ) # define TracyCMessage( txt, size ) ___tracy_emit_message( txt, size, TRACY_CALLSTACK ); # define TracyCMessageL( txt ) ___tracy_emit_messageL( txt, TRACY_CALLSTACK ); # define TracyCMessageC( txt, size, color ) ___tracy_emit_messageC( txt, size, color, TRACY_CALLSTACK ); # define TracyCMessageLC( txt, color ) ___tracy_emit_messageLC( txt, color, TRACY_CALLSTACK ); #else # define TracyCAlloc( ptr, size ) ___tracy_emit_memory_alloc( ptr, size, 0 ); # define TracyCFree( ptr ) ___tracy_emit_memory_free( ptr, 0 ); # define TracyCSecureAlloc( ptr, size ) ___tracy_emit_memory_alloc( ptr, size, 1 ); # define TracyCSecureFree( ptr ) ___tracy_emit_memory_free( ptr, 1 ); # define TracyCAllocN( ptr, size, name ) ___tracy_emit_memory_alloc_named( ptr, size, 0, name ); # define TracyCFreeN( ptr, name ) ___tracy_emit_memory_free_named( ptr, 0, name ); # define TracyCSecureAllocN( ptr, size, name ) ___tracy_emit_memory_alloc_named( ptr, size, 1, name ); # define TracyCSecureFreeN( ptr, name ) ___tracy_emit_memory_free_named( ptr, 1, name ); # define TracyCMessage( txt, size ) ___tracy_emit_message( txt, size, 0 ); # define TracyCMessageL( txt ) ___tracy_emit_messageL( txt, 0 ); # define TracyCMessageC( txt, size, color ) ___tracy_emit_messageC( txt, size, color, 0 ); # define TracyCMessageLC( txt, color ) ___tracy_emit_messageLC( txt, color, 0 ); #endif TRACY_API void ___tracy_emit_frame_mark( const char* name ); TRACY_API void ___tracy_emit_frame_mark_start( const char* name ); TRACY_API void ___tracy_emit_frame_mark_end( const char* name ); TRACY_API void ___tracy_emit_frame_image( const void* image, uint16_t w, uint16_t h, uint8_t offset, int flip ); #define TracyCFrameMark ___tracy_emit_frame_mark( 0 ); #define TracyCFrameMarkNamed( name ) ___tracy_emit_frame_mark( name ); #define TracyCFrameMarkStart( name ) ___tracy_emit_frame_mark_start( name ); #define TracyCFrameMarkEnd( name ) ___tracy_emit_frame_mark_end( name ); #define TracyCFrameImage( image, width, height, offset, flip ) ___tracy_emit_frame_image( image, width, height, offset, flip ); TRACY_API void ___tracy_emit_plot( const char* name, double val ); TRACY_API void ___tracy_emit_message_appinfo( const char* txt, size_t size ); #define TracyCPlot( name, val ) ___tracy_emit_plot( name, val ); #define TracyCAppInfo( txt, size ) ___tracy_emit_message_appinfo( txt, size ); #ifdef TRACY_HAS_CALLSTACK # define TracyCZoneS( ctx, depth, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define TracyCZoneNS( ctx, name, depth, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, 0 }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define TracyCZoneCS( ctx, color, depth, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { NULL, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define TracyCZoneNCS( ctx, name, color, depth, active ) static const struct ___tracy_source_location_data TracyConcat(__tracy_source_location,__LINE__) = { name, __func__, __FILE__, (uint32_t)__LINE__, color }; TracyCZoneCtx ctx = ___tracy_emit_zone_begin_callstack( &TracyConcat(__tracy_source_location,__LINE__), depth, active ); # define TracyCAllocS( ptr, size, depth ) ___tracy_emit_memory_alloc_callstack( ptr, size, depth, 0 ) # define TracyCFreeS( ptr, depth ) ___tracy_emit_memory_free_callstack( ptr, depth, 0 ) # define TracyCSecureAllocS( ptr, size, depth ) ___tracy_emit_memory_alloc_callstack( ptr, size, depth, 1 ) # define TracyCSecureFreeS( ptr, depth ) ___tracy_emit_memory_free_callstack( ptr, depth, 1 ) # define TracyCAllocNS( ptr, size, depth, name ) ___tracy_emit_memory_alloc_callstack_named( ptr, size, depth, 0, name ) # define TracyCFreeNS( ptr, depth, name ) ___tracy_emit_memory_free_callstack_named( ptr, depth, 0, name ) # define TracyCSecureAllocNS( ptr, size, depth, name ) ___tracy_emit_memory_alloc_callstack_named( ptr, size, depth, 1, name ) # define TracyCSecureFreeNS( ptr, depth, name ) ___tracy_emit_memory_free_callstack_named( ptr, depth, 1, name ) # define TracyCMessageS( txt, size, depth ) ___tracy_emit_message( txt, size, depth ); # define TracyCMessageLS( txt, depth ) ___tracy_emit_messageL( txt, depth ); # define TracyCMessageCS( txt, size, color, depth ) ___tracy_emit_messageC( txt, size, color, depth ); # define TracyCMessageLCS( txt, color, depth ) ___tracy_emit_messageLC( txt, color, depth ); #else # define TracyCZoneS( ctx, depth, active ) TracyCZone( ctx, active ) # define TracyCZoneNS( ctx, name, depth, active ) TracyCZoneN( ctx, name, active ) # define TracyCZoneCS( ctx, color, depth, active ) TracyCZoneC( ctx, color, active ) # define TracyCZoneNCS( ctx, name, color, depth, active ) TracyCZoneNC( ctx, name, color, active ) # define TracyCAllocS( ptr, size, depth ) TracyCAlloc( ptr, size ) # define TracyCFreeS( ptr, depth ) TracyCFree( ptr ) # define TracyCSecureAllocS( ptr, size, depth ) TracyCSecureAlloc( ptr, size ) # define TracyCSecureFreeS( ptr, depth ) TracyCSecureFree( ptr ) # define TracyCAllocNS( ptr, size, depth, name ) TracyCAllocN( ptr, size, name ) # define TracyCFreeNS( ptr, depth, name ) TracyCFreeN( ptr, name ) # define TracyCSecureAllocNS( ptr, size, depth, name ) TracyCSecureAllocN( ptr, size, name ) # define TracyCSecureFreeNS( ptr, depth, name ) TracyCSecureFreeN( ptr, name ) # define TracyCMessageS( txt, size, depth ) TracyCMessage( txt, size ) # define TracyCMessageLS( txt, depth ) TracyCMessageL( txt ) # define TracyCMessageCS( txt, size, color, depth ) TracyCMessageC( txt, size, color ) # define TracyCMessageLCS( txt, color, depth ) TracyCMessageLC( txt, color ) #endif #define TracyCIsConnected ___tracy_connected() TRACY_API void ___tracy_fiber_enter( const char* fiber ); TRACY_API void ___tracy_fiber_leave( void ); #ifdef TRACY_FIBERS # define TracyCFiberEnter( fiber ) ___tracy_fiber_enter( fiber ); # define TracyCFiberLeave ___tracy_fiber_leave(); #endif #endif #ifdef __cplusplus } #endif #endif
whupdup/frame
real/third_party/tracy/TracyC.h
C++
gpl-3.0
16,843
// // Tracy profiler // ---------------- // // For fast integration, compile and // link with this source file (and none // other) in your executable (or in the // main DLL / shared object on multi-DLL // projects). // // Define TRACY_ENABLE to enable profiler. #include "common/TracySystem.cpp" #ifdef TRACY_ENABLE #ifdef _MSC_VER # pragma warning(push, 0) #endif #include "common/tracy_lz4.cpp" #include "client/TracyProfiler.cpp" #include "client/TracyCallstack.cpp" #include "client/TracySysTime.cpp" #include "client/TracySysTrace.cpp" #include "common/TracySocket.cpp" #include "client/tracy_rpmalloc.cpp" #include "client/TracyDxt1.cpp" #include "client/TracyAlloc.cpp" #if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6 # include "libbacktrace/alloc.cpp" # include "libbacktrace/dwarf.cpp" # include "libbacktrace/fileline.cpp" # include "libbacktrace/mmapio.cpp" # include "libbacktrace/posix.cpp" # include "libbacktrace/sort.cpp" # include "libbacktrace/state.cpp" # if TRACY_HAS_CALLSTACK == 4 # include "libbacktrace/macho.cpp" # else # include "libbacktrace/elf.cpp" # endif # include "common/TracyStackFrames.cpp" #endif #ifdef _MSC_VER # pragma comment(lib, "ws2_32.lib") # pragma comment(lib, "dbghelp.lib") # pragma comment(lib, "advapi32.lib") # pragma comment(lib, "user32.lib") # pragma warning(pop) #endif #endif
whupdup/frame
real/third_party/tracy/TracyClient.cpp
C++
gpl-3.0
1,445
#ifndef __TRACYD3D11_HPP__ #define __TRACYD3D11_HPP__ #ifndef TRACY_ENABLE #define TracyD3D11Context(device,queue) nullptr #define TracyD3D11Destroy(ctx) #define TracyD3D11ContextName(ctx, name, size) #define TracyD3D11NewFrame(ctx) #define TracyD3D11Zone(ctx, name) #define TracyD3D11ZoneC(ctx, name, color) #define TracyD3D11NamedZone(ctx, varname, name, active) #define TracyD3D11NamedZoneC(ctx, varname, name, color, active) #define TracyD3D12ZoneTransient(ctx, varname, name, active) #define TracyD3D11ZoneS(ctx, name, depth) #define TracyD3D11ZoneCS(ctx, name, color, depth) #define TracyD3D11NamedZoneS(ctx, varname, name, depth, active) #define TracyD3D11NamedZoneCS(ctx, varname, name, color, depth, active) #define TracyD3D12ZoneTransientS(ctx, varname, name, depth, active) #define TracyD3D11Collect(ctx) namespace tracy { class D3D11ZoneScope {}; } using TracyD3D11Ctx = void*; #else #include <atomic> #include <assert.h> #include <stdlib.h> #include "Tracy.hpp" #include "client/TracyProfiler.hpp" #include "client/TracyCallstack.hpp" #include "common/TracyAlign.hpp" #include "common/TracyAlloc.hpp" namespace tracy { class D3D11Ctx { friend class D3D11ZoneScope; enum { QueryCount = 64 * 1024 }; public: D3D11Ctx( ID3D11Device* device, ID3D11DeviceContext* devicectx ) : m_device( device ) , m_devicectx( devicectx ) , m_context( GetGpuCtxCounter().fetch_add( 1, std::memory_order_relaxed ) ) , m_head( 0 ) , m_tail( 0 ) { assert( m_context != 255 ); for (int i = 0; i < QueryCount; i++) { HRESULT hr = S_OK; D3D11_QUERY_DESC desc; desc.MiscFlags = 0; desc.Query = D3D11_QUERY_TIMESTAMP; hr |= device->CreateQuery(&desc, &m_queries[i]); desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT; hr |= device->CreateQuery(&desc, &m_disjoints[i]); m_disjointMap[i] = nullptr; assert(SUCCEEDED(hr)); } // Force query the initial GPU timestamp (pipeline stall) D3D11_QUERY_DATA_TIMESTAMP_DISJOINT disjoint; UINT64 timestamp; for (int attempts = 0; attempts < 50; attempts++) { devicectx->Begin(m_disjoints[0]); devicectx->End(m_queries[0]); devicectx->End(m_disjoints[0]); devicectx->Flush(); while (devicectx->GetData(m_disjoints[0], &disjoint, sizeof(disjoint), 0) == S_FALSE) /* Nothing */; if (disjoint.Disjoint) continue; while (devicectx->GetData(m_queries[0], &timestamp, sizeof(timestamp), 0) == S_FALSE) /* Nothing */; break; } int64_t tgpu = timestamp * (1000000000ull / disjoint.Frequency); int64_t tcpu = Profiler::GetTime(); uint8_t flags = 0; const float period = 1.f; auto* item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuNewContext ); MemWrite( &item->gpuNewContext.cpuTime, tcpu ); MemWrite( &item->gpuNewContext.gpuTime, tgpu ); memset(&item->gpuNewContext.thread, 0, sizeof(item->gpuNewContext.thread)); MemWrite( &item->gpuNewContext.period, period ); MemWrite( &item->gpuNewContext.context, m_context ); MemWrite( &item->gpuNewContext.flags, flags ); MemWrite( &item->gpuNewContext.type, GpuContextType::Direct3D11 ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); } ~D3D11Ctx() { for (int i = 0; i < QueryCount; i++) { m_queries[i]->Release(); m_disjoints[i]->Release(); m_disjointMap[i] = nullptr; } } void Name( const char* name, uint16_t len ) { auto ptr = (char*)tracy_malloc( len ); memcpy( ptr, name, len ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuContextName ); MemWrite( &item->gpuContextNameFat.context, m_context ); MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr ); MemWrite( &item->gpuContextNameFat.size, len ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); } void Collect() { ZoneScopedC( Color::Red4 ); if( m_tail == m_head ) return; #ifdef TRACY_ON_DEMAND if( !GetProfiler().IsConnected() ) { m_head = m_tail = 0; return; } #endif auto start = m_tail; auto end = m_head + QueryCount; auto cnt = (end - start) % QueryCount; while (cnt > 1) { auto mid = start + cnt / 2; bool available = m_devicectx->GetData(m_disjointMap[mid % QueryCount], nullptr, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK && m_devicectx->GetData(m_queries[mid % QueryCount], nullptr, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH) == S_OK; if (available) { start = mid; } else { end = mid; } cnt = (end - start) % QueryCount; } start %= QueryCount; while (m_tail != start) { D3D11_QUERY_DATA_TIMESTAMP_DISJOINT disjoint; UINT64 time; m_devicectx->GetData(m_disjointMap[m_tail], &disjoint, sizeof(disjoint), 0); m_devicectx->GetData(m_queries[m_tail], &time, sizeof(time), 0); time *= (1000000000ull / disjoint.Frequency); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuTime); MemWrite(&item->gpuTime.gpuTime, (int64_t)time); MemWrite(&item->gpuTime.queryId, (uint16_t)m_tail); MemWrite(&item->gpuTime.context, m_context); Profiler::QueueSerialFinish(); m_tail = (m_tail + 1) % QueryCount; } } private: tracy_force_inline unsigned int NextQueryId() { const auto id = m_head; m_head = ( m_head + 1 ) % QueryCount; assert( m_head != m_tail ); return id; } tracy_force_inline ID3D11Query* TranslateQueryId( unsigned int id ) { return m_queries[id]; } tracy_force_inline ID3D11Query* MapDisjointQueryId( unsigned int id, unsigned int disjointId ) { m_disjointMap[id] = m_disjoints[disjointId]; return m_disjoints[disjointId]; } tracy_force_inline uint8_t GetId() const { return m_context; } ID3D11Device* m_device; ID3D11DeviceContext* m_devicectx; ID3D11Query* m_queries[QueryCount]; ID3D11Query* m_disjoints[QueryCount]; ID3D11Query* m_disjointMap[QueryCount]; // Multiple time queries can have one disjoint query uint8_t m_context; unsigned int m_head; unsigned int m_tail; }; class D3D11ZoneScope { public: tracy_force_inline D3D11ZoneScope( D3D11Ctx* ctx, const SourceLocationData* srcloc, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); ctx->m_devicectx->Begin(ctx->MapDisjointQueryId(queryId, queryId)); ctx->m_devicectx->End(ctx->TranslateQueryId(queryId)); m_disjointId = queryId; auto* item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); } tracy_force_inline D3D11ZoneScope( D3D11Ctx* ctx, const SourceLocationData* srcloc, int depth, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); ctx->m_devicectx->Begin(ctx->MapDisjointQueryId(queryId, queryId)); ctx->m_devicectx->End(ctx->TranslateQueryId(queryId)); m_disjointId = queryId; auto* item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginCallstackSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); GetProfiler().SendCallstack( depth ); } tracy_force_inline D3D11ZoneScope(D3D11Ctx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, bool active) #ifdef TRACY_ON_DEMAND : m_active(active&& GetProfiler().IsConnected()) #else : m_active(active) #endif { if( !m_active ) return; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); ctx->m_devicectx->Begin(ctx->MapDisjointQueryId(queryId, queryId)); ctx->m_devicectx->End(ctx->TranslateQueryId(queryId)); m_disjointId = queryId; const auto sourceLocation = Profiler::AllocSourceLocation(line, source, sourceSz, function, functionSz, name, nameSz); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, sourceLocation); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline D3D11ZoneScope(D3D11Ctx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, int depth, bool active) #ifdef TRACY_ON_DEMAND : m_active(active&& GetProfiler().IsConnected()) #else : m_active(active) #endif { if( !m_active ) return; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); ctx->m_devicectx->Begin(ctx->MapDisjointQueryId(queryId, queryId)); ctx->m_devicectx->End(ctx->TranslateQueryId(queryId)); m_disjointId = queryId; const auto sourceLocation = Profiler::AllocSourceLocation(line, source, sourceSz, function, functionSz, name, nameSz); auto* item = Profiler::QueueSerialCallstack(Callstack(depth)); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocCallstackSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, sourceLocation); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline ~D3D11ZoneScope() { if( !m_active ) return; const auto queryId = m_ctx->NextQueryId(); m_ctx->m_devicectx->End(m_ctx->TranslateQueryId(queryId)); m_ctx->m_devicectx->End(m_ctx->MapDisjointQueryId(queryId, m_disjointId)); auto* item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneEndSerial ); MemWrite( &item->gpuZoneEnd.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneEnd.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneEnd.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneEnd.context, m_ctx->GetId() ); Profiler::QueueSerialFinish(); } private: const bool m_active; D3D11Ctx* m_ctx; unsigned int m_disjointId; }; static inline D3D11Ctx* CreateD3D11Context( ID3D11Device* device, ID3D11DeviceContext* devicectx ) { auto ctx = (D3D11Ctx*)tracy_malloc( sizeof( D3D11Ctx ) ); new(ctx) D3D11Ctx( device, devicectx ); return ctx; } static inline void DestroyD3D11Context( D3D11Ctx* ctx ) { ctx->~D3D11Ctx(); tracy_free( ctx ); } } using TracyD3D11Ctx = tracy::D3D11Ctx*; #define TracyD3D11Context( device, devicectx ) tracy::CreateD3D11Context( device, devicectx ); #define TracyD3D11Destroy(ctx) tracy::DestroyD3D11Context(ctx); #define TracyD3D11ContextName(ctx, name, size) ctx->Name(name, size); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyD3D11Zone( ctx, name ) TracyD3D11NamedZoneS( ctx, ___tracy_gpu_zone, name, TRACY_CALLSTACK, true ) # define TracyD3D11ZoneC( ctx, name, color ) TracyD3D11NamedZoneCS( ctx, ___tracy_gpu_zone, name, color, TRACY_CALLSTACK, true ) # define TracyD3D11NamedZone( ctx, varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyD3D11NamedZoneC( ctx, varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyD3D11ZoneTransient(ctx, varname, name, active) TracyD3D11ZoneTransientS(ctx, varname, cmdList, name, TRACY_CALLSTACK, active) #else # define TracyD3D11Zone( ctx, name ) TracyD3D11NamedZone( ctx, ___tracy_gpu_zone, name, true ) # define TracyD3D11ZoneC( ctx, name, color ) TracyD3D11NamedZoneC( ctx, ___tracy_gpu_zone, name, color, true ) # define TracyD3D11NamedZone( ctx, varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), active ); # define TracyD3D11NamedZoneC( ctx, varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), active ); # define TracyD3D11ZoneTransient(ctx, varname, name, active) tracy::D3D11ZoneScope varname{ ctx, __LINE__, __FILE__, strlen(__FILE__), __FUNCTION__, strlen(__FUNCTION__), name, strlen(name), active }; #endif #ifdef TRACY_HAS_CALLSTACK # define TracyD3D11ZoneS( ctx, name, depth ) TracyD3D11NamedZoneS( ctx, ___tracy_gpu_zone, name, depth, true ) # define TracyD3D11ZoneCS( ctx, name, color, depth ) TracyD3D11NamedZoneCS( ctx, ___tracy_gpu_zone, name, color, depth, true ) # define TracyD3D11NamedZoneS( ctx, varname, name, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active ); # define TracyD3D11NamedZoneCS( ctx, varname, name, color, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D11ZoneScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active ); # define TracyD3D11ZoneTransientS(ctx, varname, name, depth, active) tracy::D3D11ZoneScope varname{ ctx, __LINE__, __FILE__, strlen(__FILE__), __FUNCTION__, strlen(__FUNCTION__), name, strlen(name), depth, active }; #else # define TracyD3D11ZoneS( ctx, name, depth, active ) TracyD3D11Zone( ctx, name ) # define TracyD3D11ZoneCS( ctx, name, color, depth, active ) TracyD3D11ZoneC( name, color ) # define TracyD3D11NamedZoneS( ctx, varname, name, depth, active ) TracyD3D11NamedZone( ctx, varname, name, active ) # define TracyD3D11NamedZoneCS( ctx, varname, name, color, depth, active ) TracyD3D11NamedZoneC( ctx, varname, name, color, active ) # define TracyD3D11ZoneTransientS(ctx, varname, name, depth, active) TracyD3D12ZoneTransient(ctx, varname, name, active) #endif #define TracyD3D11Collect( ctx ) ctx->Collect(); #endif #endif
whupdup/frame
real/third_party/tracy/TracyD3D11.hpp
C++
gpl-3.0
16,965
#ifndef __TRACYD3D12_HPP__ #define __TRACYD3D12_HPP__ #ifndef TRACY_ENABLE #define TracyD3D12Context(device, queue) nullptr #define TracyD3D12Destroy(ctx) #define TracyD3D12ContextName(ctx, name, size) #define TracyD3D12NewFrame(ctx) #define TracyD3D12Zone(ctx, cmdList, name) #define TracyD3D12ZoneC(ctx, cmdList, name, color) #define TracyD3D12NamedZone(ctx, varname, cmdList, name, active) #define TracyD3D12NamedZoneC(ctx, varname, cmdList, name, color, active) #define TracyD3D12ZoneTransient(ctx, varname, cmdList, name, active) #define TracyD3D12ZoneS(ctx, cmdList, name, depth) #define TracyD3D12ZoneCS(ctx, cmdList, name, color, depth) #define TracyD3D12NamedZoneS(ctx, varname, cmdList, name, depth, active) #define TracyD3D12NamedZoneCS(ctx, varname, cmdList, name, color, depth, active) #define TracyD3D12ZoneTransientS(ctx, varname, cmdList, name, depth, active) #define TracyD3D12Collect(ctx) namespace tracy { class D3D12ZoneScope {}; } using TracyD3D12Ctx = void*; #else #include "Tracy.hpp" #include "client/TracyProfiler.hpp" #include "client/TracyCallstack.hpp" #include <cstdlib> #include <cassert> #include <d3d12.h> #include <dxgi.h> #include <wrl/client.h> #include <queue> namespace tracy { struct D3D12QueryPayload { uint32_t m_queryIdStart = 0; uint32_t m_queryCount = 0; }; // Command queue context. class D3D12QueueCtx { friend class D3D12ZoneScope; static constexpr uint32_t MaxQueries = 64 * 1024; // Queries are begin and end markers, so we can store half as many total time durations. Must be even! bool m_initialized = false; ID3D12Device* m_device = nullptr; ID3D12CommandQueue* m_queue = nullptr; uint8_t m_context; Microsoft::WRL::ComPtr<ID3D12QueryHeap> m_queryHeap; Microsoft::WRL::ComPtr<ID3D12Resource> m_readbackBuffer; // In-progress payload. uint32_t m_queryLimit = MaxQueries; uint32_t m_queryCounter = 0; uint32_t m_previousQueryCounter = 0; uint32_t m_activePayload = 0; Microsoft::WRL::ComPtr<ID3D12Fence> m_payloadFence; std::queue<D3D12QueryPayload> m_payloadQueue; int64_t m_prevCalibration = 0; int64_t m_qpcToNs = int64_t{ 1000000000 / GetFrequencyQpc() }; public: D3D12QueueCtx(ID3D12Device* device, ID3D12CommandQueue* queue) : m_device(device) , m_queue(queue) , m_context(GetGpuCtxCounter().fetch_add(1, std::memory_order_relaxed)) { // Verify we support timestamp queries on this queue. if (queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_COPY) { D3D12_FEATURE_DATA_D3D12_OPTIONS3 featureData{}; bool Success = SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS3, &featureData, sizeof(featureData))); assert(Success && featureData.CopyQueueTimestampQueriesSupported && "Platform does not support profiling of copy queues."); } uint64_t timestampFrequency; if (FAILED(queue->GetTimestampFrequency(&timestampFrequency))) { assert(false && "Failed to get timestamp frequency."); } uint64_t cpuTimestamp; uint64_t gpuTimestamp; if (FAILED(queue->GetClockCalibration(&gpuTimestamp, &cpuTimestamp))) { assert(false && "Failed to get queue clock calibration."); } // Save the device cpu timestamp, not the profiler's timestamp. m_prevCalibration = cpuTimestamp * m_qpcToNs; cpuTimestamp = Profiler::GetTime(); D3D12_QUERY_HEAP_DESC heapDesc{}; heapDesc.Type = queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_COPY ? D3D12_QUERY_HEAP_TYPE_COPY_QUEUE_TIMESTAMP : D3D12_QUERY_HEAP_TYPE_TIMESTAMP; heapDesc.Count = m_queryLimit; heapDesc.NodeMask = 0; // #TODO: Support multiple adapters. while (FAILED(device->CreateQueryHeap(&heapDesc, IID_PPV_ARGS(&m_queryHeap)))) { m_queryLimit /= 2; heapDesc.Count = m_queryLimit; } // Create a readback buffer, which will be used as a destination for the query data. D3D12_RESOURCE_DESC readbackBufferDesc{}; readbackBufferDesc.Alignment = 0; readbackBufferDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; readbackBufferDesc.Width = m_queryLimit * sizeof(uint64_t); readbackBufferDesc.Height = 1; readbackBufferDesc.DepthOrArraySize = 1; readbackBufferDesc.Format = DXGI_FORMAT_UNKNOWN; readbackBufferDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; // Buffers are always row major. readbackBufferDesc.MipLevels = 1; readbackBufferDesc.SampleDesc.Count = 1; readbackBufferDesc.SampleDesc.Quality = 0; readbackBufferDesc.Flags = D3D12_RESOURCE_FLAG_NONE; D3D12_HEAP_PROPERTIES readbackHeapProps{}; readbackHeapProps.Type = D3D12_HEAP_TYPE_READBACK; readbackHeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; readbackHeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; readbackHeapProps.CreationNodeMask = 0; readbackHeapProps.VisibleNodeMask = 0; // #TODO: Support multiple adapters. if (FAILED(device->CreateCommittedResource(&readbackHeapProps, D3D12_HEAP_FLAG_NONE, &readbackBufferDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&m_readbackBuffer)))) { assert(false && "Failed to create query readback buffer."); } if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_payloadFence)))) { assert(false && "Failed to create payload fence."); } auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuNewContext); MemWrite(&item->gpuNewContext.cpuTime, cpuTimestamp); MemWrite(&item->gpuNewContext.gpuTime, gpuTimestamp); memset(&item->gpuNewContext.thread, 0, sizeof(item->gpuNewContext.thread)); MemWrite(&item->gpuNewContext.period, 1E+09f / static_cast<float>(timestampFrequency)); MemWrite(&item->gpuNewContext.context, m_context); MemWrite(&item->gpuNewContext.flags, GpuContextCalibration); MemWrite(&item->gpuNewContext.type, GpuContextType::Direct3D12); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem(*item); #endif Profiler::QueueSerialFinish(); m_initialized = true; } void NewFrame() { m_payloadQueue.emplace(D3D12QueryPayload{ m_previousQueryCounter, m_queryCounter }); m_previousQueryCounter += m_queryCounter; m_queryCounter = 0; if (m_previousQueryCounter >= m_queryLimit) { m_previousQueryCounter -= m_queryLimit; } m_queue->Signal(m_payloadFence.Get(), ++m_activePayload); } void Name( const char* name, uint16_t len ) { auto ptr = (char*)tracy_malloc( len ); memcpy( ptr, name, len ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuContextName ); MemWrite( &item->gpuContextNameFat.context, m_context ); MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr ); MemWrite( &item->gpuContextNameFat.size, len ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); } void Collect() { ZoneScopedC(Color::Red4); #ifdef TRACY_ON_DEMAND if (!GetProfiler().IsConnected()) { m_queryCounter = 0; return; } #endif // Find out what payloads are available. const auto newestReadyPayload = m_payloadFence->GetCompletedValue(); const auto payloadCount = m_payloadQueue.size() - (m_activePayload - newestReadyPayload); if (!payloadCount) { return; // No payloads are available yet, exit out. } D3D12_RANGE mapRange{ 0, m_queryLimit * sizeof(uint64_t) }; // Map the readback buffer so we can fetch the query data from the GPU. void* readbackBufferMapping = nullptr; if (FAILED(m_readbackBuffer->Map(0, &mapRange, &readbackBufferMapping))) { assert(false && "Failed to map readback buffer."); } auto* timestampData = static_cast<uint64_t*>(readbackBufferMapping); for (uint32_t i = 0; i < payloadCount; ++i) { const auto& payload = m_payloadQueue.front(); for (uint32_t j = 0; j < payload.m_queryCount; ++j) { const auto counter = (payload.m_queryIdStart + j) % m_queryLimit; const auto timestamp = timestampData[counter]; const auto queryId = counter; auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuTime); MemWrite(&item->gpuTime.gpuTime, timestamp); MemWrite(&item->gpuTime.queryId, static_cast<uint16_t>(queryId)); MemWrite(&item->gpuTime.context, m_context); Profiler::QueueSerialFinish(); } m_payloadQueue.pop(); } m_readbackBuffer->Unmap(0, nullptr); // Recalibrate to account for drift. uint64_t cpuTimestamp; uint64_t gpuTimestamp; if (FAILED(m_queue->GetClockCalibration(&gpuTimestamp, &cpuTimestamp))) { assert(false && "Failed to get queue clock calibration."); } cpuTimestamp *= m_qpcToNs; const auto cpuDelta = cpuTimestamp - m_prevCalibration; if (cpuDelta > 0) { m_prevCalibration = cpuTimestamp; cpuTimestamp = Profiler::GetTime(); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuCalibration); MemWrite(&item->gpuCalibration.gpuTime, gpuTimestamp); MemWrite(&item->gpuCalibration.cpuTime, cpuTimestamp); MemWrite(&item->gpuCalibration.cpuDelta, cpuDelta); MemWrite(&item->gpuCalibration.context, m_context); Profiler::QueueSerialFinish(); } } private: tracy_force_inline uint32_t NextQueryId() { assert(m_queryCounter < m_queryLimit && "Submitted too many GPU queries! Consider increasing MaxQueries."); const uint32_t id = (m_previousQueryCounter + m_queryCounter) % m_queryLimit; m_queryCounter += 2; // Allocate space for a begin and end query. return id; } tracy_force_inline uint8_t GetId() const { return m_context; } }; class D3D12ZoneScope { const bool m_active; D3D12QueueCtx* m_ctx = nullptr; ID3D12GraphicsCommandList* m_cmdList = nullptr; uint32_t m_queryId = 0; // Used for tracking in nested zones. public: tracy_force_inline D3D12ZoneScope(D3D12QueueCtx* ctx, ID3D12GraphicsCommandList* cmdList, const SourceLocationData* srcLocation, bool active) #ifdef TRACY_ON_DEMAND : m_active(active && GetProfiler().IsConnected()) #else : m_active(active) #endif { if (!m_active) return; m_ctx = ctx; m_cmdList = cmdList; m_queryId = ctx->NextQueryId(); cmdList->EndQuery(ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, m_queryId); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, reinterpret_cast<uint64_t>(srcLocation)); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(m_queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline D3D12ZoneScope(D3D12QueueCtx* ctx, ID3D12GraphicsCommandList* cmdList, const SourceLocationData* srcLocation, int depth, bool active) #ifdef TRACY_ON_DEMAND : m_active(active&& GetProfiler().IsConnected()) #else : m_active(active) #endif { if (!m_active) return; m_ctx = ctx; m_cmdList = cmdList; m_queryId = ctx->NextQueryId(); cmdList->EndQuery(ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, m_queryId); auto* item = Profiler::QueueSerialCallstack(Callstack(depth)); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginCallstackSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, reinterpret_cast<uint64_t>(srcLocation)); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(m_queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline D3D12ZoneScope(D3D12QueueCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, ID3D12GraphicsCommandList* cmdList, bool active) #ifdef TRACY_ON_DEMAND : m_active(active&& GetProfiler().IsConnected()) #else : m_active(active) #endif { if (!m_active) return; m_ctx = ctx; m_cmdList = cmdList; m_queryId = ctx->NextQueryId(); cmdList->EndQuery(ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, m_queryId); const auto sourceLocation = Profiler::AllocSourceLocation(line, source, sourceSz, function, functionSz, name, nameSz); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, sourceLocation); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(m_queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline D3D12ZoneScope(D3D12QueueCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, ID3D12GraphicsCommandList* cmdList, int depth, bool active) #ifdef TRACY_ON_DEMAND : m_active(active&& GetProfiler().IsConnected()) #else : m_active(active) #endif { if (!m_active) return; m_ctx = ctx; m_cmdList = cmdList; m_queryId = ctx->NextQueryId(); cmdList->EndQuery(ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, m_queryId); const auto sourceLocation = Profiler::AllocSourceLocation(line, source, sourceSz, function, functionSz, name, nameSz); auto* item = Profiler::QueueSerialCallstack(Callstack(depth)); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocCallstackSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, sourceLocation); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, static_cast<uint16_t>(m_queryId)); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline ~D3D12ZoneScope() { if (!m_active) return; const auto queryId = m_queryId + 1; // Our end query slot is immediately after the begin slot. m_cmdList->EndQuery(m_ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, queryId); auto* item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneEndSerial); MemWrite(&item->gpuZoneEnd.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneEnd.thread, GetThreadHandle()); MemWrite(&item->gpuZoneEnd.queryId, static_cast<uint16_t>(queryId)); MemWrite(&item->gpuZoneEnd.context, m_ctx->GetId()); Profiler::QueueSerialFinish(); m_cmdList->ResolveQueryData(m_ctx->m_queryHeap.Get(), D3D12_QUERY_TYPE_TIMESTAMP, m_queryId, 2, m_ctx->m_readbackBuffer.Get(), m_queryId * sizeof(uint64_t)); } }; static inline D3D12QueueCtx* CreateD3D12Context(ID3D12Device* device, ID3D12CommandQueue* queue) { auto* ctx = static_cast<D3D12QueueCtx*>(tracy_malloc(sizeof(D3D12QueueCtx))); new (ctx) D3D12QueueCtx{ device, queue }; return ctx; } static inline void DestroyD3D12Context(D3D12QueueCtx* ctx) { ctx->~D3D12QueueCtx(); tracy_free(ctx); } } using TracyD3D12Ctx = tracy::D3D12QueueCtx*; #define TracyD3D12Context(device, queue) tracy::CreateD3D12Context(device, queue); #define TracyD3D12Destroy(ctx) tracy::DestroyD3D12Context(ctx); #define TracyD3D12ContextName(ctx, name, size) ctx->Name(name, size); #define TracyD3D12NewFrame(ctx) ctx->NewFrame(); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyD3D12Zone(ctx, cmdList, name) TracyD3D12NamedZoneS(ctx, ___tracy_gpu_zone, cmdList, name, TRACY_CALLSTACK, true) # define TracyD3D12ZoneC(ctx, cmdList, name, color) TracyD3D12NamedZoneCS(ctx, ___tracy_gpu_zone, cmdList, name, color, TRACY_CALLSTACK, true) # define TracyD3D12NamedZone(ctx, varname, cmdList, name, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), TRACY_CALLSTACK, active }; # define TracyD3D12NamedZoneC(ctx, varname, cmdList, name, color, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), TRACY_CALLSTACK, active }; # define TracyD3D12ZoneTransient(ctx, varname, cmdList, name, active) TracyD3D12ZoneTransientS(ctx, varname, cmdList, name, TRACY_CALLSTACK, active) #else # define TracyD3D12Zone(ctx, cmdList, name) TracyD3D12NamedZone(ctx, ___tracy_gpu_zone, cmdList, name, true) # define TracyD3D12ZoneC(ctx, cmdList, name, color) TracyD3D12NamedZoneC(ctx, ___tracy_gpu_zone, cmdList, name, color, true) # define TracyD3D12NamedZone(ctx, varname, cmdList, name, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), active }; # define TracyD3D12NamedZoneC(ctx, varname, cmdList, name, color, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), active }; # define TracyD3D12ZoneTransient(ctx, varname, cmdList, name, active) tracy::D3D12ZoneScope varname{ ctx, __LINE__, __FILE__, strlen(__FILE__), __FUNCTION__, strlen(__FUNCTION__), name, strlen(name), cmdList, active }; #endif #ifdef TRACY_HAS_CALLSTACK # define TracyD3D12ZoneS(ctx, cmdList, name, depth) TracyD3D12NamedZoneS(ctx, ___tracy_gpu_zone, cmdList, name, depth, true) # define TracyD3D12ZoneCS(ctx, cmdList, name, color, depth) TracyD3D12NamedZoneCS(ctx, ___tracy_gpu_zone, cmdList, name, color, depth, true) # define TracyD3D12NamedZoneS(ctx, varname, cmdList, name, depth, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), depth, active }; # define TracyD3D12NamedZoneCS(ctx, varname, cmdList, name, color, depth, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location, __LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::D3D12ZoneScope varname{ ctx, cmdList, &TracyConcat(__tracy_gpu_source_location, __LINE__), depth, active }; # define TracyD3D12ZoneTransientS(ctx, varname, cmdList, name, depth, active) tracy::D3D12ZoneScope varname{ ctx, __LINE__, __FILE__, strlen(__FILE__), __FUNCTION__, strlen(__FUNCTION__), name, strlen(name), cmdList, depth, active }; #else # define TracyD3D12ZoneS(ctx, cmdList, name, depth) TracyD3D12Zone(ctx, cmdList, name) # define TracyD3D12ZoneCS(ctx, cmdList, name, color, depth) TracyD3D12Zone(ctx, cmdList, name, color) # define TracyD3D12NamedZoneS(ctx, varname, cmdList, name, depth, active) TracyD3D12NamedZone(ctx, varname, cmdList, name, active) # define TracyD3D12NamedZoneCS(ctx, varname, cmdList, name, color, depth, active) TracyD3D12NamedZoneC(ctx, varname, cmdList, name, color, active) # define TracyD3D12ZoneTransientS(ctx, varname, cmdList, name, depth, active) TracyD3D12ZoneTransient(ctx, varname, cmdList, name, active) #endif #define TracyD3D12Collect(ctx) ctx->Collect(); #endif #endif
whupdup/frame
real/third_party/tracy/TracyD3D12.hpp
C++
gpl-3.0
19,720
#ifndef __TRACYLUA_HPP__ #define __TRACYLUA_HPP__ // Include this file after you include lua headers. #ifndef TRACY_ENABLE #include <string.h> namespace tracy { namespace detail { static inline int noop( lua_State* L ) { return 0; } } static inline void LuaRegister( lua_State* L ) { lua_newtable( L ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneBegin" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneBeginN" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneBeginS" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneBeginNS" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneEnd" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneText" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "ZoneName" ); lua_pushcfunction( L, detail::noop ); lua_setfield( L, -2, "Message" ); lua_setglobal( L, "tracy" ); } static inline char* FindEnd( char* ptr ) { unsigned int cnt = 1; while( cnt != 0 ) { if( *ptr == '(' ) cnt++; else if( *ptr == ')' ) cnt--; ptr++; } return ptr; } static inline void LuaRemove( char* script ) { while( *script ) { if( strncmp( script, "tracy.", 6 ) == 0 ) { if( strncmp( script + 6, "Zone", 4 ) == 0 ) { if( strncmp( script + 10, "End()", 5 ) == 0 ) { memset( script, ' ', 15 ); script += 15; } else if( strncmp( script + 10, "Begin()", 7 ) == 0 ) { memset( script, ' ', 17 ); script += 17; } else if( strncmp( script + 10, "Text(", 5 ) == 0 ) { auto end = FindEnd( script + 15 ); memset( script, ' ', end - script ); script = end; } else if( strncmp( script + 10, "Name(", 5 ) == 0 ) { auto end = FindEnd( script + 15 ); memset( script, ' ', end - script ); script = end; } else if( strncmp( script + 10, "BeginN(", 7 ) == 0 ) { auto end = FindEnd( script + 17 ); memset( script, ' ', end - script ); script = end; } else if( strncmp( script + 10, "BeginS(", 7 ) == 0 ) { auto end = FindEnd( script + 17 ); memset( script, ' ', end - script ); script = end; } else if( strncmp( script + 10, "BeginNS(", 8 ) == 0 ) { auto end = FindEnd( script + 18 ); memset( script, ' ', end - script ); script = end; } else { script += 10; } } else if( strncmp( script + 6, "Message(", 8 ) == 0 ) { auto end = FindEnd( script + 14 ); memset( script, ' ', end - script ); script = end; } else { script += 6; } } else { script++; } } } } #else #include <assert.h> #include <limits> #include "common/TracyColor.hpp" #include "common/TracyAlign.hpp" #include "common/TracyForceInline.hpp" #include "common/TracySystem.hpp" #include "client/TracyProfiler.hpp" namespace tracy { #ifdef TRACY_ON_DEMAND TRACY_API LuaZoneState& GetLuaZoneState(); #endif namespace detail { #ifdef TRACY_HAS_CALLSTACK static tracy_force_inline void SendLuaCallstack( lua_State* L, uint32_t depth ) { assert( depth <= 64 ); lua_Debug dbg[64]; const char* func[64]; uint32_t fsz[64]; uint32_t ssz[64]; uint8_t cnt; uint16_t spaceNeeded = sizeof( cnt ); for( cnt=0; cnt<depth; cnt++ ) { if( lua_getstack( L, cnt+1, dbg+cnt ) == 0 ) break; lua_getinfo( L, "Snl", dbg+cnt ); func[cnt] = dbg[cnt].name ? dbg[cnt].name : dbg[cnt].short_src; fsz[cnt] = uint32_t( strlen( func[cnt] ) ); ssz[cnt] = uint32_t( strlen( dbg[cnt].source ) ); spaceNeeded += fsz[cnt] + ssz[cnt]; } spaceNeeded += cnt * ( 4 + 2 + 2 ); // source line, function string length, source string length auto ptr = (char*)tracy_malloc( spaceNeeded + 2 ); auto dst = ptr; memcpy( dst, &spaceNeeded, 2 ); dst += 2; memcpy( dst, &cnt, 1 ); dst++; for( uint8_t i=0; i<cnt; i++ ) { const uint32_t line = dbg[i].currentline; memcpy( dst, &line, 4 ); dst += 4; assert( fsz[i] <= std::numeric_limits<uint16_t>::max() ); memcpy( dst, fsz+i, 2 ); dst += 2; memcpy( dst, func[i], fsz[i] ); dst += fsz[i]; assert( ssz[i] <= std::numeric_limits<uint16_t>::max() ); memcpy( dst, ssz+i, 2 ); dst += 2; memcpy( dst, dbg[i].source, ssz[i] ), dst += ssz[i]; } assert( dst - ptr == spaceNeeded + 2 ); TracyQueuePrepare( QueueType::CallstackAlloc ); MemWrite( &item->callstackAllocFat.ptr, (uint64_t)ptr ); MemWrite( &item->callstackAllocFat.nativePtr, (uint64_t)Callstack( depth ) ); TracyQueueCommit( callstackAllocFatThread ); } static inline int LuaZoneBeginS( lua_State* L ) { #ifdef TRACY_ON_DEMAND const auto zoneCnt = GetLuaZoneState().counter++; if( zoneCnt != 0 && !GetLuaZoneState().active ) return 0; GetLuaZoneState().active = GetProfiler().IsConnected(); if( !GetLuaZoneState().active ) return 0; #endif #ifdef TRACY_CALLSTACK const uint32_t depth = TRACY_CALLSTACK; #else const auto depth = uint32_t( lua_tointeger( L, 1 ) ); #endif SendLuaCallstack( L, depth ); lua_Debug dbg; lua_getstack( L, 1, &dbg ); lua_getinfo( L, "Snl", &dbg ); const auto srcloc = Profiler::AllocSourceLocation( dbg.currentline, dbg.source, dbg.name ? dbg.name : dbg.short_src ); TracyQueuePrepare( QueueType::ZoneBeginAllocSrcLocCallstack ); MemWrite( &item->zoneBegin.time, Profiler::GetTime() ); MemWrite( &item->zoneBegin.srcloc, srcloc ); TracyQueueCommit( zoneBeginThread ); return 0; } static inline int LuaZoneBeginNS( lua_State* L ) { #ifdef TRACY_ON_DEMAND const auto zoneCnt = GetLuaZoneState().counter++; if( zoneCnt != 0 && !GetLuaZoneState().active ) return 0; GetLuaZoneState().active = GetProfiler().IsConnected(); if( !GetLuaZoneState().active ) return 0; #endif #ifdef TRACY_CALLSTACK const uint32_t depth = TRACY_CALLSTACK; #else const auto depth = uint32_t( lua_tointeger( L, 2 ) ); #endif SendLuaCallstack( L, depth ); lua_Debug dbg; lua_getstack( L, 1, &dbg ); lua_getinfo( L, "Snl", &dbg ); size_t nsz; const auto name = lua_tolstring( L, 1, &nsz ); const auto srcloc = Profiler::AllocSourceLocation( dbg.currentline, dbg.source, dbg.name ? dbg.name : dbg.short_src, name, nsz ); TracyQueuePrepare( QueueType::ZoneBeginAllocSrcLocCallstack ); MemWrite( &item->zoneBegin.time, Profiler::GetTime() ); MemWrite( &item->zoneBegin.srcloc, srcloc ); TracyQueueCommit( zoneBeginThread ); return 0; } #endif static inline int LuaZoneBegin( lua_State* L ) { #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK return LuaZoneBeginS( L ); #else #ifdef TRACY_ON_DEMAND const auto zoneCnt = GetLuaZoneState().counter++; if( zoneCnt != 0 && !GetLuaZoneState().active ) return 0; GetLuaZoneState().active = GetProfiler().IsConnected(); if( !GetLuaZoneState().active ) return 0; #endif lua_Debug dbg; lua_getstack( L, 1, &dbg ); lua_getinfo( L, "Snl", &dbg ); const auto srcloc = Profiler::AllocSourceLocation( dbg.currentline, dbg.source, dbg.name ? dbg.name : dbg.short_src ); TracyQueuePrepare( QueueType::ZoneBeginAllocSrcLoc ); MemWrite( &item->zoneBegin.time, Profiler::GetTime() ); MemWrite( &item->zoneBegin.srcloc, srcloc ); TracyQueueCommit( zoneBeginThread ); return 0; #endif } static inline int LuaZoneBeginN( lua_State* L ) { #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK return LuaZoneBeginNS( L ); #else #ifdef TRACY_ON_DEMAND const auto zoneCnt = GetLuaZoneState().counter++; if( zoneCnt != 0 && !GetLuaZoneState().active ) return 0; GetLuaZoneState().active = GetProfiler().IsConnected(); if( !GetLuaZoneState().active ) return 0; #endif lua_Debug dbg; lua_getstack( L, 1, &dbg ); lua_getinfo( L, "Snl", &dbg ); size_t nsz; const auto name = lua_tolstring( L, 1, &nsz ); const auto srcloc = Profiler::AllocSourceLocation( dbg.currentline, dbg.source, dbg.name ? dbg.name : dbg.short_src, name, nsz ); TracyQueuePrepare( QueueType::ZoneBeginAllocSrcLoc ); MemWrite( &item->zoneBegin.time, Profiler::GetTime() ); MemWrite( &item->zoneBegin.srcloc, srcloc ); TracyQueueCommit( zoneBeginThread ); return 0; #endif } static inline int LuaZoneEnd( lua_State* L ) { #ifdef TRACY_ON_DEMAND assert( GetLuaZoneState().counter != 0 ); GetLuaZoneState().counter--; if( !GetLuaZoneState().active ) return 0; if( !GetProfiler().IsConnected() ) { GetLuaZoneState().active = false; return 0; } #endif TracyQueuePrepare( QueueType::ZoneEnd ); MemWrite( &item->zoneEnd.time, Profiler::GetTime() ); TracyQueueCommit( zoneEndThread ); return 0; } static inline int LuaZoneText( lua_State* L ) { #ifdef TRACY_ON_DEMAND if( !GetLuaZoneState().active ) return 0; if( !GetProfiler().IsConnected() ) { GetLuaZoneState().active = false; return 0; } #endif auto txt = lua_tostring( L, 1 ); const auto size = strlen( txt ); assert( size < std::numeric_limits<uint16_t>::max() ); auto ptr = (char*)tracy_malloc( size ); memcpy( ptr, txt, size ); TracyQueuePrepare( QueueType::ZoneText ); MemWrite( &item->zoneTextFat.text, (uint64_t)ptr ); MemWrite( &item->zoneTextFat.size, (uint16_t)size ); TracyQueueCommit( zoneTextFatThread ); return 0; } static inline int LuaZoneName( lua_State* L ) { #ifdef TRACY_ON_DEMAND if( !GetLuaZoneState().active ) return 0; if( !GetProfiler().IsConnected() ) { GetLuaZoneState().active = false; return 0; } #endif auto txt = lua_tostring( L, 1 ); const auto size = strlen( txt ); assert( size < std::numeric_limits<uint16_t>::max() ); auto ptr = (char*)tracy_malloc( size ); memcpy( ptr, txt, size ); TracyQueuePrepare( QueueType::ZoneName ); MemWrite( &item->zoneTextFat.text, (uint64_t)ptr ); MemWrite( &item->zoneTextFat.size, (uint16_t)size ); TracyQueueCommit( zoneTextFatThread ); return 0; } static inline int LuaMessage( lua_State* L ) { #ifdef TRACY_ON_DEMAND if( !GetProfiler().IsConnected() ) return 0; #endif auto txt = lua_tostring( L, 1 ); const auto size = strlen( txt ); assert( size < std::numeric_limits<uint16_t>::max() ); auto ptr = (char*)tracy_malloc( size ); memcpy( ptr, txt, size ); TracyQueuePrepare( QueueType::Message ); MemWrite( &item->messageFat.time, Profiler::GetTime() ); MemWrite( &item->messageFat.text, (uint64_t)ptr ); MemWrite( &item->messageFat.size, (uint16_t)size ); TracyQueueCommit( messageFatThread ); return 0; } } static inline void LuaRegister( lua_State* L ) { lua_newtable( L ); lua_pushcfunction( L, detail::LuaZoneBegin ); lua_setfield( L, -2, "ZoneBegin" ); lua_pushcfunction( L, detail::LuaZoneBeginN ); lua_setfield( L, -2, "ZoneBeginN" ); #ifdef TRACY_HAS_CALLSTACK lua_pushcfunction( L, detail::LuaZoneBeginS ); lua_setfield( L, -2, "ZoneBeginS" ); lua_pushcfunction( L, detail::LuaZoneBeginNS ); lua_setfield( L, -2, "ZoneBeginNS" ); #else lua_pushcfunction( L, detail::LuaZoneBegin ); lua_setfield( L, -2, "ZoneBeginS" ); lua_pushcfunction( L, detail::LuaZoneBeginN ); lua_setfield( L, -2, "ZoneBeginNS" ); #endif lua_pushcfunction( L, detail::LuaZoneEnd ); lua_setfield( L, -2, "ZoneEnd" ); lua_pushcfunction( L, detail::LuaZoneText ); lua_setfield( L, -2, "ZoneText" ); lua_pushcfunction( L, detail::LuaZoneName ); lua_setfield( L, -2, "ZoneName" ); lua_pushcfunction( L, detail::LuaMessage ); lua_setfield( L, -2, "Message" ); lua_setglobal( L, "tracy" ); } static inline void LuaRemove( char* script ) {} } #endif #endif
whupdup/frame
real/third_party/tracy/TracyLua.hpp
C++
gpl-3.0
12,761
#ifndef __TRACYOPENCL_HPP__ #define __TRACYOPENCL_HPP__ #if !defined TRACY_ENABLE #define TracyCLContext(c, x) nullptr #define TracyCLDestroy(c) #define TracyCLContextName(c, x, y) #define TracyCLNamedZone(c, x, y, z) #define TracyCLNamedZoneC(c, x, y, z, w) #define TracyCLZone(c, x) #define TracyCLZoneC(c, x, y) #define TracyCLZoneTransient(c,x,y,z) #define TracyCLNamedZoneS(c, x, y, z, w) #define TracyCLNamedZoneCS(c, x, y, z, w, v) #define TracyCLZoneS(c, x, y) #define TracyCLZoneCS(c, x, y, z) #define TracyCLZoneTransientS(c,x,y,z,w) #define TracyCLNamedZoneSetEvent(x, e) #define TracyCLZoneSetEvent(e) #define TracyCLCollect(c) namespace tracy { class OpenCLCtxScope {}; } using TracyCLCtx = void*; #else #include <CL/cl.h> #include <atomic> #include <cassert> #include <sstream> #include "Tracy.hpp" #include "client/TracyCallstack.hpp" #include "client/TracyProfiler.hpp" #include "common/TracyAlloc.hpp" #define TRACY_CL_TO_STRING_INDIRECT(T) #T #define TRACY_CL_TO_STRING(T) TRACY_CL_TO_STRING_INDIRECT(T) #define TRACY_CL_ASSERT(p) if(!(p)) { \ TracyMessageL( "TRACY_CL_ASSERT failed on " __FILE__ ":" TRACY_CL_TO_STRING(__LINE__) ); \ assert(false && "TRACY_CL_ASSERT failed"); \ } #define TRACY_CL_CHECK_ERROR(err) if(err != CL_SUCCESS) { \ std::ostringstream oss; \ oss << "TRACY_CL_CHECK_ERROR failed on " << __FILE__ << ":" << __LINE__ \ << ": error code " << err; \ auto msg = oss.str(); \ TracyMessage(msg.data(), msg.size()); \ assert(false && "TRACY_CL_CHECK_ERROR failed"); \ } namespace tracy { enum class EventPhase : uint8_t { Begin, End }; struct EventInfo { cl_event event; EventPhase phase; }; class OpenCLCtx { public: enum { QueryCount = 64 * 1024 }; OpenCLCtx(cl_context context, cl_device_id device) : m_contextId(GetGpuCtxCounter().fetch_add(1, std::memory_order_relaxed)) , m_head(0) , m_tail(0) { int64_t tcpu, tgpu; TRACY_CL_ASSERT(m_contextId != 255); cl_int err = CL_SUCCESS; cl_command_queue queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &err); TRACY_CL_CHECK_ERROR(err) uint32_t dummyValue = 42; cl_mem dummyBuffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(uint32_t), nullptr, &err); TRACY_CL_CHECK_ERROR(err) cl_event writeBufferEvent; TRACY_CL_CHECK_ERROR(clEnqueueWriteBuffer(queue, dummyBuffer, CL_FALSE, 0, sizeof(uint32_t), &dummyValue, 0, nullptr, &writeBufferEvent)); TRACY_CL_CHECK_ERROR(clWaitForEvents(1, &writeBufferEvent)); tcpu = Profiler::GetTime(); cl_int eventStatus; TRACY_CL_CHECK_ERROR(clGetEventInfo(writeBufferEvent, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &eventStatus, nullptr)); TRACY_CL_ASSERT(eventStatus == CL_COMPLETE); TRACY_CL_CHECK_ERROR(clGetEventProfilingInfo(writeBufferEvent, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &tgpu, nullptr)); TRACY_CL_CHECK_ERROR(clReleaseEvent(writeBufferEvent)); TRACY_CL_CHECK_ERROR(clReleaseMemObject(dummyBuffer)); TRACY_CL_CHECK_ERROR(clReleaseCommandQueue(queue)); auto item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuNewContext); MemWrite(&item->gpuNewContext.cpuTime, tcpu); MemWrite(&item->gpuNewContext.gpuTime, tgpu); memset(&item->gpuNewContext.thread, 0, sizeof(item->gpuNewContext.thread)); MemWrite(&item->gpuNewContext.period, 1.0f); MemWrite(&item->gpuNewContext.type, GpuContextType::OpenCL); MemWrite(&item->gpuNewContext.context, (uint8_t) m_contextId); MemWrite(&item->gpuNewContext.flags, (uint8_t)0); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem(*item); #endif Profiler::QueueSerialFinish(); } void Name( const char* name, uint16_t len ) { auto ptr = (char*)tracy_malloc( len ); memcpy( ptr, name, len ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuContextName ); MemWrite( &item->gpuContextNameFat.context, (uint8_t)m_contextId ); MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr ); MemWrite( &item->gpuContextNameFat.size, len ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); } void Collect() { ZoneScopedC(Color::Red4); if (m_tail == m_head) return; #ifdef TRACY_ON_DEMAND if (!GetProfiler().IsConnected()) { m_head = m_tail = 0; } #endif for (; m_tail != m_head; m_tail = (m_tail + 1) % QueryCount) { EventInfo eventInfo = GetQuery(m_tail); cl_int eventStatus; cl_int err = clGetEventInfo(eventInfo.event, CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(cl_int), &eventStatus, nullptr); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clGetEventInfo falied with error code " << err << ", on event " << eventInfo.event << ", skipping..."; auto msg = oss.str(); TracyMessage(msg.data(), msg.size()); if (eventInfo.event == nullptr) { TracyMessageL("A TracyCLZone must be paird with a TracyCLZoneSetEvent, check your code!"); } assert(false && "clGetEventInfo failed, maybe a TracyCLZone is not paired with TracyCLZoneSetEvent"); continue; } if (eventStatus != CL_COMPLETE) return; cl_int eventInfoQuery = (eventInfo.phase == EventPhase::Begin) ? CL_PROFILING_COMMAND_START : CL_PROFILING_COMMAND_END; cl_ulong eventTimeStamp = 0; err = clGetEventProfilingInfo(eventInfo.event, eventInfoQuery, sizeof(cl_ulong), &eventTimeStamp, nullptr); if (err == CL_PROFILING_INFO_NOT_AVAILABLE) { TracyMessageL("command queue is not created with CL_QUEUE_PROFILING_ENABLE flag, check your code!"); assert(false && "command queue is not created with CL_QUEUE_PROFILING_ENABLE flag"); } else TRACY_CL_CHECK_ERROR(err); TRACY_CL_ASSERT(eventTimeStamp != 0); auto item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuTime); MemWrite(&item->gpuTime.gpuTime, (int64_t)eventTimeStamp); MemWrite(&item->gpuTime.queryId, (uint16_t)m_tail); MemWrite(&item->gpuTime.context, m_contextId); Profiler::QueueSerialFinish(); if (eventInfo.phase == EventPhase::End) { // Done with the event, so release it TRACY_CL_CHECK_ERROR(clReleaseEvent(eventInfo.event)); } } } tracy_force_inline uint8_t GetId() const { return m_contextId; } tracy_force_inline unsigned int NextQueryId(EventInfo eventInfo) { const auto id = m_head; m_head = (m_head + 1) % QueryCount; TRACY_CL_ASSERT(m_head != m_tail); m_query[id] = eventInfo; return id; } tracy_force_inline EventInfo& GetQuery(unsigned int id) { TRACY_CL_ASSERT(id < QueryCount); return m_query[id]; } private: unsigned int m_contextId; EventInfo m_query[QueryCount]; unsigned int m_head; // index at which a new event should be inserted unsigned int m_tail; // oldest event }; class OpenCLCtxScope { public: tracy_force_inline OpenCLCtxScope(OpenCLCtx* ctx, const SourceLocationData* srcLoc, bool is_active) #ifdef TRACY_ON_DEMAND : m_active(is_active&& GetProfiler().IsConnected()) #else : m_active(is_active) #endif , m_ctx(ctx) , m_event(nullptr) { if (!m_active) return; m_beginQueryId = ctx->NextQueryId(EventInfo{ nullptr, EventPhase::Begin }); auto item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, (uint64_t)srcLoc); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, (uint16_t)m_beginQueryId); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline OpenCLCtxScope(OpenCLCtx* ctx, const SourceLocationData* srcLoc, int depth, bool is_active) #ifdef TRACY_ON_DEMAND : m_active(is_active&& GetProfiler().IsConnected()) #else : m_active(is_active) #endif , m_ctx(ctx) , m_event(nullptr) { if (!m_active) return; m_beginQueryId = ctx->NextQueryId(EventInfo{ nullptr, EventPhase::Begin }); GetProfiler().SendCallstack(depth); auto item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginCallstackSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, (uint64_t)srcLoc); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, (uint16_t)m_beginQueryId); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline OpenCLCtxScope(OpenCLCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, bool is_active) #ifdef TRACY_ON_DEMAND : m_active(is_active && GetProfiler().IsConnected()) #else : m_active(is_active) #endif , m_ctx(ctx) , m_event(nullptr) { if (!m_active) return; m_beginQueryId = ctx->NextQueryId(EventInfo{ nullptr, EventPhase::Begin }); const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocSerial ); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, srcloc); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, (uint16_t)m_beginQueryId); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline OpenCLCtxScope(OpenCLCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, int depth, bool is_active) #ifdef TRACY_ON_DEMAND : m_active(is_active && GetProfiler().IsConnected()) #else : m_active(is_active) #endif , m_ctx(ctx) , m_event(nullptr) { if (!m_active) return; m_beginQueryId = ctx->NextQueryId(EventInfo{ nullptr, EventPhase::Begin }); const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); auto item = Profiler::QueueSerialCallstack( Callstack( depth ) ); MemWrite(&item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocCallstackSerial); MemWrite(&item->gpuZoneBegin.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneBegin.srcloc, srcloc); MemWrite(&item->gpuZoneBegin.thread, GetThreadHandle()); MemWrite(&item->gpuZoneBegin.queryId, (uint16_t)m_beginQueryId); MemWrite(&item->gpuZoneBegin.context, ctx->GetId()); Profiler::QueueSerialFinish(); } tracy_force_inline void SetEvent(cl_event event) { if (!m_active) return; m_event = event; TRACY_CL_CHECK_ERROR(clRetainEvent(m_event)); m_ctx->GetQuery(m_beginQueryId).event = m_event; } tracy_force_inline ~OpenCLCtxScope() { if (!m_active) return; const auto queryId = m_ctx->NextQueryId(EventInfo{ m_event, EventPhase::End }); auto item = Profiler::QueueSerial(); MemWrite(&item->hdr.type, QueueType::GpuZoneEndSerial); MemWrite(&item->gpuZoneEnd.cpuTime, Profiler::GetTime()); MemWrite(&item->gpuZoneEnd.thread, GetThreadHandle()); MemWrite(&item->gpuZoneEnd.queryId, (uint16_t)queryId); MemWrite(&item->gpuZoneEnd.context, m_ctx->GetId()); Profiler::QueueSerialFinish(); } const bool m_active; OpenCLCtx* m_ctx; cl_event m_event; unsigned int m_beginQueryId; }; static inline OpenCLCtx* CreateCLContext(cl_context context, cl_device_id device) { auto ctx = (OpenCLCtx*)tracy_malloc(sizeof(OpenCLCtx)); new (ctx) OpenCLCtx(context, device); return ctx; } static inline void DestroyCLContext(OpenCLCtx* ctx) { ctx->~OpenCLCtx(); tracy_free(ctx); } } // namespace tracy using TracyCLCtx = tracy::OpenCLCtx*; #define TracyCLContext(context, device) tracy::CreateCLContext(context, device); #define TracyCLDestroy(ctx) tracy::DestroyCLContext(ctx); #define TracyCLContextName(context, name, size) ctx->Name(name, size); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyCLNamedZone(ctx, varname, name, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyCLNamedZoneC(ctx, varname, name, color, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyCLZone(ctx, name) TracyCLNamedZoneS(ctx, __tracy_gpu_zone, name, TRACY_CALLSTACK, true) # define TracyCLZoneC(ctx, name, color) TracyCLNamedZoneCS(ctx, __tracy_gpu_zone, name, color, TRACY_CALLSTACK, true) # define TracyCLZoneTransient( ctx, varname, name, active ) tracy::OpenCLCtxScope varname( ctx, __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), TRACY_CALLSTACK, active ); #else # define TracyCLNamedZone(ctx, varname, name, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__){ name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), active); # define TracyCLNamedZoneC(ctx, varname, name, color, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__){ name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), active); # define TracyCLZone(ctx, name) TracyCLNamedZone(ctx, __tracy_gpu_zone, name, true) # define TracyCLZoneC(ctx, name, color) TracyCLNamedZoneC(ctx, __tracy_gpu_zone, name, color, true ) # define TracyCLZoneTransient( ctx, varname, name, active ) tracy::OpenCLCtxScope varname( ctx, __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), active ); #endif #ifdef TRACY_HAS_CALLSTACK # define TracyCLNamedZoneS(ctx, varname, name, depth, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__){ name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active); # define TracyCLNamedZoneCS(ctx, varname, name, color, depth, active) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__){ name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::OpenCLCtxScope varname(ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active); # define TracyCLZoneS(ctx, name, depth) TracyCLNamedZoneS(ctx, __tracy_gpu_zone, name, depth, true) # define TracyCLZoneCS(ctx, name, color, depth) TracyCLNamedZoneCS(ctx, __tracy_gpu_zone, name, color, depth, true) # define TracyCLZoneTransientS( ctx, varname, name, depth, active ) tracy::OpenCLCtxScope varname( ctx, __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), depth, active ); #else # define TracyCLNamedZoneS(ctx, varname, name, depth, active) TracyCLNamedZone(ctx, varname, name, active) # define TracyCLNamedZoneCS(ctx, varname, name, color, depth, active) TracyCLNamedZoneC(ctx, varname, name, color, active) # define TracyCLZoneS(ctx, name, depth) TracyCLZone(ctx, name) # define TracyCLZoneCS(ctx, name, color, depth) TracyCLZoneC(ctx, name, color) # define TracyCLZoneTransientS( ctx, varname, name, depth, active ) TracyCLZoneTransient( ctx, varname, name, active ) #endif #define TracyCLNamedZoneSetEvent(varname, event) varname.SetEvent(event) #define TracyCLZoneSetEvent(event) __tracy_gpu_zone.SetEvent(event) #define TracyCLCollect(ctx) ctx->Collect() #endif #endif
whupdup/frame
real/third_party/tracy/TracyOpenCL.hpp
C++
gpl-3.0
18,552
#ifndef __TRACYOPENGL_HPP__ #define __TRACYOPENGL_HPP__ #if !defined TRACY_ENABLE || defined __APPLE__ #define TracyGpuContext #define TracyGpuContextName(x,y) #define TracyGpuNamedZone(x,y,z) #define TracyGpuNamedZoneC(x,y,z,w) #define TracyGpuZone(x) #define TracyGpuZoneC(x,y) #define TracyGpuZoneTransient(x,y,z) #define TracyGpuCollect #define TracyGpuNamedZoneS(x,y,z,w) #define TracyGpuNamedZoneCS(x,y,z,w,a) #define TracyGpuZoneS(x,y) #define TracyGpuZoneCS(x,y,z) #define TracyGpuZoneTransientS(x,y,z,w) namespace tracy { struct SourceLocationData; class GpuCtxScope { public: GpuCtxScope( const SourceLocationData*, bool ) {} GpuCtxScope( const SourceLocationData*, int, bool ) {} }; } #else #include <atomic> #include <assert.h> #include <stdlib.h> #include "Tracy.hpp" #include "client/TracyProfiler.hpp" #include "client/TracyCallstack.hpp" #include "common/TracyAlign.hpp" #include "common/TracyAlloc.hpp" #if !defined GL_TIMESTAMP && defined GL_TIMESTAMP_EXT # define GL_TIMESTAMP GL_TIMESTAMP_EXT # define GL_QUERY_COUNTER_BITS GL_QUERY_COUNTER_BITS_EXT # define glGetQueryObjectiv glGetQueryObjectivEXT # define glGetQueryObjectui64v glGetQueryObjectui64vEXT # define glQueryCounter glQueryCounterEXT #endif #define TracyGpuContext tracy::GetGpuCtx().ptr = (tracy::GpuCtx*)tracy::tracy_malloc( sizeof( tracy::GpuCtx ) ); new(tracy::GetGpuCtx().ptr) tracy::GpuCtx; #define TracyGpuContextName( name, size ) tracy::GetGpuCtx().ptr->Name( name, size ); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyGpuNamedZone( varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyGpuNamedZoneC( varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), TRACY_CALLSTACK, active ); # define TracyGpuZone( name ) TracyGpuNamedZoneS( ___tracy_gpu_zone, name, TRACY_CALLSTACK, true ) # define TracyGpuZoneC( name, color ) TracyGpuNamedZoneCS( ___tracy_gpu_zone, name, color, TRACY_CALLSTACK, true ) # define TracyGpuZoneTransient( varname, name, active ) tracy::GpuCtxScope varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), TRACY_CALLSTACK, active ); #else # define TracyGpuNamedZone( varname, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), active ); # define TracyGpuNamedZoneC( varname, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), active ); # define TracyGpuZone( name ) TracyGpuNamedZone( ___tracy_gpu_zone, name, true ) # define TracyGpuZoneC( name, color ) TracyGpuNamedZoneC( ___tracy_gpu_zone, name, color, true ) # define TracyGpuZoneTransient( varname, name, active ) tracy::GpuCtxScope varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), active ); #endif #define TracyGpuCollect tracy::GetGpuCtx().ptr->Collect(); #ifdef TRACY_HAS_CALLSTACK # define TracyGpuNamedZoneS( varname, name, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active ); # define TracyGpuNamedZoneCS( varname, name, color, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::GpuCtxScope varname( &TracyConcat(__tracy_gpu_source_location,__LINE__), depth, active ); # define TracyGpuZoneS( name, depth ) TracyGpuNamedZoneS( ___tracy_gpu_zone, name, depth, true ) # define TracyGpuZoneCS( name, color, depth ) TracyGpuNamedZoneCS( ___tracy_gpu_zone, name, color, depth, true ) # define TracyGpuZoneTransientS( varname, name, depth, active ) tracy::GpuCtxScope varname( __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), depth, active ); #else # define TracyGpuNamedZoneS( varname, name, depth, active ) TracyGpuNamedZone( varname, name, active ) # define TracyGpuNamedZoneCS( varname, name, color, depth, active ) TracyGpuNamedZoneC( varname, name, color, active ) # define TracyGpuZoneS( name, depth ) TracyGpuZone( name ) # define TracyGpuZoneCS( name, color, depth ) TracyGpuZoneC( name, color ) # define TracyGpuZoneTransientS( varname, name, depth, active ) TracyGpuZoneTransient( varname, name, active ) #endif namespace tracy { class GpuCtx { friend class GpuCtxScope; enum { QueryCount = 64 * 1024 }; public: GpuCtx() : m_context( GetGpuCtxCounter().fetch_add( 1, std::memory_order_relaxed ) ) , m_head( 0 ) , m_tail( 0 ) { assert( m_context != 255 ); glGenQueries( QueryCount, m_query ); int64_t tgpu; glGetInteger64v( GL_TIMESTAMP, &tgpu ); int64_t tcpu = Profiler::GetTime(); GLint bits; glGetQueryiv( GL_TIMESTAMP, GL_QUERY_COUNTER_BITS, &bits ); const float period = 1.f; const auto thread = GetThreadHandle(); TracyLfqPrepare( QueueType::GpuNewContext ); MemWrite( &item->gpuNewContext.cpuTime, tcpu ); MemWrite( &item->gpuNewContext.gpuTime, tgpu ); MemWrite( &item->gpuNewContext.thread, thread ); MemWrite( &item->gpuNewContext.period, period ); MemWrite( &item->gpuNewContext.context, m_context ); MemWrite( &item->gpuNewContext.flags, uint8_t( 0 ) ); MemWrite( &item->gpuNewContext.type, GpuContextType::OpenGl ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif TracyLfqCommit; } void Name( const char* name, uint16_t len ) { auto ptr = (char*)tracy_malloc( len ); memcpy( ptr, name, len ); TracyLfqPrepare( QueueType::GpuContextName ); MemWrite( &item->gpuContextNameFat.context, m_context ); MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr ); MemWrite( &item->gpuContextNameFat.size, len ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif TracyLfqCommit; } void Collect() { ZoneScopedC( Color::Red4 ); if( m_tail == m_head ) return; #ifdef TRACY_ON_DEMAND if( !GetProfiler().IsConnected() ) { m_head = m_tail = 0; return; } #endif while( m_tail != m_head ) { GLint available; glGetQueryObjectiv( m_query[m_tail], GL_QUERY_RESULT_AVAILABLE, &available ); if( !available ) return; uint64_t time; glGetQueryObjectui64v( m_query[m_tail], GL_QUERY_RESULT, &time ); TracyLfqPrepare( QueueType::GpuTime ); MemWrite( &item->gpuTime.gpuTime, (int64_t)time ); MemWrite( &item->gpuTime.queryId, (uint16_t)m_tail ); MemWrite( &item->gpuTime.context, m_context ); TracyLfqCommit; m_tail = ( m_tail + 1 ) % QueryCount; } } private: tracy_force_inline unsigned int NextQueryId() { const auto id = m_head; m_head = ( m_head + 1 ) % QueryCount; assert( m_head != m_tail ); return id; } tracy_force_inline unsigned int TranslateOpenGlQueryId( unsigned int id ) { return m_query[id]; } tracy_force_inline uint8_t GetId() const { return m_context; } unsigned int m_query[QueryCount]; uint8_t m_context; unsigned int m_head; unsigned int m_tail; }; class GpuCtxScope { public: tracy_force_inline GpuCtxScope( const SourceLocationData* srcloc, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; const auto queryId = GetGpuCtx().ptr->NextQueryId(); glQueryCounter( GetGpuCtx().ptr->TranslateOpenGlQueryId( queryId ), GL_TIMESTAMP ); TracyLfqPrepare( QueueType::GpuZoneBegin ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); memset( &item->gpuZoneBegin.thread, 0, sizeof( item->gpuZoneBegin.thread ) ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, GetGpuCtx().ptr->GetId() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); TracyLfqCommit; } tracy_force_inline GpuCtxScope( const SourceLocationData* srcloc, int depth, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; const auto queryId = GetGpuCtx().ptr->NextQueryId(); glQueryCounter( GetGpuCtx().ptr->TranslateOpenGlQueryId( queryId ), GL_TIMESTAMP ); #ifdef TRACY_FIBERS TracyLfqPrepare( QueueType::GpuZoneBegin ); memset( &item->gpuZoneBegin.thread, 0, sizeof( item->gpuZoneBegin.thread ) ); #else GetProfiler().SendCallstack( depth ); TracyLfqPrepare( QueueType::GpuZoneBeginCallstack ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); #endif MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, GetGpuCtx().ptr->GetId() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); TracyLfqCommit; } tracy_force_inline GpuCtxScope( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; const auto queryId = GetGpuCtx().ptr->NextQueryId(); glQueryCounter( GetGpuCtx().ptr->TranslateOpenGlQueryId( queryId ), GL_TIMESTAMP ); TracyLfqPrepare( QueueType::GpuZoneBeginAllocSrcLoc ); const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); memset( &item->gpuZoneBegin.thread, 0, sizeof( item->gpuZoneBegin.thread ) ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, GetGpuCtx().ptr->GetId() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); TracyLfqCommit; } tracy_force_inline GpuCtxScope( uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, int depth, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; const auto queryId = GetGpuCtx().ptr->NextQueryId(); glQueryCounter( GetGpuCtx().ptr->TranslateOpenGlQueryId( queryId ), GL_TIMESTAMP ); #ifdef TRACY_FIBERS TracyLfqPrepare( QueueType::GpuZoneBeginAllocSrcLoc ); memset( &item->gpuZoneBegin.thread, 0, sizeof( item->gpuZoneBegin.thread ) ); #else GetProfiler().SendCallstack( depth ); TracyLfqPrepare( QueueType::GpuZoneBeginAllocSrcLocCallstack ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); #endif const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, GetGpuCtx().ptr->GetId() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); TracyLfqCommit; } tracy_force_inline ~GpuCtxScope() { if( !m_active ) return; const auto queryId = GetGpuCtx().ptr->NextQueryId(); glQueryCounter( GetGpuCtx().ptr->TranslateOpenGlQueryId( queryId ), GL_TIMESTAMP ); TracyLfqPrepare( QueueType::GpuZoneEnd ); MemWrite( &item->gpuZoneEnd.cpuTime, Profiler::GetTime() ); memset( &item->gpuZoneEnd.thread, 0, sizeof( item->gpuZoneEnd.thread ) ); MemWrite( &item->gpuZoneEnd.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneEnd.context, GetGpuCtx().ptr->GetId() ); TracyLfqCommit; } private: const bool m_active; }; } #endif #endif
whupdup/frame
real/third_party/tracy/TracyOpenGL.hpp
C++
gpl-3.0
13,347
#ifndef __TRACYVULKAN_HPP__ #define __TRACYVULKAN_HPP__ #if !defined TRACY_ENABLE #define TracyVkContext(x,y,z,w) nullptr #define TracyVkContextCalibrated(x,y,z,w,a,b) nullptr #define TracyVkDestroy(x) #define TracyVkContextName(c,x,y) #define TracyVkNamedZone(c,x,y,z,w) #define TracyVkNamedZoneC(c,x,y,z,w,a) #define TracyVkZone(c,x,y) #define TracyVkZoneC(c,x,y,z) #define TracyVkZoneTransient(c,x,y,z,w) #define TracyVkCollect(c,x) #define TracyVkNamedZoneS(c,x,y,z,w,a) #define TracyVkNamedZoneCS(c,x,y,z,w,v,a) #define TracyVkZoneS(c,x,y,z) #define TracyVkZoneCS(c,x,y,z,w) #define TracyVkZoneTransientS(c,x,y,z,w,a) namespace tracy { class VkCtxScope {}; } using TracyVkCtx = void*; #else #if !defined VK_NULL_HANDLE # error "You must include Vulkan headers before including TracyVulkan.hpp" #endif #include <assert.h> #include <stdlib.h> #include "Tracy.hpp" #include "client/TracyProfiler.hpp" #include "client/TracyCallstack.hpp" namespace tracy { class VkCtx { friend class VkCtxScope; enum { QueryCount = 64 * 1024 }; public: VkCtx( VkPhysicalDevice physdev, VkDevice device, VkQueue queue, VkCommandBuffer cmdbuf, PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT, PFN_vkGetCalibratedTimestampsEXT _vkGetCalibratedTimestampsEXT ) : m_device( device ) , m_timeDomain( VK_TIME_DOMAIN_DEVICE_EXT ) , m_context( GetGpuCtxCounter().fetch_add( 1, std::memory_order_relaxed ) ) , m_head( 0 ) , m_tail( 0 ) , m_oldCnt( 0 ) , m_queryCount( QueryCount ) , m_vkGetCalibratedTimestampsEXT( _vkGetCalibratedTimestampsEXT ) { assert( m_context != 255 ); if( _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT && _vkGetCalibratedTimestampsEXT ) { uint32_t num; _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT( physdev, &num, nullptr ); if( num > 4 ) num = 4; VkTimeDomainEXT data[4]; _vkGetPhysicalDeviceCalibrateableTimeDomainsEXT( physdev, &num, data ); VkTimeDomainEXT supportedDomain = (VkTimeDomainEXT)-1; #if defined _WIN32 supportedDomain = VK_TIME_DOMAIN_QUERY_PERFORMANCE_COUNTER_EXT; #elif defined __linux__ && defined CLOCK_MONOTONIC_RAW supportedDomain = VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT; #endif for( uint32_t i=0; i<num; i++ ) { if( data[i] == supportedDomain ) { m_timeDomain = data[i]; break; } } } VkPhysicalDeviceProperties prop; vkGetPhysicalDeviceProperties( physdev, &prop ); const float period = prop.limits.timestampPeriod; VkQueryPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; poolInfo.queryCount = m_queryCount; poolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; while( vkCreateQueryPool( device, &poolInfo, nullptr, &m_query ) != VK_SUCCESS ) { m_queryCount /= 2; poolInfo.queryCount = m_queryCount; } VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &cmdbuf; vkBeginCommandBuffer( cmdbuf, &beginInfo ); vkCmdResetQueryPool( cmdbuf, m_query, 0, m_queryCount ); vkEndCommandBuffer( cmdbuf ); vkQueueSubmit( queue, 1, &submitInfo, VK_NULL_HANDLE ); vkQueueWaitIdle( queue ); int64_t tcpu, tgpu; if( m_timeDomain == VK_TIME_DOMAIN_DEVICE_EXT ) { vkBeginCommandBuffer( cmdbuf, &beginInfo ); vkCmdWriteTimestamp( cmdbuf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, m_query, 0 ); vkEndCommandBuffer( cmdbuf ); vkQueueSubmit( queue, 1, &submitInfo, VK_NULL_HANDLE ); vkQueueWaitIdle( queue ); tcpu = Profiler::GetTime(); vkGetQueryPoolResults( device, m_query, 0, 1, sizeof( tgpu ), &tgpu, sizeof( tgpu ), VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT ); vkBeginCommandBuffer( cmdbuf, &beginInfo ); vkCmdResetQueryPool( cmdbuf, m_query, 0, 1 ); vkEndCommandBuffer( cmdbuf ); vkQueueSubmit( queue, 1, &submitInfo, VK_NULL_HANDLE ); vkQueueWaitIdle( queue ); } else { enum { NumProbes = 32 }; VkCalibratedTimestampInfoEXT spec[2] = { { VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, nullptr, VK_TIME_DOMAIN_DEVICE_EXT }, { VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, nullptr, m_timeDomain }, }; uint64_t ts[2]; uint64_t deviation[NumProbes]; for( int i=0; i<NumProbes; i++ ) { _vkGetCalibratedTimestampsEXT( device, 2, spec, ts, deviation+i ); } uint64_t minDeviation = deviation[0]; for( int i=1; i<NumProbes; i++ ) { if( minDeviation > deviation[i] ) { minDeviation = deviation[i]; } } m_deviation = minDeviation * 3 / 2; #if defined _WIN32 m_qpcToNs = int64_t( 1000000000. / GetFrequencyQpc() ); #endif Calibrate( device, m_prevCalibration, tgpu ); tcpu = Profiler::GetTime(); } uint8_t flags = 0; if( m_timeDomain != VK_TIME_DOMAIN_DEVICE_EXT ) flags |= GpuContextCalibration; auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuNewContext ); MemWrite( &item->gpuNewContext.cpuTime, tcpu ); MemWrite( &item->gpuNewContext.gpuTime, tgpu ); memset( &item->gpuNewContext.thread, 0, sizeof( item->gpuNewContext.thread ) ); MemWrite( &item->gpuNewContext.period, period ); MemWrite( &item->gpuNewContext.context, m_context ); MemWrite( &item->gpuNewContext.flags, flags ); MemWrite( &item->gpuNewContext.type, GpuContextType::Vulkan ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); m_res = (int64_t*)tracy_malloc( sizeof( int64_t ) * m_queryCount ); } ~VkCtx() { tracy_free( m_res ); vkDestroyQueryPool( m_device, m_query, nullptr ); } void Name( const char* name, uint16_t len ) { auto ptr = (char*)tracy_malloc( len ); memcpy( ptr, name, len ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuContextName ); MemWrite( &item->gpuContextNameFat.context, m_context ); MemWrite( &item->gpuContextNameFat.ptr, (uint64_t)ptr ); MemWrite( &item->gpuContextNameFat.size, len ); #ifdef TRACY_ON_DEMAND GetProfiler().DeferItem( *item ); #endif Profiler::QueueSerialFinish(); } void Collect( VkCommandBuffer cmdbuf ) { ZoneScopedC( Color::Red4 ); if( m_tail == m_head ) return; #ifdef TRACY_ON_DEMAND if( !GetProfiler().IsConnected() ) { vkCmdResetQueryPool( cmdbuf, m_query, 0, m_queryCount ); m_head = m_tail = m_oldCnt = 0; int64_t tgpu; if( m_timeDomain != VK_TIME_DOMAIN_DEVICE_EXT ) Calibrate( m_device, m_prevCalibration, tgpu ); return; } #endif unsigned int cnt; if( m_oldCnt != 0 ) { cnt = m_oldCnt; m_oldCnt = 0; } else { cnt = m_head < m_tail ? m_queryCount - m_tail : m_head - m_tail; } if( vkGetQueryPoolResults( m_device, m_query, m_tail, cnt, sizeof( int64_t ) * m_queryCount, m_res, sizeof( int64_t ), VK_QUERY_RESULT_64_BIT ) == VK_NOT_READY ) { m_oldCnt = cnt; return; } for( unsigned int idx=0; idx<cnt; idx++ ) { auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuTime ); MemWrite( &item->gpuTime.gpuTime, m_res[idx] ); MemWrite( &item->gpuTime.queryId, uint16_t( m_tail + idx ) ); MemWrite( &item->gpuTime.context, m_context ); Profiler::QueueSerialFinish(); } if( m_timeDomain != VK_TIME_DOMAIN_DEVICE_EXT ) { int64_t tgpu, tcpu; Calibrate( m_device, tcpu, tgpu ); const auto refCpu = Profiler::GetTime(); const auto delta = tcpu - m_prevCalibration; if( delta > 0 ) { m_prevCalibration = tcpu; auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuCalibration ); MemWrite( &item->gpuCalibration.gpuTime, tgpu ); MemWrite( &item->gpuCalibration.cpuTime, refCpu ); MemWrite( &item->gpuCalibration.cpuDelta, delta ); MemWrite( &item->gpuCalibration.context, m_context ); Profiler::QueueSerialFinish(); } } vkCmdResetQueryPool( cmdbuf, m_query, m_tail, cnt ); m_tail += cnt; if( m_tail == m_queryCount ) m_tail = 0; } private: tracy_force_inline unsigned int NextQueryId() { const auto id = m_head; m_head = ( m_head + 1 ) % m_queryCount; assert( m_head != m_tail ); return id; } tracy_force_inline uint8_t GetId() const { return m_context; } tracy_force_inline void Calibrate( VkDevice device, int64_t& tCpu, int64_t& tGpu ) { assert( m_timeDomain != VK_TIME_DOMAIN_DEVICE_EXT ); VkCalibratedTimestampInfoEXT spec[2] = { { VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, nullptr, VK_TIME_DOMAIN_DEVICE_EXT }, { VK_STRUCTURE_TYPE_CALIBRATED_TIMESTAMP_INFO_EXT, nullptr, m_timeDomain }, }; uint64_t ts[2]; uint64_t deviation; do { m_vkGetCalibratedTimestampsEXT( device, 2, spec, ts, &deviation ); } while( deviation > m_deviation ); #if defined _WIN32 tGpu = ts[0]; tCpu = ts[1] * m_qpcToNs; #elif defined __linux__ && defined CLOCK_MONOTONIC_RAW tGpu = ts[0]; tCpu = ts[1]; #else assert( false ); #endif } VkDevice m_device; VkQueryPool m_query; VkTimeDomainEXT m_timeDomain; uint64_t m_deviation; int64_t m_qpcToNs; int64_t m_prevCalibration; uint8_t m_context; unsigned int m_head; unsigned int m_tail; unsigned int m_oldCnt; unsigned int m_queryCount; int64_t* m_res; PFN_vkGetCalibratedTimestampsEXT m_vkGetCalibratedTimestampsEXT; }; class VkCtxScope { public: tracy_force_inline VkCtxScope( VkCtx* ctx, const SourceLocationData* srcloc, VkCommandBuffer cmdbuf, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_cmdbuf = cmdbuf; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); vkCmdWriteTimestamp( cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, ctx->m_query, queryId ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); } tracy_force_inline VkCtxScope( VkCtx* ctx, const SourceLocationData* srcloc, VkCommandBuffer cmdbuf, int depth, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_cmdbuf = cmdbuf; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); vkCmdWriteTimestamp( cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, ctx->m_query, queryId ); auto item = Profiler::QueueSerialCallstack( Callstack( depth ) ); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginCallstackSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, (uint64_t)srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); } tracy_force_inline VkCtxScope( VkCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, VkCommandBuffer cmdbuf, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_cmdbuf = cmdbuf; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); vkCmdWriteTimestamp( cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, ctx->m_query, queryId ); const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); } tracy_force_inline VkCtxScope( VkCtx* ctx, uint32_t line, const char* source, size_t sourceSz, const char* function, size_t functionSz, const char* name, size_t nameSz, VkCommandBuffer cmdbuf, int depth, bool is_active ) #ifdef TRACY_ON_DEMAND : m_active( is_active && GetProfiler().IsConnected() ) #else : m_active( is_active ) #endif { if( !m_active ) return; m_cmdbuf = cmdbuf; m_ctx = ctx; const auto queryId = ctx->NextQueryId(); vkCmdWriteTimestamp( cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, ctx->m_query, queryId ); const auto srcloc = Profiler::AllocSourceLocation( line, source, sourceSz, function, functionSz, name, nameSz ); auto item = Profiler::QueueSerialCallstack( Callstack( depth ) ); MemWrite( &item->hdr.type, QueueType::GpuZoneBeginAllocSrcLocCallstackSerial ); MemWrite( &item->gpuZoneBegin.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneBegin.srcloc, srcloc ); MemWrite( &item->gpuZoneBegin.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneBegin.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneBegin.context, ctx->GetId() ); Profiler::QueueSerialFinish(); } tracy_force_inline ~VkCtxScope() { if( !m_active ) return; const auto queryId = m_ctx->NextQueryId(); vkCmdWriteTimestamp( m_cmdbuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, m_ctx->m_query, queryId ); auto item = Profiler::QueueSerial(); MemWrite( &item->hdr.type, QueueType::GpuZoneEndSerial ); MemWrite( &item->gpuZoneEnd.cpuTime, Profiler::GetTime() ); MemWrite( &item->gpuZoneEnd.thread, GetThreadHandle() ); MemWrite( &item->gpuZoneEnd.queryId, uint16_t( queryId ) ); MemWrite( &item->gpuZoneEnd.context, m_ctx->GetId() ); Profiler::QueueSerialFinish(); } private: const bool m_active; VkCommandBuffer m_cmdbuf; VkCtx* m_ctx; }; static inline VkCtx* CreateVkContext( VkPhysicalDevice physdev, VkDevice device, VkQueue queue, VkCommandBuffer cmdbuf, PFN_vkGetPhysicalDeviceCalibrateableTimeDomainsEXT gpdctd, PFN_vkGetCalibratedTimestampsEXT gct ) { auto ctx = (VkCtx*)tracy_malloc( sizeof( VkCtx ) ); new(ctx) VkCtx( physdev, device, queue, cmdbuf, gpdctd, gct ); return ctx; } static inline void DestroyVkContext( VkCtx* ctx ) { ctx->~VkCtx(); tracy_free( ctx ); } } using TracyVkCtx = tracy::VkCtx*; #define TracyVkContext( physdev, device, queue, cmdbuf ) tracy::CreateVkContext( physdev, device, queue, cmdbuf, nullptr, nullptr ); #define TracyVkContextCalibrated( physdev, device, queue, cmdbuf, gpdctd, gct ) tracy::CreateVkContext( physdev, device, queue, cmdbuf, gpdctd, gct ); #define TracyVkDestroy( ctx ) tracy::DestroyVkContext( ctx ); #define TracyVkContextName( ctx, name, size ) ctx->Name( name, size ); #if defined TRACY_HAS_CALLSTACK && defined TRACY_CALLSTACK # define TracyVkNamedZone( ctx, varname, cmdbuf, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, TRACY_CALLSTACK, active ); # define TracyVkNamedZoneC( ctx, varname, cmdbuf, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, TRACY_CALLSTACK, active ); # define TracyVkZone( ctx, cmdbuf, name ) TracyVkNamedZoneS( ctx, ___tracy_gpu_zone, cmdbuf, name, TRACY_CALLSTACK, true ) # define TracyVkZoneC( ctx, cmdbuf, name, color ) TracyVkNamedZoneCS( ctx, ___tracy_gpu_zone, cmdbuf, name, color, TRACY_CALLSTACK, true ) # define TracyVkZoneTransient( ctx, varname, cmdbuf, name, active ) TracyVkZoneTransientS( ctx, varname, cmdbuf, name, TRACY_CALLSTACK, active ) #else # define TracyVkNamedZone( ctx, varname, cmdbuf, name, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, active ); # define TracyVkNamedZoneC( ctx, varname, cmdbuf, name, color, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, active ); # define TracyVkZone( ctx, cmdbuf, name ) TracyVkNamedZone( ctx, ___tracy_gpu_zone, cmdbuf, name, true ) # define TracyVkZoneC( ctx, cmdbuf, name, color ) TracyVkNamedZoneC( ctx, ___tracy_gpu_zone, cmdbuf, name, color, true ) # define TracyVkZoneTransient( ctx, varname, cmdbuf, name, active ) tracy::VkCtxScope varname( ctx, __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), cmdbuf, active ); #endif #define TracyVkCollect( ctx, cmdbuf ) ctx->Collect( cmdbuf ); #ifdef TRACY_HAS_CALLSTACK # define TracyVkNamedZoneS( ctx, varname, cmdbuf, name, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, 0 }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, depth, active ); # define TracyVkNamedZoneCS( ctx, varname, cmdbuf, name, color, depth, active ) static constexpr tracy::SourceLocationData TracyConcat(__tracy_gpu_source_location,__LINE__) { name, __FUNCTION__, __FILE__, (uint32_t)__LINE__, color }; tracy::VkCtxScope varname( ctx, &TracyConcat(__tracy_gpu_source_location,__LINE__), cmdbuf, depth, active ); # define TracyVkZoneS( ctx, cmdbuf, name, depth ) TracyVkNamedZoneS( ctx, ___tracy_gpu_zone, cmdbuf, name, depth, true ) # define TracyVkZoneCS( ctx, cmdbuf, name, color, depth ) TracyVkNamedZoneCS( ctx, ___tracy_gpu_zone, cmdbuf, name, color, depth, true ) # define TracyVkZoneTransientS( ctx, varname, cmdbuf, name, depth, active ) tracy::VkCtxScope varname( ctx, __LINE__, __FILE__, strlen( __FILE__ ), __FUNCTION__, strlen( __FUNCTION__ ), name, strlen( name ), cmdbuf, depth, active ); #else # define TracyVkNamedZoneS( ctx, varname, cmdbuf, name, depth, active ) TracyVkNamedZone( ctx, varname, cmdbuf, name, active ) # define TracyVkNamedZoneCS( ctx, varname, cmdbuf, name, color, depth, active ) TracyVkNamedZoneC( ctx, varname, cmdbuf, name, color, active ) # define TracyVkZoneS( ctx, cmdbuf, name, depth ) TracyVkZone( ctx, cmdbuf, name ) # define TracyVkZoneCS( ctx, cmdbuf, name, color, depth ) TracyVkZoneC( ctx, cmdbuf, name, color ) # define TracyVkZoneTransientS( ctx, varname, cmdbuf, name, depth, active ) TracyVkZoneTransient( ctx, varname, cmdbuf, name, active ) #endif #endif #endif
whupdup/frame
real/third_party/tracy/TracyVulkan.hpp
C++
gpl-3.0
21,365
#ifdef _WIN32 # include <windows.h> # include <io.h> #else # include <unistd.h> #endif #include <atomic> #include <chrono> #include <inttypes.h> #include <mutex> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "../../common/TracyProtocol.hpp" #include "../../common/TracyStackFrames.hpp" #include "../../server/TracyFileWrite.hpp" #include "../../server/TracyMemory.hpp" #include "../../server/TracyPrint.hpp" #include "../../server/TracyWorker.hpp" #ifdef _WIN32 # include "../../getopt/getopt.h" #endif // This atomic is written by a signal handler (SigInt). Traditionally that would // have had to be `volatile sig_atomic_t`, and annoyingly, `bool` was // technically not allowed there, even though in practice it would work. // The good thing with C++11 atomics is that we can use atomic<bool> instead // here and be on the actually supported path. static std::atomic<bool> s_disconnect { false }; void SigInt( int ) { // Relaxed order is closest to a traditional `volatile` write. // We don't need stronger ordering since this signal handler doesn't do // anything else that would need to be ordered relatively to this. s_disconnect.store(true, std::memory_order_relaxed); } static bool s_isStdoutATerminal = false; void InitIsStdoutATerminal() { #ifdef _WIN32 s_isStdoutATerminal = _isatty( fileno( stdout ) ); #else s_isStdoutATerminal = isatty( fileno( stdout ) ); #endif } bool IsStdoutATerminal() { return s_isStdoutATerminal; } #define ANSI_RESET "\033[0m" #define ANSI_BOLD "\033[1m" #define ANSI_BLACK "\033[30m" #define ANSI_RED "\033[31m" #define ANSI_GREEN "\033[32m" #define ANSI_YELLOW "\033[33m" #define ANSI_MAGENTA "\033[35m" #define ANSI_CYAN "\033[36m" #define ANSI_ERASE_LINE "\033[2K" // Like printf, but if stdout is a terminal, prepends the output with // the given `ansiEscape` and appends ANSI_RESET. void AnsiPrintf( const char* ansiEscape, const char* format, ... ) { if( IsStdoutATerminal() ) { // Prepend ansiEscape and append ANSI_RESET. char buf[256]; va_list args; va_start( args, format ); vsnprintf( buf, sizeof buf, format, args ); va_end( args ); printf( "%s%s" ANSI_RESET, ansiEscape, buf ); } else { // Just a normal printf. va_list args; va_start( args, format ); vfprintf( stdout, format, args ); va_end( args ); } } [[noreturn]] void Usage() { printf( "Usage: capture -o output.tracy [-a address] [-p port] [-f] [-s seconds]\n" ); exit( 1 ); } int main( int argc, char** argv ) { #ifdef _WIN32 if( !AttachConsole( ATTACH_PARENT_PROCESS ) ) { AllocConsole(); SetConsoleMode( GetStdHandle( STD_OUTPUT_HANDLE ), 0x07 ); } #endif InitIsStdoutATerminal(); bool overwrite = false; const char* address = "127.0.0.1"; const char* output = nullptr; int port = 8086; int seconds = -1; int c; while( ( c = getopt( argc, argv, "a:o:p:fs:" ) ) != -1 ) { switch( c ) { case 'a': address = optarg; break; case 'o': output = optarg; break; case 'p': port = atoi( optarg ); break; case 'f': overwrite = true; break; case 's': seconds = atoi (optarg); break; default: Usage(); break; } } if( !address || !output ) Usage(); struct stat st; if( stat( output, &st ) == 0 && !overwrite ) { printf( "Output file %s already exists! Use -f to force overwrite.\n", output ); return 4; } FILE* test = fopen( output, "wb" ); if( !test ) { printf( "Cannot open output file %s for writing!\n", output ); return 5; } fclose( test ); unlink( output ); printf( "Connecting to %s:%i...", address, port ); fflush( stdout ); tracy::Worker worker( address, port ); while( !worker.IsConnected() ) { const auto handshake = worker.GetHandshakeStatus(); if( handshake == tracy::HandshakeProtocolMismatch ) { printf( "\nThe client you are trying to connect to uses incompatible protocol version.\nMake sure you are using the same Tracy version on both client and server.\n" ); return 1; } if( handshake == tracy::HandshakeNotAvailable ) { printf( "\nThe client you are trying to connect to is no longer able to sent profiling data,\nbecause another server was already connected to it.\nYou can do the following:\n\n 1. Restart the client application.\n 2. Rebuild the client application with on-demand mode enabled.\n" ); return 2; } if( handshake == tracy::HandshakeDropped ) { printf( "\nThe client you are trying to connect to has disconnected during the initial\nconnection handshake. Please check your network configuration.\n" ); return 3; } } while( !worker.HasData() ) std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); printf( "\nQueue delay: %s\nTimer resolution: %s\n", tracy::TimeToString( worker.GetDelay() ), tracy::TimeToString( worker.GetResolution() ) ); #ifdef _WIN32 signal( SIGINT, SigInt ); #else struct sigaction sigint, oldsigint; memset( &sigint, 0, sizeof( sigint ) ); sigint.sa_handler = SigInt; sigaction( SIGINT, &sigint, &oldsigint ); #endif auto& lock = worker.GetMbpsDataLock(); const auto t0 = std::chrono::high_resolution_clock::now(); while( worker.IsConnected() ) { // Relaxed order is sufficient here because `s_disconnect` is only ever // set by this thread or by the SigInt handler, and that handler does // nothing else than storing `s_disconnect`. if( s_disconnect.load( std::memory_order_relaxed ) ) { worker.Disconnect(); // Relaxed order is sufficient because only this thread ever reads // this value. s_disconnect.store(false, std::memory_order_relaxed ); break; } lock.lock(); const auto mbps = worker.GetMbpsData().back(); const auto compRatio = worker.GetCompRatio(); const auto netTotal = worker.GetDataTransferred(); lock.unlock(); // Output progress info only if destination is a TTY to avoid bloating // log files (so this is not just about usage of ANSI color codes). if( IsStdoutATerminal() ) { const char* unit = "Mbps"; float unitsPerMbps = 1.f; if( mbps < 0.1f ) { unit = "Kbps"; unitsPerMbps = 1000.f; } AnsiPrintf( ANSI_ERASE_LINE ANSI_CYAN ANSI_BOLD, "\r%7.2f %s", mbps * unitsPerMbps, unit ); printf( " /"); AnsiPrintf( ANSI_CYAN ANSI_BOLD, "%5.1f%%", compRatio * 100.f ); printf( " ="); AnsiPrintf( ANSI_YELLOW ANSI_BOLD, "%7.2f Mbps", mbps / compRatio ); printf( " | "); AnsiPrintf( ANSI_YELLOW, "Tx: "); AnsiPrintf( ANSI_GREEN, "%s", tracy::MemSizeToString( netTotal ) ); printf( " | "); AnsiPrintf( ANSI_RED ANSI_BOLD, "%s", tracy::MemSizeToString( tracy::memUsage ) ); printf( " | "); AnsiPrintf( ANSI_RED, "%s", tracy::TimeToString( worker.GetLastTime() ) ); fflush( stdout ); } std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); if( seconds != -1 ) { const auto dur = std::chrono::high_resolution_clock::now() - t0; if( std::chrono::duration_cast<std::chrono::seconds>(dur).count() >= seconds ) { // Relaxed order is sufficient because only this thread ever reads // this value. s_disconnect.store(true, std::memory_order_relaxed ); } } } const auto t1 = std::chrono::high_resolution_clock::now(); const auto& failure = worker.GetFailureType(); if( failure != tracy::Worker::Failure::None ) { AnsiPrintf( ANSI_RED ANSI_BOLD, "\nInstrumentation failure: %s", tracy::Worker::GetFailureString( failure ) ); auto& fd = worker.GetFailureData(); if( !fd.message.empty() ) { printf( "\nContext: %s", fd.message.c_str() ); } if( fd.callstack != 0 ) { AnsiPrintf( ANSI_BOLD, "\n%sFailure callstack:%s\n" ); auto& cs = worker.GetCallstack( fd.callstack ); int fidx = 0; int bidx = 0; for( auto& entry : cs ) { auto frameData = worker.GetCallstackFrame( entry ); if( !frameData ) { printf( "%3i. %p\n", fidx++, (void*)worker.GetCanonicalPointer( entry ) ); } else { const auto fsz = frameData->size; for( uint8_t f=0; f<fsz; f++ ) { const auto& frame = frameData->data[f]; auto txt = worker.GetString( frame.name ); if( fidx == 0 && f != fsz-1 ) { auto test = tracy::s_tracyStackFrames; bool match = false; do { if( strcmp( txt, *test ) == 0 ) { match = true; break; } } while( *++test ); if( match ) continue; } bidx++; if( f == fsz-1 ) { printf( "%3i. ", fidx++ ); } else { AnsiPrintf( ANSI_BLACK ANSI_BOLD, "inl. " ); } AnsiPrintf( ANSI_CYAN, "%s ", txt ); txt = worker.GetString( frame.file ); if( frame.line == 0 ) { AnsiPrintf( ANSI_YELLOW, "(%s)", txt ); } else { AnsiPrintf( ANSI_YELLOW, "(%s:%" PRIu32 ")", txt, frame.line ); } if( frameData->imageName.Active() ) { AnsiPrintf( ANSI_MAGENTA, " %s\n", worker.GetString( frameData->imageName ) ); } else { printf( "\n" ); } } } } } } printf( "\nFrames: %" PRIu64 "\nTime span: %s\nZones: %s\nElapsed time: %s\nSaving trace...", worker.GetFrameCount( *worker.GetFramesBase() ), tracy::TimeToString( worker.GetLastTime() ), tracy::RealToString( worker.GetZoneCount() ), tracy::TimeToString( std::chrono::duration_cast<std::chrono::nanoseconds>( t1 - t0 ).count() ) ); fflush( stdout ); auto f = std::unique_ptr<tracy::FileWrite>( tracy::FileWrite::Open( output ) ); if( f ) { worker.Write( *f, false ); AnsiPrintf( ANSI_GREEN ANSI_BOLD, " done!\n" ); f->Finish(); const auto stats = f->GetCompressionStatistics(); printf( "Trace size %s (%.2f%% ratio)\n", tracy::MemSizeToString( stats.second ), 100.f * stats.second / stats.first ); } else { AnsiPrintf( ANSI_RED ANSI_BOLD, " failed!\n"); } return 0; }
whupdup/frame
real/third_party/tracy/capture/src/capture.cpp
C++
gpl-3.0
12,121
#ifdef TRACY_ENABLE #include <atomic> #include "../common/TracyAlloc.hpp" #include "../common/TracyForceInline.hpp" #include "../common/TracyYield.hpp" namespace tracy { extern thread_local bool RpThreadInitDone; extern std::atomic<int> RpInitDone; extern std::atomic<int> RpInitLock; tracy_no_inline static void InitRpmallocPlumbing() { const auto done = RpInitDone.load( std::memory_order_acquire ); if( !done ) { int expected = 0; while( !RpInitLock.compare_exchange_weak( expected, 1, std::memory_order_release, std::memory_order_relaxed ) ) { expected = 0; YieldThread(); } const auto done = RpInitDone.load( std::memory_order_acquire ); if( !done ) { rpmalloc_initialize(); RpInitDone.store( 1, std::memory_order_release ); } RpInitLock.store( 0, std::memory_order_release ); } rpmalloc_thread_initialize(); RpThreadInitDone = true; } TRACY_API void InitRpmalloc() { if( !RpThreadInitDone ) InitRpmallocPlumbing(); } } #endif
whupdup/frame
real/third_party/tracy/client/TracyAlloc.cpp
C++
gpl-3.0
1,048
namespace tracy { #if defined __linux__ && defined __ARM_ARCH static const char* DecodeArmImplementer( uint32_t v ) { static char buf[16]; switch( v ) { case 0x41: return "ARM"; case 0x42: return "Broadcom"; case 0x43: return "Cavium"; case 0x44: return "DEC"; case 0x46: return "Fujitsu"; case 0x48: return "HiSilicon"; case 0x49: return "Infineon"; case 0x4d: return "Motorola"; case 0x4e: return "Nvidia"; case 0x50: return "Applied Micro"; case 0x51: return "Qualcomm"; case 0x53: return "Samsung"; case 0x54: return "Texas Instruments"; case 0x56: return "Marvell"; case 0x61: return "Apple"; case 0x66: return "Faraday"; case 0x68: return "HXT"; case 0x69: return "Intel"; case 0xc0: return "Ampere Computing"; default: break; } sprintf( buf, "0x%x", v ); return buf; } static const char* DecodeArmPart( uint32_t impl, uint32_t part ) { static char buf[16]; switch( impl ) { case 0x41: // ARM switch( part ) { case 0x810: return "810"; case 0x920: return "920"; case 0x922: return "922"; case 0x926: return "926"; case 0x940: return "940"; case 0x946: return "946"; case 0x966: return "966"; case 0xa20: return "1020"; case 0xa22: return "1022"; case 0xa26: return "1026"; case 0xb02: return "11 MPCore"; case 0xb36: return "1136"; case 0xb56: return "1156"; case 0xb76: return "1176"; case 0xc05: return " Cortex-A5"; case 0xc07: return " Cortex-A7"; case 0xc08: return " Cortex-A8"; case 0xc09: return " Cortex-A9"; case 0xc0c: return " Cortex-A12"; case 0xc0d: return " Rockchip RK3288"; case 0xc0e: return " Cortex-A17"; case 0xc0f: return " Cortex-A15"; case 0xc14: return " Cortex-R4"; case 0xc15: return " Cortex-R5"; case 0xc17: return " Cortex-R7"; case 0xc18: return " Cortex-R8"; case 0xc20: return " Cortex-M0"; case 0xc21: return " Cortex-M1"; case 0xc23: return " Cortex-M3"; case 0xc24: return " Cortex-M4"; case 0xc27: return " Cortex-M7"; case 0xc60: return " Cortex-M0+"; case 0xd00: return " AArch64 simulator"; case 0xd01: return " Cortex-A32"; case 0xd02: return " Cortex-A34"; case 0xd03: return " Cortex-A53"; case 0xd04: return " Cortex-A35"; case 0xd05: return " Cortex-A55"; case 0xd06: return " Cortex-A65"; case 0xd07: return " Cortex-A57"; case 0xd08: return " Cortex-A72"; case 0xd09: return " Cortex-A73"; case 0xd0a: return " Cortex-A75"; case 0xd0b: return " Cortex-A76"; case 0xd0c: return " Neoverse N1"; case 0xd0d: return " Cortex-A77"; case 0xd0e: return " Cortex-A76AE"; case 0xd0f: return " AEMv8"; case 0xd13: return " Cortex-R52"; case 0xd20: return " Cortex-M23"; case 0xd21: return " Cortex-M33"; case 0xd22: return " Cortex-M55"; case 0xd40: return " Neoverse V1"; case 0xd41: return " Cortex-A78"; case 0xd42: return " Cortex-A78AE"; case 0xd43: return " Cortex-A65AE"; case 0xd44: return " Cortex-X1"; case 0xd47: return " Cortex-A710"; case 0xd48: return " Cortex-X2"; case 0xd49: return " Neoverse N2"; case 0xd4a: return " Neoverse E1"; case 0xd4b: return " Cortex-A78C"; case 0xd4c: return " Cortex-X1C"; default: break; } case 0x42: // Broadcom switch( part ) { case 0xf: return " Brahma B15"; case 0x100: return " Brahma B53"; case 0x516: return " ThunderX2"; default: break; } case 0x43: // Cavium switch( part ) { case 0xa0: return " ThunderX"; case 0xa1: return " ThunderX 88XX"; case 0xa2: return " ThunderX 81XX"; case 0xa3: return " ThunderX 83XX"; case 0xaf: return " ThunderX2 99xx"; case 0xb0: return " OcteonTX2"; case 0xb1: return " OcteonTX2 T98"; case 0xb2: return " OcteonTX2 T96"; case 0xb3: return " OcteonTX2 F95"; case 0xb4: return " OcteonTX2 F95N"; case 0xb5: return " OcteonTX2 F95MM"; case 0xb6: return " OcteonTX2 F95O"; case 0xb8: return " ThunderX3 T110"; default: break; } case 0x44: // DEC switch( part ) { case 0xa10: return " SA110"; case 0xa11: return " SA1100"; default: break; } case 0x46: // Fujitsu switch( part ) { case 0x1: return " A64FX"; default: break; } case 0x48: // HiSilicon switch( part ) { case 0xd01: return " TSV100"; case 0xd40: return " Kirin 980"; default: break; } case 0x4e: // Nvidia switch( part ) { case 0x0: return " Denver"; case 0x3: return " Denver 2"; case 0x4: return " Carmel"; default: break; } case 0x50: // Applied Micro switch( part ) { case 0x0: return " X-Gene"; default: break; } case 0x51: // Qualcomm switch( part ) { case 0xf: return " Scorpion"; case 0x2d: return " Scorpion"; case 0x4d: return " Krait"; case 0x6f: return " Krait"; case 0x200: return " Kryo"; case 0x201: return " Kryo Silver (Snapdragon 821)"; case 0x205: return " Kryo Gold"; case 0x211: return " Kryo Silver (Snapdragon 820)"; case 0x800: return " Kryo 260 / 280 Gold"; case 0x801: return " Kryo 260 / 280 Silver"; case 0x802: return " Kryo 385 Gold"; case 0x803: return " Kryo 385 Silver"; case 0x804: return " Kryo 485 Gold"; case 0x805: return " Kryo 4xx/5xx Silver"; case 0xc00: return " Falkor"; case 0xc01: return " Saphira"; default: break; } case 0x53: // Samsung switch( part ) { case 0x1: return " Exynos M1/M2"; case 0x2: return " Exynos M3"; case 0x3: return " Exynos M4"; case 0x4: return " Exynos M5"; default: break; } case 0x54: // Texas Instruments switch( part ) { case 0x925: return " TI925"; default: break; } case 0x56: // Marvell switch( part ) { case 0x131: return " Feroceon 88FR131"; case 0x581: return " PJ4 / PJ4B"; case 0x584: return " PJ4B-MP / PJ4C"; default: break; } case 0x61: // Apple switch( part ) { case 0x1: return " Cyclone"; case 0x2: return " Typhoon"; case 0x3: return " Typhoon/Capri"; case 0x4: return " Twister"; case 0x5: return " Twister/Elba/Malta"; case 0x6: return " Hurricane"; case 0x7: return " Hurricane/Myst"; case 0x22: return " M1 Icestorm"; case 0x23: return " M1 Firestorm"; case 0x24: return " M1 Icestorm Pro"; case 0x25: return " M1 Firestorm Pro"; case 0x28: return " M1 Icestorm Max"; case 0x29: return " M1 Firestorm Max"; default: break; } case 0x66: // Faraday switch( part ) { case 0x526: return " FA526"; case 0x626: return " FA626"; default: break; } case 0x68: // HXT switch( part ) { case 0x0: return " Phecda"; default: break; } case 0xc0: // Ampere Computing switch( part ) { case 0xac3: return " Ampere1"; default: break; } default: break; } sprintf( buf, " 0x%x", part ); return buf; } #elif defined __APPLE__ && TARGET_OS_IPHONE == 1 static const char* DecodeIosDevice( const char* id ) { static const char* DeviceTable[] = { "i386", "32-bit simulator", "x86_64", "64-bit simulator", "iPhone1,1", "iPhone", "iPhone1,2", "iPhone 3G", "iPhone2,1", "iPhone 3GS", "iPhone3,1", "iPhone 4 (GSM)", "iPhone3,2", "iPhone 4 (GSM)", "iPhone3,3", "iPhone 4 (CDMA)", "iPhone4,1", "iPhone 4S", "iPhone5,1", "iPhone 5 (A1428)", "iPhone5,2", "iPhone 5 (A1429)", "iPhone5,3", "iPhone 5c (A1456/A1532)", "iPhone5,4", "iPhone 5c (A1507/A1516/1526/A1529)", "iPhone6,1", "iPhone 5s (A1433/A1533)", "iPhone6,2", "iPhone 5s (A1457/A1518/A1528/A1530)", "iPhone7,1", "iPhone 6 Plus", "iPhone7,2", "iPhone 6", "iPhone8,1", "iPhone 6S", "iPhone8,2", "iPhone 6S Plus", "iPhone8,4", "iPhone SE", "iPhone9,1", "iPhone 7 (CDMA)", "iPhone9,2", "iPhone 7 Plus (CDMA)", "iPhone9,3", "iPhone 7 (GSM)", "iPhone9,4", "iPhone 7 Plus (GSM)", "iPhone10,1", "iPhone 8 (CDMA)", "iPhone10,2", "iPhone 8 Plus (CDMA)", "iPhone10,3", "iPhone X (CDMA)", "iPhone10,4", "iPhone 8 (GSM)", "iPhone10,5", "iPhone 8 Plus (GSM)", "iPhone10,6", "iPhone X (GSM)", "iPhone11,2", "iPhone XS", "iPhone11,4", "iPhone XS Max", "iPhone11,6", "iPhone XS Max China", "iPhone11,8", "iPhone XR", "iPhone12,1", "iPhone 11", "iPhone12,3", "iPhone 11 Pro", "iPhone12,5", "iPhone 11 Pro Max", "iPhone12,8", "iPhone SE 2nd Gen", "iPhone13,1", "iPhone 12 Mini", "iPhone13,2", "iPhone 12", "iPhone13,3", "iPhone 12 Pro", "iPhone13,4", "iPhone 12 Pro Max", "iPhone14,2", "iPhone 13 Pro", "iPhone14,3", "iPhone 13 Pro Max", "iPhone14,4", "iPhone 13 Mini", "iPhone14,5", "iPhone 13", "iPhone14,6", "iPhone SE 3rd Gen", "iPad1,1", "iPad (A1219/A1337)", "iPad2,1", "iPad 2 (A1395)", "iPad2,2", "iPad 2 (A1396)", "iPad2,3", "iPad 2 (A1397)", "iPad2,4", "iPad 2 (A1395)", "iPad2,5", "iPad Mini (A1432)", "iPad2,6", "iPad Mini (A1454)", "iPad2,7", "iPad Mini (A1455)", "iPad3,1", "iPad 3 (A1416)", "iPad3,2", "iPad 3 (A1403)", "iPad3,3", "iPad 3 (A1430)", "iPad3,4", "iPad 4 (A1458)", "iPad3,5", "iPad 4 (A1459)", "iPad3,6", "iPad 4 (A1460)", "iPad4,1", "iPad Air (A1474)", "iPad4,2", "iPad Air (A1475)", "iPad4,3", "iPad Air (A1476)", "iPad4,4", "iPad Mini 2 (A1489)", "iPad4,5", "iPad Mini 2 (A1490)", "iPad4,6", "iPad Mini 2 (A1491)", "iPad4,7", "iPad Mini 3 (A1599)", "iPad4,8", "iPad Mini 3 (A1600)", "iPad4,9", "iPad Mini 3 (A1601)", "iPad5,1", "iPad Mini 4 (A1538)", "iPad5,2", "iPad Mini 4 (A1550)", "iPad5,3", "iPad Air 2 (A1566)", "iPad5,4", "iPad Air 2 (A1567)", "iPad6,3", "iPad Pro 9.7\" (A1673)", "iPad6,4", "iPad Pro 9.7\" (A1674)", "iPad6,5", "iPad Pro 9.7\" (A1675)", "iPad6,7", "iPad Pro 12.9\" (A1584)", "iPad6,8", "iPad Pro 12.9\" (A1652)", "iPad6,11", "iPad 5th gen (A1822)", "iPad6,12", "iPad 5th gen (A1823)", "iPad7,1", "iPad Pro 12.9\" 2nd gen (A1670)", "iPad7,2", "iPad Pro 12.9\" 2nd gen (A1671/A1821)", "iPad7,3", "iPad Pro 10.5\" (A1701)", "iPad7,4", "iPad Pro 10.5\" (A1709)", "iPad7,5", "iPad 6th gen (A1893)", "iPad7,6", "iPad 6th gen (A1954)", "iPad7,11", "iPad 7th gen 10.2\" (Wifi)", "iPad7,12", "iPad 7th gen 10.2\" (Wifi+Cellular)", "iPad8,1", "iPad Pro 11\" (A1980)", "iPad8,2", "iPad Pro 11\" (A1980)", "iPad8,3", "iPad Pro 11\" (A1934/A1979/A2013)", "iPad8,4", "iPad Pro 11\" (A1934/A1979/A2013)", "iPad8,5", "iPad Pro 12.9\" 3rd gen (A1876)", "iPad8,6", "iPad Pro 12.9\" 3rd gen (A1876)", "iPad8,7", "iPad Pro 12.9\" 3rd gen (A1895/A1983/A2014)", "iPad8,8", "iPad Pro 12.9\" 3rd gen (A1895/A1983/A2014)", "iPad8,9", "iPad Pro 11\" 2nd gen (Wifi)", "iPad8,10", "iPad Pro 11\" 2nd gen (Wifi+Cellular)", "iPad8,11", "iPad Pro 12.9\" 4th gen (Wifi)", "iPad8,12", "iPad Pro 12.9\" 4th gen (Wifi+Cellular)", "iPad11,1", "iPad Mini 5th gen (A2133)", "iPad11,2", "iPad Mini 5th gen (A2124/A2125/A2126)", "iPad11,3", "iPad Air 3rd gen (A2152)", "iPad11,4", "iPad Air 3rd gen (A2123/A2153/A2154)", "iPad11,6", "iPad 8th gen (WiFi)", "iPad11,7", "iPad 8th gen (WiFi+Cellular)", "iPad13,1", "iPad Air 4th gen (WiFi)", "iPad13,2", "iPad Air 4th gen (WiFi+Cellular)", "iPad13,4", "iPad Pro 11\" 3rd gen", "iPad13,5", "iPad Pro 11\" 3rd gen", "iPad13,6", "iPad Pro 11\" 3rd gen", "iPad13,7", "iPad Pro 11\" 3rd gen", "iPad13,8", "iPad Pro 12.9\" 5th gen", "iPad13,9", "iPad Pro 12.9\" 5th gen", "iPad13,10", "iPad Pro 12.9\" 5th gen", "iPad13,11", "iPad Pro 12.9\" 5th gen", "iPad13,16", "iPad Air 5th Gen (WiFi)", "iPad13,17", "iPad Air 5th Gen (WiFi+Cellular)", "iPod1,1", "iPod Touch", "iPod2,1", "iPod Touch 2nd gen", "iPod3,1", "iPod Touch 3rd gen", "iPod4,1", "iPod Touch 4th gen", "iPod5,1", "iPod Touch 5th gen", "iPod7,1", "iPod Touch 6th gen", "iPod9,1", "iPod Touch 7th gen", nullptr }; auto ptr = DeviceTable; while( *ptr ) { if( strcmp( ptr[0], id ) == 0 ) return ptr[1]; ptr += 2; } return id; } #endif }
whupdup/frame
real/third_party/tracy/client/TracyArmCpuTable.hpp
C++
gpl-3.0
13,769
#include <new> #include <stdio.h> #include <string.h> #include "TracyCallstack.hpp" #include "TracyFastVector.hpp" #include "TracyStringHelpers.hpp" #include "../common/TracyAlloc.hpp" #include "../common/TracyStackFrames.hpp" #include "TracyDebug.hpp" #ifdef TRACY_HAS_CALLSTACK #if TRACY_HAS_CALLSTACK == 1 # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> # include <psapi.h> # include <algorithm> # ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable : 4091 ) # endif # include <dbghelp.h> # ifdef _MSC_VER # pragma warning( pop ) # endif #elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6 # include "../libbacktrace/backtrace.hpp" # include <algorithm> # include <dlfcn.h> # include <cxxabi.h> # include <stdlib.h> # include "TracyFastVector.hpp" #elif TRACY_HAS_CALLSTACK == 5 # include <dlfcn.h> # include <cxxabi.h> #endif #ifdef TRACY_DBGHELP_LOCK # include "TracyProfiler.hpp" # define DBGHELP_INIT TracyConcat( TRACY_DBGHELP_LOCK, Init() ) # define DBGHELP_LOCK TracyConcat( TRACY_DBGHELP_LOCK, Lock() ); # define DBGHELP_UNLOCK TracyConcat( TRACY_DBGHELP_LOCK, Unlock() ); extern "C" { void DBGHELP_INIT; void DBGHELP_LOCK; void DBGHELP_UNLOCK; }; #endif #if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 5 || TRACY_HAS_CALLSTACK == 6 extern "C" int ___tracy_demangle( const char* mangled, char* out, size_t len ); #ifndef TRACY_DEMANGLE extern "C" int ___tracy_demangle( const char* mangled, char* out, size_t len ) { if( !mangled || mangled[0] != '_' ) return 0; int status; abi::__cxa_demangle( mangled, out, &len, &status ); return status == 0; } #endif #endif namespace tracy { #if TRACY_HAS_CALLSTACK == 1 enum { MaxCbTrace = 16 }; enum { MaxNameSize = 8*1024 }; int cb_num; CallstackEntry cb_data[MaxCbTrace]; extern "C" { typedef DWORD (__stdcall *t_SymAddrIncludeInlineTrace)( HANDLE hProcess, DWORD64 Address ); typedef BOOL (__stdcall *t_SymQueryInlineTrace)( HANDLE hProcess, DWORD64 StartAddress, DWORD StartContext, DWORD64 StartRetAddress, DWORD64 CurAddress, LPDWORD CurContext, LPDWORD CurFrameIndex ); typedef BOOL (__stdcall *t_SymFromInlineContext)( HANDLE hProcess, DWORD64 Address, ULONG InlineContext, PDWORD64 Displacement, PSYMBOL_INFO Symbol ); typedef BOOL (__stdcall *t_SymGetLineFromInlineContext)( HANDLE hProcess, DWORD64 qwAddr, ULONG InlineContext, DWORD64 qwModuleBaseAddress, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line64 ); TRACY_API ___tracy_t_RtlWalkFrameChain ___tracy_RtlWalkFrameChain = 0; t_SymAddrIncludeInlineTrace _SymAddrIncludeInlineTrace = 0; t_SymQueryInlineTrace _SymQueryInlineTrace = 0; t_SymFromInlineContext _SymFromInlineContext = 0; t_SymGetLineFromInlineContext _SymGetLineFromInlineContext = 0; } struct ModuleCache { uint64_t start; uint64_t end; char* name; }; static FastVector<ModuleCache>* s_modCache; struct KernelDriver { uint64_t addr; const char* mod; const char* path; }; KernelDriver* s_krnlCache = nullptr; size_t s_krnlCacheCnt; void InitCallstack() { ___tracy_RtlWalkFrameChain = (___tracy_t_RtlWalkFrameChain)GetProcAddress( GetModuleHandleA( "ntdll.dll" ), "RtlWalkFrameChain" ); _SymAddrIncludeInlineTrace = (t_SymAddrIncludeInlineTrace)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymAddrIncludeInlineTrace" ); _SymQueryInlineTrace = (t_SymQueryInlineTrace)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymQueryInlineTrace" ); _SymFromInlineContext = (t_SymFromInlineContext)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymFromInlineContext" ); _SymGetLineFromInlineContext = (t_SymGetLineFromInlineContext)GetProcAddress( GetModuleHandleA( "dbghelp.dll" ), "SymGetLineFromInlineContext" ); #ifdef TRACY_DBGHELP_LOCK DBGHELP_INIT; DBGHELP_LOCK; #endif SymInitialize( GetCurrentProcess(), nullptr, true ); SymSetOptions( SYMOPT_LOAD_LINES ); DWORD needed; LPVOID dev[4096]; if( EnumDeviceDrivers( dev, sizeof(dev), &needed ) != 0 ) { char windir[MAX_PATH]; if( !GetWindowsDirectoryA( windir, sizeof( windir ) ) ) memcpy( windir, "c:\\windows", 11 ); const auto windirlen = strlen( windir ); const auto sz = needed / sizeof( LPVOID ); s_krnlCache = (KernelDriver*)tracy_malloc( sizeof(KernelDriver) * sz ); int cnt = 0; for( size_t i=0; i<sz; i++ ) { char fn[MAX_PATH]; const auto len = GetDeviceDriverBaseNameA( dev[i], fn, sizeof( fn ) ); if( len != 0 ) { auto buf = (char*)tracy_malloc_fast( len+3 ); buf[0] = '<'; memcpy( buf+1, fn, len ); memcpy( buf+len+1, ">", 2 ); s_krnlCache[cnt] = KernelDriver { (uint64_t)dev[i], buf }; const auto len = GetDeviceDriverFileNameA( dev[i], fn, sizeof( fn ) ); if( len != 0 ) { char full[MAX_PATH]; char* path = fn; if( memcmp( fn, "\\SystemRoot\\", 12 ) == 0 ) { memcpy( full, windir, windirlen ); strcpy( full + windirlen, fn + 11 ); path = full; } SymLoadModuleEx( GetCurrentProcess(), nullptr, path, nullptr, (DWORD64)dev[i], 0, nullptr, 0 ); const auto psz = strlen( path ); auto pptr = (char*)tracy_malloc_fast( psz+1 ); memcpy( pptr, path, psz ); pptr[psz] = '\0'; s_krnlCache[cnt].path = pptr; } cnt++; } } s_krnlCacheCnt = cnt; std::sort( s_krnlCache, s_krnlCache + s_krnlCacheCnt, []( const KernelDriver& lhs, const KernelDriver& rhs ) { return lhs.addr > rhs.addr; } ); } s_modCache = (FastVector<ModuleCache>*)tracy_malloc( sizeof( FastVector<ModuleCache> ) ); new(s_modCache) FastVector<ModuleCache>( 512 ); HANDLE proc = GetCurrentProcess(); HMODULE mod[1024]; if( EnumProcessModules( proc, mod, sizeof( mod ), &needed ) != 0 ) { const auto sz = needed / sizeof( HMODULE ); for( size_t i=0; i<sz; i++ ) { MODULEINFO info; if( GetModuleInformation( proc, mod[i], &info, sizeof( info ) ) != 0 ) { const auto base = uint64_t( info.lpBaseOfDll ); char name[1024]; const auto res = GetModuleFileNameA( mod[i], name, 1021 ); if( res > 0 ) { auto ptr = name + res; while( ptr > name && *ptr != '\\' && *ptr != '/' ) ptr--; if( ptr > name ) ptr++; const auto namelen = name + res - ptr; auto cache = s_modCache->push_next(); cache->start = base; cache->end = base + info.SizeOfImage; cache->name = (char*)tracy_malloc_fast( namelen+3 ); cache->name[0] = '['; memcpy( cache->name+1, ptr, namelen ); cache->name[namelen+1] = ']'; cache->name[namelen+2] = '\0'; } } } } #ifdef TRACY_DBGHELP_LOCK DBGHELP_UNLOCK; #endif } void EndCallstack() { } const char* DecodeCallstackPtrFast( uint64_t ptr ) { static char ret[MaxNameSize]; const auto proc = GetCurrentProcess(); char buf[sizeof( SYMBOL_INFO ) + MaxNameSize]; auto si = (SYMBOL_INFO*)buf; si->SizeOfStruct = sizeof( SYMBOL_INFO ); si->MaxNameLen = MaxNameSize; #ifdef TRACY_DBGHELP_LOCK DBGHELP_LOCK; #endif if( SymFromAddr( proc, ptr, nullptr, si ) == 0 ) { *ret = '\0'; } else { memcpy( ret, si->Name, si->NameLen ); ret[si->NameLen] = '\0'; } #ifdef TRACY_DBGHELP_LOCK DBGHELP_UNLOCK; #endif return ret; } const char* GetKernelModulePath( uint64_t addr ) { assert( addr >> 63 != 0 ); if( !s_krnlCache ) return nullptr; auto it = std::lower_bound( s_krnlCache, s_krnlCache + s_krnlCacheCnt, addr, []( const KernelDriver& lhs, const uint64_t& rhs ) { return lhs.addr > rhs; } ); if( it == s_krnlCache + s_krnlCacheCnt ) return nullptr; return it->path; } static const char* GetModuleNameAndPrepareSymbols( uint64_t addr ) { if( ( addr >> 63 ) != 0 ) { if( s_krnlCache ) { auto it = std::lower_bound( s_krnlCache, s_krnlCache + s_krnlCacheCnt, addr, []( const KernelDriver& lhs, const uint64_t& rhs ) { return lhs.addr > rhs; } ); if( it != s_krnlCache + s_krnlCacheCnt ) { return it->mod; } } return "<kernel>"; } for( auto& v : *s_modCache ) { if( addr >= v.start && addr < v.end ) { return v.name; } } HMODULE mod[1024]; DWORD needed; HANDLE proc = GetCurrentProcess(); InitRpmalloc(); if( EnumProcessModules( proc, mod, sizeof( mod ), &needed ) != 0 ) { const auto sz = needed / sizeof( HMODULE ); for( size_t i=0; i<sz; i++ ) { MODULEINFO info; if( GetModuleInformation( proc, mod[i], &info, sizeof( info ) ) != 0 ) { const auto base = uint64_t( info.lpBaseOfDll ); if( addr >= base && addr < base + info.SizeOfImage ) { char name[1024]; const auto res = GetModuleFileNameA( mod[i], name, 1021 ); if( res > 0 ) { // since this is the first time we encounter this module, load its symbols (needed for modules loaded after SymInitialize) SymLoadModuleEx(proc, NULL, name, NULL, (DWORD64)info.lpBaseOfDll, info.SizeOfImage, NULL, 0); auto ptr = name + res; while( ptr > name && *ptr != '\\' && *ptr != '/' ) ptr--; if( ptr > name ) ptr++; const auto namelen = name + res - ptr; auto cache = s_modCache->push_next(); cache->start = base; cache->end = base + info.SizeOfImage; cache->name = (char*)tracy_malloc_fast( namelen+3 ); cache->name[0] = '['; memcpy( cache->name+1, ptr, namelen ); cache->name[namelen+1] = ']'; cache->name[namelen+2] = '\0'; return cache->name; } } } } } return "[unknown]"; } CallstackSymbolData DecodeSymbolAddress( uint64_t ptr ) { CallstackSymbolData sym; IMAGEHLP_LINE64 line; DWORD displacement = 0; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); #ifdef TRACY_DBGHELP_LOCK DBGHELP_LOCK; #endif const auto res = SymGetLineFromAddr64( GetCurrentProcess(), ptr, &displacement, &line ); if( res == 0 || line.LineNumber >= 0xF00000 ) { sym.file = "[unknown]"; sym.line = 0; sym.needFree = false; } else { sym.file = CopyString( line.FileName ); sym.line = line.LineNumber; sym.needFree = true; } #ifdef TRACY_DBGHELP_LOCK DBGHELP_UNLOCK; #endif return sym; } CallstackSymbolData DecodeCodeAddress( uint64_t ptr ) { CallstackSymbolData sym = {}; const auto proc = GetCurrentProcess(); bool done = false; char buf[sizeof( SYMBOL_INFO ) + MaxNameSize]; auto si = (SYMBOL_INFO*)buf; si->SizeOfStruct = sizeof( SYMBOL_INFO ); si->MaxNameLen = MaxNameSize; IMAGEHLP_LINE64 line; DWORD displacement = 0; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); #ifdef TRACY_DBGHELP_LOCK DBGHELP_LOCK; #endif #if !defined TRACY_NO_CALLSTACK_INLINES if( _SymAddrIncludeInlineTrace ) { DWORD inlineNum = _SymAddrIncludeInlineTrace( proc, ptr ); DWORD ctx = 0; DWORD idx; BOOL doInline = FALSE; if( inlineNum != 0 ) doInline = _SymQueryInlineTrace( proc, ptr, 0, ptr, ptr, &ctx, &idx ); if( doInline ) { if( _SymGetLineFromInlineContext( proc, ptr, ctx, 0, &displacement, &line ) != 0 ) { sym.file = CopyString( line.FileName ); sym.line = line.LineNumber; sym.needFree = true; done = true; if( _SymFromInlineContext( proc, ptr, ctx, nullptr, si ) != 0 ) { sym.symAddr = si->Address; } else { sym.symAddr = 0; } } } } #endif if( !done ) { const auto res = SymGetLineFromAddr64( proc, ptr, &displacement, &line ); if( res == 0 || line.LineNumber >= 0xF00000 ) { sym.file = "[unknown]"; sym.line = 0; sym.symAddr = 0; sym.needFree = false; } else { sym.file = CopyString( line.FileName ); sym.line = line.LineNumber; sym.needFree = true; if( SymFromAddr( proc, ptr, nullptr, si ) != 0 ) { sym.symAddr = si->Address; } else { sym.symAddr = 0; } } } #ifdef TRACY_DBGHELP_LOCK DBGHELP_UNLOCK; #endif return sym; } CallstackEntryData DecodeCallstackPtr( uint64_t ptr ) { int write; const auto proc = GetCurrentProcess(); InitRpmalloc(); #ifdef TRACY_DBGHELP_LOCK DBGHELP_LOCK; #endif const auto moduleName = GetModuleNameAndPrepareSymbols(ptr); #if !defined TRACY_NO_CALLSTACK_INLINES BOOL doInline = FALSE; DWORD ctx = 0; DWORD inlineNum = 0; if( _SymAddrIncludeInlineTrace ) { inlineNum = _SymAddrIncludeInlineTrace( proc, ptr ); if( inlineNum > MaxCbTrace - 1 ) inlineNum = MaxCbTrace - 1; DWORD idx; if( inlineNum != 0 ) doInline = _SymQueryInlineTrace( proc, ptr, 0, ptr, ptr, &ctx, &idx ); } if( doInline ) { write = inlineNum; cb_num = 1 + inlineNum; } else #endif { write = 0; cb_num = 1; } char buf[sizeof( SYMBOL_INFO ) + MaxNameSize]; auto si = (SYMBOL_INFO*)buf; si->SizeOfStruct = sizeof( SYMBOL_INFO ); si->MaxNameLen = MaxNameSize; const auto symValid = SymFromAddr( proc, ptr, nullptr, si ) != 0; IMAGEHLP_LINE64 line; DWORD displacement = 0; line.SizeOfStruct = sizeof(IMAGEHLP_LINE64); { const char* filename; const auto res = SymGetLineFromAddr64( proc, ptr, &displacement, &line ); if( res == 0 || line.LineNumber >= 0xF00000 ) { filename = "[unknown]"; cb_data[write].line = 0; } else { filename = line.FileName; cb_data[write].line = line.LineNumber; } cb_data[write].name = symValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleName ); cb_data[write].file = CopyStringFast( filename ); if( symValid ) { cb_data[write].symLen = si->Size; cb_data[write].symAddr = si->Address; } else { cb_data[write].symLen = 0; cb_data[write].symAddr = 0; } } #if !defined TRACY_NO_CALLSTACK_INLINES if( doInline ) { for( DWORD i=0; i<inlineNum; i++ ) { auto& cb = cb_data[i]; const auto symInlineValid = _SymFromInlineContext( proc, ptr, ctx, nullptr, si ) != 0; const char* filename; if( _SymGetLineFromInlineContext( proc, ptr, ctx, 0, &displacement, &line ) == 0 ) { filename = "[unknown]"; cb.line = 0; } else { filename = line.FileName; cb.line = line.LineNumber; } cb.name = symInlineValid ? CopyStringFast( si->Name, si->NameLen ) : CopyStringFast( moduleName ); cb.file = CopyStringFast( filename ); if( symInlineValid ) { cb.symLen = si->Size; cb.symAddr = si->Address; } else { cb.symLen = 0; cb.symAddr = 0; } ctx++; } } #endif #ifdef TRACY_DBGHELP_LOCK DBGHELP_UNLOCK; #endif return { cb_data, uint8_t( cb_num ), moduleName }; } #elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6 enum { MaxCbTrace = 16 }; struct backtrace_state* cb_bts; int cb_num; CallstackEntry cb_data[MaxCbTrace]; int cb_fixup; #ifdef TRACY_DEBUGINFOD debuginfod_client* s_debuginfod; struct DebugInfo { uint8_t* buildid; size_t buildid_size; char* filename; int fd; }; FastVector<DebugInfo> s_di_known( 16 ); #endif #ifdef __linux struct KernelSymbol { uint64_t addr; const char* name; const char* mod; }; KernelSymbol* s_kernelSym = nullptr; size_t s_kernelSymCnt; static void InitKernelSymbols() { FILE* f = fopen( "/proc/kallsyms", "rb" ); if( !f ) return; tracy::FastVector<KernelSymbol> tmpSym( 1024 ); size_t linelen = 16 * 1024; // linelen must be big enough to prevent reallocs in getline() auto linebuf = (char*)tracy_malloc( linelen ); ssize_t sz; while( ( sz = getline( &linebuf, &linelen, f ) ) != -1 ) { auto ptr = linebuf; uint64_t addr = 0; while( *ptr != ' ' ) { auto v = *ptr; if( v >= '0' && v <= '9' ) { v -= '0'; } else if( v >= 'a' && v <= 'f' ) { v -= 'a'; v += 10; } else if( v >= 'A' && v <= 'F' ) { v -= 'A'; v += 10; } else { assert( false ); } assert( ( v & ~0xF ) == 0 ); addr <<= 4; addr |= v; ptr++; } if( addr == 0 ) continue; ptr++; if( *ptr != 'T' && *ptr != 't' ) continue; ptr += 2; const auto namestart = ptr; while( *ptr != '\t' && *ptr != '\n' ) ptr++; const auto nameend = ptr; const char* modstart = nullptr; const char* modend; if( *ptr == '\t' ) { ptr += 2; modstart = ptr; while( *ptr != ']' ) ptr++; modend = ptr; } auto strname = (char*)tracy_malloc_fast( nameend - namestart + 1 ); memcpy( strname, namestart, nameend - namestart ); strname[nameend-namestart] = '\0'; char* strmod = nullptr; if( modstart ) { strmod = (char*)tracy_malloc_fast( modend - modstart + 1 ); memcpy( strmod, modstart, modend - modstart ); strmod[modend-modstart] = '\0'; } auto sym = tmpSym.push_next(); sym->addr = addr; sym->name = strname; sym->mod = strmod; } tracy_free_fast( linebuf ); fclose( f ); if( tmpSym.empty() ) return; std::sort( tmpSym.begin(), tmpSym.end(), []( const KernelSymbol& lhs, const KernelSymbol& rhs ) { return lhs.addr > rhs.addr; } ); s_kernelSymCnt = tmpSym.size(); s_kernelSym = (KernelSymbol*)tracy_malloc_fast( sizeof( KernelSymbol ) * s_kernelSymCnt ); memcpy( s_kernelSym, tmpSym.data(), sizeof( KernelSymbol ) * s_kernelSymCnt ); TracyDebug( "Loaded %zu kernel symbols\n", s_kernelSymCnt ); } #endif void InitCallstack() { cb_bts = backtrace_create_state( nullptr, 0, nullptr, nullptr ); #ifdef __linux InitKernelSymbols(); #endif #ifdef TRACY_DEBUGINFOD s_debuginfod = debuginfod_begin(); #endif } #ifdef TRACY_DEBUGINFOD void ClearDebugInfoVector( FastVector<DebugInfo>& vec ) { for( auto& v : vec ) { tracy_free( v.buildid ); tracy_free( v.filename ); if( v.fd >= 0 ) close( v.fd ); } vec.clear(); } DebugInfo* FindDebugInfo( FastVector<DebugInfo>& vec, const uint8_t* buildid_data, size_t buildid_size ) { for( auto& v : vec ) { if( v.buildid_size == buildid_size && memcmp( v.buildid, buildid_data, buildid_size ) == 0 ) { return &v; } } return nullptr; } int GetDebugInfoDescriptor( const char* buildid_data, size_t buildid_size, const char* filename ) { auto buildid = (uint8_t*)buildid_data; auto it = FindDebugInfo( s_di_known, buildid, buildid_size ); if( it ) return it->fd >= 0 ? dup( it->fd ) : -1; int fd = debuginfod_find_debuginfo( s_debuginfod, buildid, buildid_size, nullptr ); it = s_di_known.push_next(); it->buildid_size = buildid_size; it->buildid = (uint8_t*)tracy_malloc( buildid_size ); memcpy( it->buildid, buildid, buildid_size ); const auto fnsz = strlen( filename ) + 1; it->filename = (char*)tracy_malloc( fnsz ); memcpy( it->filename, filename, fnsz ); it->fd = fd >= 0 ? fd : -1; return it->fd; } const uint8_t* GetBuildIdForImage( const char* image, size_t& size ) { assert( image ); for( auto& v : s_di_known ) { if( strcmp( image, v.filename ) == 0 ) { size = v.buildid_size; return v.buildid; } } return nullptr; } debuginfod_client* GetDebuginfodClient() { return s_debuginfod; } #endif void EndCallstack() { #ifdef TRACY_DEBUGINFOD ClearDebugInfoVector( s_di_known ); debuginfod_end( s_debuginfod ); #endif } static int FastCallstackDataCb( void* data, uintptr_t pc, uintptr_t lowaddr, const char* fn, int lineno, const char* function ) { if( function ) { strcpy( (char*)data, function ); } else { const char* symname = nullptr; auto vptr = (void*)pc; Dl_info dlinfo; if( dladdr( vptr, &dlinfo ) ) { symname = dlinfo.dli_sname; } if( symname ) { strcpy( (char*)data, symname ); } else { *(char*)data = '\0'; } } return 1; } static void FastCallstackErrorCb( void* data, const char* /*msg*/, int /*errnum*/ ) { *(char*)data = '\0'; } const char* DecodeCallstackPtrFast( uint64_t ptr ) { static char ret[1024]; backtrace_pcinfo( cb_bts, ptr, FastCallstackDataCb, FastCallstackErrorCb, ret ); return ret; } static int SymbolAddressDataCb( void* data, uintptr_t pc, uintptr_t lowaddr, const char* fn, int lineno, const char* function ) { auto& sym = *(CallstackSymbolData*)data; if( !fn ) { sym.file = "[unknown]"; sym.line = 0; sym.needFree = false; } else { sym.file = CopyString( fn ); sym.line = lineno; sym.needFree = true; } return 1; } static void SymbolAddressErrorCb( void* data, const char* /*msg*/, int /*errnum*/ ) { auto& sym = *(CallstackSymbolData*)data; sym.file = "[unknown]"; sym.line = 0; sym.needFree = false; } CallstackSymbolData DecodeSymbolAddress( uint64_t ptr ) { CallstackSymbolData sym; backtrace_pcinfo( cb_bts, ptr, SymbolAddressDataCb, SymbolAddressErrorCb, &sym ); return sym; } static int CodeDataCb( void* data, uintptr_t pc, uintptr_t lowaddr, const char* fn, int lineno, const char* function ) { if( !fn ) return 1; const auto fnsz = strlen( fn ); if( fnsz >= s_tracySkipSubframesMinLen ) { auto ptr = s_tracySkipSubframes; do { if( fnsz >= ptr->len && memcmp( fn + fnsz - ptr->len, ptr->str, ptr->len ) == 0 ) return 0; ptr++; } while( ptr->str ); } auto& sym = *(CallstackSymbolData*)data; sym.file = CopyString( fn ); sym.line = lineno; sym.needFree = true; sym.symAddr = lowaddr; return 1; } static void CodeErrorCb( void* /*data*/, const char* /*msg*/, int /*errnum*/ ) { } CallstackSymbolData DecodeCodeAddress( uint64_t ptr ) { CallstackSymbolData sym = { "[unknown]", 0, false, 0 }; backtrace_pcinfo( cb_bts, ptr, CodeDataCb, CodeErrorCb, &sym ); return sym; } static int CallstackDataCb( void* /*data*/, uintptr_t pc, uintptr_t lowaddr, const char* fn, int lineno, const char* function ) { enum { DemangleBufLen = 64*1024 }; char demangled[DemangleBufLen]; cb_data[cb_num].symLen = 0; cb_data[cb_num].symAddr = (uint64_t)lowaddr; if( !fn && !function ) { const char* symname = nullptr; auto vptr = (void*)pc; ptrdiff_t symoff = 0; Dl_info dlinfo; if( dladdr( vptr, &dlinfo ) ) { symname = dlinfo.dli_sname; symoff = (char*)pc - (char*)dlinfo.dli_saddr; if( ___tracy_demangle( symname, demangled, DemangleBufLen ) ) symname = demangled; } if( !symname ) symname = "[unknown]"; if( symoff == 0 ) { cb_data[cb_num].name = CopyStringFast( symname ); } else { char buf[32]; const auto offlen = sprintf( buf, " + %td", symoff ); const auto namelen = strlen( symname ); auto name = (char*)tracy_malloc_fast( namelen + offlen + 1 ); memcpy( name, symname, namelen ); memcpy( name + namelen, buf, offlen ); name[namelen + offlen] = '\0'; cb_data[cb_num].name = name; } cb_data[cb_num].file = CopyStringFast( "[unknown]" ); cb_data[cb_num].line = 0; } else { if( !fn ) fn = "[unknown]"; if( !function ) { function = "[unknown]"; } else if( ___tracy_demangle( function, demangled, DemangleBufLen ) ) { function = demangled; } cb_data[cb_num].name = CopyStringFast( function ); cb_data[cb_num].file = CopyStringFast( fn ); cb_data[cb_num].line = lineno; } if( ++cb_num >= MaxCbTrace ) { return 1; } else { return 0; } } static void CallstackErrorCb( void* /*data*/, const char* /*msg*/, int /*errnum*/ ) { for( int i=0; i<cb_num; i++ ) { tracy_free_fast( (void*)cb_data[i].name ); tracy_free_fast( (void*)cb_data[i].file ); } cb_data[0].name = CopyStringFast( "[error]" ); cb_data[0].file = CopyStringFast( "[error]" ); cb_data[0].line = 0; cb_num = 1; } void SymInfoCallback( void* /*data*/, uintptr_t pc, const char* symname, uintptr_t symval, uintptr_t symsize ) { cb_data[cb_num-1].symLen = (uint32_t)symsize; cb_data[cb_num-1].symAddr = (uint64_t)symval; } void SymInfoError( void* /*data*/, const char* /*msg*/, int /*errnum*/ ) { cb_data[cb_num-1].symLen = 0; cb_data[cb_num-1].symAddr = 0; } CallstackEntryData DecodeCallstackPtr( uint64_t ptr ) { InitRpmalloc(); if( ptr >> 63 == 0 ) { cb_num = 0; backtrace_pcinfo( cb_bts, ptr, CallstackDataCb, CallstackErrorCb, nullptr ); assert( cb_num > 0 ); backtrace_syminfo( cb_bts, ptr, SymInfoCallback, SymInfoError, nullptr ); const char* symloc = nullptr; Dl_info dlinfo; if( dladdr( (void*)ptr, &dlinfo ) ) symloc = dlinfo.dli_fname; return { cb_data, uint8_t( cb_num ), symloc ? symloc : "[unknown]" }; } #ifdef __linux else if( s_kernelSym ) { auto it = std::lower_bound( s_kernelSym, s_kernelSym + s_kernelSymCnt, ptr, []( const KernelSymbol& lhs, const uint64_t& rhs ) { return lhs.addr > rhs; } ); if( it != s_kernelSym + s_kernelSymCnt ) { cb_data[0].name = CopyStringFast( it->name ); cb_data[0].file = CopyStringFast( "<kernel>" ); cb_data[0].line = 0; cb_data[0].symLen = 0; cb_data[0].symAddr = it->addr; return { cb_data, 1, it->mod ? it->mod : "<kernel>" }; } } #endif cb_data[0].name = CopyStringFast( "[unknown]" ); cb_data[0].file = CopyStringFast( "<kernel>" ); cb_data[0].line = 0; cb_data[0].symLen = 0; cb_data[0].symAddr = 0; return { cb_data, 1, "<kernel>" }; } #elif TRACY_HAS_CALLSTACK == 5 void InitCallstack() { } void EndCallstack() { } const char* DecodeCallstackPtrFast( uint64_t ptr ) { static char ret[1024]; auto vptr = (void*)ptr; const char* symname = nullptr; Dl_info dlinfo; if( dladdr( vptr, &dlinfo ) && dlinfo.dli_sname ) { symname = dlinfo.dli_sname; } if( symname ) { strcpy( ret, symname ); } else { *ret = '\0'; } return ret; } CallstackSymbolData DecodeSymbolAddress( uint64_t ptr ) { const char* symloc = nullptr; Dl_info dlinfo; if( dladdr( (void*)ptr, &dlinfo ) ) symloc = dlinfo.dli_fname; if( !symloc ) symloc = "[unknown]"; return CallstackSymbolData { symloc, 0, false, 0 }; } CallstackSymbolData DecodeCodeAddress( uint64_t ptr ) { return DecodeSymbolAddress( ptr ); } CallstackEntryData DecodeCallstackPtr( uint64_t ptr ) { static CallstackEntry cb; cb.line = 0; enum { DemangleBufLen = 64*1024 }; char demangled[DemangleBufLen]; const char* symname = nullptr; const char* symloc = nullptr; auto vptr = (void*)ptr; ptrdiff_t symoff = 0; void* symaddr = nullptr; Dl_info dlinfo; if( dladdr( vptr, &dlinfo ) ) { symloc = dlinfo.dli_fname; symname = dlinfo.dli_sname; symoff = (char*)ptr - (char*)dlinfo.dli_saddr; symaddr = dlinfo.dli_saddr; if( ___tracy_demangle( symname, demangled, DemangleBufLen ) ) symname = demangled; } if( !symname ) symname = "[unknown]"; if( !symloc ) symloc = "[unknown]"; if( symoff == 0 ) { cb.name = CopyString( symname ); } else { char buf[32]; const auto offlen = sprintf( buf, " + %td", symoff ); const auto namelen = strlen( symname ); auto name = (char*)tracy_malloc( namelen + offlen + 1 ); memcpy( name, symname, namelen ); memcpy( name + namelen, buf, offlen ); name[namelen + offlen] = '\0'; cb.name = name; } cb.file = CopyString( "[unknown]" ); cb.symLen = 0; cb.symAddr = (uint64_t)symaddr; return { &cb, 1, symloc }; } #endif } #endif
whupdup/frame
real/third_party/tracy/client/TracyCallstack.cpp
C++
gpl-3.0
31,017
#ifndef __TRACYCALLSTACK_H__ #define __TRACYCALLSTACK_H__ #ifndef TRACY_NO_CALLSTACK # if !defined _WIN32 # include <sys/param.h> # endif # if defined _WIN32 # include "../common/TracyUwp.hpp" # ifndef TRACY_UWP # define TRACY_HAS_CALLSTACK 1 # endif # elif defined __ANDROID__ # if !defined __arm__ || __ANDROID_API__ >= 21 # define TRACY_HAS_CALLSTACK 2 # else # define TRACY_HAS_CALLSTACK 5 # endif # elif defined __linux # if defined _GNU_SOURCE && defined __GLIBC__ # define TRACY_HAS_CALLSTACK 3 # else # define TRACY_HAS_CALLSTACK 2 # endif # elif defined __APPLE__ # define TRACY_HAS_CALLSTACK 4 # elif defined BSD # define TRACY_HAS_CALLSTACK 6 # endif #endif #endif
whupdup/frame
real/third_party/tracy/client/TracyCallstack.h
C++
gpl-3.0
750
#ifndef __TRACYCALLSTACK_HPP__ #define __TRACYCALLSTACK_HPP__ #include "../common/TracyApi.h" #include "TracyCallstack.h" #if TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5 # include <unwind.h> #elif TRACY_HAS_CALLSTACK >= 3 # include <execinfo.h> #endif #ifdef TRACY_HAS_CALLSTACK #ifdef TRACY_DEBUGINFOD # include <elfutils/debuginfod.h> #endif #include <assert.h> #include <stdint.h> #include "../common/TracyAlloc.hpp" #include "../common/TracyForceInline.hpp" namespace tracy { struct CallstackSymbolData { const char* file; uint32_t line; bool needFree; uint64_t symAddr; }; struct CallstackEntry { const char* name; const char* file; uint32_t line; uint32_t symLen; uint64_t symAddr; }; struct CallstackEntryData { const CallstackEntry* data; uint8_t size; const char* imageName; }; CallstackSymbolData DecodeSymbolAddress( uint64_t ptr ); CallstackSymbolData DecodeCodeAddress( uint64_t ptr ); const char* DecodeCallstackPtrFast( uint64_t ptr ); CallstackEntryData DecodeCallstackPtr( uint64_t ptr ); void InitCallstack(); void EndCallstack(); const char* GetKernelModulePath( uint64_t addr ); #ifdef TRACY_DEBUGINFOD const uint8_t* GetBuildIdForImage( const char* image, size_t& size ); debuginfod_client* GetDebuginfodClient(); #endif #if TRACY_HAS_CALLSTACK == 1 extern "C" { typedef unsigned long (__stdcall *___tracy_t_RtlWalkFrameChain)( void**, unsigned long, unsigned long ); TRACY_API extern ___tracy_t_RtlWalkFrameChain ___tracy_RtlWalkFrameChain; } static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 && depth < 63 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) ); const auto num = ___tracy_RtlWalkFrameChain( (void**)( trace + 1 ), depth, 0 ); *trace = num; return trace; } #elif TRACY_HAS_CALLSTACK == 2 || TRACY_HAS_CALLSTACK == 5 struct BacktraceState { void** current; void** end; }; static _Unwind_Reason_Code tracy_unwind_callback( struct _Unwind_Context* ctx, void* arg ) { auto state = (BacktraceState*)arg; uintptr_t pc = _Unwind_GetIP( ctx ); if( pc ) { if( state->current == state->end ) return _URC_END_OF_STACK; *state->current++ = (void*)pc; } return _URC_NO_REASON; } static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 && depth < 63 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + depth ) * sizeof( uintptr_t ) ); BacktraceState state = { (void**)(trace+1), (void**)(trace+1+depth) }; _Unwind_Backtrace( tracy_unwind_callback, &state ); *trace = (uintptr_t*)state.current - trace + 1; return trace; } #elif TRACY_HAS_CALLSTACK == 3 || TRACY_HAS_CALLSTACK == 4 || TRACY_HAS_CALLSTACK == 6 static tracy_force_inline void* Callstack( int depth ) { assert( depth >= 1 ); auto trace = (uintptr_t*)tracy_malloc( ( 1 + (size_t)depth ) * sizeof( uintptr_t ) ); const auto num = (size_t)backtrace( (void**)(trace+1), depth ); *trace = num; return trace; } #endif } #endif #endif
whupdup/frame
real/third_party/tracy/client/TracyCallstack.hpp
C++
gpl-3.0
3,093
#ifndef __TRACYPRINT_HPP__ #define __TRACYPRINT_HPP__ #ifdef TRACY_VERBOSE # include <stdio.h> # define TracyDebug(...) fprintf( stderr, __VA_ARGS__ ); #else # define TracyDebug(...) #endif #endif
whupdup/frame
real/third_party/tracy/client/TracyDebug.hpp
C++
gpl-3.0
202