Sprite Sheet Packer — Go source
Pack loose sprites into one optimized sheet with atlas JSON and CSS — entirely in your browser. Nothing uploads.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// sprite-sheet-packer — MaxRects best-short-side-fit sheet packer (Go port).
// Go port of the pure src/lib/sprite-packer.ts: the TS lib has no canvas
// dependency at all, so this is a 1:1 port of the full contract — validation,
// biggest-first ordering, sheet growth, MaxRects splitting, power-of-two
// rounding, plus the JSON-atlas and CSS emitters. Drawing stays in the browser.
package spritesheet
import (
"encoding/json"
"fmt"
"sort"
"strings"
)
// Error codes mirror the TS PackError codes.
const (
CodeEmpty = "empty"
CodeInvalid = "invalid"
CodeOverflow = "overflow"
)
// PackError is the Go twin of the TS PackError class.
type PackError struct {
Code string
Message string
}
func (e *PackError) Error() string { return e.Message }
// SpriteSize is one input sprite.
type SpriteSize struct {
ID string
W int
H int
}
// PackedRect is one placed sprite on the sheet.
type PackedRect struct {
ID string
X, Y int
W, H int
Rotated bool
}
// PackResult is the final sheet: power-of-two dims plus rects in input order.
type PackResult struct {
SheetW int
SheetH int
Rects []PackedRect
}
// PackOptions mirrors the TS PackOptions. A zero MaxWidth/MaxHeight means
// "unset" and falls back to DefaultCap (4096) — the Go zero-value analogue
// of the TS `?? DEFAULT_CAP` default.
type PackOptions struct {
MaxWidth int
MaxHeight int
AllowRotate bool
}
type freeRect struct{ x, y, w, h int }
const minSheet = 64
const defaultCap = 4096
// Pack runs MaxRects best-short-side-fit packing over a growing
// power-of-two sheet. Returns *PackError{CodeEmpty|CodeInvalid|CodeOverflow}.
func Pack(sizes []SpriteSize, opts PackOptions) (PackResult, error) {
if len(sizes) == 0 {
return PackResult{}, &PackError{CodeEmpty, "Nothing to pack — add at least one sprite."}
}
seen := map[string]bool{}
for _, s := range sizes {
if s.W <= 0 || s.H <= 0 {
return PackResult{}, &PackError{CodeInvalid, fmt.Sprintf("Sprite %q needs positive pixel dimensions.", s.ID)}
}
if seen[s.ID] {
return PackResult{}, &PackError{CodeInvalid, fmt.Sprintf("Duplicate sprite id %q.", s.ID)}
}
seen[s.ID] = true
}
maxWidth, maxHeight := opts.MaxWidth, opts.MaxHeight
if maxWidth == 0 {
maxWidth = defaultCap
}
if maxHeight == 0 {
maxHeight = defaultCap
}
// Biggest sprites first (max side, then area, then id).
order := make([]SpriteSize, len(sizes))
copy(order, sizes)
sort.Slice(order, func(i, j int) bool {
a, b := order[i], order[j]
if max(a.W, a.H) != max(b.W, b.H) {
return max(a.W, a.H) > max(b.W, b.H)
}
if a.W*a.H != b.W*b.H {
return a.W*a.H > b.W*b.H
}
return a.ID < b.ID
})
sheetW := pow2floor(minInt(minSheet, maxWidth))
sheetH := pow2floor(minInt(minSheet, maxHeight))
for {
placed, failed := tryPack(order, sheetW, sheetH, opts.AllowRotate)
if failed == "" {
return finish(sizes, placed), nil
}
nextW, nextH := sheetW, sheetH
if sheetW <= sheetH {
nextW = sheetW * 2
} else {
nextH = sheetH * 2
}
if nextW > maxWidth || nextH > maxHeight {
return PackResult{}, &PackError{CodeOverflow, fmt.Sprintf(
"%q does not fit within %d×%d — split the batch or raise the cap.", failed, maxWidth, maxHeight)}
}
sheetW, sheetH = nextW, nextH
}
}
// tryPack is one MaxRects pass over a fixed candidate sheet: all rects, or
// the first id that failed.
func tryPack(order []SpriteSize, w, h int, allowRotate bool) ([]PackedRect, string) {
free := []freeRect{{0, 0, w, h}}
placed := make([]PackedRect, 0, len(order))
for _, s := range order {
f, fw, fh, rotated, ok := bestFit(free, s, allowRotate)
if !ok {
return nil, s.ID
}
rect := PackedRect{ID: s.ID, X: f.x, Y: f.y, W: fw, H: fh, Rotated: rotated}
placed = append(placed, rect)
free = splitFree(free, rect)
}
return placed, ""
}
// bestFit is best-short-side-fit: ties broken by the long side, then by
// first-seen free rect.
func bestFit(free []freeRect, s SpriteSize, allowRotate bool) (freeRect, int, int, bool, bool) {
type fit struct {
f freeRect
w, h int
rotated bool
short, long int
}
var best *fit
cands := []struct {
w, h int
rotated bool
}{{s.W, s.H, false}}
if allowRotate && s.W != s.H {
cands = append(cands, struct {
w, h int
rotated bool
}{s.H, s.W, true})
}
for _, f := range free {
for _, c := range cands {
if c.w > f.w || c.h > f.h {
continue
}
lw, lh := f.w-c.w, f.h-c.h
short, long := lw, lh
if lh < short {
short = lh
}
if lw > long {
long = lw
}
if best == nil || short < best.short || (short == best.short && long < best.long) {
best = &fit{f, c.w, c.h, c.rotated, short, long}
}
}
}
if best == nil {
return freeRect{}, 0, 0, false, false
}
return best.f, best.w, best.h, best.rotated, true
}
// splitFree carves the placed rect out of every free rect it touches, then
// prunes contained ones (the j<i clause keeps exactly one of an identical pair).
func splitFree(free []freeRect, p PackedRect) []freeRect {
next := []freeRect{}
for _, f := range free {
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 = append(next, f)
continue
}
if p.X > f.x {
next = append(next, freeRect{f.x, f.y, p.X - f.x, f.h})
}
if p.X+p.W < f.x+f.w {
next = append(next, freeRect{p.X + p.W, f.y, f.x + f.w - (p.X + p.W), f.h})
}
if p.Y > f.y {
next = append(next, freeRect{f.x, f.y, f.w, p.Y - f.y})
}
if p.Y+p.H < f.y+f.h {
next = append(next, freeRect{f.x, p.Y + p.H, f.w, f.y + f.h - (p.Y + p.H)})
}
}
out := make([]freeRect, 0, len(next))
for i, a := range next {
keep := true
for j, b := range next {
if j != i && containsRect(b, a) && !(containsRect(a, b) && j > i) {
keep = false
break
}
}
if keep {
out = append(out, a)
}
}
return out
}
func containsRect(outer, inner freeRect) bool {
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
}
// finish reorders to input order and rounds the bounding box up to
// power-of-two sheet dims.
func finish(sizes []SpriteSize, placed []PackedRect) PackResult {
byID := map[string]PackedRect{}
bw, bh := 1, 1
for _, p := range placed {
byID[p.ID] = p
if p.X+p.W > bw {
bw = p.X + p.W
}
if p.Y+p.H > bh {
bh = p.Y + p.H
}
}
rects := make([]PackedRect, 0, len(sizes))
for _, s := range sizes {
rects = append(rects, byID[s.ID])
}
return PackResult{SheetW: pow2ceil(bw), SheetH: pow2ceil(bh), Rects: rects}
}
func pow2ceil(n int) int {
p := 1
for p < n {
p *= 2
}
return p
}
func pow2floor(n int) int {
p := 1
for p*2 <= n {
p *= 2
}
return p
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
// AtlasJSON renders the generic JSON atlas: one frame entry per sprite, sheet
// metadata for engines. The frames object is assembled manually so entries
// stay in pack-input order (a Go map would scramble the keys).
func AtlasJSON(name string, r PackResult) string {
type frameXY struct {
X int `json:"x"`
Y int `json:"y"`
W int `json:"w"`
H int `json:"h"`
}
type frameEntry struct {
Frame frameXY `json:"frame"`
Rotated bool `json:"rotated"`
}
var meta struct {
Size struct {
W int `json:"w"`
H int `json:"h"`
} `json:"size"`
Name string `json:"name"`
}
meta.Size.W, meta.Size.H = r.SheetW, r.SheetH
meta.Name = name
metaBytes, _ := json.Marshal(meta)
parts := make([]string, 0, len(r.Rects))
for _, rect := range r.Rects {
entry, _ := json.Marshal(frameEntry{FrameXY{rect.X, rect.Y, rect.W, rect.H}, rect.Rotated})
key, _ := json.Marshal(rect.ID)
parts = append(parts, "\n "+string(key)+": "+string(entry))
}
return "{\n \"frames\": {" + strings.Join(parts, ",") + "\n },\n \"meta\": " + string(metaBytes) + "\n}"
}
// SpriteCSS emits one .sprite-<id> class per rect, positioned against the
// shared sheet image.
func SpriteCSS(r PackResult, sheetName string) string {
var b strings.Builder
for i, rect := range r.Rects {
if i > 0 {
b.WriteString("\n")
}
fmt.Fprintf(&b, ".sprite-%s {\n width: %dpx;\n height: %dpx;\n background-image: url('%s');\n background-position: -%dpx -%dpx;\n}",
rect.ID, rect.W, rect.H, sheetName, rect.X, rect.Y)
}
return b.String()
}
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 →