### Pack Rectangles with stb_rect_pack.h Source: https://context7.com/nothings/stb/llms.txt Example of using stb_rect_pack.h to pack rectangles into a target area, suitable for texture atlas generation. The heuristic can be optionally set. The output indicates which rectangles were successfully packed and their positions. ```c #define STB_RECT_PACK_IMPLEMENTATION #include "stb_rect_pack.h" #include int main(void) { const int ATLAS_W = 512, ATLAS_H = 512; const int NUM_RECTS = 20; stbrp_context ctx; stbrp_node nodes[ATLAS_W]; /* at least as wide as the atlas */ stbrp_init_target(&ctx, ATLAS_W, ATLAS_H, nodes, ATLAS_W); /* Optionally choose heuristic */ stbrp_setup_heuristic(&ctx, STBRP_HEURISTIC_Skyline_BL_sortHeight); stbrp_rect rects[NUM_RECTS]; for (int i = 0; i < NUM_RECTS; i++) { rects[i].id = i; rects[i].w = 32 + (i % 5) * 16; /* widths: 32, 48, 64, 80, 96 */ rects[i].h = 32 + (i % 3) * 16; /* heights: 32, 48, 64 */ } int all_packed = stbrp_pack_rects(&ctx, rects, NUM_RECTS); printf("All packed: %s\n", all_packed ? "yes" : "no"); for (int i = 0; i < NUM_RECTS; i++) { if (rects[i].was_packed) printf("rect[%d]: %dx%d -> (%d,%d)\n", rects[i].id, rects[i].w, rects[i].h, rects[i].x, rects[i].y); else printf("rect[%d]: DID NOT FIT\n", rects[i].id); } return 0; } ``` -------------------------------- ### Load Image with stb_image.h Source: https://context7.com/nothings/stb/llms.txt Demonstrates loading various image formats from files, memory, or custom I/O callbacks. Use stbi_load for 8-bit images, stbi_load_16 for 16-bit, and stbi_loadf for HDR images. Free loaded pixel data with stbi_image_free. ```c #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include int main(void) { /* --- load from file (8-bit RGBA) --- */ int width, height, channels_in_file; unsigned char *pixels = stbi_load("photo.jpg", &width, &height, &channels_in_file, STBI_rgb_alpha); if (!pixels) { fprintf(stderr, "Load failed: %s\n", stbi_failure_reason()); return 1; } /* pixels[y * width*4 + x*4 + 0..3] = R,G,B,A */ printf("Loaded %dx%d image (%d channels in file)\n", width, height, channels_in_file); stbi_image_free(pixels); /* --- query dimensions without decoding --- */ int w, h, n; if (stbi_info("photo.jpg", &w, &h, &n)) printf("Image is %dx%d with %d channels\n", w, h, n); /* --- load 16-bit PNG --- */ unsigned short *data16 = stbi_load_16("depth.png", &w, &h, &n, 1); if (data16) stbi_image_free(data16); /* --- load HDR as float --- */ float *hdr = stbi_loadf("environment.hdr", &w, &h, &n, 0); if (hdr) stbi_image_free(hdr); /* --- load from memory buffer --- */ extern unsigned char png_bytes[]; extern int png_len; unsigned char *mem_pixels = stbi_load_from_memory( png_bytes, png_len, &w, &h, &n, STBI_rgb); if (mem_pixels) stbi_image_free(mem_pixels); /* --- custom I/O callbacks --- */ stbi_io_callbacks cb; cb.read = my_read_func; /* int read(void *user, char *data, int size) */ cb.skip = my_skip_func; /* void skip(void *user, int n) */ cb.eof = my_eof_func; /* int eof(void *user) */ unsigned char *cb_pixels = stbi_load_from_callbacks(&cb, my_user_data, &w, &h, &n, STBI_default); if (cb_pixels) stbi_image_free(cb_pixels); return 0; } ``` -------------------------------- ### Generate 3D Perlin Noise with stb_perlin.h Source: https://context7.com/nothings/stb/llms.txt Demonstrates basic 3D Perlin noise generation. The wrapping parameters (last three arguments) should be powers of two for tileable textures. A seed can be provided for reproducible noise. ```c #define STB_PERLIN_IMPLEMENTATION #include "stb_perlin.h" #include int main(void) { /* Basic 3-D noise — value in approximately [-1, 1] */ float v = stb_perlin_noise3(1.5f, 2.3f, 0.7f, 0, 0, 0); /* 0 = no wrapping */ printf("noise = %f\n", v); /* Seeded noise — different "universe" per seed */ float vs = stb_perlin_noise3_seed(1.5f, 2.3f, 0.7f, 0, 0, 0, 42); /* Tileable noise wrapping at 8×8 (must be powers of 2) */ float tile = stb_perlin_noise3(3.1f, 0.0f, 0.0f, 8, 8, 0); /* Fractal Brownian Motion — cloudy / terrain-like */ float fbm = stb_perlin_fbm_noise3(1.5f, 2.3f, 0.0f, 2.0f, /* lacunarity */ 0.5f, /* gain */ 6); /* octaves */ /* Ridge noise — sharp mountain ridges */ float ridge = stb_perlin_ridge_noise3(1.5f, 2.3f, 0.0f, 2.0f, 0.5f, 1.0f, 6); /* Turbulence — fire / marble-like */ float turb = stb_perlin_turbulence_noise3(1.5f, 2.3f, 0.0f, 2.0f, 0.5f, 6); /* Generate a 64×64 heightmap */ float hmap[64][64]; for (int y = 0; y < 64; y++) for (int x = 0; x < 64; x++) hmap[y][x] = stb_perlin_fbm_noise3( x / 16.0f, y / 16.0f, 0.0f, 2.0f, 0.5f, 5); return 0; } ``` -------------------------------- ### Dynamic Arrays and Hash Maps with stb_ds.h Source: https://context7.com/nothings/stb/llms.txt Demonstrates dynamic array and hash map operations using stb_ds.h. Ensure the underlying pointer is always stored back after mutation as operations are macro-based. ```c #define STB_DS_IMPLEMENTATION #include "stb_ds.h" #include #include int main(void) { /* === Dynamic array === */ int *arr = NULL; arrput(arr, 10); arrput(arr, 20); arrput(arr, 30); arrins(arr, 1, 15); /* insert 15 at index 1 */ printf("len=%td cap=%zu\n", arrlen(arr), arrcap(arr)); for (int i = 0; i < arrlen(arr); i++) printf(" arr[%d] = %d\n", i, arr[i]); int popped = arrpop(arr); /* removes and returns last element */ arrdel(arr, 0); /* delete element at index 0 */ arrfree(arr); /* === Integer-keyed hash map === */ struct { int key; float value; } *scores = NULL; hmput(scores, 42, 3.14f); hmput(scores, 100, 2.71f); printf("scores[42] = %f\n", hmget(scores, 42)); printf("exists 99? %s\n", hmgeti(scores, 99) < 0 ? "no" : "yes"); hmdel(scores, 42); for (int i = 0; i < hmlen(scores); i++) printf(" key=%d val=%f\n", scores[i].key, scores[i].value); hmfree(scores); /* === String-keyed hash map === */ struct { char *key; int value; } *words = NULL; sh_new_arena(words); /* arena allocates key copies */ shput(words, "hello", 1); shput(words, "world", 2); shput(words, "hello", 99); /* update existing key */ printf("hello=%d\n", shget(words, "hello")); printf("len=%td\n", shlen(words)); shdel(words, "world"); shfree(words); return 0; } ``` -------------------------------- ### Compress RGBA to DXT5, DXT1, and BC4 using stb_dxt.h Source: https://context7.com/nothings/stb/llms.txt Compresses 4x4 RGBA pixel blocks to DXT1, DXT5, BC4, or BC5 formats. Ensure the source block is exactly 4x4 RGBA. The caller must handle image tiling and padding. ```c #define STB_DXT_IMPLEMENTATION #include "stb_dxt.h" #include #include int main(void) { /* Compress a 256×256 RGBA image to DXT5 */ const int W = 256, H = 256; unsigned char src_rgba[W * H * 4]; /* filled by caller */ /* DXT5 output: 16 bytes per 4×4 block */ int blocks_x = W / 4, blocks_y = H / 4; unsigned char *dxt5 = malloc(blocks_x * blocks_y * 16); unsigned char *out = dxt5; for (int by = 0; by < blocks_y; by++) { for (int bx = 0; bx < blocks_x; bx++) { /* Extract 4×4 block (row-major RGBA) */ unsigned char block[4 * 4 * 4]; for (int row = 0; row < 4; row++) memcpy(block + row*16, src_rgba + ((by*4 + row)*W + bx*4)*4, 16); stb_compress_dxt_block(out, block, 1, /* alpha=1 → DXT5 */ STB_DXT_HIGHQUAL); /* two refinement passes */ out += 16; } } /* DXT1 (no alpha) — 8 bytes per block */ unsigned char *dxt1 = malloc(blocks_x * blocks_y * 8); out = dxt1; for (int by = 0; by < blocks_y; by++) for (int bx = 0; bx < blocks_x; bx++) { unsigned char block[64]; /* ... fill block ... */ stb_compress_dxt_block(out, block, 0 /* no alpha */, STB_DXT_NORMAL); out += 8; } /* BC4 single-channel */ unsigned char *bc4 = malloc(blocks_x * blocks_y * 8); stb_compress_bc4_block(bc4, src_rgba /* one byte per pixel needed */); free(dxt5); free(dxt1); free(bc4); return 0; } ``` -------------------------------- ### Include stb_image Implementation Source: https://github.com/nothings/stb/blob/master/tools/README.footer.md To compile stb_image, define STB_IMAGE_IMPLEMENTATION in exactly one C/C++ source file before including the header. This ensures the library's code is instantiated. ```c #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" ``` -------------------------------- ### stbi_load_from_callbacks Source: https://context7.com/nothings/stb/llms.txt Loads an image using custom I/O callbacks. The returned pixel data must be freed with `stbi_image_free()`. ```APIDOC ## stbi_load_from_callbacks ### Description Loads an image by using a set of custom I/O callbacks, allowing for reading from non-standard sources like network streams or custom file systems. The caller must free the returned pixel data using `stbi_image_free()`. ### Function Signature `unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);` ### Parameters - **clbk** (stbi_io_callbacks const *) - Pointer to a structure containing custom I/O callback functions (`read`, `skip`, `eof`). - **user** (void *) - User-defined pointer passed to the callback functions. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image. - **desired_channels** (int) - The number of channels to load the image into (e.g., `STBI_grey`, `STBI_rgb`, `STBI_rgb_alpha`). If 0, the image is loaded with its original channel count. ### Return Value Returns a pointer to the pixel data, or `NULL` on failure. ### Callbacks Structure (`stbi_io_callbacks`) - **read**: `int read(void *user, char *data, int size)` - Reads up to `size` bytes into `data`. Returns the number of bytes read, or 0 on EOF/error. - **skip**: `void skip(void *user, int n)` - Skips `n` bytes in the input stream. - **eof**: `int eof(void *user)` - Returns non-zero if EOF has been reached, zero otherwise. ``` -------------------------------- ### Generate Audio Waveforms with stb_hexwave.h Source: https://context7.com/nothings/stb/llms.txt Generates anti-aliased, morphable digital waveforms using six line segments. Useful for synthesizers to avoid aliasing artifacts. Initialize the library once, then create and generate samples for oscillators. ```c #define STB_HEXWAVE_IMPLEMENTATION #include "stb_hexwave.h" #include #include int main(void) { int sample_rate = 44100; /* Initialize library — oversample=32, filter_width=16, user_alloc=NULL */ hexwave_init(32, 16, NULL); /* Create oscillator */ HexWave *osc = malloc(sizeof(HexWave)); hexwave_create(osc, 0, /* reflect=0: sawtooth-like */ 0.5f, /* peak_time: peak halfway */ 0.0f, /* half_height: zero midpoint = triangle */ 0.0f); /* zero_wait: no silence segment */ /* Generate 1 second of audio at 440 Hz */ int num_samples = sample_rate; float *output = malloc(num_samples * sizeof(float)); float freq_ratio = 440.0f / (float)sample_rate; /* freq / sample_rate */ hexwave_generate_samples(output, num_samples, osc, freq_ratio); /* Morph waveform mid-stream (change is applied at next call) */ hexwave_change(osc, 1 /* reflect */, 0.3f, 0.5f, 0.1f); hexwave_generate_samples(output + num_samples/2, num_samples/2, osc, freq_ratio); free(output); free(osc); return 0; } ``` -------------------------------- ### Resize Images with stb_image_resize2 Source: https://context7.com/nothings/stb/llms.txt Perform high-quality image resizing using various API tiers and SIMD support. Handles alpha-weighted filtering for non-premultiplied images. The easy API offers single-call resizing for sRGB-correct or linear downscaling. The library can allocate the output buffer if NULL is passed. ```c #define STB_IMAGE_RESIZE_IMPLEMENTATION #include "stb_image_resize2.h" #include "stb_image.h" /* to load source image */ int main(void) { int sw, sh, sc; unsigned char *src = stbi_load("photo.jpg", &sw, &sh, &sc, 4); int dw = sw / 2, dh = sh / 2; unsigned char *dst = malloc(dw * dh * 4); /* Easy API — sRGB-correct downscale (Mitchell filter) */ stbir_resize_uint8_srgb(src, sw, sh, 0, dst, dw, dh, 0, STBIR_RGBA); /* Easy API — linear downscale */ stbir_resize_uint8_linear(src, sw, sh, 0, dst, dw, dh, 0, STBIR_RGBA); /* Let the library allocate the output buffer */ unsigned char *auto_dst = stbir_resize_uint8_srgb( src, sw, sh, 0, NULL, dw, dh, 0, /* pass NULL → allocated for you */ STBIR_RGBA); free(auto_dst); /* free with free() */ /* Float resize (e.g. HDR data) */ float *fsrc = (float *)src; /* pretend float input */ float *fdst = malloc(dw * dh * 4 * sizeof(float)); stbir_resize_float_linear(fsrc, sw, sh, 0, fdst, dw, dh, 0, STBIR_RGBA_PM); /* premultiplied */ stbi_image_free(src); free(dst); free(fdst); return 0; } ``` -------------------------------- ### Fast Portable Sprintf with stb_sprintf.h Source: https://context7.com/nothings/stb/llms.txt Utilizes stb_sprintf.h for a faster sprintf/snprintf replacement. Supports custom format specifiers like thousand separators and SI/JEDEC byte suffixes, as well as a streaming callback for large outputs. ```c #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" #include int main(void) { char buf[256]; /* Drop-in replacements */ stbsp_sprintf(buf, "Hello, %s! Pi=%.4f", "world", 3.14159); puts(buf); /* Hello, world! Pi=3.1416 */ stbsp_snprintf(buf, sizeof(buf), "%d items at $%.2f each", 7, 1.99); puts(buf); /* 7 items at $1.99 each */ /* Thousand separators */ stbsp_sprintf(buf, "%'d bytes", 1234567); puts(buf); /* 1,234,567 bytes */ /* SI suffixes */ stbsp_sprintf(buf, "%.2$d", 2536000); puts(buf); /* 2.54 M */ stbsp_sprintf(buf, "%.2$$d", 2536000); puts(buf); /* 2.42 Mi (binary prefix) */ /* Streaming callback — handles output larger than any single buffer */ typedef struct { char *out; int pos; } StreamCtx; StreamCtx sc = { malloc(65536), 0 }; char tmp[STB_SPRINTF_MIN]; char *my_cb(const char *buf, void *user, int len) { StreamCtx *c = user; memcpy(c->out + c->pos, buf, len); c->pos += len; return tmp; } stbsp_vsprintfcb(my_cb, &sc, tmp, "%d %s %f", args_va_list); free(sc.out); return 0; } ``` -------------------------------- ### Process GLSL file with #include directives using stb_include_file Source: https://context7.com/nothings/stb/llms.txt Processes a GLSL file, recursively loading and inlining referenced files. Emits #line directives for error reporting. Use when you need to preprocess shader source code with include directives. ```c #define STB_INCLUDE_IMPLEMENTATION #include "stb_include.h" #include #include int main(void) { char error[256] = {0}; /* Process a GLSL file with #include directives */ char *processed = stb_include_file( "shaders/main.vert", /* file to load and process */ "#define MY_VERSION 2\n", /* injected at #inject points */ "shaders/", /* directory to resolve includes from */ error); if (!processed) { fprintf(stderr, "Include error: %s\n", error); return 1; } /* 'processed' contains the fully inlined GLSL source */ printf("Processed shader (%zu bytes)\n", strlen(processed)); /* Pass to glShaderSource(), etc. */ free(processed); /* Process from an in-memory string */ const char *src = "#include \"common.glsl\"\nvoid main(){}\n"; char *out = stb_include_string( (char*)src, NULL, "shaders/", "inline_src", error); if (out) { puts(out); free(out); } return 0; } ``` -------------------------------- ### Tokenize C-like language source with stb_c_lexer Source: https://context7.com/nothings/stb/llms.txt Initializes and uses the stb_c_lexer to tokenize a C-like source string. Useful for building parsers for C-family languages. Ensure sufficient space in `string_store` for string literals. ```c #define STB_C_LEXER_IMPLEMENTATION #include "stb_c_lexer.h" #include #include #include int main(void) { const char *src = "int x = 42; float y = 3.14; // comment\n" "char *msg = \"hello\";"; stb_lexer lex; char string_store[1024]; stb_c_lexer_init(&lex, src, src + strlen(src), string_store, sizeof(string_store)); while (stb_c_lexer_get_token(&lex)) { if (lex.token == CLEX_id) printf("IDENT: %s\n", lex.string); else if (lex.token == CLEX_intlit) printf("INT: %ld\n", lex.int_number); else if (lex.token == CLEX_floatlit) printf("FLOAT: %f\n", lex.real_number); else if (lex.token == CLEX_dqstring) printf("STR: \"%s\"\n", lex.string); else if (lex.token >= 32 && lex.token < 128) printf("CHAR: '%c'\n", (char)lex.token); } /* Get source location for error reporting */ stb_lex_location loc; stb_c_lexer_get_location(&lex, lex.where_firstchar, &loc); printf("Line %d, column %d\n", loc.line_number, loc.line_offset); return 0; } ``` -------------------------------- ### Dual-Licensing Declaration Source: https://github.com/nothings/stb/blob/master/docs/stb_howto.txt This declaration is recommended for use when dual-licensing software to the public domain and under a traditional license. It provides legal clarity and broad usage rights. ```c // This software is dual-licensed to the public domain and under the following // license: you are granted a perpetual, irrevocable license to copy, modify, // publish, and distribute this file as you see fit. ``` -------------------------------- ### Decode Ogg Vorbis File (One-Shot) with stb_vorbis Source: https://context7.com/nothings/stb/llms.txt Decodes an entire Ogg Vorbis file into a buffer of 16-bit PCM samples. Ensure the 'music.ogg' file exists. The returned PCM data must be freed using `free()`. ```c /* No separate #define needed for stb_vorbis — it's a .c file; just compile it */ #include "stb_vorbis.c" #include #include int main(void) { /* --- One-shot decode to 16-bit PCM --- */ int channels, sample_rate; short *pcm; int samples = stb_vorbis_decode_filename( "music.ogg", &channels, &sample_rate, &pcm); if (samples < 0) { fprintf(stderr, "Failed to open ogg\n"); return 1; } printf("Decoded %d samples, %d ch @ %d Hz\n", samples, channels, sample_rate); /* feed pcm[0..samples*channels-1] to audio device, then: */ free(pcm); /* --- Streaming decode with seeking --- */ int error; stb_vorbis *v = stb_vorbis_open_filename("music.ogg", &error, NULL); if (!v) { fprintf(stderr, "Error: %d\n", error); return 1; } stb_vorbis_info info = stb_vorbis_get_info(v); printf("%d channels, %d Hz, %.1f seconds\n", info.channels, info.sample_rate, stb_vorbis_stream_length_in_seconds(v)); /* Read in chunks of 4096 samples per channel */ short buf[4096 * 2]; /* stereo */ int got; while ((got = stb_vorbis_get_samples_short_interleaved( v, 2, buf, 4096 * 2)) > 0) { /* got = samples per channel; buf has got*2 shorts */ } /* Seek to 30 seconds */ unsigned int target = (unsigned int)(30.0 * info.sample_rate); stb_vorbis_seek(v, target); /* Float output */ float **channel_data; int num_samples = stb_vorbis_get_frame_float(v, NULL, &channel_data); /* channel_data[ch][0..num_samples-1] — valid until next decode call */ stb_vorbis_close(v); return 0; } ``` -------------------------------- ### Rasterize Single Glyph with stb_truetype Source: https://context7.com/nothings/stb/llms.txt Demonstrates loading a font file and rasterizing a single character to a bitmap. Ensure the font file (e.g., 'Arial.ttf') is accessible. ```c #define STB_TRUETYPE_IMPLEMENTATION #include "stb_truetype.h" #include #include /* === Simple single-glyph rasterization === */ void single_glyph_demo(void) { FILE *f = fopen("Arial.ttf", "rb"); fseek(f, 0, SEEK_END); long sz = ftell(f); rewind(f); unsigned char *ttf = malloc(sz); fread(ttf, 1, sz, f); fclose(f); stbtt_fontinfo font; stbtt_InitFont(&font, ttf, stbtt_GetFontOffsetForIndex(ttf, 0)); float scale = stbtt_ScaleForPixelHeight(&font, 48.0f); int w, h, xoff, yoff; unsigned char *bitmap = stbtt_GetCodepointBitmap( &font, 0, scale, 'A', &w, &h, &xoff, &yoff); /* bitmap is w*h bytes, 1 byte per pixel (0=transparent, 255=opaque) */ stbtt_FreeBitmap(bitmap, NULL); free(ttf); } ``` -------------------------------- ### stbi_loadf Source: https://context7.com/nothings/stb/llms.txt Loads an image from a file into floating-point pixel data. Memory must be freed with `stbi_image_free()`. ```APIDOC ## stbi_loadf ### Description Loads an image from a file, decoding it into floating-point (32-bit float) per channel pixel data. This is typically used for HDR images. The caller must free the returned memory using `stbi_image_free()`. ### Function Signature `float *stbi_loadf(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);` ### Parameters - **filename** (char const *) - Path to the image file. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image file. - **desired_channels** (int) - The number of channels to load the image into (e.g., `STBI_grey`, `STBI_rgb`, `STBI_rgb_alpha`). If 0, the image is loaded with its original channel count. ### Return Value Returns a pointer to the floating-point pixel data, or `NULL` on failure. ``` -------------------------------- ### stbi_load_from_memory Source: https://context7.com/nothings/stb/llms.txt Loads an image from a memory buffer. The returned pixel data must be freed with `stbi_image_free()`. ```APIDOC ## stbi_load_from_memory ### Description Loads an image directly from a memory buffer containing the image data. The caller must free the returned pixel data using `stbi_image_free()`. ### Function Signature `unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);` ### Parameters - **buffer** (stbi_uc const *) - Pointer to the memory buffer containing the image data. - **len** (int) - The length of the memory buffer in bytes. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image. - **desired_channels** (int) - The number of channels to load the image into (e.g., `STBI_grey`, `STBI_rgb`, `STBI_rgb_alpha`). If 0, the image is loaded with its original channel count. ### Return Value Returns a pointer to the pixel data, or `NULL` on failure. ``` -------------------------------- ### stbi_failure_reason Source: https://context7.com/nothings/stb/llms.txt Returns a string describing the reason for the last failure. ```APIDOC ## stbi_failure_reason ### Description Returns a human-readable string explaining why the most recent `stbi_load*` call failed. This is useful for debugging load errors. ### Function Signature `char const *stbi_failure_reason(void);` ### Return Value A constant string describing the failure reason, or `NULL` if no failure has occurred. ``` -------------------------------- ### stbi_load_16 Source: https://context7.com/nothings/stb/llms.txt Loads a 16-bit image from a file. Returns a pointer to pixel data that must be freed with `stbi_image_free()`. ```APIDOC ## stbi_load_16 ### Description Loads an image from a file, decoding it into 16-bit per channel pixel data. The caller must free the returned memory using `stbi_image_free()`. ### Function Signature `unsigned short *stbi_load_16(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);` ### Parameters - **filename** (char const *) - Path to the image file. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image file. - **desired_channels** (int) - The number of channels to load the image into (e.g., `STBI_grey`, `STBI_rgb`, `STBI_rgb_alpha`). If 0, the image is loaded with its original channel count. ### Return Value Returns a pointer to the 16-bit pixel data, or `NULL` on failure. ``` -------------------------------- ### Bake Font Atlas with stb_truetype Source: https://context7.com/nothings/stb/llms.txt Shows how to bake a set of characters into a texture atlas for efficient rendering. Supports simple baking and advanced oversampling for better quality at small sizes. Ensure 'Arial.ttf' is available. ```c unsigned char ttf_buf[1 << 22]; fread(ttf_buf, 1, sizeof(ttf_buf), fopen("Arial.ttf", "rb")); /* Simple bake */ stbtt_bakedchar cdata[96]; unsigned char atlas[512 * 512]; stbtt_BakeFontBitmap(ttf_buf, 0, 32.0f, atlas, 512, 512, 32, 96, cdata); /* Upload 'atlas' as GL_ALPHA / GL_R8 texture, then: */ /* Retrieve quad for a character when rendering */ float x = 10.0f, y = 10.0f; stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 512, 512, 'H' - 32, &x, &y, &q, 1 /* OpenGL */); /* Draw quad from (q.x0,q.y0)-(q.x1,q.y1) with UVs (q.s0,q.t0)-(q.s1,q.t1) */ /* Advanced: pack API with oversampling */ stbtt_pack_context pc; unsigned char atlas2[1024 * 1024]; stbtt_PackBegin(&pc, atlas2, 1024, 1024, 0, 1, NULL); stbtt_PackSetOversampling(&pc, 2, 2); /* 2x oversampling for small sizes */ stbtt_packedchar pdata[96]; stbtt_PackFontRange(&pc, ttf_buf, 0, 18.0f, 32, 96, pdata); stbtt_PackEnd(&pc); /* Use stbtt_GetPackedQuad() for rendering */ ``` -------------------------------- ### stbi_load Source: https://context7.com/nothings/stb/llms.txt Loads an image from a file into a flat pixel buffer. The caller is responsible for freeing the memory using `stbi_image_free()`. ```APIDOC ## stbi_load ### Description Loads an image from a file, returning a pointer to the pixel data. The image can be decoded into different channel formats. Memory must be freed with `stbi_image_free()`. ### Function Signature `unsigned char *stbi_load(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);` ### Parameters - **filename** (char const *) - Path to the image file. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image file. - **desired_channels** (int) - The number of channels to load the image into (e.g., `STBI_grey`, `STBI_rgb`, `STBI_rgb_alpha`). If 0, the image is loaded with its original channel count. ### Return Value Returns a pointer to the pixel data, or `NULL` on failure. Use `stbi_failure_reason()` to get the error message. ``` -------------------------------- ### Write Images to Disk or Memory with stb_image_write Source: https://context7.com/nothings/stb/llms.txt Use these functions to write image data to files or memory buffers. Supports PNG, JPEG, BMP, TGA, and HDR formats. For PNG, stride_in_bytes=0 means packed rows. JPEG quality is 1-100. HDR expects float data. ```c #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #include int main(void) { int w = 256, h = 256, comp = 4; /* RGBA */ uint8_t *pixels = malloc(w * h * comp); /* fill with a red gradient */ for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { pixels[(y*w+x)*4+0] = (uint8_t)(x); /* R */ pixels[(y*w+x)*4+1] = 0; /* G */ pixels[(y*w+x)*4+2] = 0; /* B */ pixels[(y*w+x)*4+3] = 255; /* A */ } /* PNG — stride_in_bytes=0 means packed rows */ stbi_write_png("out.png", w, h, comp, pixels, 0); /* JPEG at quality 90 */ stbi_write_jpg("out.jpg", w, h, comp, pixels, 90); /* BMP */ stbi_write_bmp("out.bmp", w, h, comp, pixels); /* TGA without RLE */ stbi_write_tga_with_rle = 0; stbi_write_tga("out.tga", w, h, comp, pixels); /* HDR — expects float data */ float *fdata = malloc(w * h * 3 * sizeof(float)); stbi_write_hdr("out.hdr", w, h, 3, fdata); /* Write to memory via callback */ typedef struct { uint8_t *buf; int len; } Ctx; Ctx ctx = {0}; stbi_write_png_to_func( [](void *c, void *data, int sz){ Ctx *ctx = c; ctx->buf = realloc(ctx->buf, ctx->len + sz); memcpy(ctx->buf + ctx->len, data, sz); ctx->len += sz; }, &ctx, w, h, comp, pixels, 0); free(pixels); free(fdata); free(ctx.buf); return 0; } ``` -------------------------------- ### stbi_info Source: https://context7.com/nothings/stb/llms.txt Queries image dimensions and channel information without decoding the entire image. ```APIDOC ## stbi_info ### Description Retrieves image dimensions (width, height) and the number of channels without loading the pixel data. This is useful for pre-allocating memory or checking image properties. ### Function Signature `int stbi_info(char const *filename, int *x, int *y, int *channels_in_file);` ### Parameters - **filename** (char const *) - Path to the image file. - **x** (int *) - Output pointer for image width. - **y** (int *) - Output pointer for image height. - **channels_in_file** (int *) - Output pointer for the number of channels in the source image file. ### Return Value Returns non-zero on success, zero on failure. ``` -------------------------------- ### Track Malloc Allocations with stb_leakcheck.h Source: https://context7.com/nothings/stb/llms.txt A drop-in leak detector that wraps malloc, realloc, and free to track allocations. Call stb_leakcheck_dumpmem() at program exit to report live allocations with their source file and line number. Define STB_LEAKCHECK_IMPLEMENTATION in exactly one file. ```c /* Enable in exactly one file — put BEFORE any other includes that use malloc */ #define STB_LEAKCHECK_IMPLEMENTATION #include "stb_leakcheck.h" /* In ALL other files that should be tracked: */ #include "stb_leakcheck.h" /* no define — just redefines malloc/free/realloc */ #include #include void leaky_function(void) { void *a = malloc(64); /* intentionally leaked */ void *b = malloc(128); free(b); /* 'a' is never freed */ } int main(void) { leaky_function(); void *ok = malloc(32); free(ok); /* Print all leaked allocations to stdout */ stb_leakcheck_dumpmem(); /* Output: LEAK: 64 bytes @ stb_leakcheck_demo.c:11 */ return 0; } ``` -------------------------------- ### stbi_image_free Source: https://context7.com/nothings/stb/llms.txt Frees the memory allocated by `stbi_load`, `stbi_load_16`, `stbi_loadf`, `stbi_load_from_memory`, or `stbi_load_from_callbacks`. ```APIDOC ## stbi_image_free ### Description Frees the memory that was allocated by any of the `stbi_load*` functions. This is crucial to prevent memory leaks. ### Function Signature `void stbi_image_free(void *retval_from_stbi_load); ` ### Parameters - **retval_from_stbi_load** (void *) - The pointer returned by a `stbi_load*` function that needs to be freed. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.