Skip to content

Sprite Sheet Packer — C source

Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.

This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.

/* sprite-sheet-packer — MaxRects best-short-side-fit sheet packer. C port
 * (canonical TS: src/lib/sprite-packer.ts), C11 stdlib only: validation,
 * biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
 * rounding, plus the JSON-atlas and CSS emitters. Caller frees
 * result.rects, and the strings returned by atlas_json / sprite_css. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* One input sprite. */
typedef struct {
    const char *id;
    int w, h;
} SpriteSize;

/* One placed sprite on the sheet. */
typedef struct {
    const char *id;
    int x, y, w, h;
    int rotated;
} PackedRect;

/* The final sheet: power-of-two dims plus rects in input order. */
typedef struct {
    int sheet_w, sheet_h;
    PackedRect *rects;
    size_t n;
} PackResult;

/* Mirrors the TS PackOptions. */
typedef struct {
    int max_width, max_height;
    int allow_rotate;
} PackOptions;

/* Error codes mirror the TS PackErrorCode union. */
typedef enum { PACK_OK = 0, PACK_EMPTY, PACK_INVALID, PACK_OVERFLOW } PackCode;

/* PackError twin: pack() returns this by value; message is plain text. */
typedef struct {
    PackCode code;
    char message[256];
} PackError;

/* ---- internals ---- */

typedef struct {
    int x, y, w, h;
} FreeRect;

typedef struct {
    FreeRect f;
    int w, h, rotated;
    int short_side, long_side;
} Fit;

enum { MIN_SHEET = 64 };
enum { DEFAULT_CAP = 4096 };

static int max_int(int a, int b) { return a > b ? a : b; }
static int min_int(int a, int b) { return a < b ? a : b; }

static int pow2ceil(int n) {
    int p = 1;
    while (p < n) p *= 2;
    return p;
}

static int pow2floor(int n) {
    int p = 1;
    while (p * 2 <= n) p *= 2;
    return p;
}

static int contains_rect(const FreeRect *outer, const FreeRect *inner) {
    return outer->x <= inner->x && outer->y <= inner->y &&
           outer->x + outer->w >= inner->x + inner->w &&
           outer->y + outer->h >= inner->y + inner->h;
}

/* Biggest sprites first (max side, then area, then id). Ids are unique
   (validated before sorting), so the key is a total order and qsort's
   instability cannot change the result. */
static int cmp_order(const void *a, const void *b) {
    const SpriteSize *sa = a, *sb = b;
    int ma = max_int(sa->w, sa->h), mb = max_int(sb->w, sb->h);
    if (ma != mb) return mb - ma;
    long area_a = (long)sa->w * sa->h, area_b = (long)sb->w * sb->h;
    if (area_a != area_b) return area_b > area_a ? 1 : -1;
    return strcmp(sa->id, sb->id);
}

/* Best short side fit, ties broken by the long side, then by first-seen
   free rect. Returns NULL-equivalent via the return value when nothing fits. */
static int best_fit(const FreeRect *free_list, size_t n_free, const SpriteSize *s,
                    int allow_rotate, Fit *out) {
    int found = 0;
    Fit best;
    int best_short = 0, best_long = 0;
    /* Up to two candidates: upright plus the rotated twin when allowed. */
    struct { int w, h, rotated; } cands[2];
    size_t n_cands = 1;
    cands[0].w = s->w; cands[0].h = s->h; cands[0].rotated = 0;
    if (allow_rotate && s->w != s->h) {
        cands[1].w = s->h; cands[1].h = s->w; cands[1].rotated = 1;
        n_cands = 2;
    }
    for (size_t i = 0; i < n_free; i++) {
        const FreeRect *f = &free_list[i];
        for (size_t c = 0; c < n_cands; c++) {
            if (cands[c].w > f->w || cands[c].h > f->h) continue;
            int leftover_w = f->w - cands[c].w;
            int leftover_h = f->h - cands[c].h;
            int short_side = min_int(leftover_w, leftover_h);
            int long_side = max_int(leftover_w, leftover_h);
            if (!found || short_side < best_short ||
                (short_side == best_short && long_side < best_long)) {
                best.f = *f;
                best.w = cands[c].w;
                best.h = cands[c].h;
                best.rotated = cands[c].rotated;
                best.short_side = short_side;
                best.long_side = long_side;
                best_short = short_side;
                best_long = long_side;
                found = 1;
            }
        }
    }
    if (found) *out = best;
    return found;
}

/* MaxRects split: carve the placed rect out of every free rect it touches,
   then prune contained ones (the j<i clause keeps exactly one of an
   identical pair). */
