A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file Texture-atlas packer for the asset cook. Pure and deterministic: the
* same inputs produce byte-identical pages, so atlas packing composes
* with content-addressed staging. Shelf packing over height-sorted
* input; images that overflow one page spill onto the next.
*
* The pack core is dependency-free (raw RGBA in, raw RGBA out); PNG decode/
* encode live in thin wrappers so the algorithm stays unit-testable without
* pixel fixtures.
*/
import { PNG } from 'pngjs';
import { ShelfPacker } from '../../../sdk/src/util/shelfPack';
import { downscaledSize } from './textureCookDecision';
export interface AtlasInputImage {
/** Stable identity (the project-relative texture path). */
key: string;
width: number;
height: number;
/** RGBA8, width*height*4 bytes, row 0 = image top. */
rgba: Uint8Array;
}
export interface AtlasPlacement {
key: string;
/** Pixel rect inside the page, y from the page TOP (image space). */
x: number;
y: number;
width: number;
height: number;
}
export interface AtlasPage {
width: number;
height: number;
placements: AtlasPlacement[];
/** Composed RGBA8 page pixels (row 0 = top). */
rgba: Uint8Array;
}
export interface PackOptions {
/** Page dimension cap (default 2048). */
maxSize?: number;
/** Transparent gutter around each image, defends linear-filter bleed (default 2). */
padding?: number;
}
/**
* Shelf-pack `sorted` into one width×height page; null when anything overflows.
* All-or-nothing: the caller grows the page and asks again. Placement is
* util/shelfPack, the packer the runtime glyph atlas fills too.
*/
function tryPackPage(
sorted: AtlasInputImage[],
width: number,
height: number,
padding: number,
): AtlasPlacement[] | null {
const packer = new ShelfPacker(width, height);
const placements: AtlasPlacement[] = [];
for (const img of sorted) {
const pos = packer.pack(img.width + padding * 2, img.height + padding * 2);
if (!pos) return null;
placements.push({
key: img.key,
x: pos.x + padding,
y: pos.y + padding,
width: img.width,
height: img.height,
});
}
return placements;
}
/** Smallest power of two ≥ n (n ≥ 1). */
function nextPow2(n: number): number {
let p = 1;
while (p < n) p *= 2;
return p;
}
function composePage(images: Map<string, AtlasInputImage>, placements: AtlasPlacement[], width: number, height: number): AtlasPage {
const rgba = new Uint8Array(width * height * 4);
for (const p of placements) {
const img = images.get(p.key)!;
for (let row = 0; row < p.height; row++) {
const src = row * img.width * 4;
const dst = ((p.y + row) * width + p.x) * 4;
rgba.set(img.rgba.subarray(src, src + p.width * 4), dst);
}
}
return { width, height, placements, rgba };
}
/**
* Pack images into as few pages as possible. Pages are square powers of two:
* the smallest that fits everything remaining, capped at maxSize; when even a
* maxSize page cannot hold all remaining images it takes as many as fit (in
* order) and the rest spill onto the next page. Input order does not matter —
* images are sorted (height desc, then key) for deterministic, well-packed
* output.
*/
export function packAtlas(images: AtlasInputImage[], options: PackOptions = {}): AtlasPage[] {
const maxSize = options.maxSize ?? 2048;
const padding = options.padding ?? 2;
const byKey = new Map(images.map((i) => [i.key, i]));
if (byKey.size !== images.length) throw new Error('packAtlas: duplicate image keys');
let remaining = [...images].sort((a, b) => (b.height - a.height) || a.key.localeCompare(b.key));
for (const img of remaining) {
const needed = Math.max(img.width, img.height) + padding * 2;
if (needed > maxSize) {
throw new Error(`packAtlas: '${img.key}' (${img.width}x${img.height}) exceeds the ${maxSize} page cap`);
}
}
const pages: AtlasPage[] = [];
while (remaining.length > 0) {
// Grow a square page until everything remaining fits (or we hit the cap).
let size = nextPow2(Math.max(
remaining[0].height + padding * 2,
Math.max(...remaining.map((i) => i.width)) + padding * 2,
));
let placements: AtlasPlacement[] | null = null;
while (size <= maxSize) {
placements = tryPackPage(remaining, size, size, padding);
if (placements) break;
size *= 2;
}
if (placements) {
pages.push(composePage(byKey, placements, size, size));
remaining = [];
break;
}
// Even maxSize can't hold everything: fill one maxSize page greedily
// (prefix of the sorted order that fits), spill the rest.
const taken: AtlasInputImage[] = [];
const spill: AtlasInputImage[] = [];
for (const img of remaining) {
const attempt = tryPackPage([...taken, img], maxSize, maxSize, padding);
if (attempt) taken.push(img);
else spill.push(img);
}
pages.push(composePage(byKey, tryPackPage(taken, maxSize, maxSize, padding)!, maxSize, maxSize));
remaining = spill;
}
return pages;
}
/** Decode a PNG into the packer's input shape. */
export function decodePngImage(key: string, png: Uint8Array): AtlasInputImage {
const decoded = PNG.sync.read(Buffer.from(png));
return { key, width: decoded.width, height: decoded.height, rgba: new Uint8Array(decoded.data) };
}
/** Encode raw RGBA8 (row 0 = top) to PNG bytes. */
export function encodeRgbaPng(width: number, height: number, rgba: Uint8Array): Uint8Array {
const png = new PNG({ width, height });
Buffer.from(rgba).copy(png.data);
return new Uint8Array(PNG.sync.write(png));
}
/** Encode a composed page back to PNG bytes. */
export function encodePagePng(page: AtlasPage): Uint8Array {
return encodeRgbaPng(page.width, page.height, page.rgba);
}
/**
* Box-filter downscale so max(width, height) ≤ `maxDim`. Returns the input
* unchanged when already within the cap. Averages in premultiplied-alpha space
* (color weighted by coverage) so transparent pixels don't bleed dark fringes
* into the shrunk result. Pure + deterministic — composes with content-addressed
* staging exactly like the packer.
*/
/**
* The size a Max Size cap gives an image, without decoding it.
*
* Block alignment is judged on the ENCODED size, so predicting what a build does
* to a texture needs this number rather than the source's — from the same
* arithmetic the resize uses, or the prediction is right until a rounding case.
*/
export function downscaleRgba(img: AtlasInputImage, maxDim: number): AtlasInputImage {
const longest = Math.max(img.width, img.height);
if (!(maxDim > 0) || longest <= maxDim) return img;
const { width: nw, height: nh } = downscaledSize(img.width, img.height, maxDim);
const out = new Uint8Array(nw * nh * 4);
for (let y = 0; y < nh; y++) {
const sy0 = Math.floor((y * img.height) / nh);
const sy1 = Math.max(sy0 + 1, Math.floor(((y + 1) * img.height) / nh));
for (let x = 0; x < nw; x++) {
const sx0 = Math.floor((x * img.width) / nw);
const sx1 = Math.max(sx0 + 1, Math.floor(((x + 1) * img.width) / nw));
let r = 0, g = 0, b = 0, a = 0, n = 0;
// the colour with no weight: what a footprint that is clear all through is averaged by
let r0 = 0, g0 = 0, b0 = 0;
for (let sy = sy0; sy < sy1; sy++) {
for (let sx = sx0; sx < sx1; sx++) {
const i = (sy * img.width + sx) * 4;
const al = img.rgba[i + 3];
r += img.rgba[i] * al; g += img.rgba[i + 1] * al; b += img.rgba[i + 2] * al;
r0 += img.rgba[i]; g0 += img.rgba[i + 1]; b0 += img.rgba[i + 2];
a += al; n++;
}
}
const o = (y * nw + x) * 4;
// Weighted by coverage, so a clear texel does not dull the ones it is averaged with; and where all of them are clear, the plain mean rather than black,
// since a texture that holds numbers in its colour under a clear alpha (a weight map) has them there.
out[o] = Math.round(a > 0 ? r / a : r0 / n);
out[o + 1] = Math.round(a > 0 ? g / a : g0 / n);
out[o + 2] = Math.round(a > 0 ? b / a : b0 / n);
out[o + 3] = Math.round(a / n);
}
}
return { key: img.key, width: nw, height: nh, rgba: out };
}