Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(kiln/sprite-atlas): shelf-packed sprite atlas + JSON frame table

Matt Kissinger51b71729a756
diff --git a/index.ts b/index.ts
index 86b2a2cb..f57df873 100644
--- a/index.ts
+++ b/index.ts
@@ -135,6 +135,23 @@ export type {
LODLevel,
} from './lod';
+// -----------------------------------------------------------------------------
+// Sprite atlas packer (kiln/sprite-atlas)
+// -----------------------------------------------------------------------------
+export { packSpriteAtlas } from './sprite-atlas';
+export type {
+ PackSpriteAtlasInput,
+ PackSpriteAtlasOptions,
+ PackSpriteAtlasResult,
+ SpriteFrame,
+ SpriteFrameTable,
+} from './sprite-atlas';
+export {
+ SPRITE_ATLAS_SCHEMA_VERSION,
+ SpriteFrameSchema,
+ SpriteFrameTableSchema,
+} from './sprite-atlas';
+
// -----------------------------------------------------------------------------
// Imposter baker (kiln/imposter)
// -----------------------------------------------------------------------------
diff --git a/sprite-atlas/__tests__/pack.test.ts b/sprite-atlas/__tests__/pack.test.ts
new file mode 100644
index 00000000..bb1be84f
--- /dev/null
+++ b/sprite-atlas/__tests__/pack.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Sprite atlas packer tests — generates RGBA fixtures via sharp, then verifies
+ * frame placement, overlap, and POT sizing.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { Buffer } from 'node:buffer';
+import sharp from 'sharp';
+
+import { packSpriteAtlas } from '../pack';
+import { SpriteFrameTableSchema } from '../schema';
+
+async function solid(w: number, h: number, rgb: [number, number, number]): Promise<Buffer> {
+ return sharp({
+ create: {
+ width: w,
+ height: h,
+ channels: 4,
+ background: { r: rgb[0], g: rgb[1], b: rgb[2], alpha: 1 },
+ },
+ })
+ .png()
+ .toBuffer();
+}
+
+describe('packSpriteAtlas', () => {
+ test('packs 10 equal-size sprites with no overlap', async () => {
+ const sprites = await Promise.all(
+ Array.from({ length: 10 }, async (_unused, i) => ({
+ name: `sprite-${i}`,
+ data: await solid(32, 32, [i * 20, 80, 200]),
+ })),
+ );
+ const result = await packSpriteAtlas(sprites, { padding: 2, pot: true });
+
+ expect(result.frames.frames).toHaveLength(10);
+ expect(() => SpriteFrameTableSchema.parse(result.frames)).not.toThrow();
+
+ // Atlas is a valid PNG.
+ expect(result.atlas.subarray(0, 4).toString('hex')).toBe('89504e47');
+
+ // No two frames overlap.
+ const fs = result.frames.frames;
+ for (let i = 0; i < fs.length; i++) {
+ for (let j = i + 1; j < fs.length; j++) {
+ const a = fs[i]!;
+ const b = fs[j]!;
+ const overlap = !(a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y);
+ expect(overlap).toBe(false);
+ }
+ }
+
+ // All frames fit inside the atlas.
+ for (const f of fs) {
+ expect(f.x + f.w).toBeLessThanOrEqual(result.frames.atlasWidth);
+ expect(f.y + f.h).toBeLessThanOrEqual(result.frames.atlasHeight);
+ }
+
+ // Atlas is power-of-two.
+ expect(isPot(result.frames.atlasWidth)).toBe(true);
+ expect(isPot(result.frames.atlasHeight)).toBe(true);
+ });
+
+ test('preserves input order in the frame table', async () => {
+ const sprites = [
+ { name: 'tall', data: await solid(16, 64, [255, 0, 0]) },
+ { name: 'wide', data: await solid(128, 16, [0, 255, 0]) },
+ { name: 'small', data: await solid(8, 8, [0, 0, 255]) },
+ ];
+ const result = await packSpriteAtlas(sprites);
+ expect(result.frames.frames.map((f) => f.name)).toEqual(['tall', 'wide', 'small']);
+ });
+
+ test('respects maxSize — throws when nothing fits', async () => {
+ await expect(
+ packSpriteAtlas([{ name: 'giant', data: await solid(512, 512, [0, 0, 0]) }], {
+ maxSize: 1024,
+ padding: 0,
+ pot: false,
+ }),
+ ).resolves.toBeTruthy();
+ await expect(
+ packSpriteAtlas(
+ [
+ { name: 'a', data: await solid(900, 900, [0, 0, 0]) },
+ { name: 'b', data: await solid(900, 900, [0, 0, 0]) },
+ ],
+ { maxSize: 1024, padding: 0, pot: false },
+ ),
+ ).rejects.toThrow(/ran out of atlas room/);
+ });
+
+ test('rejects a sprite larger than maxSize', async () => {
+ await expect(
+ packSpriteAtlas([{ name: 'huge', data: await solid(600, 600, [0, 0, 0]) }], {
+ maxSize: 1024,
+ padding: 0,
+ pot: false,
+ }),
+ ).resolves.toBeTruthy();
+ await expect(
+ packSpriteAtlas([{ name: 'huge', data: await solid(1200, 1200, [0, 0, 0]) }], {
+ maxSize: 1024,
+ }),
+ ).rejects.toThrow(/larger than maxSize/);
+ });
+
+ test('padding increases spacing between frames', async () => {
+ const sprites = [
+ { name: 'a', data: await solid(32, 32, [255, 0, 0]) },
+ { name: 'b', data: await solid(32, 32, [0, 255, 0]) },
+ ];
+ const noPad = await packSpriteAtlas(sprites, { padding: 0, pot: false });
+ const padded = await packSpriteAtlas(sprites, { padding: 8, pot: false });
+ const gapNo = noPad.frames.frames[1]!.x - (noPad.frames.frames[0]!.x + noPad.frames.frames[0]!.w);
+ const gapPad = padded.frames.frames[1]!.x - (padded.frames.frames[0]!.x + padded.frames.frames[0]!.w);
+ expect(gapPad).toBeGreaterThan(gapNo);
+ });
+});
+
+function isPot(n: number): boolean {
+ return n > 0 && (n & (n - 1)) === 0;
+}
diff --git a/sprite-atlas/index.ts b/sprite-atlas/index.ts
new file mode 100644
index 00000000..77cd567a
--- /dev/null
+++ b/sprite-atlas/index.ts
@@ -0,0 +1,23 @@
+/**
+ * kiln/sprite-atlas — shelf-packed sprite atlases with JSON frame tables.
+ *
+ * import { kiln } from '@pixel-forge/core';
+ * const { atlas, frames } = await kiln.packSpriteAtlas(
+ * [{ name: 'fern-01', data: pngBuf }, ...],
+ * { maxSize: 2048, padding: 2, pot: true }
+ * );
+ */
+
+export { packSpriteAtlas } from './pack';
+export type {
+ PackSpriteAtlasInput,
+ PackSpriteAtlasOptions,
+ PackSpriteAtlasResult,
+} from './pack';
+
+export {
+ SPRITE_ATLAS_SCHEMA_VERSION,
+ SpriteFrameSchema,
+ SpriteFrameTableSchema,
+} from './schema';
+export type { SpriteFrame, SpriteFrameTable } from './schema';
diff --git a/sprite-atlas/pack.ts b/sprite-atlas/pack.ts
new file mode 100644
index 00000000..ac09db0d
--- /dev/null
+++ b/sprite-atlas/pack.ts
@@ -0,0 +1,169 @@
+/**
+ * Sprite atlas packer — shelf algorithm.
+ *
+ * Sorts sprites by descending height, places them in horizontal shelves
+ * (rows). Not the densest packing possible (MaxRects would be ~10% tighter),
+ * but simple, deterministic, and fast. For <500 sprites at typical game-asset
+ * sizes this leaves plenty of atlas headroom.
+ *
+ * Output is a single RGBA PNG plus a JSON frame table.
+ */
+
+import { Buffer } from 'node:buffer';
+import sharp from 'sharp';
+
+import {
+ SPRITE_ATLAS_SCHEMA_VERSION,
+ type SpriteFrame,
+ type SpriteFrameTable,
+} from './schema';
+
+export interface PackSpriteAtlasInput {
+ /** Species / asset name — preserved into the frame table. */
+ name: string;
+ /** PNG or other sharp-readable bytes. */
+ data: Buffer;
+}
+
+export interface PackSpriteAtlasOptions {
+ /** Maximum atlas edge in pixels. Default 2048. */
+ maxSize?: 1024 | 2048 | 4096;
+ /** Transparent pixels between packed sprites. Default 2. */
+ padding?: number;
+ /** Force the final atlas to power-of-two dimensions. Default true. */
+ pot?: boolean;
+}
+
+export interface PackSpriteAtlasResult {
+ atlas: Buffer;
+ frames: SpriteFrameTable;
+}
+
+interface Prepared {
+ name: string;
+ buf: Buffer;
+ w: number;
+ h: number;
+ sourceWidth: number;
+ sourceHeight: number;
+}
+
+interface Placed extends Prepared {
+ x: number;
+ y: number;
+}
+
+export async function packSpriteAtlas(
+ sprites: PackSpriteAtlasInput[],
+ opts: PackSpriteAtlasOptions = {},
+): Promise<PackSpriteAtlasResult> {
+ if (!sprites.length) {
+ throw new Error('packSpriteAtlas: at least one sprite is required');
+ }
+ const maxSize = opts.maxSize ?? 2048;
+ const padding = opts.padding ?? 2;
+ const pot = opts.pot ?? true;
+
+ // Normalize input PNGs through sharp so downstream composite treats them uniformly.
+ const prepared: Prepared[] = await Promise.all(
+ sprites.map(async (s): Promise<Prepared> => {
+ const { data, info } = await sharp(s.data).ensureAlpha().toBuffer({ resolveWithObject: true });
+ return {
+ name: s.name,
+ buf: data,
+ w: info.width,
+ h: info.height,
+ sourceWidth: info.width,
+ sourceHeight: info.height,
+ };
+ }),
+ );
+
+ // Sort by height descending — standard shelf heuristic.
+ const sorted = prepared.slice().sort((a, b) => b.h - a.h);
+
+ // Shelf-pack.
+ const placed: Placed[] = [];
+ let shelfX = 0;
+ let shelfY = 0;
+ let shelfH = 0;
+ let atlasW = 0;
+ for (const s of sorted) {
+ const w = s.w + padding * 2;
+ const h = s.h + padding * 2;
+ if (w > maxSize || h > maxSize) {
+ throw new Error(
+ `packSpriteAtlas: sprite "${s.name}" (${s.w}×${s.h}) larger than maxSize ${maxSize}`,
+ );
+ }
+ if (shelfX + w > maxSize) {
+ shelfY += shelfH;
+ shelfX = 0;
+ shelfH = 0;
+ }
+ if (shelfY + h > maxSize) {
+ throw new Error(
+ `packSpriteAtlas: ran out of atlas room at sprite "${s.name}". ` +
+ `Increase maxSize (currently ${maxSize}) or split the input.`,
+ );
+ }
+ placed.push({ ...s, x: shelfX + padding, y: shelfY + padding });
+ shelfX += w;
+ shelfH = Math.max(shelfH, h);
+ atlasW = Math.max(atlasW, shelfX);
+ }
+ const atlasH = shelfY + shelfH;
+
+ const finalW = pot ? nextPot(atlasW) : atlasW;
+ const finalH = pot ? nextPot(atlasH) : atlasH;
+
+ const composites: sharp.OverlayOptions[] = placed.map((p) => ({
+ input: p.buf,
+ left: p.x,
+ top: p.y,
+ }));
+ const atlas = await sharp({
+ create: {
+ width: finalW,
+ height: finalH,
+ channels: 4,
+ background: { r: 0, g: 0, b: 0, alpha: 0 },
+ },
+ })
+ .composite(composites)
+ .png()
+ .toBuffer();
+
+ // Build the frame table in the INPUT order (not the packed order).
+ const byName = new Map(placed.map((p) => [p.name, p]));
+ const frames: SpriteFrame[] = sprites.map((s) => {
+ const p = byName.get(s.name);
+ if (!p) throw new Error(`packSpriteAtlas: missing placement for "${s.name}"`);
+ return {
+ name: s.name,
+ x: p.x,
+ y: p.y,
+ w: p.w,
+ h: p.h,
+ sourceWidth: p.sourceWidth,
+ sourceHeight: p.sourceHeight,
+ };
+ });
+
+ return {
+ atlas,
+ frames: {
+ version: SPRITE_ATLAS_SCHEMA_VERSION,
+ atlasWidth: finalW,
+ atlasHeight: finalH,
+ padding,
+ frames,
+ },
+ };
+}
+
+function nextPot(n: number): number {
+ let p = 1;
+ while (p < n) p *= 2;
+ return p;
+}
diff --git a/sprite-atlas/schema.ts b/sprite-atlas/schema.ts
new file mode 100644
index 00000000..1223a27c
--- /dev/null
+++ b/sprite-atlas/schema.ts
@@ -0,0 +1,37 @@
+/**
+ * SpriteFrameTable — sidecar emitted alongside a packed sprite atlas.
+ *
+ * TIJ's GPUBillboardSystem reads either (frame) to render a single species
+ * or the full table to pick tiles by species name at runtime.
+ */
+
+import { z } from 'zod';
+
+export const SPRITE_ATLAS_SCHEMA_VERSION = 1 as const;
+
+export const SpriteFrameSchema = z.object({
+ /** Species / asset name, matches the input entry. */
+ name: z.string(),
+ /** Top-left x in atlas pixels. */
+ x: z.number().int().nonnegative(),
+ /** Top-left y in atlas pixels. */
+ y: z.number().int().nonnegative(),
+ /** Width in atlas pixels (post-trim if trimming was enabled). */
+ w: z.number().int().positive(),
+ /** Height in atlas pixels. */
+ h: z.number().int().positive(),
+ /** Original (un-trimmed) width, useful for restoring layout on the consumer. */
+ sourceWidth: z.number().int().positive(),
+ /** Original un-trimmed height. */
+ sourceHeight: z.number().int().positive(),
+});
+export type SpriteFrame = z.infer<typeof SpriteFrameSchema>;
+
+export const SpriteFrameTableSchema = z.object({
+ version: z.literal(SPRITE_ATLAS_SCHEMA_VERSION),
+ atlasWidth: z.number().int().positive(),
+ atlasHeight: z.number().int().positive(),
+ padding: z.number().int().nonnegative(),
+ frames: z.array(SpriteFrameSchema),
+});
+export type SpriteFrameTable = z.infer<typeof SpriteFrameTableSchema>;