static size_t split_free(FreeRect **next, size_t n_next, const PackedRect *p) {
    /* Each intersecting free rect emits at most 4 pieces, so the result fits
       in n_next * 4 (+ n_next untouched) entries. */
    FreeRect *out = malloc((n_next * 5 + 1) * sizeof *out);
    if (!out) abort();
    size_t n_out = 0;
    for (size_t i = 0; i < n_next; i++) {
        FreeRect f = (*next)[i];
        int intersects = p->x < f.x + f.w && p->x + p->w > f.x &&
                         p->y < f.y + f.h && p->y + p->h > f.y;
        if (!intersects) {
            out[n_out++] = f;
            continue;
        }
        if (p->x > f.x) {
            out[n_out].x = f.x; out[n_out].y = f.y;
            out[n_out].w = p->x - f.x; out[n_out].h = f.h;
            n_out++;
        }
        if (p->x + p->w < f.x + f.w) {
            out[n_out].x = p->x + p->w; out[n_out].y = f.y;
            out[n_out].w = f.x + f.w - (p->x + p->w); out[n_out].h = f.h;
            n_out++;
        }
        if (p->y > f.y) {
            out[n_out].x = f.x; out[n_out].y = f.y;
            out[n_out].w = f.w; out[n_out].h = p->y - f.y;
            n_out++;
        }
        if (p->y + p->h < f.y + f.h) {
            out[n_out].x = f.x; out[n_out].y = p->y + p->h;
            out[n_out].w = f.w; out[n_out].h = f.y + f.h - (p->y + p->h);
            n_out++;
        }
    }
    size_t kept = 0;
    for (size_t i = 0; i < n_out; i++) {
        int keep = 1;
        for (size_t j = 0; j < n_out; j++) {
            if (j != i && contains_rect(&out[j], &out[i]) &&
                !(contains_rect(&out[i], &out[j]) && j > i)) {
                keep = 0;
                break;
            }
        }
        if (keep) out[kept++] = out[i];
    }
    FreeRect *shrunk = realloc(out, (kept ? kept : 1) * sizeof *out);
    free(*next);
    *next = shrunk ? shrunk : out;
    return kept;
}

/* One MaxRects pass over a fixed candidate sheet: all rects, or the first
   id that failed (returned through failed_id). */
static int try_pack(const SpriteSize *order, size_t n, int W, int H, int allow_rotate,
                    PackedRect *placed, const char **failed_id) {
    FreeRect *free_list = malloc(sizeof *free_list);
    if (!free_list) abort();
    size_t n_free = 0;
    free_list[n_free].x = 0; free_list[n_free].y = 0;
    free_list[n_free].w = W; free_list[n_free].h = H;
    n_free++;
    for (size_t i = 0; i < n; i++) {
        Fit best;
        if (!best_fit(free_list, n_free, &order[i], allow_rotate, &best)) {
            free(free_list);
            *failed_id = order[i].id;
            return 0;
        }
        placed[i].id = order[i].id;
        placed[i].x = best.f.x;
        placed[i].y = best.f.y;
        placed[i].w = best.w;
        placed[i].h = best.h;
        placed[i].rotated = best.rotated;
        n_free = split_free(&free_list, n_free, &placed[i]);
    }
    free(free_list);
    return 1;
}

/* Reorder to input order and round the bounding box up to power-of-two
   sheet dims. */
static void finish(const SpriteSize *sizes, size_t n, const PackedRect *placed,
                   PackedRect *out_rects, PackResult *out) {
    int bw = 1, bh = 1;
    for (size_t i = 0; i < n; i++) {
        bw = max_int(bw, placed[i].x + placed[i].w);
        bh = max_int(bh, placed[i].y + placed[i].h);
    }
    /* Input order: match each size to its placed rect by id. */
    for (size_t i = 0; i < n; i++) {
        for (size_t j = 0; j < n; j++) {
            if (strcmp(sizes[i].id, placed[j].id) == 0) {
                out_rects[i] = placed[j];
                break;
            }
        }
    }
    out->sheet_w = pow2ceil(bw);
    out->sheet_h = pow2ceil(bh);
    out->n = n;
}

/* MaxRects best-short-side-fit packing over a growing power-of-two sheet.
   On success *out owns result.rects (free with free()). */
