Skip to content

Sprite Sheet Packer — Python source

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

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

# sprite-sheet-packer — MaxRects best-short-side-fit sheet packer (stdlib only).
# Python port of src/lib/sprite-packer.ts: the TS lib is already pure (no
# canvas, no DOM), so this mirrors the full contract — validation, biggest-
# first ordering, sheet growth, MaxRects splitting, power-of-two rounding,
# plus the JSON-atlas and CSS emitters. json is stdlib.
from __future__ import annotations

import json
from dataclasses import dataclass
from typing import List, Optional


class PackError(Exception):
    """The Python twin of the TS PackError class."""

    def __init__(self, code: str, message: str) -> None:
        super().__init__(message)
        self.code = code


@dataclass
class SpriteSize:
    id: str
    w: int
    h: int


@dataclass
class PackedRect:
    id: str
    x: int
    y: int
    w: int
    h: int
    rotated: bool


@dataclass
class PackResult:
    sheet_w: int
    sheet_h: int
    rects: List[PackedRect]


@dataclass
class PackOptions:
    max_width: int = 4096
    max_height: int = 4096
    allow_rotate: bool = False


@dataclass
class _FreeRect:
    x: int
    y: int
    w: int
    h: int


MIN_SHEET = 64
DEFAULT_CAP = 4096


def pack(sizes: List[SpriteSize], opts: Optional[PackOptions] = None) -> PackResult:
    """MaxRects best-short-side-fit packing over a growing power-of-two sheet."""
    o = opts or PackOptions()
    if not sizes:
        raise PackError("empty", "Nothing to pack — add at least one sprite.")

    seen = set()
    for s in sizes:
        if not (s.w > 0 and s.h > 0):
            raise PackError("invalid", f'Sprite "{s.id}" needs positive pixel dimensions.')
        if s.id in seen:
            raise PackError("invalid", f'Duplicate sprite id "{s.id}".')
        seen.add(s.id)

    max_w, max_h = o.max_width, o.max_height

    # Biggest sprites first (max side, then area, then id).
    order = sorted(sizes, key=lambda s: (-max(s.w, s.h), -(s.w * s.h), s.id))

    sheet_w = _pow2_floor(min(MIN_SHEET, max_w))
    sheet_h = _pow2_floor(min(MIN_SHEET, max_h))
    while True:
        placed, failed = _try_pack(order, sheet_w, sheet_h, o.allow_rotate)
        if failed is None:
            return _finish(sizes, placed)
        next_w = sheet_w * 2 if sheet_w <= sheet_h else sheet_w
        next_h = sheet_h if sheet_w <= sheet_h else sheet_h * 2
        if next_w > max_w or next_h > max_h:
            raise PackError(
                "overflow",
                f'"{failed}" does not fit within {max_w}×{max_h} — split the batch or raise the cap.',
            )
        sheet_w, sheet_h = next_w, next_h


def _try_pack(order, w, h, allow_rotate):
    """One MaxRects pass over a fixed candidate sheet: rects, or the failed id."""
    free = [_FreeRect(0, 0, w, h)]
    placed = []
    for s in order:
        best = _best_fit(free, s, allow_rotate)
        if best is None:
            return None, s.id
        rect = PackedRect(s.id, best[0].x, best[0].y, best[1], best[2], best[3])
        placed.append(rect)
        free = _split_free(free, rect)
    return placed, None


def _best_fit(free, s, allow_rotate):
    """Best short side fit, ties broken by the long side, then by first-seen free rect."""
    best = None  # (free_rect, w, h, rotated, short, long)
    candidates = [(s.w, s.h, False)]
    if allow_rotate and s.w != s.h:
        candidates.append((s.h, s.w, True))
    for f in free:
        for cw, ch, rotated in candidates:
            if cw > f.w or ch > f.h:
                continue
            leftover_w = f.w - cw
            leftover_h = f.h - ch
            short = min(leftover_w, leftover_h)
            long = max(leftover_w, leftover_h)
            if best is None or short < best[4] or (short == best[4] and long < best[5]):
                best = (f, cw, ch, rotated, short, long)
    return best


def _split_free(free, p):
    """MaxRects split: carve the placed rect out of every free rect it touches."""
    nxt = []
    for f in free:
        intersects = p.x < f.x + f.w and p.x + p.w > f.x and p.y < f.y + f.h and p.y + p.h > f.y
        if not intersects:
            nxt.append(f)
            continue
        if p.x > f.x:
            nxt.append(_FreeRect(f.x, f.y, p.x - f.x, f.h))
        if p.x + p.w < f.x + f.w:
            nxt.append(_FreeRect(p.x + p.w, f.y, f.x + f.w - (p.x + p.w), f.h))
        if p.y > f.y:
            nxt.append(_FreeRect(f.x, f.y, f.w, p.y - f.y))
        if p.y + p.h < f.y + f.h:
            nxt.append(_FreeRect(f.x, p.y + p.h, f.w, f.y + f.h - (p.y + p.h)))
    # Prune free rects fully contained in another; the j<i clause keeps exactly
    # one of an identical pair.
    return [
        a
        for i, a in enumerate(nxt)
        if not any(j != i and _contains(b, a) and not (_contains(a, b) and j > i) for j, b in enumerate(nxt))
    ]


def _contains(outer: _FreeRect, inner: _FreeRect) -> bool:
    return (
        outer.x <= inner.x
        and outer.y <= inner.y
        and outer.x + outer.w >= inner.x + inner.w
        and outer.y + outer.h >= inner.y + inner.h
    )


def _finish(sizes, placed):
    """Reorder to input order and round the bounding box up to power-of-two dims."""
    by_id = {p.id: p for p in placed}
    bw = bh = 1
    for p in placed:
        bw = max(bw, p.x + p.w)
        bh = max(bh, p.y + p.h)
    return PackResult(
        sheet_w=_pow2_ceil(bw),
        sheet_h=_pow2_ceil(bh),
        rects=[by_id[s.id] for s in sizes],
    )


def _pow2_ceil(n: int) -> int:
    p = 1
    while p < n:
        p *= 2
    return p


def _pow2_floor(n: int) -> int:
    p = 1
    while p * 2 <= n:
        p *= 2
    return p


def atlas_json(name: str, r: PackResult) -> str:
    """Generic JSON atlas: one frame entry per sprite, sheet metadata for engines."""
    frames = {}
    for rect in r.rects:
        frames[rect.id] = {
            "frame": {"x": rect.x, "y": rect.y, "w": rect.w, "h": rect.h},
            "rotated": rect.rotated,
        }
    return json.dumps(
        {"frames": frames, "meta": {"size": {"w": r.sheet_w, "h": r.sheet_h}, "name": name}},
        indent=2,
    )


def sprite_css(r: PackResult, sheet_name: str) -> str:
    """One .sprite-<id> class per rect, positioned against the shared sheet image."""
    blocks = []
    for rect in r.rects:
        blocks.append(
            f".sprite-{rect.id} {{\n"
            f"  width: {rect.w}px;\n"
            f"  height: {rect.h}px;\n"
            f"  background-image: url('{sheet_name}');\n"
            f"  background-position: -{rect.x}px -{rect.y}px;\n"
            f"}}"
        )
    return "\n".join(blocks)

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 →