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++17 port
// (canonical TS: src/lib/sprite-packer.ts), standard library only: validation,
// biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
// rounding, plus the JSON-atlas and CSS emitters.
#include <algorithm>
#include <cstdio>
#include <stdexcept>
#include <string>
#include <vector>

// One input sprite.
struct SpriteSize {
    std::string id;
    int w, h;
};

// One placed sprite on the sheet.
struct PackedRect {
    std::string id;
    int x, y, w, h;
    bool rotated;
};

// The final sheet: power-of-two dims plus rects in input order.
struct PackResult {
    int sheet_w, sheet_h;
    std::vector<PackedRect> rects;
};

// Mirrors the TS PackOptions.
struct PackOptions {
    int max_width = 4096;
    int max_height = 4096;
    bool allow_rotate = false;
};

// The C++ twin of the TS PackError class.
class PackError : public std::runtime_error {
public:
    std::string code; // 'empty' | 'invalid' | 'overflow'
    PackError(std::string c, const std::string &m)
        : std::runtime_error(m), code(std::move(c)) {}
};

namespace {

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

constexpr int kMinSheet = 64;

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

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

bool containsRect(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;
}

// Best short side fit, ties broken by the long side, then by first-seen free
// rect. Returns false when nothing fits.
bool bestFit(const std::vector<FreeRect> &free_list, const SpriteSize &s,
             bool allow_rotate, FreeRect &out_f, int &out_w, int &out_h,
             bool &out_rotated) {
    bool found = false;
    int best_short = 0, best_long = 0;
    struct Cand { int w, h; bool rotated; };
    Cand cands[2] = {{s.w, s.h, false}};
    int n_cands = 1;
    if (allow_rotate && s.w != s.h) {
        cands[1] = {s.h, s.w, true};
        n_cands = 2;
    }
    for (const FreeRect &f : free_list) {
        for (int 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 = std::min(leftover_w, leftover_h);
            int long_side = std::max(leftover_w, leftover_h);
            if (!found || short_side < best_short ||
                (short_side == best_short && long_side < best_long)) {
                out_f = f;
                out_w = cands[c].w;
                out_h = cands[c].h;
                out_rotated = cands[c].rotated;
                best_short = short_side;
                best_long = long_side;
                found = true;
            }
        }
    }
    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).
std::vector<FreeRect> splitFree(const std::vector<FreeRect> &free_list, const PackedRect &p) {
    std::vector<FreeRect> next;
    for (const FreeRect &f : free_list) {
        bool 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) {
            next.push_back(f);
            continue;
        }
        if (p.x > f.x) next.push_back({f.x, f.y, p.x - f.x, f.h});
        if (p.x + p.w < f.x + f.w) next.push_back({p.x + p.w, f.y, f.x + f.w - (p.x + p.w), f.h});
        if (p.y > f.y) next.push_back({f.x, f.y, f.w, p.y - f.y});
        if (p.y + p.h < f.y + f.h) next.push_back({f.x, p.y + p.h, f.w, f.y + f.h - (p.y + p.h)});
    }
    std::vector<FreeRect> kept;
    for (size_t i = 0; i < next.size(); i++) {
        bool keep = true;
        for (size_t j = 0; j < next.size(); j++) {
            if (j != i && containsRect(next[j], next[i]) &&
                !(containsRect(next[i], next[j]) && j > i)) {
                keep = false;
                break;
            }
        }
        if (keep) kept.push_back(next[i]);
    }
    return kept;
}

// One MaxRects pass over a fixed candidate sheet: all rects, or the first id
// that failed (returned through failed_id).
bool tryPack(const std::vector<SpriteSize> &order, int W, int H, bool allow_rotate,
             std::vector<PackedRect> &placed, std::string &failed_id) {
    std::vector<FreeRect> free_list{{0, 0, W, H}};
    for (const SpriteSize &s : order) {
        FreeRect f;
        int w, h;
        bool rotated;
        if (!bestFit(free_list, s, allow_rotate, f, w, h, rotated)) {
            failed_id = s.id;
            return false;
        }
        placed.push_back({s.id, f.x, f.y, w, h, rotated});
        free_list = splitFree(free_list, placed.back());
    }
    return true;
}

// Minimal JSON string escaping (the atlas ids are plain slugs).
std::string jsonStr(const std::string &s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        if (c == '"' || c == '\\') {
            out += '\\';
            out += (char)c;
        } else if (c < 0x20) {
            char buf[8];
            std::snprintf(buf, sizeof buf, "\\u%04x", c);
            out += buf;
        } else {
            out += (char)c;
        }
    }
    out += '"';
    return out;
}

} // namespace