PackError pack(const SpriteSize *sizes, size_t n, const PackOptions *opts, PackResult *out) {
    PackError err;
    err.code = PACK_OK;
    err.message[0] = '\0';
    out->rects = NULL;
    out->n = 0;
    out->sheet_w = 0;
    out->sheet_h = 0;

    if (n == 0) {
        err.code = PACK_EMPTY;
        snprintf(err.message, sizeof err.message, "Nothing to pack — add at least one sprite.");
        return err;
    }
    for (size_t i = 0; i < n; i++) {
        if (sizes[i].w <= 0 || sizes[i].h <= 0) {
            err.code = PACK_INVALID;
            snprintf(err.message, sizeof err.message,
                     "Sprite \"%s\" needs positive pixel dimensions.", sizes[i].id);
            return err;
        }
        for (size_t j = 0; j < i; j++) {
            if (strcmp(sizes[i].id, sizes[j].id) == 0) {
                err.code = PACK_INVALID;
                snprintf(err.message, sizeof err.message, "Duplicate sprite id \"%s\".", sizes[i].id);
                return err;
            }
        }
    }

    int max_width = opts ? opts->max_width : DEFAULT_CAP;
    int max_height = opts ? opts->max_height : DEFAULT_CAP;
    int allow_rotate = opts ? opts->allow_rotate : 0;
    if (max_width == 0) max_width = DEFAULT_CAP;
    if (max_height == 0) max_height = DEFAULT_CAP;

    SpriteSize *order = malloc(n * sizeof *order);
    PackedRect *placed = malloc(n * sizeof *placed);
    PackedRect *out_rects = malloc(n * sizeof *out_rects);
    if (!order || !placed || !out_rects) abort(); /* snippet-grade: OOM aborts */
    memcpy(order, sizes, n * sizeof *order);
    qsort(order, n, sizeof *order, cmp_order);

    int sheet_w = pow2floor(min_int(MIN_SHEET, max_width));
    int sheet_h = pow2floor(min_int(MIN_SHEET, max_height));
    for (;;) {
        const char *failed = NULL;
        if (try_pack(order, n, sheet_w, sheet_h, allow_rotate, placed, &failed)) {
            finish(sizes, n, placed, out_rects, out);
            free(order);
            free(placed);
            out->rects = out_rects;
            return err;
        }
        int next_w = sheet_w, next_h = sheet_h;
        if (sheet_w <= sheet_h) next_w = sheet_w * 2; else next_h = sheet_h * 2;
        if (next_w > max_width || next_h > max_height) {
            err.code = PACK_OVERFLOW;
            snprintf(err.message, sizeof err.message,
                     "\"%s\" does not fit within %d×%d — split the batch or raise the cap.",
                     failed, max_width, max_height);
            free(order);
            free(placed);
            free(out_rects);
            return err;
        }
        sheet_w = next_w;
        sheet_h = next_h;
    }
}

/* Minimal JSON string escaping (the atlas ids are plain slugs). */
static void json_str(char *dst, size_t cap, const char *s) {
    size_t d = 0;
    dst[d++] = '"';
    for (const char *p = s; *p && d + 7 < cap; p++) {
        unsigned char c = (unsigned char)*p;
        if (c == '"' || c == '\\') {
            dst[d++] = '\\';
            dst[d++] = (char)c;
        } else if (c < 0x20) {
            d += (size_t)snprintf(dst + d, 7, "\\u%04x", c);
        } else {
            dst[d++] = (char)c;
        }
    }
    dst[d++] = '"';
    dst[d] = '\0';
}

/* Generic JSON atlas: one frame entry per sprite (assembled manually so the
   entries stay in pack-input order), sheet metadata for engines. Caller
   frees the returned string. */
char *atlas_json(const char *name, const PackResult *r) {
    size_t cap = 128 + r->n * 160 + strlen(name);
    char *out = malloc(cap);
    if (!out) return NULL;
    size_t d = 0;
    d += (size_t)snprintf(out + d, cap - d, "{\n  \"frames\": {");
    for (size_t i = 0; i < r->n; i++) {
        const PackedRect *rect = &r->rects[i];
        char key[256];
        json_str(key, sizeof key, rect->id);
        d += (size_t)snprintf(out + d, cap - d,
                              "%s\n    %s: {\n      \"frame\": {\n"
                              "        \"x\": %d,\n        \"y\": %d,\n"
                              "        \"w\": %d,\n        \"h\": %d\n"
                              "      },\n      \"rotated\": %s\n    }",
                              i > 0 ? "," : "", key,
                              rect->x, rect->y, rect->w, rect->h,
                              rect->rotated ? "true" : "false");
    }
    char name_key[256];
    json_str(name_key, sizeof name_key, name);
    d += (size_t)snprintf(out + d, cap - d,
                          "\n  },\n  \"meta\": {\n    \"size\": {\n"
                          "      \"w\": %d,\n      \"h\": %d\n    },\n"
                          "    \"name\": %s\n  }\n}",
                          r->sheet_w, r->sheet_h, name_key);
    return out;
}

/* One .sprite-<id> class per rect, positioned against the shared sheet
   image. Caller frees the returned string. */
char *sprite_css(const PackResult *r, const char *sheet_name) {
    size_t cap = 16 + r->n * (192 + strlen(sheet_name));
    char *out = malloc(cap);
    if (!out) return NULL;
    size_t d = 0;
    for (size_t i = 0; i < r->n; i++) {
        const PackedRect *rect = &r->rects[i];
        d += (size_t)snprintf(out + d, cap - d,
                              "%s.sprite-%s {\n  width: %dpx;\n  height: %dpx;\n"
                              "  background-image: url('%s');\n"
                              "  background-position: -%dpx -%dpx;\n}",
                              i > 0 ? "\n" : "", rect->id, rect->w, rect->h,
                              sheet_name, rect->x, rect->y);
    }
    return out;
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →