diff --git a/text_rendering/atlas.png b/text_rendering/atlas.png index 18aabd1..a0cfd30 100644 Binary files a/text_rendering/atlas.png and b/text_rendering/atlas.png differ diff --git a/text_rendering/cache.c b/text_rendering/cache.c index c891b3a..0113b95 100644 --- a/text_rendering/cache.c +++ b/text_rendering/cache.c @@ -16,13 +16,14 @@ static struct hm_ref *hash_table; static struct font_glyph cache_array[CACHE_SIZE] = {0}; // bitmap size is aligned to word -#define _BSIZE ((CACHE_SIZE+0x3f)&(~0x3f)) +// 2^6 == 64 bits, number of bits in a uint64_t +#define _BSIZE (((CACHE_SIZE+0x3f)&(~0x3f))>>6) static uint64_t bitmap[_BSIZE] = {0}; // bitmap operations -#define B_RESET() memset(bitmap, 0, _BSIZE*sizeof(uint64_t)) -#define B_SET(x) bitmap[(x)/_BSIZE] |= 1<<((x)%_BSIZE) -#define B_TEST(x) (bitmap[(x)/_BSIZE]&(1<<((x)%_BSIZE))) +#define B_RESET() for (int i = 0; i < _BSIZE; bitmap[i++] = 0); +#define B_SET(x) bitmap[(x)>>6] |= (uint64_t)1<<((x)%64) +#define B_TEST(x) (bitmap[(x)>>6]&((uint64_t)1<<((x)%64))) // reset the bitmap every n cycles #define NCYCLES (CACHE_SIZE/2) @@ -71,6 +72,18 @@ unsigned int cache_get(void) // find an open spot in the cache // TODO: use __builtin_clz to speed this up for (; x < CACHE_SIZE; x++) { + //printf("testing spot %d\n", x); + //print_byte(bitmap[0]>>56); + //print_byte(bitmap[0]>>48); + //print_byte(bitmap[0]>>40); + //print_byte(bitmap[0]>>32); + //print_byte(bitmap[0]>>24); + //print_byte(bitmap[0]>>16); + //print_byte(bitmap[0]>>8); + //print_byte(bitmap[0]); + //printf("%lx", bitmap[i]); + //printf("\n"); + if (!B_TEST(x)) break; } diff --git a/text_rendering/font.c b/text_rendering/font.c index 036cfce..812c6c3 100644 --- a/text_rendering/font.c +++ b/text_rendering/font.c @@ -1,42 +1,31 @@ #define _POSIX_C_SOURCE 200809l #define STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC -#define MSDF_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include #include #include "font.h" -#include "msdf_c/stb_truetype.h" -#include "msdf_c/msdf.h" +#include "stb_truetype.h" #include "stb_image_write.h" #include "util.h" #include "cache.h" #define UTF8(c) (c&0x80) -#define BDEPTH 3 +#define BDEPTH 1 #define BORDER 4 -// Generates a cached atlas of font glyphs encoded usign a signed distance field -// https://www.youtube.com/watch?v=1b5hIMqz_wM -// https://github.com/pjako/msdf_c -// this way the texture atlas for the font will be bigger but we save up the space -// needed for rendering the font in multiple sizes - -// as of now only monospaced fonts work correctly since no kerning information is stored - - -const unsigned int glyph_w = 32; -const unsigned int glyph_h = 32; +// FIXME: as of now only monospaced fonts work correctly since no kerning information +// is stored struct priv { stbtt_fontinfo stb; - msdf_AllocCtx ctx; - msdf_Result msdf; float scale; + int baseline; + unsigned char *bitmap; }; #define PRIV(x) ((struct priv *)x->priv) @@ -56,8 +45,9 @@ struct font_atlas * font_init(void) } -// loads a font into memory, storing all the ASCII characters in the atlas -int font_load(struct font_atlas *atlas, const char *path) +// loads a font into memory, storing all the ASCII characters in the atlas, each font +// atlas structure holds glyphs of a specific size +int font_load(struct font_atlas *atlas, const char *path, int size) { if (!atlas || !path) return -1; @@ -69,23 +59,24 @@ int font_load(struct font_atlas *atlas, const char *path) err = stbtt_InitFont(&(PRIV(atlas)->stb), (unsigned char *)atlas->file, 0); ERROR(err == 0, -1); - PRIV(atlas)->scale = stbtt_ScaleForPixelHeight(&(PRIV(atlas)->stb), glyph_h); - //int ascent, descent, linegap, baseline; - //int x0,y0,x1,y1; - //stbtt_GetFontVMetrics(&(PRIV(atlas)->stb), &ascent, &descent, &linegap); - //stbtt_GetFontBoundingBox(&(PRIV(atlas)->stb), &x0, &y0, &x1, &y1); - //baseline = PRIV(atlas)->scale * -y0; - //atlas->glyph_max_w = (PRIV(atlas)->scale*x1) - (PRIV(atlas)->scale*x0); - //atlas->glyph_max_h = (baseline+PRIV(atlas)->scale*y1) - (baseline+PRIV(atlas)->scale*y0); - //atlas->atlas = emalloc(atlas->glyph_max_w*atlas->glyph_max_h*CACHE_SIZE); - - atlas->atlas = emalloc(CACHE_SIZE*BDEPTH*glyph_h*glyph_w); - memset(atlas->atlas, 0, CACHE_SIZE*BDEPTH*glyph_h*glyph_w); + int ascent, descent, linegap, baseline; + int x0,y0,x1,y1; + float scale; + scale = stbtt_ScaleForPixelHeight(&(PRIV(atlas)->stb), size); + stbtt_GetFontVMetrics(&(PRIV(atlas)->stb), &ascent, &descent, &linegap); + stbtt_GetFontBoundingBox(&(PRIV(atlas)->stb), &x0, &y0, &x1, &y1); + baseline = scale * -y0; + atlas->glyph_max_w = (scale*x1) - (scale*x0); + atlas->glyph_max_h = (baseline+scale*y1) - (baseline+scale*y0); + atlas->atlas = emalloc(CACHE_SIZE*BDEPTH*atlas->glyph_max_w*atlas->glyph_max_h); + memset(atlas->atlas, 0, CACHE_SIZE*BDEPTH*atlas->glyph_max_w*atlas->glyph_max_h); + PRIV(atlas)->baseline = atlas->glyph_max_h - baseline; + PRIV(atlas)->scale = scale; + PRIV(atlas)->bitmap = emalloc(BDEPTH*atlas->glyph_max_w*atlas->glyph_max_h); // FIXME: make this a square atlas - atlas->width = glyph_w*CACHE_SIZE/4; - atlas->height = glyph_h*4; - - PRIV(atlas)->ctx = (msdf_AllocCtx){_emalloc, _efree, NULL}; + atlas->width = atlas->glyph_max_w*CACHE_SIZE/4; + atlas->height = atlas->glyph_max_h*4; + atlas->size = size; cache_init(); @@ -103,6 +94,7 @@ int font_free(struct font_atlas *atlas) { efree(atlas->atlas); efree(atlas->file); + efree(PRIV(atlas)->bitmap); efree(atlas->priv); efree(atlas); cache_destroy(); @@ -127,73 +119,65 @@ const struct font_glyph * font_get_glyph_texture(struct font_atlas *atlas, unsig // generate the sdf and put it into the cache // TODO: generate the whole block at once int idx = stbtt_FindGlyphIndex(&PRIV(atlas)->stb, code); - // FIXME: what happens if I change the range? - int err; - err = msdf_genGlyph(&PRIV(atlas)->msdf, + int x0,y0,x1,y1,gw,gh,l,off_x,off_y,adv; + stbtt_GetGlyphBitmapBoxSubpixel( &PRIV(atlas)->stb, idx, - BORDER, PRIV(atlas)->scale, - 2.0f/glyph_h, - &PRIV(atlas)->ctx); - // msdf_genGlyph returns 0 only when there are no contours, so only for - // whitespace and such, for those insert a zero uv map into the cache - // FIXME: this is a waste of space - if (!err) { - PRIV(atlas)->msdf.width = 0; - PRIV(atlas)->msdf.height = 0; - } + PRIV(atlas)->scale, + 0,0, + &x0,&y0, + &x1, &y1); + gw = x1 - x0; + gh = y1 - y0; + stbtt_GetGlyphHMetrics(&PRIV(atlas)->stb, idx, &adv, &l); + adv *= PRIV(atlas)->scale; + off_x = PRIV(atlas)->scale*l; + off_y = atlas->glyph_max_h+y0; + stbtt_MakeGlyphBitmapSubpixel( + &PRIV(atlas)->stb, + PRIV(atlas)->bitmap, + atlas->glyph_max_w, + atlas->glyph_max_h, + atlas->glyph_max_w, + PRIV(atlas)->scale, + PRIV(atlas)->scale, + 0, 0, + idx); + // TODO: bounds check usign atlas height + // TODO: clear spot area in the atlas before writing on it unsigned int spot = cache_get(); - unsigned int oy = (glyph_h * spot) / atlas->width; - unsigned int ox = (glyph_h * spot) % atlas->height; + unsigned int oy = ((atlas->glyph_max_w * spot) / atlas->width) * atlas->glyph_max_h; + unsigned int ox = (atlas->glyph_max_w * spot) % atlas->width; unsigned int w = atlas->width; - // sum magic shit - struct {unsigned char r,g,b;} *a = (void *)atlas->atlas; - msdf_Result *res = &PRIV(atlas)->msdf; - float s = glyph_h; - float tw = ((s * 0.7f) + s) / (s * 2.0f); - float ta = tw - 0.5f; - float ts = 0.5 - ta / 2; - float te = ts + ta; - - #define NORMALIZE(x) x = x > ts ? (x > te ? 1.0f : (x-ts)/ta+0.0f) : (0.0f) - - for (int y = 0; y < res->height; y++) { - int yPos = res->width * 3 * y; - for (int x = 0; x < res->width; x++) { - - int i = yPos + (x * 3); - float r = res->rgb[i+0]; - float g = res->rgb[i+1]; - float b = res->rgb[i+2]; - - r = (r + s) / (s * 2.0f); - g = (g + s) / (s * 2.0f); - b = (b + s) / (s * 2.0f); - - NORMALIZE(r); - NORMALIZE(g); - NORMALIZE(b); - - a[(oy+y)*w + (ox+x)].r = r * 255.0f; // (r > 0.5f) ? 255.0f : r * 255.0f; - a[(oy+y)*w + (ox+x)].g = g * 255.0f; // (g > 0.5f) ? 255.0f : g * 255.0f; - a[(oy+y)*w + (ox+x)].b = b * 255.0f; // (b > 0.5f) ? 255.0f : b * 255.0f; + unsigned char *a = (void *)atlas->atlas; + + //printf("max:%d %d spot:%d : %d %d %d %d\n", atlas->glyph_max_w, atlas->glyph_max_h, spot, ox, oy, off_x, off_y); + + for (int y = 0; y < gh; y++) { + for (int x = 0; x < gw; x++) { + int c, r; + r = (oy+y)*w; + c = ox+x; + a[r+c] = PRIV(atlas)->bitmap[y*atlas->glyph_max_w+x]; } } + // FIXME: get the advance struct font_glyph g = { .codepoint = code, .u = ox, .v = oy, - .w = res->width, - .h = res->height, + .w = gw, + .h = gh, + .x = off_x, + .y = off_y, + .a = adv, }; const struct font_glyph *ret = cache_insert(&g, spot); - efree(PRIV(atlas)->msdf.rgb); - return ret; } diff --git a/text_rendering/font.h b/text_rendering/font.h index b5d31d6..5dbbccd 100644 --- a/text_rendering/font.h +++ b/text_rendering/font.h @@ -4,29 +4,35 @@ /* width and height of a glyph contain the kering advance * (u,v) - * +----------*---+ - - * | .ii. | | ^ - * | @@@@@@. |<->| | - * | V@Mio@@o |adv| | - * | :i. V@V | | | - * | :oM@@M | | | - * | :@@@MM@M | | | - * | @@o o@M | | | - * |:@@. M@M | | | - * | @@@o@@@@ | | | - * | :M@@V:@@.| | v - * +----------*---+ - + * +-------------*---+ - + * | ^ | | ^ + * | |oy | | | + * | v | | | + * | .ii. | | | + * | @@@@@@. |<->| | + * | V@Mio@@o |adv| | + * | :i. V@V | | | + * | :oM@@M | | | + * | :@@@MM@M | | | + * | @@o o@M | | | + * |<->:@@. M@M | | | + * |ox @@@o@@@@ | | | + * | :M@@V:@@.| | v + * +-------------*---+ - * |<------------->| * w */ +// TODO: the advance isn't unique for every pair of characters struct font_glyph { unsigned int codepoint; - unsigned int u, v, w, h; + unsigned int u, v, w, h, a, x, y; }; struct font_atlas { - unsigned int glyphs, width, height; + unsigned int width, height; unsigned char *atlas; + unsigned int glyph_max_w, glyph_max_h; + int size; int file_size; char *file; void *priv; @@ -34,7 +40,7 @@ struct font_atlas { struct font_atlas * font_init(void); -int font_load(struct font_atlas *atlas, const char *path); +int font_load(struct font_atlas *atlas, const char *path, int size); int font_free(struct font_atlas *atlas); const struct font_glyph * font_get_glyph_texture(struct font_atlas *atlas, unsigned int code, int *updated); void font_dump(const struct font_atlas *atlas, const char *path); diff --git a/text_rendering/font_fragshader.glsl b/text_rendering/font_fragshader.glsl new file mode 100644 index 0000000..51ba398 --- /dev/null +++ b/text_rendering/font_fragshader.glsl @@ -0,0 +1,14 @@ +#version 330 + +// viewsize.x = viewport width in pixels; viewsize.y = viewport height in pixels +uniform vec2 viewsize; +// texture uv coordinate in texture space +in vec2 texture_coord; +uniform sampler2D texture_sampler; + +out vec4 color; + +void main() +{ + color = mix(vec4(0.0f,0.0f,0.0f,1.0f), vec4(1.0f,1.0f,1.0f,1.0f), texture(texture_sampler, texture_coord)) + vec4(1.0f,0.0f,0.0f,1.0f); +} diff --git a/text_rendering/font_vertshader.glsl b/text_rendering/font_vertshader.glsl new file mode 100644 index 0000000..240063f --- /dev/null +++ b/text_rendering/font_vertshader.glsl @@ -0,0 +1,20 @@ +#version 330 core + +// viewsize.x = viewport width in pixels; viewsize.y = viewport height in pixels +uniform vec2 viewsize; + +// both position and and uv are in pixels +layout(location = 0) in vec2 position; +layout(location = 1) in vec2 uv; + +out vec2 texture_coord; + +void main() +{ + vec4 pos = vec4(position.x, position.y, 0.0f, 1.0f); + vec2 v = viewsize / 2; + pos.xy = (pos.xy - v) / v; + + gl_Position = pos; + texture_coord = uv / viewsize; +} diff --git a/text_rendering/main.c b/text_rendering/main.c index 9c6e7c5..13130e9 100644 --- a/text_rendering/main.c +++ b/text_rendering/main.c @@ -1,3 +1,5 @@ +#include +#include #include #include @@ -22,9 +24,15 @@ int main(void) ren_render_text("ciao mamma", 100, 100, 100, 100, 12); SDL_GL_SwapWindow(win); - while(1); + SDL_Event e; + while(1) { + SDL_WaitEvent(&e); + if (e.type == SDL_QUIT) + break; + } ren_free(); SDL_DestroyWindow(win); + SDL_Quit(); return 0; } diff --git a/text_rendering/msdf_c/.gitignore b/text_rendering/msdf_c/.gitignore deleted file mode 100644 index 4d8154c..0000000 --- a/text_rendering/msdf_c/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -build -.vscode -.DS_Store \ No newline at end of file diff --git a/text_rendering/msdf_c/Readme.md b/text_rendering/msdf_c/Readme.md deleted file mode 100644 index 6e4f858..0000000 --- a/text_rendering/msdf_c/Readme.md +++ /dev/null @@ -1,27 +0,0 @@ -# msdf_c 0.1 -A pure C99 multi-channel signed distance field generator. Handles MSDF bitmap -Generation from given ttf/otf font (outlines). -Single Header STB-style library - ---- - -[This library is my take on improving msdf-c with some fixes and improving its API](https://github.com/solenum/msdf-c) - -[Based on the C++ implementation by Viktor Chlumský.](https://github.com/Chlumsky/msdfgen) - -~~~ -// example fragment shader -// scale is render_width/glyph_width -// render_width being the width of each rendered glyph -float median(float r, float g, float b) { - return max(min(r, g), min(max(r, g), b)); -} - -void main() -{ - vec3 sample = texture(u_texture, uv).rgb; - float dist = scale * (median(sample.r, sample.g, sample.b) - 0.5); - float o = clamp(dist + 0.5, 0.0, 1.0); - color = vec4(vec3(1.0), o); -} -~~~ diff --git a/text_rendering/msdf_c/msdf.c b/text_rendering/msdf_c/msdf.c deleted file mode 100644 index 3ca1194..0000000 --- a/text_rendering/msdf_c/msdf.c +++ /dev/null @@ -1,4 +0,0 @@ -#define STB_TRUETYPE_IMPLEMENTATION -#include "stb_truetype.h" -#define MSDF_IMPLEMENTATION -#include "msdf.h" diff --git a/text_rendering/msdf_c/msdf.h b/text_rendering/msdf_c/msdf.h deleted file mode 100644 index e303e23..0000000 --- a/text_rendering/msdf_c/msdf.h +++ /dev/null @@ -1,1395 +0,0 @@ -/* msdf - Handles multi-channel signed distance field bitmap - generation from given ttf (stb_truetype.h) font. - https://github.com/exezin/msdf-c - Depends on stb_truetype.h to load the ttf file. - This is in an unstable state, ymmv. - Based on the C++ implementation by Viktor Chlumský. - https://github.com/Chlumsky/msdfgen -*/ - -#ifndef MSDF_H -#define MSDF_H - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - int glyphIdx; - int left_bearing; - int advance; - int ix0, ix1; - int iy0, iy1; -} ex_metrics_t; - -typedef struct msdf_Result { - int glyphIdx; - int left_bearing; - int advance; - float* rgb; - int width; - int height; - int yOffset; -} msdf_Result; - -typedef struct msdf_AllocCtx { - void* (*alloc)(size_t size, void* ctx); - // free is optional and will not be called if it is null (useful for area allocators that free everything at once) - void (*free)(void* ptr, void* ctx); - void* ctx; -} msdf_AllocCtx; - -/* - Generates a bitmap from the specified glyph index of a stbtt font - - Returned result is 1 for success or 0 in case of an error - */ -int msdf_genGlyph(msdf_Result* result, stbtt_fontinfo *font, int stbttGlyphIndex, uint32_t borderWidth, float scale, float range, msdf_AllocCtx* alloc); - -#ifdef __cplusplus -} -#endif - -#ifdef MSDF_IMPLEMENTATION -// pixel at (x, y) in bitmap (arr) -#define msdf_pixelAt(x, y, w, arr) ((msdf_Vec3){arr[(3 * (((y)*w) + x))], arr[(3 * (((y)*w) + x)) + 1], arr[(3 * (((y)*w) + x)) + 2]}) - -#define msdf_max(x, y) (((x) > (y)) ? (x) : (y)) -#define msdf_min(x, y) (((x) < (y)) ? (x) : (y)) - -#define MSDF_INF -1e24 -#define MSDF_EDGE_THRESHOLD 0.02 - -#ifndef MSDF_PI -#define MSDF_PI 3.14159265358979323846 -#endif - -typedef float msdf_Vec2[2]; -typedef float msdf_Vec3[3]; - -typedef struct -{ - double dist; - double d; -} msdf_signedDistance; - -// the possible types: -// STBTT_vmove = start of a contour -// STBTT_vline = linear segment -// STBTT_vcurve = quadratic segment -// STBTT_vcubic = cubic segment -typedef struct -{ - int color; - msdf_Vec2 p[4]; - int type; -} msdf_EdgeSegment; - -// defines what color channel an edge belongs to -typedef enum -{ - msdf_edgeColor_black = 0, - msdf_edgeColor_red = 1, - msdf_edgeColor_green = 2, - msdf_edgeColor_yellow = 3, - msdf_edgeColor_blue = 4, - msdf_edgeColor_magenta = 5, - msdf_edgeColor_cyan = 6, - msdf_edgeColor_white = 7 -} msdf_edgeColor; - -static double msdf_median(double a, double b, double c) -{ - return msdf_max(msdf_min(a, b), msdf_min(msdf_max(a, b), c)); -} - -static int msdf_nonZeroSign(double n) -{ - return 2 * (n > 0) - 1; -} - -static double msdf_cross(msdf_Vec2 a, msdf_Vec2 b) -{ - return a[0] * b[1] - a[1] * b[0]; -} - -static void msdf_v2Scale(msdf_Vec2 r, msdf_Vec2 const v, float const s) -{ - int i; - for (i = 0; i < 2; ++i) - r[i] = v[i] * s; -} - -static float msdf_v2MulInner(msdf_Vec2 const a, msdf_Vec2 const b) -{ - float p = 0.; - int i; - for (i = 0; i < 2; ++i) - p += b[i] * a[i]; - return p; -} - -static float msdf_v2Leng(msdf_Vec2 const v) -{ - return sqrtf(msdf_v2MulInner(v, v)); -} - -static void msdf_v2Norm(msdf_Vec2 r, msdf_Vec2 const v) -{ - float k = 1.0 / msdf_v2Leng(v); - msdf_v2Scale(r, v, k); -} - -static void msdf_v2Sub(msdf_Vec2 r, msdf_Vec2 const a, msdf_Vec2 const b) -{ - int i; - for (i = 0; i < 2; ++i) - r[i] = a[i] - b[i]; -} - -int msdf_solveQuadratic(double x[2], double a, double b, double c) -{ - if (fabs(a) < 1e-14) - { - if (fabs(b) < 1e-14) - { - if (c == 0) - return -1; - return 0; - } - x[0] = -c / b; - return 1; - } - - double dscr = b * b - 4 * a * c; - if (dscr > 0) - { - dscr = sqrt(dscr); - x[0] = (-b + dscr) / (2 * a); - x[1] = (-b - dscr) / (2 * a); - return 2; - } - else if (dscr == 0) - { - x[0] = -b / (2 * a); - return 1; - } - else - { - return 0; - } -} - -int msdf_solveCubicNormed(double *x, double a, double b, double c) -{ - double a2 = a * a; - double q = (a2 - 3 * b) / 9; - double r = (a * (2 * a2 - 9 * b) + 27 * c) / 54; - double r2 = r * r; - double q3 = q * q * q; - double A, B; - if (r2 < q3) - { - double t = r / sqrt(q3); - if (t < -1) - t = -1; - if (t > 1) - t = 1; - t = acos(t); - a /= 3; - q = -2 * sqrt(q); - x[0] = q * cos(t / 3) - a; - x[1] = q * cos((t + 2 * MSDF_PI) / 3) - a; - x[2] = q * cos((t - 2 * MSDF_PI) / 3) - a; - return 3; - } - else - { - A = -pow(fabs(r) + sqrt(r2 - q3), 1 / 3.); - if (r < 0) - A = -A; - B = A == 0 ? 0 : q / A; - a /= 3; - x[0] = (A + B) - a; - x[1] = -0.5 * (A + B) - a; - x[2] = 0.5 * sqrt(3.) * (A - B); - if (fabs(x[2]) < 1e-14) - return 2; - return 1; - } -} - -int msdf_solveCubic(double x[3], double a, double b, double c, double d) -{ - if (fabs(a) < 1e-14) - return msdf_solveQuadratic(x, b, c, d); - - return msdf_solveCubicNormed(x, b / a, c / a, d / a); -} - -void msdf_getOrtho(msdf_Vec2 r, msdf_Vec2 const v, int polarity, int allow_zero) -{ - double len = msdf_v2Leng(v); - - if (len == 0) - { - if (polarity) - { - r[0] = 0; - r[1] = !allow_zero; - } - else - { - r[0] = 0; - r[1] = -!allow_zero; - } - return; - } - - if (polarity) - { - r[0] = -v[1] / len; - r[1] = v[0] / len; - } - else - { - r[0] = v[1] / len; - r[1] = -v[0] / len; - } -} - -int msdf_pixelClash(const msdf_Vec3 a, const msdf_Vec3 b, double threshold) -{ - int aIn = (a[0] > .5f) + (a[1] > .5f) + (a[2] > .5f) >= 2; - int bIn = (b[0] > .5f) + (b[1] > .5f) + (b[2] > .5f) >= 2; - if (aIn != bIn) - return 0; - if ((a[0] > .5f && a[1] > .5f && a[2] > .5f) || (a[0] < .5f && a[1] < .5f && a[2] < .5f) || (b[0] > .5f && b[1] > .5f && b[2] > .5f) || (b[0] < .5f && b[1] < .5f && b[2] < .5f)) - return 0; - float aa, ab, ba, bb, ac, bc; - if ((a[0] > .5f) != (b[0] > .5f) && (a[0] < .5f) != (b[0] < .5f)) - { - aa = a[0], ba = b[0]; - if ((a[1] > .5f) != (b[1] > .5f) && (a[1] < .5f) != (b[1] < .5f)) - { - ab = a[1], bb = b[1]; - ac = a[2], bc = b[2]; - } - else if ((a[2] > .5f) != (b[2] > .5f) && (a[2] < .5f) != (b[2] < .5f)) - { - ab = a[2], bb = b[2]; - ac = a[1], bc = b[1]; - } - else - { - return 0; - } - } - else if ((a[1] > .5f) != (b[1] > .5f) && (a[1] < .5f) != (b[1] < .5f) && (a[2] > .5f) != (b[2] > .5f) && (a[2] < .5f) != (b[2] < .5f)) - { - aa = a[1], ba = b[1]; - ab = a[2], bb = b[2]; - ac = a[0], bc = b[0]; - } - else - { - return 0; - } - return (fabsf(aa - ba) >= threshold) && (fabsf(ab - bb) >= threshold) && fabsf(ac - .5f) >= fabsf(bc - .5f); -} - -void msdf_mix(msdf_Vec2 r, msdf_Vec2 a, msdf_Vec2 b, double weight) -{ - r[0] = (1 - weight) * a[0] + weight * b[0]; - r[1] = (1 - weight) * a[1] + weight * b[1]; -} - -void msdf_linearDirection(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - r[0] = e->p[1][0] - e->p[0][0]; - r[1] = e->p[1][1] - e->p[0][1]; -} - -void msdf_quadraticDirection(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - msdf_Vec2 a, b; - msdf_v2Sub(a, e->p[1], e->p[0]); - msdf_v2Sub(b, e->p[2], e->p[1]); - msdf_mix(r, a, b, param); -} - -void msdf_cubicDirection(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - msdf_Vec2 a, b, c, d, t; - msdf_v2Sub(a, e->p[1], e->p[0]); - msdf_v2Sub(b, e->p[2], e->p[1]); - msdf_mix(c, a, b, param); - msdf_v2Sub(a, e->p[3], e->p[2]); - msdf_mix(d, b, a, param); - msdf_mix(t, c, d, param); - - if (!t[0] && !t[1]) - { - if (param == 0) - { - r[0] = e->p[2][0] - e->p[0][0]; - r[1] = e->p[2][1] - e->p[0][1]; - return; - } - if (param == 1) - { - r[0] = e->p[3][0] - e->p[1][0]; - r[1] = e->p[3][1] - e->p[1][1]; - return; - } - } - - r[0] = t[0]; - r[1] = t[1]; -} - -void msdf_direction(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - switch (e->type) - { - case STBTT_vline: - { - msdf_linearDirection(r, e, param); - break; - } - case STBTT_vcurve: - { - msdf_quadraticDirection(r, e, param); - break; - } - case STBTT_vcubic: - { - msdf_cubicDirection(r, e, param); - break; - } - } -} - -void msdf_linearPoint(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - msdf_mix(r, e->p[0], e->p[1], param); -} - -void msdf_quadraticPoint(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - msdf_Vec2 a, b; - msdf_mix(a, e->p[0], e->p[1], param); - msdf_mix(b, e->p[1], e->p[2], param); - msdf_mix(r, a, b, param); -} - -void msdf_cubicPoint(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - msdf_Vec2 p12, a, b, c, d; - msdf_mix(p12, e->p[1], e->p[2], param); - - msdf_mix(a, e->p[0], e->p[1], param); - msdf_mix(b, a, p12, param); - - msdf_mix(c, e->p[2], e->p[3], param); - msdf_mix(d, p12, c, param); - - msdf_mix(r, b, d, param); -} - -void msdf_point(msdf_Vec2 r, msdf_EdgeSegment *e, double param) -{ - switch (e->type) - { - case STBTT_vline: - { - msdf_linearPoint(r, e, param); - break; - } - case STBTT_vcurve: - { - msdf_quadraticPoint(r, e, param); - break; - } - case STBTT_vcubic: - { - msdf_cubicPoint(r, e, param); - break; - } - } -} - -// linear edge signed distance -msdf_signedDistance msdf_linearDist(msdf_EdgeSegment *e, msdf_Vec2 origin, double *param) -{ - msdf_Vec2 aq, ab, eq; - msdf_v2Sub(aq, origin, e->p[0]); - msdf_v2Sub(ab, e->p[1], e->p[0]); - *param = msdf_v2MulInner(aq, ab) / msdf_v2MulInner(ab, ab); - msdf_v2Sub(eq, e->p[*param > .5], origin); - - double endpoint_distance = msdf_v2Leng(eq); - if (*param > 0 && *param < 1) - { - msdf_Vec2 ab_ortho; - msdf_getOrtho(ab_ortho, ab, 0, 0); - double ortho_dist = msdf_v2MulInner(ab_ortho, aq); - if (fabs(ortho_dist) < endpoint_distance) - return (msdf_signedDistance){ortho_dist, 0}; - } - - msdf_v2Norm(ab, ab); - msdf_v2Norm(eq, eq); - double dist = msdf_nonZeroSign(msdf_cross(aq, ab)) * endpoint_distance; - double d = fabs(msdf_v2MulInner(ab, eq)); - return (msdf_signedDistance){dist, d}; -} - -// quadratic edge signed distance -msdf_signedDistance msdf_quadraticDist(msdf_EdgeSegment *e, msdf_Vec2 origin, double *param) -{ - msdf_Vec2 qa, ab, br; - msdf_v2Sub(qa, e->p[0], origin); - msdf_v2Sub(ab, e->p[1], e->p[0]); - br[0] = e->p[0][0] + e->p[2][0] - e->p[1][0] - e->p[1][0]; - br[1] = e->p[0][1] + e->p[2][1] - e->p[1][1] - e->p[1][1]; - - double a = msdf_v2MulInner(br, br); - double b = 3 * msdf_v2MulInner(ab, br); - double c = 2 * msdf_v2MulInner(ab, ab) + msdf_v2MulInner(qa, br); - double d = msdf_v2MulInner(qa, ab); - double t[3]; - int solutions = msdf_solveCubic(t, a, b, c, d); - - // distance from a - double min_distance = msdf_nonZeroSign(msdf_cross(ab, qa)) * msdf_v2Leng(qa); - *param = -msdf_v2MulInner(qa, ab) / msdf_v2MulInner(ab, ab); - { - msdf_Vec2 a, b; - msdf_v2Sub(a, e->p[2], e->p[1]); - msdf_v2Sub(b, e->p[2], origin); - - // distance from b - double distance = msdf_nonZeroSign(msdf_cross(a, b)) * msdf_v2Leng(b); - if (fabs(distance) < fabs(min_distance)) - { - min_distance = distance; - - msdf_v2Sub(a, origin, e->p[1]); - msdf_v2Sub(b, e->p[2], e->p[1]); - *param = msdf_v2MulInner(a, b) / msdf_v2MulInner(b, b); - } - } - - for (int i = 0; i < solutions; ++i) - { - if (t[i] > 0 && t[i] < 1) - { - // end_point = p[0]+2*t[i]*ab+t[i]*t[i]*br; - msdf_Vec2 end_point, a, b; - end_point[0] = e->p[0][0] + 2 * t[i] * ab[0] + t[i] * t[i] * br[0]; - end_point[1] = e->p[0][1] + 2 * t[i] * ab[1] + t[i] * t[i] * br[1]; - - msdf_v2Sub(a, e->p[2], e->p[0]); - msdf_v2Sub(b, end_point, origin); - double distance = msdf_nonZeroSign(msdf_cross(a, b)) * msdf_v2Leng(b); - if (fabs(distance) <= fabs(min_distance)) - { - min_distance = distance; - *param = t[i]; - } - } - } - - if (*param >= 0 && *param <= 1) - return (msdf_signedDistance){min_distance, 0}; - - msdf_Vec2 aa, bb; - msdf_v2Norm(ab, ab); - msdf_v2Norm(qa, qa); - msdf_v2Sub(aa, e->p[2], e->p[1]); - msdf_v2Norm(aa, aa); - msdf_v2Sub(bb, e->p[2], origin); - msdf_v2Norm(bb, bb); - - if (*param < .5) - return (msdf_signedDistance){min_distance, fabs(msdf_v2MulInner(ab, qa))}; - else - return (msdf_signedDistance){min_distance, fabs(msdf_v2MulInner(aa, bb))}; -} - -// cubic edge signed distance -msdf_signedDistance msdf_cubicDist(msdf_EdgeSegment *e, msdf_Vec2 origin, double *param) -{ - msdf_Vec2 qa, ab, br, as; - msdf_v2Sub(qa, e->p[0], origin); - msdf_v2Sub(ab, e->p[1], e->p[0]); - br[0] = e->p[2][0] - e->p[1][0] - ab[0]; - br[1] = e->p[2][1] - e->p[1][1] - ab[1]; - as[0] = (e->p[3][0] - e->p[2][0]) - (e->p[2][0] - e->p[1][0]) - br[0]; - as[1] = (e->p[3][1] - e->p[2][1]) - (e->p[2][1] - e->p[1][1]) - br[1]; - - msdf_Vec2 ep_dir; - msdf_direction(ep_dir, e, 0); - - // distance from a - double min_distance = msdf_nonZeroSign(msdf_cross(ep_dir, qa)) * msdf_v2Leng(qa); - *param = -msdf_v2MulInner(qa, ep_dir) / msdf_v2MulInner(ep_dir, ep_dir); - { - msdf_Vec2 a; - msdf_v2Sub(a, e->p[3], origin); - - msdf_direction(ep_dir, e, 1); - // distance from b - double distance = msdf_nonZeroSign(msdf_cross(ep_dir, a)) * msdf_v2Leng(a); - if (fabs(distance) < fabs(min_distance)) - { - min_distance = distance; - - a[0] = origin[0] + ep_dir[0] - e->p[3][0]; - a[1] = origin[1] + ep_dir[1] - e->p[3][1]; - *param = msdf_v2MulInner(a, ep_dir) / msdf_v2MulInner(ep_dir, ep_dir); - } - } - - const int search_starts = 4; - for (int i = 0; i <= search_starts; ++i) - { - double t = (double)i / search_starts; - for (int step = 0;; ++step) - { - msdf_Vec2 qpt; - msdf_point(qpt, e, t); - msdf_v2Sub(qpt, qpt, origin); - msdf_Vec2 d; - msdf_direction(d, e, t); - double distance = msdf_nonZeroSign(msdf_cross(d, qpt)) * msdf_v2Leng(qpt); - if (fabs(distance) < fabs(min_distance)) - { - min_distance = distance; - *param = t; - } - if (step == search_starts) - break; - - msdf_Vec2 d1, d2; - d1[0] = 3 * as[0] * t * t + 6 * br[0] * t + 3 * ab[0]; - d1[1] = 3 * as[1] * t * t + 6 * br[1] * t + 3 * ab[1]; - d2[0] = 6 * as[0] * t + 6 * br[0]; - d2[1] = 6 * as[1] * t + 6 * br[1]; - - t -= msdf_v2MulInner(qpt, d1) / (msdf_v2MulInner(d1, d1) + msdf_v2MulInner(qpt, d2)); - if (t < 0 || t > 1) - break; - } - } - - if (*param >= 0 && *param <= 1) - return (msdf_signedDistance){min_distance, 0}; - - msdf_Vec2 d0, d1; - msdf_direction(d0, e, 0); - msdf_direction(d1, e, 1); - msdf_v2Norm(d0, d0); - msdf_v2Norm(d1, d1); - msdf_v2Norm(qa, qa); - msdf_Vec2 a; - msdf_v2Sub(a, e->p[3], origin); - msdf_v2Norm(a, a); - - if (*param < .5) - return (msdf_signedDistance){min_distance, fabs(msdf_v2MulInner(d0, qa))}; - else - return (msdf_signedDistance){min_distance, fabs(msdf_v2MulInner(d1, a))}; -} - -void msdf_distToPseudo(msdf_signedDistance *distance, msdf_Vec2 origin, double param, msdf_EdgeSegment *e) { - if (param < 0) { - msdf_Vec2 dir, p; - msdf_direction(dir, e, 0); - msdf_v2Norm(dir, dir); - msdf_Vec2 aq = {origin[0], origin[1]}; - msdf_point(p, e, 0); - msdf_v2Sub(aq, origin, p); - double ts = msdf_v2MulInner(aq, dir); - if (ts < 0) { - double pseudo_dist = msdf_cross(aq, dir); - if (fabs(pseudo_dist) <= fabs(distance->dist)) { - distance->dist = pseudo_dist; - distance->d = 0; - } - } - } else if (param > 1) { - msdf_Vec2 dir, p; - msdf_direction(dir, e, 1); - msdf_v2Norm(dir, dir); - msdf_Vec2 bq = {origin[0], origin[1]}; - msdf_point(p, e, 1); - msdf_v2Sub(bq, origin, p); - double ts = msdf_v2MulInner(bq, dir); - if (ts > 0) { - double pseudo_dist = msdf_cross(bq, dir); - if (fabs(pseudo_dist) <= fabs(distance->dist)) { - distance->dist = pseudo_dist; - distance->d = 0; - } - } - } -} - -int msdf_signedCompare(msdf_signedDistance a, msdf_signedDistance b) { - return fabs(a.dist) < fabs(b.dist) || (fabs(a.dist) == fabs(b.dist) && a.d < b.d); -} - -int msdf_isCorner(msdf_Vec2 a, msdf_Vec2 b, double threshold) { - return msdf_v2MulInner(a, b) <= 0 || fabs(msdf_cross(a, b)) > threshold; -} - -void msdf_switchColor(msdf_edgeColor *color, unsigned long long *seed, msdf_edgeColor banned) -{ - msdf_edgeColor combined = *color & banned; - if (combined == msdf_edgeColor_red || combined == msdf_edgeColor_green || combined == msdf_edgeColor_blue) { - *color = (msdf_edgeColor)(combined ^ msdf_edgeColor_white); - return; - } - - if (*color == msdf_edgeColor_black || *color == msdf_edgeColor_white) { - static const msdf_edgeColor start[3] = {msdf_edgeColor_cyan, msdf_edgeColor_magenta, msdf_edgeColor_yellow}; - *color = start[*seed & 3]; - *seed /= 3; - return; - } - - int shifted = *color << (1 + (*seed & 1)); - *color = (msdf_edgeColor)((shifted | shifted >> 3) & msdf_edgeColor_white); - *seed >>= 1; -} - -void msdf_linearSplit(msdf_EdgeSegment *e, msdf_EdgeSegment *p1, msdf_EdgeSegment *p2, msdf_EdgeSegment *p3) -{ - msdf_Vec2 p; - - msdf_point(p, e, 1 / 3.0); - memcpy(&p1->p[0], e->p[0], sizeof(msdf_Vec2)); - memcpy(&p1->p[1], p, sizeof(msdf_Vec2)); - p1->color = e->color; - - msdf_point(p, e, 1 / 3.0); - memcpy(&p2->p[0], p, sizeof(msdf_Vec2)); - msdf_point(p, e, 2 / 3.0); - memcpy(&p2->p[1], p, sizeof(msdf_Vec2)); - p2->color = e->color; - - msdf_point(p, e, 2 / 3.0); - memcpy(&p3->p[0], p, sizeof(msdf_Vec2)); - msdf_point(p, e, 2 / 3.0); - memcpy(&p3->p[1], e->p[1], sizeof(msdf_Vec2)); - p3->color = e->color; -} - -void msdf_quadraticSplit(msdf_EdgeSegment *e, msdf_EdgeSegment *p1, msdf_EdgeSegment *p2, msdf_EdgeSegment *p3) -{ - msdf_Vec2 p, a, b; - - memcpy(&p1->p[0], e->p[0], sizeof(msdf_Vec2)); - msdf_mix(p, e->p[0], e->p[1], 1 / 3.0); - memcpy(&p1->p[1], p, sizeof(msdf_Vec2)); - msdf_point(p, e, 1 / 3.0); - memcpy(&p1->p[2], p, sizeof(msdf_Vec2)); - p1->color = e->color; - - msdf_point(p, e, 1 / 3.0); - memcpy(&p2->p[0], p, sizeof(msdf_Vec2)); - msdf_mix(a, e->p[0], e->p[1], 5 / 9.0); - msdf_mix(b, e->p[1], e->p[2], 4 / 9.0); - msdf_mix(p, a, b, 0.5); - memcpy(&p2->p[1], p, sizeof(msdf_Vec2)); - msdf_point(p, e, 2 / 3.0); - memcpy(&p2->p[2], p, sizeof(msdf_Vec2)); - p2->color = e->color; - - msdf_point(p, e, 2 / 3.0); - memcpy(&p3->p[0], p, sizeof(msdf_Vec2)); - msdf_mix(p, e->p[1], e->p[2], 2 / 3.0); - memcpy(&p3->p[1], p, sizeof(msdf_Vec2)); - memcpy(&p3->p[2], e->p[2], sizeof(msdf_Vec2)); - p3->color = e->color; -} - -void msdf_cubicSplit(msdf_EdgeSegment *e, msdf_EdgeSegment *p1, msdf_EdgeSegment *p2, msdf_EdgeSegment *p3) -{ - msdf_Vec2 p, a, b, c, d; - - memcpy(&p1->p[0], e->p[0], sizeof(msdf_Vec2)); // p1 0 - if (e->p[0] == e->p[1]) { - memcpy(&p1->p[1], e->p[0], sizeof(msdf_Vec2)); // ? p1 1 - } else { - msdf_mix(p, e->p[0], e->p[1], 1 / 3.0); - memcpy(&p1->p[1], p, sizeof(msdf_Vec2)); // ? p1 1 - } - msdf_mix(a, e->p[0], e->p[1], 1 / 3.0); - msdf_mix(b, e->p[1], e->p[2], 1 / 3.0); - msdf_mix(p, a, b, 1 / 3.0); - memcpy(&p1->p[2], p, sizeof(msdf_Vec2)); // p1 2 - msdf_point(p, e, 1 / 3.0); - memcpy(&p1->p[3], p, sizeof(msdf_Vec2)); // p1 3 - p1->color = e->color; - - msdf_point(p, e, 1 / 3.0); - memcpy(&p2->p[0], p, sizeof(msdf_Vec2)); // p2 0 - msdf_mix(a, e->p[0], e->p[1], 1 / 3.0); - msdf_mix(b, e->p[1], e->p[2], 1 / 3.0); - msdf_mix(c, a, b, 1 / 3.0); - msdf_mix(a, e->p[1], e->p[2], 1 / 3.0); - msdf_mix(b, e->p[2], e->p[3], 1 / 3.0); - msdf_mix(d, a, b, 1 / 3.0); - msdf_mix(p, c, d, 2 / 3.0); - memcpy(&p2->p[1], p, sizeof(msdf_Vec2)); // p2 1 - msdf_mix(a, e->p[0], e->p[1], 2 / 3.0); - msdf_mix(b, e->p[1], e->p[2], 2 / 3.0); - msdf_mix(c, a, b, 2 / 3.0); - msdf_mix(a, e->p[1], e->p[2], 2 / 3.0); - msdf_mix(b, e->p[2], e->p[3], 2 / 3.0); - msdf_mix(d, a, b, 2 / 3.0); - msdf_mix(p, c, d, 1 / 3.0); - memcpy(&p2->p[2], p, sizeof(msdf_Vec2)); // p2 2 - msdf_point(p, e, 2 / 3.0); - memcpy(&p2->p[3], p, sizeof(msdf_Vec2)); // p2 3 - p2->color = e->color; - - msdf_point(p, e, 2 / 3.0); - memcpy(&p3->p[0], p, sizeof(msdf_Vec2)); // p3 0 - - msdf_mix(a, e->p[1], e->p[2], 2 / 3.0); - msdf_mix(b, e->p[2], e->p[3], 2 / 3.0); - msdf_mix(p, a, b, 2 / 3.0); - memcpy(&p3->p[1], p, sizeof(msdf_Vec2)); // p3 1 - - if (e->p[2] == e->p[3]) { - memcpy(&p3->p[2], e->p[3], sizeof(msdf_Vec2)); // ? p3 2 - } else { - msdf_mix(p, e->p[2], e->p[3], 2 / 3.0); - memcpy(&p3->p[2], p, sizeof(msdf_Vec2)); // ? p3 2 - } - - memcpy(&p3->p[3], e->p[3], sizeof(msdf_Vec2)); // p3 3 -} - -void msdf_edgeSplit(msdf_EdgeSegment *e, msdf_EdgeSegment *p1, msdf_EdgeSegment *p2, msdf_EdgeSegment *p3) -{ - switch (e->type) { - case STBTT_vline: { - msdf_linearSplit(e, p1, p2, p3); - break; - } - case STBTT_vcurve: { - msdf_quadraticSplit(e, p1, p2, p3); - break; - } - case STBTT_vcubic: { - msdf_cubicSplit(e, p1, p2, p3); - break; - } - } -} - -double msdf_shoelace(const msdf_Vec2 a, const msdf_Vec2 b) -{ - return (b[0] - a[0]) * (a[1] + b[1]); -} - - -void* msdf__alloc(size_t size, void* ctx) { - return malloc(size); -} -void msdf__free(void* ptr, void* ctx) { - free(ptr); -} - -int msdf_genGlyph(msdf_Result* result, stbtt_fontinfo *font, int stbttGlyphIndex, uint32_t borderWidth, float scale, float range, msdf_AllocCtx* alloc) { - msdf_AllocCtx allocCtx; - - if (alloc) { - allocCtx = *alloc; - } else { - allocCtx.alloc = msdf__alloc; - allocCtx.free = msdf__free; - allocCtx.ctx = NULL; - } - - //char f = c; - // Funit to pixel scale - //float scale = stbtt_ScaleForMappingEmToPixels(font, h); - int glyphIdx = stbttGlyphIndex; - // get glyph bounding box (scaled later) - int ix0, iy0, ix1, iy1; - float xoff = .0, yoff = .0; - stbtt_GetGlyphBox(font, glyphIdx, &ix0, &iy0, &ix1, &iy1); - - float glyphWidth = ix1 - ix0; - float glyphHeight = iy1 - iy0; - float borderWidthF32 = borderWidth; - float wF32 = ceilf(glyphWidth * scale); - float hF32 = ceilf(glyphHeight * scale); - wF32 += 2.f * borderWidth; - hF32 += 2.f * borderWidth; - int w = wF32; - int h = hF32; - - float* bitmap = (float*) allocCtx.alloc(w * h * 3 * sizeof(float), allocCtx.ctx); - memset(bitmap, 0x0, w * h * 3 * sizeof(float)); - - // em scale - //scale = stbtt_ScaleForMappingEmToPixels(font, h); - - //if (autofit) - //{ - - // calculate new height - //float newh = h + (h - (iy1 - iy0) * scale) - 4; - - // calculate new scale - // see 'stbtt_ScaleForMappingEmToPixels' in stb_truetype.h - //uint8_t *p = font->data + font->head + 18; - //int unitsPerEm = p[0] * 256 + p[1]; - //scale = ((float)h) / ((float)unitsPerEm); - - // make sure we are centered - //xoff = .0; - //yoff = .0; - //} - - // get left offset and advance - //int left_bearing, advance; - //stbtt_GetGlyphHMetrics(font, glyphIdx, &advance, &left_bearing); - //left_bearing *= scale; - - int32_t glyphOrgX = ix0 * scale; - int32_t glyphOrgY = iy0 * scale; - - int32_t borderWidthX = borderWidth; - int32_t borderWidthY = borderWidth; - - // org 8,8 - // - bord 4,4 - // erg: 4,4 - - // calculate offset for centering glyph on bitmap - - //glyphOrgX >= 2 ? (glyphOrgX) : (); - int32_t translateX = (glyphOrgX - borderWidth);//borderWidth + ((w / 2) - ((ix1 - ix0) * scale) / 2 - leftBearingScaled); - int32_t translateY = (glyphOrgY - borderWidth);//borderWidth + ((h / 2) - ((iy1 - iy0) * scale) / 2 - ((float) iy0) * scale); - //translateY = 8; - // set the glyph metrics - // (pre-scale them) - - #if 0 - if (metrics) - { - metrics->left_bearing = left_bearing; - metrics->advance = advance * scale; - metrics->ix0 = ix0 * scale; - metrics->ix1 = ix1 * scale; - metrics->iy0 = iy0 * scale; - metrics->iy1 = iy1 * scale; - metrics->glyphIdx = glyphIdx; - } - #endif - - stbtt_vertex *verts; - int num_verts = stbtt_GetGlyphShape(font, glyphIdx, &verts); - - // figure out how many contours exist - int contour_count = 0; - for (int i = 0; i < num_verts; i++) { - if (verts[i].type == STBTT_vmove) { - contour_count++; - } - } - - if (contour_count == 0) { - return 0; - } - - // determin what vertices belong to what contours - typedef struct { - size_t start, end; - } msdf_Indices; - msdf_Indices *contours = allocCtx.alloc(sizeof(msdf_Indices) * contour_count, allocCtx.ctx); - int j = 0; - for (int i = 0; i <= num_verts; i++) { - if (verts[i].type == STBTT_vmove) { - if (i > 0) { - contours[j].end = i; - j++; - } - - contours[j].start = i; - } else if (i >= num_verts) { - contours[j].end = i; - } - } - - typedef struct { - msdf_signedDistance min_distance; - msdf_EdgeSegment *near_edge; - double near_param; - } msdf_EdgePoint; - - typedef struct { - msdf_EdgeSegment *edges; - size_t edge_count; - } msdf_Contour; - - // process verts into series of contour-specific edge lists - msdf_Vec2 initial = {0, 0}; // fix this? - msdf_Contour *contour_data = allocCtx.alloc(sizeof(msdf_Contour) * contour_count, allocCtx.ctx); - double cscale = 64.0; - for (int i = 0; i < contour_count; i++) { - size_t count = contours[i].end - contours[i].start; - contour_data[i].edges = allocCtx.alloc(sizeof(msdf_EdgeSegment) * count, allocCtx.ctx); - contour_data[i].edge_count = 0; - - size_t k = 0; - for (int j = contours[i].start; j < contours[i].end; j++) { - msdf_EdgeSegment *e = &contour_data[i].edges[k]; - stbtt_vertex *v = &verts[j]; - e->type = v->type; - e->color = msdf_edgeColor_white; - - switch (v->type) { - case STBTT_vmove: { - msdf_Vec2 p = {v->x / cscale, v->y / cscale}; - memcpy(&initial, p, sizeof(msdf_Vec2)); - break; - } - - case STBTT_vline: { - msdf_Vec2 p = {v->x / cscale, v->y / cscale}; - memcpy(&e->p[0], initial, sizeof(msdf_Vec2)); - memcpy(&e->p[1], p, sizeof(msdf_Vec2)); - memcpy(&initial, p, sizeof(msdf_Vec2)); - contour_data[i].edge_count++; - k++; - break; - } - - case STBTT_vcurve: { - msdf_Vec2 p = {v->x / cscale, v->y / cscale}; - msdf_Vec2 c = {v->cx / cscale, v->cy / cscale}; - memcpy(&e->p[0], initial, sizeof(msdf_Vec2)); - memcpy(&e->p[1], c, sizeof(msdf_Vec2)); - memcpy(&e->p[2], p, sizeof(msdf_Vec2)); - - if ((e->p[0][0] == e->p[1][0] && e->p[0][1] == e->p[1][1]) || - (e->p[1][0] == e->p[2][0] && e->p[1][1] == e->p[2][1])) - { - e->p[1][0] = 0.5 * (e->p[0][0] + e->p[2][0]); - e->p[1][1] = 0.5 * (e->p[0][1] + e->p[2][1]); - } - - memcpy(&initial, p, sizeof(msdf_Vec2)); - contour_data[i].edge_count++; - k++; - break; - } - - case STBTT_vcubic: { - msdf_Vec2 p = {v->x / cscale, v->y / cscale}; - msdf_Vec2 c = {v->cx / cscale, v->cy / cscale}; - msdf_Vec2 c1 = {v->cx1 / cscale, v->cy1 / cscale}; - memcpy(&e->p[0], initial, sizeof(msdf_Vec2)); - memcpy(&e->p[1], c, sizeof(msdf_Vec2)); - memcpy(&e->p[2], c1, sizeof(msdf_Vec2)); - memcpy(&e->p[3], p, sizeof(msdf_Vec2)); - memcpy(&initial, p, sizeof(msdf_Vec2)); - contour_data[i].edge_count++; - k++; - break; - } - } - } - } - - // calculate edge-colors - uint64_t seed = 0; - double anglethreshold = 3.0; - double crossthreshold = sin(anglethreshold); - size_t corner_count = 0; - for (int i = 0; i < contour_count; ++i) { - for (int j = 0; j < contour_data[i].edge_count; ++j) { - corner_count++; - } - } - - int *corners = allocCtx.alloc(sizeof(int) * corner_count, allocCtx.ctx); - int cornerIndex = 0; - for (int i = 0; i < contour_count; ++i) { - - if (contour_data[i].edge_count > 0) { - msdf_Vec2 prev_dir, dir; - msdf_direction(prev_dir, &contour_data[i].edges[contour_data[i].edge_count - 1], 1); - - int index = 0; - for (int j = 0; j < contour_data[i].edge_count; ++j, ++index) { - msdf_EdgeSegment *e = &contour_data[i].edges[j]; - msdf_direction(dir, e, 0); - msdf_v2Norm(dir, dir); - msdf_v2Norm(prev_dir, prev_dir); - if (msdf_isCorner(prev_dir, dir, crossthreshold)) { - corners[cornerIndex++] = index; - } - msdf_direction(prev_dir, e, 1); - } - } - - if (cornerIndex == 0) { - for (int j = 0; j < contour_data[i].edge_count; ++j) { - contour_data[i].edges[j].color = msdf_edgeColor_white; - } - } else if (cornerIndex == 1) { - msdf_edgeColor colors[3] = {msdf_edgeColor_white, msdf_edgeColor_white}; - msdf_switchColor(&colors[0], &seed, msdf_edgeColor_black); - colors[2] = colors[0]; - msdf_switchColor(&colors[2], &seed, msdf_edgeColor_black); - - int corner = corners[0]; - if (contour_data[i].edge_count >= 3) { - int m = contour_data[i].edge_count; - for (int j = 0; j < m; ++j) { - contour_data[i].edges[(corner + j) % m].color = (colors + 1)[(int)(3 + 2.875 * i / (m - 1) - 1.4375 + .5) - 3]; - } - } else if (contour_data[i].edge_count >= 1) { - msdf_EdgeSegment *parts[7] = {NULL}; - msdf_edgeSplit(&contour_data[i].edges[0], parts[0 + 3 * corner], parts[1 + 3 * corner], parts[2 + 3 * corner]); - if (contour_data[i].edge_count >= 2) { - msdf_edgeSplit(&contour_data[i].edges[1], parts[3 - 3 * corner], parts[4 - 3 * corner], parts[5 - 3 * corner]); - parts[0]->color = parts[1]->color = colors[0]; - parts[2]->color = parts[3]->color = colors[1]; - parts[4]->color = parts[5]->color = colors[2]; - } else { - parts[0]->color = colors[0]; - parts[1]->color = colors[1]; - parts[2]->color = colors[2]; - } - if (allocCtx.free) { - allocCtx.free(contour_data[i].edges, allocCtx.ctx); - } - contour_data[i].edges = allocCtx.alloc(sizeof(msdf_EdgeSegment) * 7, allocCtx.ctx); - contour_data[i].edge_count = 0; - int index = 0; - for (int j = 0; parts[j]; ++j) { - memcpy(&contour_data[i].edges[index++], &parts[j], sizeof(msdf_EdgeSegment)); - contour_data[i].edge_count++; - } - } - } else { - int spline = 0; - int start = corners[0]; - int m = contour_data[i].edge_count; - msdf_edgeColor color = msdf_edgeColor_white; - msdf_switchColor(&color, &seed, msdf_edgeColor_black); - msdf_edgeColor initial_color = color; - for (int j = 0; j < m; ++j) { - int index = (start + j) % m; - if (spline + 1 < corner_count && corners[spline + 1] == index) { - ++spline; - - msdf_edgeColor s = (msdf_edgeColor)((spline == corner_count - 1) * initial_color); - msdf_switchColor(&color, &seed, s); - } - contour_data[i].edges[index].color = color; - } - } - } - - if (allocCtx.free) { - allocCtx.free(corners, allocCtx.ctx); - } - - // normalize shape - for (int i = 0; i < contour_count; i++) { - if (contour_data[i].edge_count == 1) { - msdf_EdgeSegment *parts[3] = {0}; - msdf_edgeSplit(&contour_data[i].edges[0], parts[0], parts[1], parts[2]); - if (allocCtx.free) { - allocCtx.free(contour_data[i].edges, allocCtx.ctx); - } - contour_data[i].edges = allocCtx.alloc(sizeof(msdf_EdgeSegment) * 3, allocCtx.ctx); - contour_data[i].edge_count = 3; - for (int j = 0; j < 3; j++) { - memcpy(&contour_data[i].edges[j], parts[j], sizeof(msdf_EdgeSegment)); - } - } - } - - // calculate windings - int *windings = allocCtx.alloc(sizeof(int) * contour_count, allocCtx.ctx); - for (int i = 0; i < contour_count; i++) { - size_t edge_count = contour_data[i].edge_count; - if (edge_count == 0) { - windings[i] = 0; - continue; - } - - double total = 0; - - if (edge_count == 1) { - msdf_Vec2 a, b, c; - msdf_point(a, &contour_data[i].edges[0], 0); - msdf_point(b, &contour_data[i].edges[0], 1 / 3.0); - msdf_point(c, &contour_data[i].edges[0], 2 / 3.0); - total += msdf_shoelace(a, b); - total += msdf_shoelace(b, c); - total += msdf_shoelace(c, a); - } else if (edge_count == 2) { - msdf_Vec2 a, b, c, d; - msdf_point(a, &contour_data[i].edges[0], 0); - msdf_point(b, &contour_data[i].edges[0], 0.5); - msdf_point(c, &contour_data[i].edges[1], 0); - msdf_point(d, &contour_data[i].edges[1], 0.5); - total += msdf_shoelace(a, b); - total += msdf_shoelace(b, c); - total += msdf_shoelace(c, d); - total += msdf_shoelace(d, a); - } else { - msdf_Vec2 prev; - msdf_point(prev, &contour_data[i].edges[edge_count - 1], 0); - for (int j = 0; j < edge_count; j++) { - msdf_Vec2 cur; - msdf_point(cur, &contour_data[i].edges[j], 0); - total += msdf_shoelace(prev, cur); - memcpy(prev, cur, sizeof(msdf_Vec2)); - } - } - - windings[i] = ((0 < total) - (total < 0)); // sign - } - - typedef struct { - double r, g, b; - double med; - } msdf_MultiDistance; - - msdf_MultiDistance *contour_sd; - contour_sd = allocCtx.alloc(sizeof(msdf_MultiDistance) * contour_count, allocCtx.ctx); - - float invRange = 1.0 / range; - - for (int y = 0; y < h; ++y) { - int row = iy0 > iy1 ? y : h - y - 1; - for (int x = 0; x < w; ++x) { - float a64 = 64.0; - msdf_Vec2 p = {(translateX + x + xoff) / (scale * a64), (translateY + y + yoff) / (scale * a64)}; - //p[0] = ; - //p[1] = ; - msdf_EdgePoint sr, sg, sb; - sr.near_edge = sg.near_edge = sb.near_edge = NULL; - sr.near_param = sg.near_param = sb.near_param = 0; - sr.min_distance.dist = sg.min_distance.dist = sb.min_distance.dist = MSDF_INF; - sr.min_distance.d = sg.min_distance.d = sb.min_distance.d = 1; - double d = fabs(MSDF_INF); - double neg_dist = -MSDF_INF; - double pos_dist = MSDF_INF; - int winding = 0; - - // calculate distance to contours from current point (and if its inside or outside of the shape?) - for (int j = 0; j < contour_count; ++j) { - msdf_EdgePoint r, g, b; - r.near_edge = g.near_edge = b.near_edge = NULL; - r.near_param = g.near_param = b.near_param = 0; - r.min_distance.dist = g.min_distance.dist = b.min_distance.dist = MSDF_INF; - r.min_distance.d = g.min_distance.d = b.min_distance.d = 1; - - for (int k = 0; k < contour_data[j].edge_count; ++k) { - msdf_EdgeSegment *e = &contour_data[j].edges[k]; - double param; - msdf_signedDistance distance; - distance.dist = MSDF_INF; - distance.d = 1; - - // calculate signed distance - switch (e->type) { - case STBTT_vline: { - distance = msdf_linearDist(e, p, ¶m); - break; - } - case STBTT_vcurve: { - distance = msdf_quadraticDist(e, p, ¶m); - break; - } - case STBTT_vcubic: { - distance = msdf_cubicDist(e, p, ¶m); - break; - } - } - - if (e->color & msdf_edgeColor_red && msdf_signedCompare(distance, r.min_distance)) { - r.min_distance = distance; - r.near_edge = e; - r.near_param = param; - } - if (e->color & msdf_edgeColor_green && msdf_signedCompare(distance, g.min_distance)) { - g.min_distance = distance; - g.near_edge = e; - g.near_param = param; - } - if (e->color & msdf_edgeColor_blue && msdf_signedCompare(distance, b.min_distance)) { - b.min_distance = distance; - b.near_edge = e; - b.near_param = param; - } - } - - if (msdf_signedCompare(r.min_distance, sr.min_distance)) { - sr = r; - } - if (msdf_signedCompare(g.min_distance, sg.min_distance)) { - sg = g; - } - if (msdf_signedCompare(b.min_distance, sb.min_distance)) { - sb = b; - } - - double med_min_dist = fabs(msdf_median(r.min_distance.dist, g.min_distance.dist, b.min_distance.dist)); - - if (med_min_dist < d) { - d = med_min_dist; - winding = -windings[j]; - } - - if (r.near_edge) { - msdf_distToPseudo(&r.min_distance, p, r.near_param, r.near_edge); - } - if (g.near_edge) { - msdf_distToPseudo(&g.min_distance, p, g.near_param, g.near_edge); - } - if (b.near_edge) { - msdf_distToPseudo(&b.min_distance, p, b.near_param, b.near_edge); - } - - med_min_dist = msdf_median(r.min_distance.dist, g.min_distance.dist, b.min_distance.dist); - contour_sd[j].r = r.min_distance.dist; - contour_sd[j].g = g.min_distance.dist; - contour_sd[j].b = b.min_distance.dist; - contour_sd[j].med = med_min_dist; - - if (windings[j] > 0 && med_min_dist >= 0 && fabs(med_min_dist) < fabs(pos_dist)) { - pos_dist = med_min_dist; - } - if (windings[j] < 0 && med_min_dist <= 0 && fabs(med_min_dist) < fabs(neg_dist)) { - neg_dist = med_min_dist; - } - } - - if (sr.near_edge) { - msdf_distToPseudo(&sr.min_distance, p, sr.near_param, sr.near_edge); - } - if (sg.near_edge) { - msdf_distToPseudo(&sg.min_distance, p, sg.near_param, sg.near_edge); - } - if (sb.near_edge) { - msdf_distToPseudo(&sb.min_distance, p, sb.near_param, sb.near_edge); - } - - msdf_MultiDistance msd; - msd.r = msd.g = msd.b = msd.med = MSDF_INF; - if (pos_dist >= 0 && fabs(pos_dist) <= fabs(neg_dist)) { - msd.med = MSDF_INF; - winding = 1; - for (int i = 0; i < contour_count; ++i) { - if (windings[i] > 0 && contour_sd[i].med > msd.med && fabs(contour_sd[i].med) < fabs(neg_dist)) { - msd = contour_sd[i]; - } - } - } else if (neg_dist <= 0 && fabs(neg_dist) <= fabs(pos_dist)) { - msd.med = -MSDF_INF; - winding = -1; - for (int i = 0; i < contour_count; ++i) { - if (windings[i] < 0 && contour_sd[i].med < msd.med && fabs(contour_sd[i].med) < fabs(pos_dist)) { - msd = contour_sd[i]; - } - } - } - - for (int i = 0; i < contour_count; ++i) { - if (windings[i] != winding && fabs(contour_sd[i].med) < fabs(msd.med)) { - msd = contour_sd[i]; - } - } - - if (msdf_median(sr.min_distance.dist, sg.min_distance.dist, sb.min_distance.dist) == msd.med) { - msd.r = sr.min_distance.dist; - msd.g = sg.min_distance.dist; - msd.b = sb.min_distance.dist; - } - - size_t index = 3 * ((row * w) + x); - - float mr = ((float)msd.r) * invRange + 0.5f; - float mg = ((float)msd.g) * invRange + 0.5f; - float mb = ((float)msd.b) * invRange + 0.5f; - bitmap[index + 0] = mr; - bitmap[index + 1] = mg; - bitmap[index + 2] = mb; - - } - } - - if (allocCtx.free) { - for (int i = 0; i < contour_count; i++) { - allocCtx.free(contour_data[i].edges, allocCtx.ctx); - } - allocCtx.free(contour_data, allocCtx.ctx); - allocCtx.free(contour_sd, allocCtx.ctx); - allocCtx.free(contours, allocCtx.ctx); - allocCtx.free(windings, allocCtx.ctx); - allocCtx.free(verts, allocCtx.ctx); - } - - // msdf error correction - typedef struct { - int x, y; - } msdf_Clash; - msdf_Clash *clashes = allocCtx.alloc(sizeof(msdf_Clash) * w * h, allocCtx.ctx); - size_t cindex = 0; - - double tx = MSDF_EDGE_THRESHOLD / (scale * range); - double ty = MSDF_EDGE_THRESHOLD / (scale * range); - for (int y = 0; y < h; y++) { - for (int x = 0; x < w; x++) { - if ((x > 0 && msdf_pixelClash(msdf_pixelAt(x, y, w, bitmap), msdf_pixelAt(msdf_max(x - 1, 0), y, w, bitmap), tx)) || (x < w - 1 && msdf_pixelClash(msdf_pixelAt(x, y, w, bitmap), msdf_pixelAt(msdf_min(x + 1, w - 1), y, w, bitmap), tx)) || (y > 0 && msdf_pixelClash(msdf_pixelAt(x, y, w, bitmap), msdf_pixelAt(x, msdf_max(y - 1, 0), w, bitmap), ty)) || (y < h - 1 && msdf_pixelClash(msdf_pixelAt(x, y, w, bitmap), msdf_pixelAt(x, msdf_min(y + 1, h - 1), w, bitmap), ty))) { - clashes[cindex].x = x; - clashes[cindex++].y = y; - } - } - } - - for (int i = 0; i < cindex; i++) { - size_t index = 3 * ((clashes[i].y * w) + clashes[i].x); - float med = msdf_median(bitmap[index], bitmap[index + 1], bitmap[index + 2]); - bitmap[index + 0] = med; - bitmap[index + 1] = med; - bitmap[index + 2] = med; - } - - if (allocCtx.free) { - allocCtx.free(clashes, allocCtx.ctx); - } - - result->glyphIdx = glyphIdx; - result->rgb = bitmap; - result->width = w; - result->height = h; - result->yOffset = translateY; - - return 1; -} -#endif -#endif // MSDF_H diff --git a/text_rendering/msdf_c/sample/fonts/Roboto-Regular.ttf b/text_rendering/msdf_c/sample/fonts/Roboto-Regular.ttf deleted file mode 100644 index ddf4bfa..0000000 Binary files a/text_rendering/msdf_c/sample/fonts/Roboto-Regular.ttf and /dev/null differ diff --git a/text_rendering/msdf_c/sample/fonts/RobotoLicense.txt b/text_rendering/msdf_c/sample/fonts/RobotoLicense.txt deleted file mode 100644 index f49a4e1..0000000 --- a/text_rendering/msdf_c/sample/fonts/RobotoLicense.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. \ No newline at end of file diff --git a/text_rendering/msdf_c/sample/sample b/text_rendering/msdf_c/sample/sample deleted file mode 100755 index 215b1df..0000000 Binary files a/text_rendering/msdf_c/sample/sample and /dev/null differ diff --git a/text_rendering/msdf_c/sample/sample.c b/text_rendering/msdf_c/sample/sample.c deleted file mode 100644 index bc88ef6..0000000 --- a/text_rendering/msdf_c/sample/sample.c +++ /dev/null @@ -1,210 +0,0 @@ -//#include "svpng.h" -#define STB_IMAGE_WRITE_IMPLEMENTATION -#include "stb_image_write.h" -#define STB_TRUETYPE_IMPLEMENTATION -#include "../stb_truetype.h" -#define MSDF_IMPLEMENTATION -#include "../msdf.h" - -#include "stdio.h" - - -#ifndef SAMPLE_ROOT -#define SAMPLE_ROOT "" -#endif - -typedef struct Range { - void* content; - size_t size; -} Range; - -Range g_fileRead(const char* fileName) { - Range range = {NULL, 0}; - - FILE* fileHandle = fopen(fileName, "rb"); - if (fileHandle == NULL) { - assert(!"File not fount"); - return range; - } - - fseek(fileHandle, 0, SEEK_END); // seek to end of file - size_t size = ftell(fileHandle); // get current file pointer - fseek(fileHandle, 0, SEEK_SET); // seek back to beginning of file - - if (size == 0) { - assert(!"File size zero"); - return range; - } - - void* mem = malloc(size); - size_t readSize = fread(mem, 1, size, fileHandle); - if (readSize == size) { - range.content = mem; - range.size = size; - } else { - free(mem); - } - fclose(fileHandle); - return range; -} - -static void* g_alloc(size_t size, void* ctx) { - return malloc(size); -} - -static void g_free(void* ptr, void* ctx) { - return free(ptr); -} - -float g_min(float a, float b) { - return a > b ? b : a; -} - -float g_max(float a, float b) { - return a > b ? a : b; -} - -float g_clamp(float val, float min, float max) { - return g_min(g_max(val, min), max); -} - -float g_median(float r, float g, float b) { - return g_max(g_min(r, g), g_min(g_max(r, g), b)); -} - -float g_map(float min, float max, float v) { - return (v - min) / (max - min); -} - -int main() { - stbtt_fontinfo stbttInfo; - - Range fontFile = g_fileRead("./fonts/Roboto-Regular.ttf"); - - if (fontFile.content == NULL) { - assert(!"could not load font from disk"); - return 1; - } - - if (!stbtt_InitFont(&stbttInfo, fontFile.content, stbtt_GetFontOffsetForIndex(fontFile.content, 0))) { - assert(!"Couldn't parse font"); - return 1; - } - - - int ascent, descent; - stbtt_GetFontVMetrics(&stbttInfo, &ascent, &descent, 0); - - int borderSize = 4; - int genSize = 32+borderSize; - float genScale = stbtt_ScaleForPixelHeight(&stbttInfo, genSize); - - // int glyph = 0x00e8; // è - int glyph = 0x069D; - - int glyphIdx = stbtt_FindGlyphIndex(&stbttInfo, glyph); - - msdf_AllocCtx allocCtx = {g_alloc, g_free, NULL}; - - - printf("bruh\n"); - - msdf_Result result; - int success = msdf_genGlyph(&result, &stbttInfo, glyphIdx, borderSize, genScale, 2.0f / genSize, &allocCtx); - - if (success == 0) { - assert(!"Failed to generate msdf glyph"); - return 1; - } - printf("bruh\n"); - -// FILE* fp = fopen(SAMPLE_ROOT "/sdf.png", "wb"); - - uint8_t* pixels = malloc(sizeof(uint8_t) * result.width * result.height * 3); - float scale = genSize; - float maxValue = 1.0 * (scale); - float transistionWidth = ((((((float) genSize) * 0.7f) + scale) / (scale * 2.0f))); - float transistionAbs = (transistionWidth - 0.5); - float transistStart = 0.5 - transistionAbs / 2; - float transistEnd = transistStart + transistionAbs; - - //float ff = expf(0.01); - for (int y = 0; y < result.height; y++) { - int yPos = result.width * 3 * y; - uint8_t* pixelRow = pixels + (y * result.width * 3); - for (int x = 0; x < result.width; x++) { - int indexSdf = yPos + (x * 3); - float r = result.rgb[indexSdf + 0]; - float g = result.rgb[indexSdf + 1]; - float b = result.rgb[indexSdf + 2]; - - - r = ((((r) + scale) / (scale * 2.0f))); - g = ((((g) + scale) / (scale * 2.0f))); - b = ((((b) + scale) / (scale * 2.0f))); - - if (r > transistStart) { - if (r > (transistEnd)) { - r = 1.0f; - } else { - r = 0.0f + (r - transistStart) / (transistionAbs); - } - } else { - r = 0.0f; - } - if (g > transistStart) { - if (g > (transistEnd)) { - g = 1.0f; - } else { - g = 0.0f + (g - transistStart) / (transistionAbs); - } - } else { - g = 0.0f; - } - if (b > transistStart) { - if (b > (transistEnd)) { - b = 1.0f; - } else { - b = 0.0f + (b - transistStart) / (transistionAbs); - } - } else { - b = 0.0f; - } - - pixelRow[x * 3 + 0] = r * 255.0f; // (r > 0.5f) ? 255.0f : r * 255.0f; - pixelRow[x * 3 + 1] = g * 255.0f; // (g > 0.5f) ? 255.0f : g * 255.0f; - pixelRow[x * 3 + 2] = b * 255.0f; // (b > 0.5f) ? 255.0f : b * 255.0f; - } - } -// printf("bruh\n"); -// -// svpng(fp, result.width, result.height, pixels, 0); - stbi_write_png("./sdf.png", result.width, result.height, 3, pixels, 3*result.width); -// fclose(fp); - - // apply sdf -// -// FILE* finalImage = fopen(SAMPLE_ROOT "/final.png", "wb"); -// -// uint8_t* rgbaFinal = malloc(sizeof(uint8_t) * result.width * result.height * 4); -// -// for (int y = 0; y < result.height; y++) { -// uint8_t* pixelRow = pixels + (y * result.width * 3); -// uint8_t* rgbaFinalRow = rgbaFinal + (y * result.width * 4); -// for (int x = 0; x < result.width; x++) { -// float r = ((float)pixelRow[x * 3 + 0]) / 255.0f;// = r * 255.0f; // (r > 0.5f) ? 255.0f : r * 255.0f; -// float g = ((float)pixelRow[x * 3 + 1]) / 255.0f;// = g * 255.0f; // (g > 0.5f) ? 255.0f : g * 255.0f; -// float b = ((float)pixelRow[x * 3 + 2]) / 255.0f;// = b * 255.0f; // (b > 0.5f) ? 255.0f : b * 255.0f; -// float dist = g_median(r, g, b); -// float opacity = g_clamp(dist - 0.5f, 0, 1) * 2.0f; -// rgbaFinalRow[x * 4 + 0] = 0;//255.0f; -// rgbaFinalRow[x * 4 + 1] = 0;//255.0f; -// rgbaFinalRow[x * 4 + 2] = 0;//255.0f; -// rgbaFinalRow[x * 4 + 3] = opacity * 255.0f; -// -// } -// } -// svpng(finalImage, result.width, result.height, rgbaFinal, 1); -// fclose(finalImage); - return 0; -} \ No newline at end of file diff --git a/text_rendering/msdf_c/sample/sdf.png b/text_rendering/msdf_c/sample/sdf.png deleted file mode 100644 index 9040c3e..0000000 Binary files a/text_rendering/msdf_c/sample/sdf.png and /dev/null differ diff --git a/text_rendering/msdf_c/sample/stb_image_write.h b/text_rendering/msdf_c/sample/stb_image_write.h deleted file mode 100644 index e4b32ed..0000000 --- a/text_rendering/msdf_c/sample/stb_image_write.h +++ /dev/null @@ -1,1724 +0,0 @@ -/* stb_image_write - v1.16 - public domain - http://nothings.org/stb - writes out PNG/BMP/TGA/JPEG/HDR images to C stdio - Sean Barrett 2010-2015 - no warranty implied; use at your own risk - - Before #including, - - #define STB_IMAGE_WRITE_IMPLEMENTATION - - in the file that you want to have the implementation. - - Will probably not work correctly with strict-aliasing optimizations. - -ABOUT: - - This header file is a library for writing images to C stdio or a callback. - - The PNG output is not optimal; it is 20-50% larger than the file - written by a decent optimizing implementation; though providing a custom - zlib compress function (see STBIW_ZLIB_COMPRESS) can mitigate that. - This library is designed for source code compactness and simplicity, - not optimal image file size or run-time performance. - -BUILDING: - - You can #define STBIW_ASSERT(x) before the #include to avoid using assert.h. - You can #define STBIW_MALLOC(), STBIW_REALLOC(), and STBIW_FREE() to replace - malloc,realloc,free. - You can #define STBIW_MEMMOVE() to replace memmove() - You can #define STBIW_ZLIB_COMPRESS to use a custom zlib-style compress function - for PNG compression (instead of the builtin one), it must have the following signature: - unsigned char * my_compress(unsigned char *data, int data_len, int *out_len, int quality); - The returned data will be freed with STBIW_FREE() (free() by default), - so it must be heap allocated with STBIW_MALLOC() (malloc() by default), - -UNICODE: - - If compiling for Windows and you wish to use Unicode filenames, compile - with - #define STBIW_WINDOWS_UTF8 - and pass utf8-encoded filenames. Call stbiw_convert_wchar_to_utf8 to convert - Windows wchar_t filenames to utf8. - -USAGE: - - There are five functions, one for each image file format: - - int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); - int stbi_write_jpg(char const *filename, int w, int h, int comp, const void *data, int quality); - int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); - - void stbi_flip_vertically_on_write(int flag); // flag is non-zero to flip data vertically - - There are also five equivalent functions that use an arbitrary write function. You are - expected to open/close your file-equivalent before and after calling these: - - int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); - int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); - int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); - int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - - where the callback is: - void stbi_write_func(void *context, void *data, int size); - - You can configure it with these global variables: - int stbi_write_tga_with_rle; // defaults to true; set to 0 to disable RLE - int stbi_write_png_compression_level; // defaults to 8; set to higher for more compression - int stbi_write_force_png_filter; // defaults to -1; set to 0..5 to force a filter mode - - - You can define STBI_WRITE_NO_STDIO to disable the file variant of these - functions, so the library will not use stdio.h at all. However, this will - also disable HDR writing, because it requires stdio for formatted output. - - Each function returns 0 on failure and non-0 on success. - - The functions create an image file defined by the parameters. The image - is a rectangle of pixels stored from left-to-right, top-to-bottom. - Each pixel contains 'comp' channels of data stored interleaved with 8-bits - per channel, in the following order: 1=Y, 2=YA, 3=RGB, 4=RGBA. (Y is - monochrome color.) The rectangle is 'w' pixels wide and 'h' pixels tall. - The *data pointer points to the first byte of the top-left-most pixel. - For PNG, "stride_in_bytes" is the distance in bytes from the first byte of - a row of pixels to the first byte of the next row of pixels. - - PNG creates output files with the same number of components as the input. - The BMP format expands Y to RGB in the file format and does not - output alpha. - - PNG supports writing rectangles of data even when the bytes storing rows of - data are not consecutive in memory (e.g. sub-rectangles of a larger image), - by supplying the stride between the beginning of adjacent rows. The other - formats do not. (Thus you cannot write a native-format BMP through the BMP - writer, both because it is in BGR order and because it may have padding - at the end of the line.) - - PNG allows you to set the deflate compression level by setting the global - variable 'stbi_write_png_compression_level' (it defaults to 8). - - HDR expects linear float data. Since the format is always 32-bit rgb(e) - data, alpha (if provided) is discarded, and for monochrome data it is - replicated across all three channels. - - TGA supports RLE or non-RLE compressed data. To use non-RLE-compressed - data, set the global variable 'stbi_write_tga_with_rle' to 0. - - JPEG does ignore alpha channels in input data; quality is between 1 and 100. - Higher quality looks better but results in a bigger image. - JPEG baseline (no JPEG progressive). - -CREDITS: - - - Sean Barrett - PNG/BMP/TGA - Baldur Karlsson - HDR - Jean-Sebastien Guay - TGA monochrome - Tim Kelsey - misc enhancements - Alan Hickman - TGA RLE - Emmanuel Julien - initial file IO callback implementation - Jon Olick - original jo_jpeg.cpp code - Daniel Gibson - integrate JPEG, allow external zlib - Aarni Koskela - allow choosing PNG filter - - bugfixes: - github:Chribba - Guillaume Chereau - github:jry2 - github:romigrou - Sergio Gonzalez - Jonas Karlsson - Filip Wasil - Thatcher Ulrich - github:poppolopoppo - Patrick Boettcher - github:xeekworx - Cap Petschulat - Simon Rodriguez - Ivan Tikhonov - github:ignotion - Adam Schackart - Andrew Kensler - -LICENSE - - See end of file for license information. - -*/ - -#ifndef INCLUDE_STB_IMAGE_WRITE_H -#define INCLUDE_STB_IMAGE_WRITE_H - -#include - -// if STB_IMAGE_WRITE_STATIC causes problems, try defining STBIWDEF to 'inline' or 'static inline' -#ifndef STBIWDEF -#ifdef STB_IMAGE_WRITE_STATIC -#define STBIWDEF static -#else -#ifdef __cplusplus -#define STBIWDEF extern "C" -#else -#define STBIWDEF extern -#endif -#endif -#endif - -#ifndef STB_IMAGE_WRITE_STATIC // C++ forbids static forward declarations -STBIWDEF int stbi_write_tga_with_rle; -STBIWDEF int stbi_write_png_compression_level; -STBIWDEF int stbi_write_force_png_filter; -#endif - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga(char const *filename, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr(char const *filename, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality); - -#ifdef STBIW_WINDOWS_UTF8 -STBIWDEF int stbiw_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); -#endif -#endif - -typedef void stbi_write_func(void *context, void *data, int size); - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data, int stride_in_bytes); -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const void *data); -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int w, int h, int comp, const float *data); -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality); - -STBIWDEF void stbi_flip_vertically_on_write(int flip_boolean); - -#endif//INCLUDE_STB_IMAGE_WRITE_H - -#ifdef STB_IMAGE_WRITE_IMPLEMENTATION - -#ifdef _WIN32 - #ifndef _CRT_SECURE_NO_WARNINGS - #define _CRT_SECURE_NO_WARNINGS - #endif - #ifndef _CRT_NONSTDC_NO_DEPRECATE - #define _CRT_NONSTDC_NO_DEPRECATE - #endif -#endif - -#ifndef STBI_WRITE_NO_STDIO -#include -#endif // STBI_WRITE_NO_STDIO - -#include -#include -#include -#include - -#if defined(STBIW_MALLOC) && defined(STBIW_FREE) && (defined(STBIW_REALLOC) || defined(STBIW_REALLOC_SIZED)) -// ok -#elif !defined(STBIW_MALLOC) && !defined(STBIW_FREE) && !defined(STBIW_REALLOC) && !defined(STBIW_REALLOC_SIZED) -// ok -#else -#error "Must define all or none of STBIW_MALLOC, STBIW_FREE, and STBIW_REALLOC (or STBIW_REALLOC_SIZED)." -#endif - -#ifndef STBIW_MALLOC -#define STBIW_MALLOC(sz) malloc(sz) -#define STBIW_REALLOC(p,newsz) realloc(p,newsz) -#define STBIW_FREE(p) free(p) -#endif - -#ifndef STBIW_REALLOC_SIZED -#define STBIW_REALLOC_SIZED(p,oldsz,newsz) STBIW_REALLOC(p,newsz) -#endif - - -#ifndef STBIW_MEMMOVE -#define STBIW_MEMMOVE(a,b,sz) memmove(a,b,sz) -#endif - - -#ifndef STBIW_ASSERT -#include -#define STBIW_ASSERT(x) assert(x) -#endif - -#define STBIW_UCHAR(x) (unsigned char) ((x) & 0xff) - -#ifdef STB_IMAGE_WRITE_STATIC -static int stbi_write_png_compression_level = 8; -static int stbi_write_tga_with_rle = 1; -static int stbi_write_force_png_filter = -1; -#else -int stbi_write_png_compression_level = 8; -int stbi_write_tga_with_rle = 1; -int stbi_write_force_png_filter = -1; -#endif - -static int stbi__flip_vertically_on_write = 0; - -STBIWDEF void stbi_flip_vertically_on_write(int flag) -{ - stbi__flip_vertically_on_write = flag; -} - -typedef struct -{ - stbi_write_func *func; - void *context; - unsigned char buffer[64]; - int buf_used; -} stbi__write_context; - -// initialize a callback-based context -static void stbi__start_write_callbacks(stbi__write_context *s, stbi_write_func *c, void *context) -{ - s->func = c; - s->context = context; -} - -#ifndef STBI_WRITE_NO_STDIO - -static void stbi__stdio_write(void *context, void *data, int size) -{ - fwrite(data,1,size,(FILE*) context); -} - -#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) -#ifdef __cplusplus -#define STBIW_EXTERN extern "C" -#else -#define STBIW_EXTERN extern -#endif -STBIW_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); -STBIW_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); - -STBIWDEF int stbiw_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 *stbiw__fopen(char const *filename, char const *mode) -{ - FILE *f; -#if defined(_WIN32) && defined(STBIW_WINDOWS_UTF8) - wchar_t wMode[64]; - wchar_t wFilename[1024]; - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) - return 0; - - if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) - return 0; - -#if defined(_MSC_VER) && _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; -} - -static int stbi__start_write_file(stbi__write_context *s, const char *filename) -{ - FILE *f = stbiw__fopen(filename, "wb"); - stbi__start_write_callbacks(s, stbi__stdio_write, (void *) f); - return f != NULL; -} - -static void stbi__end_write_file(stbi__write_context *s) -{ - fclose((FILE *)s->context); -} - -#endif // !STBI_WRITE_NO_STDIO - -typedef unsigned int stbiw_uint32; -typedef int stb_image_write_test[sizeof(stbiw_uint32)==4 ? 1 : -1]; - -static void stbiw__writefv(stbi__write_context *s, const char *fmt, va_list v) -{ - while (*fmt) { - switch (*fmt++) { - case ' ': break; - case '1': { unsigned char x = STBIW_UCHAR(va_arg(v, int)); - s->func(s->context,&x,1); - break; } - case '2': { int x = va_arg(v,int); - unsigned char b[2]; - b[0] = STBIW_UCHAR(x); - b[1] = STBIW_UCHAR(x>>8); - s->func(s->context,b,2); - break; } - case '4': { stbiw_uint32 x = va_arg(v,int); - unsigned char b[4]; - b[0]=STBIW_UCHAR(x); - b[1]=STBIW_UCHAR(x>>8); - b[2]=STBIW_UCHAR(x>>16); - b[3]=STBIW_UCHAR(x>>24); - s->func(s->context,b,4); - break; } - default: - STBIW_ASSERT(0); - return; - } - } -} - -static void stbiw__writef(stbi__write_context *s, const char *fmt, ...) -{ - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); -} - -static void stbiw__write_flush(stbi__write_context *s) -{ - if (s->buf_used) { - s->func(s->context, &s->buffer, s->buf_used); - s->buf_used = 0; - } -} - -static void stbiw__putc(stbi__write_context *s, unsigned char c) -{ - s->func(s->context, &c, 1); -} - -static void stbiw__write1(stbi__write_context *s, unsigned char a) -{ - if ((size_t)s->buf_used + 1 > sizeof(s->buffer)) - stbiw__write_flush(s); - s->buffer[s->buf_used++] = a; -} - -static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c) -{ - int n; - if ((size_t)s->buf_used + 3 > sizeof(s->buffer)) - stbiw__write_flush(s); - n = s->buf_used; - s->buf_used = n+3; - s->buffer[n+0] = a; - s->buffer[n+1] = b; - s->buffer[n+2] = c; -} - -static void stbiw__write_pixel(stbi__write_context *s, int rgb_dir, int comp, int write_alpha, int expand_mono, unsigned char *d) -{ - unsigned char bg[3] = { 255, 0, 255}, px[3]; - int k; - - if (write_alpha < 0) - stbiw__write1(s, d[comp - 1]); - - switch (comp) { - case 2: // 2 pixels = mono + alpha, alpha is written separately, so same as 1-channel case - case 1: - if (expand_mono) - stbiw__write3(s, d[0], d[0], d[0]); // monochrome bmp - else - stbiw__write1(s, d[0]); // monochrome TGA - break; - case 4: - if (!write_alpha) { - // composite against pink background - for (k = 0; k < 3; ++k) - px[k] = bg[k] + ((d[k] - bg[k]) * d[3]) / 255; - stbiw__write3(s, px[1 - rgb_dir], px[1], px[1 + rgb_dir]); - break; - } - /* FALLTHROUGH */ - case 3: - stbiw__write3(s, d[1 - rgb_dir], d[1], d[1 + rgb_dir]); - break; - } - if (write_alpha > 0) - stbiw__write1(s, d[comp - 1]); -} - -static void stbiw__write_pixels(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, void *data, int write_alpha, int scanline_pad, int expand_mono) -{ - stbiw_uint32 zero = 0; - int i,j, j_end; - - if (y <= 0) - return; - - if (stbi__flip_vertically_on_write) - vdir *= -1; - - if (vdir < 0) { - j_end = -1; j = y-1; - } else { - j_end = y; j = 0; - } - - for (; j != j_end; j += vdir) { - for (i=0; i < x; ++i) { - unsigned char *d = (unsigned char *) data + (j*x+i)*comp; - stbiw__write_pixel(s, rgb_dir, comp, write_alpha, expand_mono, d); - } - stbiw__write_flush(s); - s->func(s->context, &zero, scanline_pad); - } -} - -static int stbiw__outfile(stbi__write_context *s, int rgb_dir, int vdir, int x, int y, int comp, int expand_mono, void *data, int alpha, int pad, const char *fmt, ...) -{ - if (y < 0 || x < 0) { - return 0; - } else { - va_list v; - va_start(v, fmt); - stbiw__writefv(s, fmt, v); - va_end(v); - stbiw__write_pixels(s,rgb_dir,vdir,x,y,comp,data,alpha,pad, expand_mono); - return 1; - } -} - -static int stbi_write_bmp_core(stbi__write_context *s, int x, int y, int comp, const void *data) -{ - if (comp != 4) { - // write RGB bitmap - int pad = (-x*3) & 3; - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *) data,0,pad, - "11 4 22 4" "4 44 22 444444", - 'B', 'M', 14+40+(x*3+pad)*y, 0,0, 14+40, // file header - 40, x,y, 1,24, 0,0,0,0,0,0); // bitmap header - } else { - // RGBA bitmaps need a v4 header - // use BI_BITFIELDS mode with 32bpp and alpha mask - // (straight BI_RGB with alpha mask doesn't work in most readers) - return stbiw__outfile(s,-1,-1,x,y,comp,1,(void *)data,1,0, - "11 4 22 4" "4 44 22 444444 4444 4 444 444 444 444", - 'B', 'M', 14+108+x*y*4, 0, 0, 14+108, // file header - 108, x,y, 1,32, 3,0,0,0,0,0, 0xff0000,0xff00,0xff,0xff000000u, 0, 0,0,0, 0,0,0, 0,0,0, 0,0,0); // bitmap V4 header - } -} - -STBIWDEF int stbi_write_bmp_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_bmp_core(&s, x, y, comp, data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_bmp(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_bmp_core(&s, x, y, comp, data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif //!STBI_WRITE_NO_STDIO - -static int stbi_write_tga_core(stbi__write_context *s, int x, int y, int comp, void *data) -{ - int has_alpha = (comp == 2 || comp == 4); - int colorbytes = has_alpha ? comp-1 : comp; - int format = colorbytes < 2 ? 3 : 2; // 3 color channels (RGB/RGBA) = 2, 1 color channel (Y/YA) = 3 - - if (y < 0 || x < 0) - return 0; - - if (!stbi_write_tga_with_rle) { - return stbiw__outfile(s, -1, -1, x, y, comp, 0, (void *) data, has_alpha, 0, - "111 221 2222 11", 0, 0, format, 0, 0, 0, 0, 0, x, y, (colorbytes + has_alpha) * 8, has_alpha * 8); - } else { - int i,j,k; - int jend, jdir; - - stbiw__writef(s, "111 221 2222 11", 0,0,format+8, 0,0,0, 0,0,x,y, (colorbytes + has_alpha) * 8, has_alpha * 8); - - if (stbi__flip_vertically_on_write) { - j = 0; - jend = y; - jdir = 1; - } else { - j = y-1; - jend = -1; - jdir = -1; - } - for (; j != jend; j += jdir) { - unsigned char *row = (unsigned char *) data + j * x * comp; - int len; - - for (i = 0; i < x; i += len) { - unsigned char *begin = row + i * comp; - int diff = 1; - len = 1; - - if (i < x - 1) { - ++len; - diff = memcmp(begin, row + (i + 1) * comp, comp); - if (diff) { - const unsigned char *prev = begin; - for (k = i + 2; k < x && len < 128; ++k) { - if (memcmp(prev, row + k * comp, comp)) { - prev += comp; - ++len; - } else { - --len; - break; - } - } - } else { - for (k = i + 2; k < x && len < 128; ++k) { - if (!memcmp(begin, row + k * comp, comp)) { - ++len; - } else { - break; - } - } - } - } - - if (diff) { - unsigned char header = STBIW_UCHAR(len - 1); - stbiw__write1(s, header); - for (k = 0; k < len; ++k) { - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin + k * comp); - } - } else { - unsigned char header = STBIW_UCHAR(len - 129); - stbiw__write1(s, header); - stbiw__write_pixel(s, -1, comp, has_alpha, 0, begin); - } - } - } - stbiw__write_flush(s); - } - return 1; -} - -STBIWDEF int stbi_write_tga_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_tga_core(&s, x, y, comp, (void *) data); -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_tga(char const *filename, int x, int y, int comp, const void *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_tga_core(&s, x, y, comp, (void *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -// ************************************************************************************************* -// Radiance RGBE HDR writer -// by Baldur Karlsson - -#define stbiw__max(a, b) ((a) > (b) ? (a) : (b)) - -#ifndef STBI_WRITE_NO_STDIO - -static void stbiw__linear_to_rgbe(unsigned char *rgbe, float *linear) -{ - int exponent; - float maxcomp = stbiw__max(linear[0], stbiw__max(linear[1], linear[2])); - - if (maxcomp < 1e-32f) { - rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; - } else { - float normalize = (float) frexp(maxcomp, &exponent) * 256.0f/maxcomp; - - rgbe[0] = (unsigned char)(linear[0] * normalize); - rgbe[1] = (unsigned char)(linear[1] * normalize); - rgbe[2] = (unsigned char)(linear[2] * normalize); - rgbe[3] = (unsigned char)(exponent + 128); - } -} - -static void stbiw__write_run_data(stbi__write_context *s, int length, unsigned char databyte) -{ - unsigned char lengthbyte = STBIW_UCHAR(length+128); - STBIW_ASSERT(length+128 <= 255); - s->func(s->context, &lengthbyte, 1); - s->func(s->context, &databyte, 1); -} - -static void stbiw__write_dump_data(stbi__write_context *s, int length, unsigned char *data) -{ - unsigned char lengthbyte = STBIW_UCHAR(length); - STBIW_ASSERT(length <= 128); // inconsistent with spec but consistent with official code - s->func(s->context, &lengthbyte, 1); - s->func(s->context, data, length); -} - -static void stbiw__write_hdr_scanline(stbi__write_context *s, int width, int ncomp, unsigned char *scratch, float *scanline) -{ - unsigned char scanlineheader[4] = { 2, 2, 0, 0 }; - unsigned char rgbe[4]; - float linear[3]; - int x; - - scanlineheader[2] = (width&0xff00)>>8; - scanlineheader[3] = (width&0x00ff); - - /* skip RLE for images too small or large */ - if (width < 8 || width >= 32768) { - for (x=0; x < width; x++) { - switch (ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - s->func(s->context, rgbe, 4); - } - } else { - int c,r; - /* encode into scratch buffer */ - for (x=0; x < width; x++) { - switch(ncomp) { - case 4: /* fallthrough */ - case 3: linear[2] = scanline[x*ncomp + 2]; - linear[1] = scanline[x*ncomp + 1]; - linear[0] = scanline[x*ncomp + 0]; - break; - default: - linear[0] = linear[1] = linear[2] = scanline[x*ncomp + 0]; - break; - } - stbiw__linear_to_rgbe(rgbe, linear); - scratch[x + width*0] = rgbe[0]; - scratch[x + width*1] = rgbe[1]; - scratch[x + width*2] = rgbe[2]; - scratch[x + width*3] = rgbe[3]; - } - - s->func(s->context, scanlineheader, 4); - - /* RLE each component separately */ - for (c=0; c < 4; c++) { - unsigned char *comp = &scratch[width*c]; - - x = 0; - while (x < width) { - // find first run - r = x; - while (r+2 < width) { - if (comp[r] == comp[r+1] && comp[r] == comp[r+2]) - break; - ++r; - } - if (r+2 >= width) - r = width; - // dump up to first run - while (x < r) { - int len = r-x; - if (len > 128) len = 128; - stbiw__write_dump_data(s, len, &comp[x]); - x += len; - } - // if there's a run, output it - if (r+2 < width) { // same test as what we break out of in search loop, so only true if we break'd - // find next byte after run - while (r < width && comp[r] == comp[x]) - ++r; - // output run up to r - while (x < r) { - int len = r-x; - if (len > 127) len = 127; - stbiw__write_run_data(s, len, comp[x]); - x += len; - } - } - } - } - } -} - -static int stbi_write_hdr_core(stbi__write_context *s, int x, int y, int comp, float *data) -{ - if (y <= 0 || x <= 0 || data == NULL) - return 0; - else { - // Each component is stored separately. Allocate scratch space for full output scanline. - unsigned char *scratch = (unsigned char *) STBIW_MALLOC(x*4); - int i, len; - char buffer[128]; - char header[] = "#?RADIANCE\n# Written by stb_image_write.h\nFORMAT=32-bit_rle_rgbe\n"; - s->func(s->context, header, sizeof(header)-1); - -#ifdef __STDC_LIB_EXT1__ - len = sprintf_s(buffer, sizeof(buffer), "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#else - len = sprintf(buffer, "EXPOSURE= 1.0000000000000\n\n-Y %d +X %d\n", y, x); -#endif - s->func(s->context, buffer, len); - - for(i=0; i < y; i++) - stbiw__write_hdr_scanline(s, x, comp, scratch, data + comp*x*(stbi__flip_vertically_on_write ? y-1-i : i)); - STBIW_FREE(scratch); - return 1; - } -} - -STBIWDEF int stbi_write_hdr_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_hdr_core(&s, x, y, comp, (float *) data); -} - -STBIWDEF int stbi_write_hdr(char const *filename, int x, int y, int comp, const float *data) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_hdr_core(&s, x, y, comp, (float *) data); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif // STBI_WRITE_NO_STDIO - - -////////////////////////////////////////////////////////////////////////////// -// -// PNG writer -// - -#ifndef STBIW_ZLIB_COMPRESS -// stretchy buffer; stbiw__sbpush() == vector<>::push_back() -- stbiw__sbcount() == vector<>::size() -#define stbiw__sbraw(a) ((int *) (void *) (a) - 2) -#define stbiw__sbm(a) stbiw__sbraw(a)[0] -#define stbiw__sbn(a) stbiw__sbraw(a)[1] - -#define stbiw__sbneedgrow(a,n) ((a)==0 || stbiw__sbn(a)+n >= stbiw__sbm(a)) -#define stbiw__sbmaybegrow(a,n) (stbiw__sbneedgrow(a,(n)) ? stbiw__sbgrow(a,n) : 0) -#define stbiw__sbgrow(a,n) stbiw__sbgrowf((void **) &(a), (n), sizeof(*(a))) - -#define stbiw__sbpush(a, v) (stbiw__sbmaybegrow(a,1), (a)[stbiw__sbn(a)++] = (v)) -#define stbiw__sbcount(a) ((a) ? stbiw__sbn(a) : 0) -#define stbiw__sbfree(a) ((a) ? STBIW_FREE(stbiw__sbraw(a)),0 : 0) - -static void *stbiw__sbgrowf(void **arr, int increment, int itemsize) -{ - int m = *arr ? 2*stbiw__sbm(*arr)+increment : increment+1; - void *p = STBIW_REALLOC_SIZED(*arr ? stbiw__sbraw(*arr) : 0, *arr ? (stbiw__sbm(*arr)*itemsize + sizeof(int)*2) : 0, itemsize * m + sizeof(int)*2); - STBIW_ASSERT(p); - if (p) { - if (!*arr) ((int *) p)[1] = 0; - *arr = (void *) ((int *) p + 2); - stbiw__sbm(*arr) = m; - } - return *arr; -} - -static unsigned char *stbiw__zlib_flushf(unsigned char *data, unsigned int *bitbuffer, int *bitcount) -{ - while (*bitcount >= 8) { - stbiw__sbpush(data, STBIW_UCHAR(*bitbuffer)); - *bitbuffer >>= 8; - *bitcount -= 8; - } - return data; -} - -static int stbiw__zlib_bitrev(int code, int codebits) -{ - int res=0; - while (codebits--) { - res = (res << 1) | (code & 1); - code >>= 1; - } - return res; -} - -static unsigned int stbiw__zlib_countm(unsigned char *a, unsigned char *b, int limit) -{ - int i; - for (i=0; i < limit && i < 258; ++i) - if (a[i] != b[i]) break; - return i; -} - -static unsigned int stbiw__zhash(unsigned char *data) -{ - stbiw_uint32 hash = data[0] + (data[1] << 8) + (data[2] << 16); - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; -} - -#define stbiw__zlib_flush() (out = stbiw__zlib_flushf(out, &bitbuf, &bitcount)) -#define stbiw__zlib_add(code,codebits) \ - (bitbuf |= (code) << bitcount, bitcount += (codebits), stbiw__zlib_flush()) -#define stbiw__zlib_huffa(b,c) stbiw__zlib_add(stbiw__zlib_bitrev(b,c),c) -// default huffman tables -#define stbiw__zlib_huff1(n) stbiw__zlib_huffa(0x30 + (n), 8) -#define stbiw__zlib_huff2(n) stbiw__zlib_huffa(0x190 + (n)-144, 9) -#define stbiw__zlib_huff3(n) stbiw__zlib_huffa(0 + (n)-256,7) -#define stbiw__zlib_huff4(n) stbiw__zlib_huffa(0xc0 + (n)-280,8) -#define stbiw__zlib_huff(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : (n) <= 255 ? stbiw__zlib_huff2(n) : (n) <= 279 ? stbiw__zlib_huff3(n) : stbiw__zlib_huff4(n)) -#define stbiw__zlib_huffb(n) ((n) <= 143 ? stbiw__zlib_huff1(n) : stbiw__zlib_huff2(n)) - -#define stbiw__ZHASH 16384 - -#endif // STBIW_ZLIB_COMPRESS - -STBIWDEF unsigned char * stbi_zlib_compress(unsigned char *data, int data_len, int *out_len, int quality) -{ -#ifdef STBIW_ZLIB_COMPRESS - // user provided a zlib compress implementation, use that - return STBIW_ZLIB_COMPRESS(data, data_len, out_len, quality); -#else // use builtin - static unsigned short lengthc[] = { 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, 259 }; - static unsigned char lengtheb[]= { 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 }; - static unsigned short distc[] = { 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, 32768 }; - static unsigned char disteb[] = { 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 }; - unsigned int bitbuf=0; - int i,j, bitcount=0; - unsigned char *out = NULL; - unsigned char ***hash_table = (unsigned char***) STBIW_MALLOC(stbiw__ZHASH * sizeof(unsigned char**)); - if (hash_table == NULL) - return NULL; - if (quality < 5) quality = 5; - - stbiw__sbpush(out, 0x78); // DEFLATE 32K window - stbiw__sbpush(out, 0x5e); // FLEVEL = 1 - stbiw__zlib_add(1,1); // BFINAL = 1 - stbiw__zlib_add(1,2); // BTYPE = 1 -- fixed huffman - - for (i=0; i < stbiw__ZHASH; ++i) - hash_table[i] = NULL; - - i=0; - while (i < data_len-3) { - // hash next 3 bytes of data to be compressed - int h = stbiw__zhash(data+i)&(stbiw__ZHASH-1), best=3; - unsigned char *bestloc = 0; - unsigned char **hlist = hash_table[h]; - int n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32768) { // if entry lies within window - int d = stbiw__zlib_countm(hlist[j], data+i, data_len-i); - if (d >= best) { best=d; bestloc=hlist[j]; } - } - } - // when hash table entry is too long, delete half the entries - if (hash_table[h] && stbiw__sbn(hash_table[h]) == 2*quality) { - STBIW_MEMMOVE(hash_table[h], hash_table[h]+quality, sizeof(hash_table[h][0])*quality); - stbiw__sbn(hash_table[h]) = quality; - } - stbiw__sbpush(hash_table[h],data+i); - - if (bestloc) { - // "lazy matching" - check match at *next* byte, and if it's better, do cur byte as literal - h = stbiw__zhash(data+i+1)&(stbiw__ZHASH-1); - hlist = hash_table[h]; - n = stbiw__sbcount(hlist); - for (j=0; j < n; ++j) { - if (hlist[j]-data > i-32767) { - int e = stbiw__zlib_countm(hlist[j], data+i+1, data_len-i-1); - if (e > best) { // if next match is better, bail on current match - bestloc = NULL; - break; - } - } - } - } - - if (bestloc) { - int d = (int) (data+i - bestloc); // distance back - STBIW_ASSERT(d <= 32767 && best <= 258); - for (j=0; best > lengthc[j+1]-1; ++j); - stbiw__zlib_huff(j+257); - if (lengtheb[j]) stbiw__zlib_add(best - lengthc[j], lengtheb[j]); - for (j=0; d > distc[j+1]-1; ++j); - stbiw__zlib_add(stbiw__zlib_bitrev(j,5),5); - if (disteb[j]) stbiw__zlib_add(d - distc[j], disteb[j]); - i += best; - } else { - stbiw__zlib_huffb(data[i]); - ++i; - } - } - // write out final bytes - for (;i < data_len; ++i) - stbiw__zlib_huffb(data[i]); - stbiw__zlib_huff(256); // end of block - // pad with 0 bits to byte boundary - while (bitcount) - stbiw__zlib_add(0,1); - - for (i=0; i < stbiw__ZHASH; ++i) - (void) stbiw__sbfree(hash_table[i]); - STBIW_FREE(hash_table); - - // store uncompressed instead if compression was worse - if (stbiw__sbn(out) > data_len + 2 + ((data_len+32766)/32767)*5) { - stbiw__sbn(out) = 2; // truncate to DEFLATE 32K window and FLEVEL = 1 - for (j = 0; j < data_len;) { - int blocklen = data_len - j; - if (blocklen > 32767) blocklen = 32767; - stbiw__sbpush(out, data_len - j == blocklen); // BFINAL = ?, BTYPE = 0 -- no compression - stbiw__sbpush(out, STBIW_UCHAR(blocklen)); // LEN - stbiw__sbpush(out, STBIW_UCHAR(blocklen >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(~blocklen)); // NLEN - stbiw__sbpush(out, STBIW_UCHAR(~blocklen >> 8)); - memcpy(out+stbiw__sbn(out), data+j, blocklen); - stbiw__sbn(out) += blocklen; - j += blocklen; - } - } - - { - // compute adler32 on input - unsigned int s1=1, s2=0; - int blocklen = (int) (data_len % 5552); - j=0; - while (j < data_len) { - for (i=0; i < blocklen; ++i) { s1 += data[j+i]; s2 += s1; } - s1 %= 65521; s2 %= 65521; - j += blocklen; - blocklen = 5552; - } - stbiw__sbpush(out, STBIW_UCHAR(s2 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s2)); - stbiw__sbpush(out, STBIW_UCHAR(s1 >> 8)); - stbiw__sbpush(out, STBIW_UCHAR(s1)); - } - *out_len = stbiw__sbn(out); - // make returned pointer freeable - STBIW_MEMMOVE(stbiw__sbraw(out), out, *out_len); - return (unsigned char *) stbiw__sbraw(out); -#endif // STBIW_ZLIB_COMPRESS -} - -static unsigned int stbiw__crc32(unsigned char *buffer, int len) -{ -#ifdef STBIW_CRC32 - return STBIW_CRC32(buffer, len); -#else - static unsigned int crc_table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0eDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - - unsigned int crc = ~0u; - int i; - for (i=0; i < len; ++i) - crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; - return ~crc; -#endif -} - -#define stbiw__wpng4(o,a,b,c,d) ((o)[0]=STBIW_UCHAR(a),(o)[1]=STBIW_UCHAR(b),(o)[2]=STBIW_UCHAR(c),(o)[3]=STBIW_UCHAR(d),(o)+=4) -#define stbiw__wp32(data,v) stbiw__wpng4(data, (v)>>24,(v)>>16,(v)>>8,(v)); -#define stbiw__wptag(data,s) stbiw__wpng4(data, s[0],s[1],s[2],s[3]) - -static void stbiw__wpcrc(unsigned char **data, int len) -{ - unsigned int crc = stbiw__crc32(*data - len - 4, len+4); - stbiw__wp32(*data, crc); -} - -static unsigned char stbiw__paeth(int a, int b, int c) -{ - int p = a + b - c, pa = abs(p-a), pb = abs(p-b), pc = abs(p-c); - if (pa <= pb && pa <= pc) return STBIW_UCHAR(a); - if (pb <= pc) return STBIW_UCHAR(b); - return STBIW_UCHAR(c); -} - -// @OPTIMIZE: provide an option that always forces left-predict or paeth predict -static void stbiw__encode_png_line(unsigned char *pixels, int stride_bytes, int width, int height, int y, int n, int filter_type, signed char *line_buffer) -{ - static int mapping[] = { 0,1,2,3,4 }; - static int firstmap[] = { 0,1,0,5,6 }; - int *mymap = (y != 0) ? mapping : firstmap; - int i; - int type = mymap[filter_type]; - unsigned char *z = pixels + stride_bytes * (stbi__flip_vertically_on_write ? height-1-y : y); - int signed_stride = stbi__flip_vertically_on_write ? -stride_bytes : stride_bytes; - - if (type==0) { - memcpy(line_buffer, z, width*n); - return; - } - - // first loop isn't optimized since it's just one pixel - for (i = 0; i < n; ++i) { - switch (type) { - case 1: line_buffer[i] = z[i]; break; - case 2: line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: line_buffer[i] = z[i] - (z[i-signed_stride]>>1); break; - case 4: line_buffer[i] = (signed char) (z[i] - stbiw__paeth(0,z[i-signed_stride],0)); break; - case 5: line_buffer[i] = z[i]; break; - case 6: line_buffer[i] = z[i]; break; - } - } - switch (type) { - case 1: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-n]; break; - case 2: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - z[i-signed_stride]; break; - case 3: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - ((z[i-n] + z[i-signed_stride])>>1); break; - case 4: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], z[i-signed_stride], z[i-signed_stride-n]); break; - case 5: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - (z[i-n]>>1); break; - case 6: for (i=n; i < width*n; ++i) line_buffer[i] = z[i] - stbiw__paeth(z[i-n], 0,0); break; - } -} - -STBIWDEF unsigned char *stbi_write_png_to_mem(const unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len) -{ - int force_filter = stbi_write_force_png_filter; - int ctype[5] = { -1, 0, 4, 2, 6 }; - unsigned char sig[8] = { 137,80,78,71,13,10,26,10 }; - unsigned char *out,*o, *filt, *zlib; - signed char *line_buffer; - int j,zlen; - - if (stride_bytes == 0) - stride_bytes = x * n; - - if (force_filter >= 5) { - force_filter = -1; - } - - filt = (unsigned char *) STBIW_MALLOC((x*n+1) * y); if (!filt) return 0; - line_buffer = (signed char *) STBIW_MALLOC(x * n); if (!line_buffer) { STBIW_FREE(filt); return 0; } - for (j=0; j < y; ++j) { - int filter_type; - if (force_filter > -1) { - filter_type = force_filter; - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, force_filter, line_buffer); - } else { // Estimate the best filter by running through all of them: - int best_filter = 0, best_filter_val = 0x7fffffff, est, i; - for (filter_type = 0; filter_type < 5; filter_type++) { - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, filter_type, line_buffer); - - // Estimate the entropy of the line using this filter; the less, the better. - est = 0; - for (i = 0; i < x*n; ++i) { - est += abs((signed char) line_buffer[i]); - } - if (est < best_filter_val) { - best_filter_val = est; - best_filter = filter_type; - } - } - if (filter_type != best_filter) { // If the last iteration already got us the best filter, don't redo it - stbiw__encode_png_line((unsigned char*)(pixels), stride_bytes, x, y, j, n, best_filter, line_buffer); - filter_type = best_filter; - } - } - // when we get here, filter_type contains the filter type, and line_buffer contains the data - filt[j*(x*n+1)] = (unsigned char) filter_type; - STBIW_MEMMOVE(filt+j*(x*n+1)+1, line_buffer, x*n); - } - STBIW_FREE(line_buffer); - zlib = stbi_zlib_compress(filt, y*( x*n+1), &zlen, stbi_write_png_compression_level); - STBIW_FREE(filt); - if (!zlib) return 0; - - // each tag requires 12 bytes of overhead - out = (unsigned char *) STBIW_MALLOC(8 + 12+13 + 12+zlen + 12); - if (!out) return 0; - *out_len = 8 + 12+13 + 12+zlen + 12; - - o=out; - STBIW_MEMMOVE(o,sig,8); o+= 8; - stbiw__wp32(o, 13); // header length - stbiw__wptag(o, "IHDR"); - stbiw__wp32(o, x); - stbiw__wp32(o, y); - *o++ = 8; - *o++ = STBIW_UCHAR(ctype[n]); - *o++ = 0; - *o++ = 0; - *o++ = 0; - stbiw__wpcrc(&o,13); - - stbiw__wp32(o, zlen); - stbiw__wptag(o, "IDAT"); - STBIW_MEMMOVE(o, zlib, zlen); - o += zlen; - STBIW_FREE(zlib); - stbiw__wpcrc(&o, zlen); - - stbiw__wp32(o,0); - stbiw__wptag(o, "IEND"); - stbiw__wpcrc(&o,0); - - STBIW_ASSERT(o == out + *out_len); - - return out; -} - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_png(char const *filename, int x, int y, int comp, const void *data, int stride_bytes) -{ - FILE *f; - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - - f = stbiw__fopen(filename, "wb"); - if (!f) { STBIW_FREE(png); return 0; } - fwrite(png, 1, len, f); - fclose(f); - STBIW_FREE(png); - return 1; -} -#endif - -STBIWDEF int stbi_write_png_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int stride_bytes) -{ - int len; - unsigned char *png = stbi_write_png_to_mem((const unsigned char *) data, stride_bytes, x, y, comp, &len); - if (png == NULL) return 0; - func(context, png, len); - STBIW_FREE(png); - return 1; -} - - -/* *************************************************************************** - * - * JPEG writer - * - * This is based on Jon Olick's jo_jpeg.cpp: - * public domain Simple, Minimalistic JPEG writer - http://www.jonolick.com/code.html - */ - -static const unsigned char stbiw__jpg_ZigZag[] = { 0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18, - 24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63 }; - -static void stbiw__jpg_writeBits(stbi__write_context *s, int *bitBufP, int *bitCntP, const unsigned short *bs) { - int bitBuf = *bitBufP, bitCnt = *bitCntP; - bitCnt += bs[1]; - bitBuf |= bs[0] << (24 - bitCnt); - while(bitCnt >= 8) { - unsigned char c = (bitBuf >> 16) & 255; - stbiw__putc(s, c); - if(c == 255) { - stbiw__putc(s, 0); - } - bitBuf <<= 8; - bitCnt -= 8; - } - *bitBufP = bitBuf; - *bitCntP = bitCnt; -} - -static void stbiw__jpg_DCT(float *d0p, float *d1p, float *d2p, float *d3p, float *d4p, float *d5p, float *d6p, float *d7p) { - float d0 = *d0p, d1 = *d1p, d2 = *d2p, d3 = *d3p, d4 = *d4p, d5 = *d5p, d6 = *d6p, d7 = *d7p; - float z1, z2, z3, z4, z5, z11, z13; - - float tmp0 = d0 + d7; - float tmp7 = d0 - d7; - float tmp1 = d1 + d6; - float tmp6 = d1 - d6; - float tmp2 = d2 + d5; - float tmp5 = d2 - d5; - float tmp3 = d3 + d4; - float tmp4 = d3 - d4; - - // Even part - float tmp10 = tmp0 + tmp3; // phase 2 - float tmp13 = tmp0 - tmp3; - float tmp11 = tmp1 + tmp2; - float tmp12 = tmp1 - tmp2; - - d0 = tmp10 + tmp11; // phase 3 - d4 = tmp10 - tmp11; - - z1 = (tmp12 + tmp13) * 0.707106781f; // c4 - d2 = tmp13 + z1; // phase 5 - d6 = tmp13 - z1; - - // Odd part - tmp10 = tmp4 + tmp5; // phase 2 - tmp11 = tmp5 + tmp6; - tmp12 = tmp6 + tmp7; - - // The rotator is modified from fig 4-8 to avoid extra negations. - z5 = (tmp10 - tmp12) * 0.382683433f; // c6 - z2 = tmp10 * 0.541196100f + z5; // c2-c6 - z4 = tmp12 * 1.306562965f + z5; // c2+c6 - z3 = tmp11 * 0.707106781f; // c4 - - z11 = tmp7 + z3; // phase 5 - z13 = tmp7 - z3; - - *d5p = z13 + z2; // phase 6 - *d3p = z13 - z2; - *d1p = z11 + z4; - *d7p = z11 - z4; - - *d0p = d0; *d2p = d2; *d4p = d4; *d6p = d6; -} - -static void stbiw__jpg_calcBits(int val, unsigned short bits[2]) { - int tmp1 = val < 0 ? -val : val; - val = val < 0 ? val-1 : val; - bits[1] = 1; - while(tmp1 >>= 1) { - ++bits[1]; - } - bits[0] = val & ((1<0)&&(DU[end0pos]==0); --end0pos) { - } - // end0pos = first element in reverse order !=0 - if(end0pos == 0) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - return DU[0]; - } - for(i = 1; i <= end0pos; ++i) { - int startpos = i; - int nrzeroes; - unsigned short bits[2]; - for (; DU[i]==0 && i<=end0pos; ++i) { - } - nrzeroes = i-startpos; - if ( nrzeroes >= 16 ) { - int lng = nrzeroes>>4; - int nrmarker; - for (nrmarker=1; nrmarker <= lng; ++nrmarker) - stbiw__jpg_writeBits(s, bitBuf, bitCnt, M16zeroes); - nrzeroes &= 15; - } - stbiw__jpg_calcBits(DU[i], bits); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, HTAC[(nrzeroes<<4)+bits[1]]); - stbiw__jpg_writeBits(s, bitBuf, bitCnt, bits); - } - if(end0pos != 63) { - stbiw__jpg_writeBits(s, bitBuf, bitCnt, EOB); - } - return DU[0]; -} - -static int stbi_write_jpg_core(stbi__write_context *s, int width, int height, int comp, const void* data, int quality) { - // Constants that don't pollute global namespace - static const unsigned char std_dc_luminance_nrcodes[] = {0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0}; - static const unsigned char std_dc_luminance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_luminance_nrcodes[] = {0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d}; - static const unsigned char std_ac_luminance_values[] = { - 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08, - 0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28, - 0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59, - 0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89, - 0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6, - 0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2, - 0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - static const unsigned char std_dc_chrominance_nrcodes[] = {0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0}; - static const unsigned char std_dc_chrominance_values[] = {0,1,2,3,4,5,6,7,8,9,10,11}; - static const unsigned char std_ac_chrominance_nrcodes[] = {0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77}; - static const unsigned char std_ac_chrominance_values[] = { - 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91, - 0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26, - 0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58, - 0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87, - 0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4, - 0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda, - 0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa - }; - // Huffman tables - static const unsigned short YDC_HT[256][2] = { {0,2},{2,3},{3,3},{4,3},{5,3},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9}}; - static const unsigned short UVDC_HT[256][2] = { {0,2},{1,2},{2,2},{6,3},{14,4},{30,5},{62,6},{126,7},{254,8},{510,9},{1022,10},{2046,11}}; - static const unsigned short YAC_HT[256][2] = { - {10,4},{0,2},{1,2},{4,3},{11,4},{26,5},{120,7},{248,8},{1014,10},{65410,16},{65411,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {12,4},{27,5},{121,7},{502,9},{2038,11},{65412,16},{65413,16},{65414,16},{65415,16},{65416,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {28,5},{249,8},{1015,10},{4084,12},{65417,16},{65418,16},{65419,16},{65420,16},{65421,16},{65422,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{503,9},{4085,12},{65423,16},{65424,16},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1016,10},{65430,16},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2039,11},{65438,16},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {123,7},{4086,12},{65446,16},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {250,8},{4087,12},{65454,16},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{32704,15},{65462,16},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65470,16},{65471,16},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65479,16},{65480,16},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1017,10},{65488,16},{65489,16},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{65497,16},{65498,16},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2040,11},{65506,16},{65507,16},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {65515,16},{65516,16},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65525,16},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const unsigned short UVAC_HT[256][2] = { - {0,2},{1,2},{4,3},{10,4},{24,5},{25,5},{56,6},{120,7},{500,9},{1014,10},{4084,12},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {11,4},{57,6},{246,8},{501,9},{2038,11},{4085,12},{65416,16},{65417,16},{65418,16},{65419,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {26,5},{247,8},{1015,10},{4086,12},{32706,15},{65420,16},{65421,16},{65422,16},{65423,16},{65424,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {27,5},{248,8},{1016,10},{4087,12},{65425,16},{65426,16},{65427,16},{65428,16},{65429,16},{65430,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {58,6},{502,9},{65431,16},{65432,16},{65433,16},{65434,16},{65435,16},{65436,16},{65437,16},{65438,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {59,6},{1017,10},{65439,16},{65440,16},{65441,16},{65442,16},{65443,16},{65444,16},{65445,16},{65446,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {121,7},{2039,11},{65447,16},{65448,16},{65449,16},{65450,16},{65451,16},{65452,16},{65453,16},{65454,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {122,7},{2040,11},{65455,16},{65456,16},{65457,16},{65458,16},{65459,16},{65460,16},{65461,16},{65462,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {249,8},{65463,16},{65464,16},{65465,16},{65466,16},{65467,16},{65468,16},{65469,16},{65470,16},{65471,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {503,9},{65472,16},{65473,16},{65474,16},{65475,16},{65476,16},{65477,16},{65478,16},{65479,16},{65480,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {504,9},{65481,16},{65482,16},{65483,16},{65484,16},{65485,16},{65486,16},{65487,16},{65488,16},{65489,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {505,9},{65490,16},{65491,16},{65492,16},{65493,16},{65494,16},{65495,16},{65496,16},{65497,16},{65498,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {506,9},{65499,16},{65500,16},{65501,16},{65502,16},{65503,16},{65504,16},{65505,16},{65506,16},{65507,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {2041,11},{65508,16},{65509,16},{65510,16},{65511,16},{65512,16},{65513,16},{65514,16},{65515,16},{65516,16},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, - {16352,14},{65517,16},{65518,16},{65519,16},{65520,16},{65521,16},{65522,16},{65523,16},{65524,16},{65525,16},{0,0},{0,0},{0,0},{0,0},{0,0}, - {1018,10},{32707,15},{65526,16},{65527,16},{65528,16},{65529,16},{65530,16},{65531,16},{65532,16},{65533,16},{65534,16},{0,0},{0,0},{0,0},{0,0},{0,0} - }; - static const int YQT[] = {16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22, - 37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99}; - static const int UVQT[] = {17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99, - 99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99}; - static const float aasf[] = { 1.0f * 2.828427125f, 1.387039845f * 2.828427125f, 1.306562965f * 2.828427125f, 1.175875602f * 2.828427125f, - 1.0f * 2.828427125f, 0.785694958f * 2.828427125f, 0.541196100f * 2.828427125f, 0.275899379f * 2.828427125f }; - - int row, col, i, k, subsample; - float fdtbl_Y[64], fdtbl_UV[64]; - unsigned char YTable[64], UVTable[64]; - - if(!data || !width || !height || comp > 4 || comp < 1) { - return 0; - } - - quality = quality ? quality : 90; - subsample = quality <= 90 ? 1 : 0; - quality = quality < 1 ? 1 : quality > 100 ? 100 : quality; - quality = quality < 50 ? 5000 / quality : 200 - quality * 2; - - for(i = 0; i < 64; ++i) { - int uvti, yti = (YQT[i]*quality+50)/100; - YTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (yti < 1 ? 1 : yti > 255 ? 255 : yti); - uvti = (UVQT[i]*quality+50)/100; - UVTable[stbiw__jpg_ZigZag[i]] = (unsigned char) (uvti < 1 ? 1 : uvti > 255 ? 255 : uvti); - } - - for(row = 0, k = 0; row < 8; ++row) { - for(col = 0; col < 8; ++col, ++k) { - fdtbl_Y[k] = 1 / (YTable [stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - fdtbl_UV[k] = 1 / (UVTable[stbiw__jpg_ZigZag[k]] * aasf[row] * aasf[col]); - } - } - - // Write Headers - { - static const unsigned char head0[] = { 0xFF,0xD8,0xFF,0xE0,0,0x10,'J','F','I','F',0,1,1,0,0,1,0,1,0,0,0xFF,0xDB,0,0x84,0 }; - static const unsigned char head2[] = { 0xFF,0xDA,0,0xC,3,1,0,2,0x11,3,0x11,0,0x3F,0 }; - const unsigned char head1[] = { 0xFF,0xC0,0,0x11,8,(unsigned char)(height>>8),STBIW_UCHAR(height),(unsigned char)(width>>8),STBIW_UCHAR(width), - 3,1,(unsigned char)(subsample?0x22:0x11),0,2,0x11,1,3,0x11,1,0xFF,0xC4,0x01,0xA2,0 }; - s->func(s->context, (void*)head0, sizeof(head0)); - s->func(s->context, (void*)YTable, sizeof(YTable)); - stbiw__putc(s, 1); - s->func(s->context, UVTable, sizeof(UVTable)); - s->func(s->context, (void*)head1, sizeof(head1)); - s->func(s->context, (void*)(std_dc_luminance_nrcodes+1), sizeof(std_dc_luminance_nrcodes)-1); - s->func(s->context, (void*)std_dc_luminance_values, sizeof(std_dc_luminance_values)); - stbiw__putc(s, 0x10); // HTYACinfo - s->func(s->context, (void*)(std_ac_luminance_nrcodes+1), sizeof(std_ac_luminance_nrcodes)-1); - s->func(s->context, (void*)std_ac_luminance_values, sizeof(std_ac_luminance_values)); - stbiw__putc(s, 1); // HTUDCinfo - s->func(s->context, (void*)(std_dc_chrominance_nrcodes+1), sizeof(std_dc_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_dc_chrominance_values, sizeof(std_dc_chrominance_values)); - stbiw__putc(s, 0x11); // HTUACinfo - s->func(s->context, (void*)(std_ac_chrominance_nrcodes+1), sizeof(std_ac_chrominance_nrcodes)-1); - s->func(s->context, (void*)std_ac_chrominance_values, sizeof(std_ac_chrominance_values)); - s->func(s->context, (void*)head2, sizeof(head2)); - } - - // Encode 8x8 macroblocks - { - static const unsigned short fillBits[] = {0x7F, 7}; - int DCY=0, DCU=0, DCV=0; - int bitBuf=0, bitCnt=0; - // comp == 2 is grey+alpha (alpha is ignored) - int ofsG = comp > 2 ? 1 : 0, ofsB = comp > 2 ? 2 : 0; - const unsigned char *dataR = (const unsigned char *)data; - const unsigned char *dataG = dataR + ofsG; - const unsigned char *dataB = dataR + ofsB; - int x, y, pos; - if(subsample) { - for(y = 0; y < height; y += 16) { - for(x = 0; x < width; x += 16) { - float Y[256], U[256], V[256]; - for(row = y, pos = 0; row < y+16; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+16; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+0, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+8, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+128, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y+136, 16, fdtbl_Y, DCY, YDC_HT, YAC_HT); - - // subsample U,V - { - float subU[64], subV[64]; - int yy, xx; - for(yy = 0, pos = 0; yy < 8; ++yy) { - for(xx = 0; xx < 8; ++xx, ++pos) { - int j = yy*32+xx*2; - subU[pos] = (U[j+0] + U[j+1] + U[j+16] + U[j+17]) * 0.25f; - subV[pos] = (V[j+0] + V[j+1] + V[j+16] + V[j+17]) * 0.25f; - } - } - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subU, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, subV, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - } else { - for(y = 0; y < height; y += 8) { - for(x = 0; x < width; x += 8) { - float Y[64], U[64], V[64]; - for(row = y, pos = 0; row < y+8; ++row) { - // row >= height => use last input row - int clamped_row = (row < height) ? row : height - 1; - int base_p = (stbi__flip_vertically_on_write ? (height-1-clamped_row) : clamped_row)*width*comp; - for(col = x; col < x+8; ++col, ++pos) { - // if col >= width => use pixel from last input column - int p = base_p + ((col < width) ? col : (width-1))*comp; - float r = dataR[p], g = dataG[p], b = dataB[p]; - Y[pos]= +0.29900f*r + 0.58700f*g + 0.11400f*b - 128; - U[pos]= -0.16874f*r - 0.33126f*g + 0.50000f*b; - V[pos]= +0.50000f*r - 0.41869f*g - 0.08131f*b; - } - } - - DCY = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, Y, 8, fdtbl_Y, DCY, YDC_HT, YAC_HT); - DCU = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, U, 8, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); - DCV = stbiw__jpg_processDU(s, &bitBuf, &bitCnt, V, 8, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); - } - } - } - - // Do the bit alignment of the EOI marker - stbiw__jpg_writeBits(s, &bitBuf, &bitCnt, fillBits); - } - - // EOI - stbiw__putc(s, 0xFF); - stbiw__putc(s, 0xD9); - - return 1; -} - -STBIWDEF int stbi_write_jpg_to_func(stbi_write_func *func, void *context, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - stbi__start_write_callbacks(&s, func, context); - return stbi_write_jpg_core(&s, x, y, comp, (void *) data, quality); -} - - -#ifndef STBI_WRITE_NO_STDIO -STBIWDEF int stbi_write_jpg(char const *filename, int x, int y, int comp, const void *data, int quality) -{ - stbi__write_context s = { 0 }; - if (stbi__start_write_file(&s,filename)) { - int r = stbi_write_jpg_core(&s, x, y, comp, data, quality); - stbi__end_write_file(&s); - return r; - } else - return 0; -} -#endif - -#endif // STB_IMAGE_WRITE_IMPLEMENTATION - -/* Revision history - 1.16 (2021-07-11) - make Deflate code emit uncompressed blocks when it would otherwise expand - support writing BMPs with alpha channel - 1.15 (2020-07-13) unknown - 1.14 (2020-02-02) updated JPEG writer to downsample chroma channels - 1.13 - 1.12 - 1.11 (2019-08-11) - - 1.10 (2019-02-07) - support utf8 filenames in Windows; fix warnings and platform ifdefs - 1.09 (2018-02-11) - fix typo in zlib quality API, improve STB_I_W_STATIC in C++ - 1.08 (2018-01-29) - add stbi__flip_vertically_on_write, external zlib, zlib quality, choose PNG filter - 1.07 (2017-07-24) - doc fix - 1.06 (2017-07-23) - writing JPEG (using Jon Olick's code) - 1.05 ??? - 1.04 (2017-03-03) - monochrome BMP expansion - 1.03 ??? - 1.02 (2016-04-02) - avoid allocating large structures on the stack - 1.01 (2016-01-16) - STBIW_REALLOC_SIZED: support allocators with no realloc support - avoid race-condition in crc initialization - minor compile issues - 1.00 (2015-09-14) - installable file IO function - 0.99 (2015-09-13) - warning fixes; TGA rle support - 0.98 (2015-04-08) - added STBIW_MALLOC, STBIW_ASSERT etc - 0.97 (2015-01-18) - fixed HDR asserts, rewrote HDR rle logic - 0.96 (2015-01-17) - add HDR output - fix monochrome BMP - 0.95 (2014-08-17) - add monochrome TGA output - 0.94 (2014-05-31) - rename private functions to avoid conflicts with stb_image.h - 0.93 (2014-05-27) - warning fixes - 0.92 (2010-08-01) - casts to unsigned char to fix warnings - 0.91 (2010-07-17) - first public release - 0.90 first internal release -*/ - -/* ------------------------------------------------------------------------------- -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. ------------------------------------------------------------------------------- -*/ diff --git a/text_rendering/msdf_c/sample/svpng.h b/text_rendering/msdf_c/sample/svpng.h deleted file mode 100644 index aa23324..0000000 --- a/text_rendering/msdf_c/sample/svpng.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright (C) 2017 Milo Yip. All rights reserved. - -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. - -* Neither the name of pngout nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR CONTRIBUTORS 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. -*/ - -/*! \file - \brief svpng() is a minimalistic C function for saving RGB/RGBA image into uncompressed PNG. - \author Milo Yip - \version 0.1.1 - \copyright MIT license - \sa http://github.com/miloyip/svpng -*/ - -#ifndef SVPNG_INC_ -#define SVPNG_INC_ - -/*! \def SVPNG_LINKAGE - \brief User customizable linkage for svpng() function. - By default this macro is empty. - User may define this macro as static for static linkage, - and/or inline in C99/C++, etc. -*/ -#ifndef SVPNG_LINKAGE -#define SVPNG_LINKAGE -#endif - -/*! \def SVPNG_OUTPUT - \brief User customizable output stream. - By default, it uses C file descriptor and fputc() to output bytes. - In C++, for example, user may use std::ostream or std::vector instead. -*/ -#ifndef SVPNG_OUTPUT -#include -#define SVPNG_OUTPUT FILE* fp -#endif - -/*! \def SVPNG_PUT - \brief Write a byte -*/ -#ifndef SVPNG_PUT -#define SVPNG_PUT(u) fputc(u, fp) -#endif - - -/*! - \brief Save a RGB/RGBA image in PNG format. - \param SVPNG_OUTPUT Output stream (by default using file descriptor). - \param w Width of the image. (<16383) - \param h Height of the image. - \param img Image pixel data in 24-bit RGB or 32-bit RGBA format. - \param alpha Whether the image contains alpha channel. -*/ -SVPNG_LINKAGE void svpng(SVPNG_OUTPUT, unsigned w, unsigned h, const unsigned char* img, int alpha) { - static const unsigned t[] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, - /* CRC32 Table */ 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; - unsigned a = 1, b = 0, c, p = w * (alpha ? 4 : 3) + 1, x, y, i; /* ADLER-a, ADLER-b, CRC, pitch */ -#define SVPNG_U8A(ua, l) for (i = 0; i < l; i++) SVPNG_PUT((ua)[i]); -#define SVPNG_U32(u) do { SVPNG_PUT((u) >> 24); SVPNG_PUT(((u) >> 16) & 255); SVPNG_PUT(((u) >> 8) & 255); SVPNG_PUT((u) & 255); } while(0) -#define SVPNG_U8C(u) do { SVPNG_PUT(u); c ^= (u); c = (c >> 4) ^ t[c & 15]; c = (c >> 4) ^ t[c & 15]; } while(0) -#define SVPNG_U8AC(ua, l) for (i = 0; i < l; i++) SVPNG_U8C((ua)[i]) -#define SVPNG_U16LC(u) do { SVPNG_U8C((u) & 255); SVPNG_U8C(((u) >> 8) & 255); } while(0) -#define SVPNG_U32C(u) do { SVPNG_U8C((u) >> 24); SVPNG_U8C(((u) >> 16) & 255); SVPNG_U8C(((u) >> 8) & 255); SVPNG_U8C((u) & 255); } while(0) -#define SVPNG_U8ADLER(u) do { SVPNG_U8C(u); a = (a + (u)) % 65521; b = (b + a) % 65521; } while(0) -#define SVPNG_BEGIN(s, l) do { SVPNG_U32(l); c = ~0U; SVPNG_U8AC(s, 4); } while(0) -#define SVPNG_END() SVPNG_U32(~c) - SVPNG_U8A("\x89PNG\r\n\32\n", 8); /* Magic */ - SVPNG_BEGIN("IHDR", 13); /* IHDR chunk { */ - SVPNG_U32C(w); SVPNG_U32C(h); /* Width & Height (8 bytes) */ - SVPNG_U8C(8); SVPNG_U8C(alpha ? 6 : 2); /* Depth=8, Color=True color with/without alpha (2 bytes) */ - SVPNG_U8AC("\0\0\0", 3); /* Compression=Deflate, Filter=No, Interlace=No (3 bytes) */ - SVPNG_END(); /* } */ - SVPNG_BEGIN("IDAT", 2 + h * (5 + p) + 4); /* IDAT chunk { */ - SVPNG_U8AC("\x78\1", 2); /* Deflate block begin (2 bytes) */ - for (y = 0; y < h; y++) { /* Each horizontal line makes a block for simplicity */ - SVPNG_U8C(y == h - 1); /* 1 for the last block, 0 for others (1 byte) */ - SVPNG_U16LC(p); SVPNG_U16LC(~p); /* Size of block in little endian and its 1's complement (4 bytes) */ - SVPNG_U8ADLER(0); /* No filter prefix (1 byte) */ - for (x = 0; x < p - 1; x++, img++) - SVPNG_U8ADLER(*img); /* Image pixel data */ - } - SVPNG_U32C((b << 16) | a); /* Deflate block end with adler (4 bytes) */ - SVPNG_END(); /* } */ - SVPNG_BEGIN("IEND", 0); SVPNG_END(); /* IEND chunk {} */ -} - -#endif /* SVPNG_INC_ */ \ No newline at end of file diff --git a/text_rendering/ren.c b/text_rendering/ren.c index 36d0847..f6cc19c 100644 --- a/text_rendering/ren.c +++ b/text_rendering/ren.c @@ -24,6 +24,7 @@ enum REN_ERR { REN_GLEW, REN_FONT, REN_BUFFER, + REN_UNIFORM, }; @@ -42,6 +43,7 @@ const char * ren_err_msg[] = { [REN_GLEW] = "GLEW Error", [REN_FONT] = "Font Error", [REN_BUFFER] = "Failed to create opengl buffer", + [REN_UNIFORM] = "Failed to get uniform location", }; // different stacks @@ -57,6 +59,7 @@ struct { GLuint font_prog; GLuint box_prog; GLuint font_buffer; + GLint viewsize_loc; struct vtstack font_stack; struct vcstack box_stack; } ren = {0}; @@ -227,6 +230,29 @@ static GLuint ren_texturergba_2d(const char *buf, int w, int h, int upscale, int } +static GLuint ren_texturer_2d(const char *buf, int w, int h, int upscale, int downscale) +{ + GLuint t; + + if (!buf || w <= 0 || h <= 0) + REN_RET(0, REN_INVAL) + + glGenTextures(1, &t); + if (!t) REN_RET(0, REN_TEXTURE) + + glBindTexture(GL_TEXTURE_2D, t); + glTexImage2D(GL_TEXTURE_2D, 0, GL_R, w, h, 0, GL_R, GL_UNSIGNED_BYTE, buf); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, downscale); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, upscale); + + return t; +} + + + // FIXME: update only the newly generated character instead of the whole texture static int update_font_texture(void) { @@ -235,7 +261,7 @@ static int update_font_texture(void) 0, 0, 0, ren.font->width, ren.font->height, - GL_RGB, + GL_R, GL_UNSIGNED_BYTE, ren.font->atlas); font_dump(ren.font, "./atlas.png"); @@ -266,9 +292,10 @@ int ren_init(SDL_Window *w) ren.font = font_init(); if (!ren.font) REN_RET(-1, REN_FONT) - if (font_load(ren.font, FONT_PATH)) REN_RET(-1, REN_FONT) + if (font_load(ren.font, FONT_PATH, 12)) REN_RET(-1, REN_FONT) + font_dump(ren.font, "./atlas.png"); - ren.font_texture = ren_texturergb_2d( + ren.font_texture = ren_texturer_2d( (const char *)ren.font->atlas, ren.font->width, ren.font->height, @@ -281,6 +308,7 @@ int ren_init(SDL_Window *w) ren.font_stack = vtstack_init(); ren.box_stack = vcstack_init(); + // generate the font buffer object glGenBuffers(1, &ren.font_buffer); if (!ren.font_buffer) REN_RET(-1, REN_BUFFER) glBindBuffer(GL_ARRAY_BUFFER, ren.font_buffer); @@ -303,6 +331,10 @@ int ren_init(SDL_Window *w) glBindBuffer(GL_ARRAY_BUFFER, 0); + // create the uniforms + ren.viewsize_loc = glGetUniformLocation(ren.font_prog, "viewsize"); + if (ren.viewsize_loc == -1) REN_RET(-1, REN_UNIFORM) + int width, height; SDL_GetWindowSize(w, &width, &height); ren_update_viewport(width, height); @@ -335,7 +367,7 @@ static int ren_draw_font_stack(void) int ren_update_viewport(int w, int h) { glViewport(0, 0, w, h); - glUniform2i(REN_SCREENSIZE_LOC, w, h); + glUniform2i(ren.viewsize_loc, w, h); return 0; } @@ -368,35 +400,38 @@ int ren_render_text(const char *str, int x, int y, int w, int h, int size) REN_RET(-1, REN_TEXTURE); } + printf("g: u=%d v=%d w=%d h=%d a=%d x=%d y=%d\n", g->u, g->v, g->w, g->h, g->a, g->x, g->y); + // x1,y1 v = (struct v_text){ - .pos = { .x = gx, .y = gy+g->h }, - .uv = { .u = g->u, .v = g->v+g->h }, + .pos = { .x = gx+g->x, .y = gy+g->y+g->h }, + .uv = { .u = g->u, .v = g->v+g->h }, }; vtstack_push(&ren.font_stack, &v); // x2,y2 v = (struct v_text){ - .pos = { .x = gx+g->w, .y = gy+g->h }, - .uv = { .u = g->u+g->w, .v = g->v+g->h }, + .pos = { .x = gx+g->x+g->w, .y = gy+g->y+g->h }, + .uv = { .u = g->u+g->w, .v = g->v+g->h }, }; vtstack_push(&ren.font_stack, &v); // x3,y3 v = (struct v_text){ - .pos = { .x = gx+g->w, .y = gy }, - .uv = { .u = g->u+g->w, .v = g->v }, + .pos = { .x = gx+g->x+g->w, .y = gy+g->y }, + .uv = { .u = g->u+g->w, .v = g->v }, }; vtstack_push(&ren.font_stack, &v); // x4,y4 v = (struct v_text){ - .pos = { .x = gx, .y = gy }, - .uv = { .u = g->u, .v = g->v }, + .pos = { .x = gx+g->x, .y = gy+g->y }, + .uv = { .u = g->u, .v = g->v }, }; vtstack_push(&ren.font_stack, &v); // TODO: possible kerning needs to be applied here - gx += g->w; + gx += g->w + g->a; if (cp == '\n') - gy += 20; // FIXME: encode and/or store line height + gy += ren.font->glyph_max_h; + // TODO: encode and/or store line height } // FIXME: here we are doing one draw call for string of text which is diff --git a/text_rendering/ren.h b/text_rendering/ren.h index 98d9e00..62b3aa6 100644 --- a/text_rendering/ren.h +++ b/text_rendering/ren.h @@ -10,7 +10,6 @@ #define REN_VERTEX_IDX 0 #define REN_UV_IDX 1 #define REN_COLOR_IDX 2 -#define REN_SCREENSIZE_LOC 0 typedef struct { diff --git a/text_rendering/msdf_c/stb_truetype.h b/text_rendering/stb_truetype.h similarity index 99% rename from text_rendering/msdf_c/stb_truetype.h rename to text_rendering/stb_truetype.h index 5e2a2e4..bbf2284 100644 --- a/text_rendering/msdf_c/stb_truetype.h +++ b/text_rendering/stb_truetype.h @@ -5074,4 +5074,4 @@ 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. ------------------------------------------------------------------------------ -*/ \ No newline at end of file +*/ diff --git a/text_rendering/test b/text_rendering/test index 5efa58c..484c873 100755 Binary files a/text_rendering/test and b/text_rendering/test differ