// MaxRects best-short-side-fit packing over a growing power-of-two sheet.
PackResult pack(const std::vector<SpriteSize> &sizes, const PackOptions &opts = PackOptions()) {
    if (sizes.empty()) throw PackError("empty", "Nothing to pack — add at least one sprite.");
    for (const SpriteSize &s : sizes) {
        if (s.w <= 0 || s.h <= 0) {
            throw PackError("invalid", "Sprite \"" + s.id + "\" needs positive pixel dimensions.");
        }
        for (const SpriteSize &seen : sizes) {
            if (&seen == &s) break;
            if (seen.id == s.id) throw PackError("invalid", "Duplicate sprite id \"" + s.id + "\".");
        }
    }

    // Biggest sprites first (max side, then area, then id). Ids are unique
    // (validated above), so the key is a total order and sort stability
    // cannot change the result.
    std::vector<SpriteSize> order = sizes;
    std::sort(order.begin(), order.end(), [](const SpriteSize &a, const SpriteSize &b) {
        int ma = std::max(a.w, a.h), mb = std::max(b.w, b.h);
        if (ma != mb) return ma > mb;
        long area_a = (long)a.w * a.h, area_b = (long)b.w * b.h;
        if (area_a != area_b) return area_a > area_b;
        return a.id < b.id;
    });

    int sheet_w = pow2floor(std::min(kMinSheet, opts.max_width));
    int sheet_h = pow2floor(std::min(kMinSheet, opts.max_height));
    for (;;) {
        std::vector<PackedRect> placed;
        std::string failed;
        if (tryPack(order, sheet_w, sheet_h, opts.allow_rotate, placed, failed)) {
            // Reorder to input order and round the bounding box up to
            // power-of-two sheet dims.
            int bw = 1, bh = 1;
            for (const PackedRect &p : placed) {
                bw = std::max(bw, p.x + p.w);
                bh = std::max(bh, p.y + p.h);
            }
            PackResult r;
            r.sheet_w = pow2ceil(bw);
            r.sheet_h = pow2ceil(bh);
            r.rects.reserve(sizes.size());
            for (const SpriteSize &s : sizes) {
                for (const PackedRect &p : placed) {
                    if (p.id == s.id) {
                        r.rects.push_back(p);
                        break;
                    }
                }
            }
            return r;
        }
        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 > opts.max_width || next_h > opts.max_height) {
            throw PackError("overflow", "\"" + failed + "\" does not fit within " +
                                            std::to_string(opts.max_width) + "×" +
                                            std::to_string(opts.max_height) +
                                            " — split the batch or raise the cap.");
        }
        sheet_w = next_w;
        sheet_h = next_h;
    }
}

// Generic JSON atlas: one frame entry per sprite (assembled manually so the
// entries stay in pack-input order), sheet metadata for engines.
std::string atlasJson(const std::string &name, const PackResult &r) {
    std::string out = "{\n  \"frames\": {";
    for (size_t i = 0; i < r.rects.size(); i++) {
        const PackedRect &rect = r.rects[i];
        char buf[256];
        std::snprintf(buf, sizeof buf, "%s\n    %s: {\n      \"frame\": {\n"
                                       "        \"x\": %d,\n        \"y\": %d,\n"
                                       "        \"w\": %d,\n        \"h\": %d\n"
                                       "      },\n      \"rotated\": %s\n    }",
                      i > 0 ? "," : "", jsonStr(rect.id).c_str(),
                      rect.x, rect.y, rect.w, rect.h, rect.rotated ? "true" : "false");
        out += buf;
    }
    out += "\n  },\n  \"meta\": {\n    \"size\": {\n";
    char buf[192];
    std::snprintf(buf, sizeof buf, "      \"w\": %d,\n      \"h\": %d\n    },\n    \"name\": %s\n  }\n}",
                  r.sheet_w, r.sheet_h, jsonStr(name).c_str());
    out += buf;
    return out;
}

// One .sprite-<id> class per rect, positioned against the shared sheet image.
std::string spriteCss(const PackResult &r, const std::string &sheet_name) {
    std::string out;
    for (size_t i = 0; i < r.rects.size(); i++) {
        const PackedRect &rect = r.rects[i];
        if (i > 0) out += '\n';
        char buf[512];
        std::snprintf(buf, sizeof buf,
                      ".sprite-%s {\n  width: %dpx;\n  height: %dpx;\n"
                      "  background-image: url('%s');\n"
                      "  background-position: -%dpx -%dpx;\n}",
                      rect.id.c_str(), rect.w, rect.h, sheet_name.c_str(), rect.x, rect.y);
        out += buf;
    }
    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 →