Skip to content

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.

refactor(assets): one packer, and packing declared like delivery is

esengine6d6739257e76
diff --git a/desktop/electron/atlasPacker.ts b/desktop/electron/atlasPacker.ts
index 928698497..9e56302c8 100644
--- a/desktop/electron/atlasPacker.ts
+++ b/desktop/electron/atlasPacker.ts
@@ -11,6 +11,7 @@
* pixel fixtures.
*/
import { PNG } from 'pngjs';
+import { ShelfPacker } from '../../sdk/src/util/shelfPack';
export interface AtlasInputImage {
/** Stable identity (the project-relative texture path). */
@@ -45,37 +46,29 @@ export interface PackOptions {
padding?: number;
}
-interface Shelf { y: number; height: number; x: number; }
-
-/** Shelf-pack `sorted` into one width×height page; null when anything overflows. */
+/**
+ * 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 shelves: Shelf[] = [];
- let yCursor = 0;
+ const packer = new ShelfPacker(width, height);
const placements: AtlasPlacement[] = [];
for (const img of sorted) {
- const w = img.width + padding * 2;
- const h = img.height + padding * 2;
- if (w > width || h > height) return null;
- let placed = false;
- for (const shelf of shelves) {
- if (h <= shelf.height && shelf.x + w <= width) {
- placements.push({ key: img.key, x: shelf.x + padding, y: shelf.y + padding, width: img.width, height: img.height });
- shelf.x += w;
- placed = true;
- break;
- }
- }
- if (!placed) {
- if (yCursor + h > height) return null;
- shelves.push({ y: yCursor, height: h, x: w });
- placements.push({ key: img.key, x: padding, y: yCursor + padding, width: img.width, height: img.height });
- yCursor += h;
- }
+ 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;
}
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 5bcfdbf89..8f29883ef 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -32,7 +32,7 @@ import { contentHashHex } from '../../sdk/src/asset/contentHash';
import { resolveRelativePath } from '../../sdk/src/tilemap/tiledPath';
// Single source for the folder→delivery-group model, shared with the editor Play
// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.
-import { resolveAssetGroup, type AssetGroupsConfig } from '../../sdk/src/asset/assetGroups';
+import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../sdk/src/asset/assetGroups';
import type { BundleMode } from '../../sdk/src/asset/AddressableManifest';
const MANIFEST = 'assets.manifest.json';
@@ -81,7 +81,8 @@ export interface CookManifestEntry extends AssetEntry {
* at the PAGE file (URL-level redirect for free) and this records where the
* original image sits inside it. Frame pixels are in image space (y from the
* page top); the runtime catalog derives uvOffset/uvScale from frame + page
- * size. Produced by the `<name>.atlas/` folder convention.
+ * size. Membership comes from {@link resolveAtlas} — a declared atlas or the
+ * `<name>.atlas/` folder convention.
*/
atlas?: {
page: number;
@@ -91,23 +92,6 @@ export interface CookManifestEntry extends AssetEntry {
};
}
-/**
- * Folder-convention atlas detection: a PNG under a `<name>.atlas/` directory is
- * packed into that directory's atlas. Returns the directory path (the atlas's
- * identity — same-named dirs elsewhere are distinct atlases) or null.
- */
-const ATLAS_DIR_RE = /^(.*?(?:^|\/)[^/]+\.atlas)\//;
-export function atlasDirOf(projectRelPath: string): string | null {
- const m = ATLAS_DIR_RE.exec(projectRelPath.replace(/\\/g, '/'));
- return m ? m[1] : null;
-}
-
-/**
- * Folder-convention subpackage detection: an asset under `subpackages/<name>/…`
- * belongs to lazy group `<name>`. Returns null for main-package assets. The
- * single source of truth for the grouping — cook (here), export layout, and the
- * manifest all derive from it.
- */
/**
* Load the project's asset-delivery config (`.esengine/asset-groups.json`) — the
* single authored source for which folders ship as remote (CDN) / subpackage
@@ -394,7 +378,7 @@ export async function cookAssets(
const entry = byUuid.get(uuid);
if (!entry || entry.type === 'scene') continue;
if (path.extname(entry.path).toLowerCase() !== '.png') continue;
- const dir = atlasDirOf(entry.path);
+ const dir = resolveAtlas(entry.path, groupsConfig)?.name ?? null;
if (!dir) continue;
let list = groups.get(dir);
if (!list) groups.set(dir, (list = []));
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c4c31e4e1..3f08779bc 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1484 stable · 17 beta · 1 deprecated
+Symbols: 1487 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -621,6 +621,7 @@ typeof ASSET_GROUP_MODES[number]
## AssetGroupsConfig — interface
```
activeProfile: string | undefined
+atlases: Record<string, AtlasDef> | undefined
groups: Record<string, AssetGroupDef> | undefined
profiles: Record<string, BuildProfile> | undefined
version: string
@@ -705,6 +706,11 @@ static new <T>(dispose_?: ((value: T) => void) | undefined): AsyncCache<T>
static prototype: AsyncCache<any>
```
+## AtlasDef — interface
+```
+folder: string
+```
+
## AttenuationModel — enum
```
Exponential = 2
@@ -5995,6 +6001,12 @@ delivery: BundleMode
name: string
```
+## ResolvedAtlas — interface
+```
+folder: string
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -10729,6 +10741,11 @@ ReplicationPlugin
(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
```
+## resolveAtlas — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAtlas | null
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 7e64dfe56..821c5930a 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1503 stable · 22 beta · 1 deprecated
+Symbols: 1506 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -621,6 +621,7 @@ typeof ASSET_GROUP_MODES[number]
## AssetGroupsConfig — interface
```
activeProfile: string | undefined
+atlases: Record<string, AtlasDef> | undefined
groups: Record<string, AssetGroupDef> | undefined
profiles: Record<string, BuildProfile> | undefined
version: string
@@ -705,6 +706,11 @@ static new <T>(dispose_?: ((value: T) => void) | undefined): AsyncCache<T>
static prototype: AsyncCache<any>
```
+## AtlasDef — interface
+```
+folder: string
+```
+
## AttenuationModel — enum
```
Exponential = 2
@@ -6188,6 +6194,12 @@ delivery: BundleMode
name: string
```
+## ResolvedAtlas — interface
+```
+folder: string
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -10972,6 +10984,11 @@ ReplicationPlugin
(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
```
+## resolveAtlas — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAtlas | null
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 041acfeae..4b25237d6 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1483 stable · 19 beta · 1 deprecated
+Symbols: 1486 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -616,6 +616,7 @@ typeof ASSET_GROUP_MODES[number]
## AssetGroupsConfig — interface
```
activeProfile: string | undefined
+atlases: Record<string, AtlasDef> | undefined
groups: Record<string, AssetGroupDef> | undefined
profiles: Record<string, BuildProfile> | undefined
version: string
@@ -700,6 +701,11 @@ static new <T>(dispose_?: ((value: T) => void) | undefined): AsyncCache<T>
static prototype: AsyncCache<any>
```
+## AtlasDef — interface
+```
+folder: string
+```
+
## AttenuationModel — enum
```
Exponential = 2
@@ -5990,6 +5996,12 @@ delivery: BundleMode
name: string
```
+## ResolvedAtlas — interface
+```
+folder: string
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -10734,6 +10746,11 @@ ReplicationPlugin
(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
```
+## resolveAtlas — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAtlas | null
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 3b4e5eaf1..eda685b2c 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1504 stable · 17 beta · 1 deprecated
+Symbols: 1507 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -616,6 +616,7 @@ typeof ASSET_GROUP_MODES[number]
## AssetGroupsConfig — interface
```
activeProfile: string | undefined
+atlases: Record<string, AtlasDef> | undefined
groups: Record<string, AssetGroupDef> | undefined
profiles: Record<string, BuildProfile> | undefined
version: string
@@ -700,6 +701,11 @@ static new <T>(dispose_?: ((value: T) => void) | undefined): AsyncCache<T>
static prototype: AsyncCache<any>
```
+## AtlasDef — interface
+```
+folder: string
+```
+
## AttenuationModel — enum
```
Exponential = 2
@@ -6235,6 +6241,12 @@ delivery: BundleMode
name: string
```
+## ResolvedAtlas — interface
+```
+folder: string
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -10984,6 +10996,11 @@ ReplicationPlugin
(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
```
+## resolveAtlas — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAtlas | null
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1241d9349..a13436261 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1494 stable · 17 beta · 1 deprecated
+Symbols: 1497 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -616,6 +616,7 @@ typeof ASSET_GROUP_MODES[number]
## AssetGroupsConfig — interface
```
activeProfile: string | undefined
+atlases: Record<string, AtlasDef> | undefined
groups: Record<string, AssetGroupDef> | undefined
profiles: Record<string, BuildProfile> | undefined
version: string
@@ -700,6 +701,11 @@ static new <T>(dispose_?: ((value: T) => void) | undefined): AsyncCache<T>
static prototype: AsyncCache<any>
```
+## AtlasDef — interface
+```
+folder: string
+```
+
## AttenuationModel — enum
```
Exponential = 2
@@ -5997,6 +6003,12 @@ delivery: BundleMode
name: string
```
+## ResolvedAtlas — interface
+```
+folder: string
+name: string
+```
+
## ResolvedTileCollision — interface
```
density: number | undefined
@@ -10756,6 +10768,11 @@ ReplicationPlugin
(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAssetGroup
```
+## resolveAtlas — function
+```
+(projectRelPath: string, config: AssetGroupsConfig | null | undefined): ResolvedAtlas | null
+```
+
## resolveAutotile — function
```
(index: TerrainIndex, neighbors: readonly boolean[]): number
diff --git a/sdk/src/asset/assetGroups.ts b/sdk/src/asset/assetGroups.ts
index b4434a89c..0fd62c0d8 100644
--- a/sdk/src/asset/assetGroups.ts
+++ b/sdk/src/asset/assetGroups.ts
@@ -45,6 +45,17 @@ export interface AssetGroupDef {
alwaysInclude?: boolean;
}
+/**
+ * One authored atlas: every texture under `folder` (recursively) packs into its
+ * pages. A SEPARATE axis from a delivery group on purpose — which assets travel
+ * together and which assets share a texture page are different decisions, and an
+ * atlas may span two groups or a group hold two atlases.
+ */
+export interface AtlasDef {
+ /** Project-relative folder whose textures pack together. */
+ folder: string;
+}
+
/** A build environment's variables — currently just the CDN root remote groups
* are served from (dev vs prod differ; the export bakes the active one in). */
export interface BuildProfile {
@@ -56,6 +67,8 @@ export interface AssetGroupsConfig {
version: string;
/** groupName → definition. */
groups?: Record<string, AssetGroupDef>;
+ /** atlasName → definition. */
+ atlases?: Record<string, AtlasDef>;
/** Which profile is active for a build (key into `profiles`). */
activeProfile?: string;
profiles?: Record<string, BuildProfile>;
@@ -77,6 +90,41 @@ export function modeToDelivery(mode: AssetGroupMode): BundleMode {
const SUBPACKAGE_RE = /^subpackages\/([^/]+)\//;
const REMOTE_RE = /^remote\/([^/]+)\//;
+const ATLAS_DIR_RE = /^(.*?(?:^|\/)[^/]+\.atlas)\//;
+
+/** The atlas an asset packs into: its name (the packing identity) and folder. */
+export interface ResolvedAtlas {
+ name: string;
+ folder: string;
+}
+
+/**
+ * The atlas a texture belongs to, or null for a standalone one. Priority mirrors
+ * {@link resolveAssetGroup}: an explicit `config.atlases` entry (longest folder
+ * prefix), else the `<name>.atlas/` folder convention, whose identity is the
+ * DIRECTORY PATH so same-named dirs stay distinct atlases.
+ */
+export function resolveAtlas(
+ projectRelPath: string,
+ config: AssetGroupsConfig | null | undefined,
+): ResolvedAtlas | null {
+ const path = projectRelPath.replace(/\\/g, '/');
+
+ if (config?.atlases) {
+ let best: { name: string; folder: string; len: number } | null = null;
+ for (const [name, def] of Object.entries(config.atlases)) {
+ const folder = def.folder.replace(/\\/g, '/').replace(/\/+$/, '');
+ if (folder === '') continue;
+ if (path.startsWith(`${folder}/`)) {
+ if (!best || folder.length > best.len) best = { name, folder, len: folder.length };
+ }
+ }
+ if (best) return { name: best.name, folder: best.folder };
+ }
+
+ const dir = ATLAS_DIR_RE.exec(path);
+ return dir ? { name: dir[1], folder: dir[1] } : null;
+}
/**
* The delivery group an asset belongs to, in priority order:
diff --git a/sdk/src/asset/index.ts b/sdk/src/asset/index.ts
index 3514ab014..b0046ec65 100644
--- a/sdk/src/asset/index.ts
+++ b/sdk/src/asset/index.ts
@@ -27,6 +27,9 @@ export {
type BuildProfile,
type AssetGroupsConfig,
type ResolvedAssetGroup,
+ resolveAtlas,
+ type AtlasDef,
+ type ResolvedAtlas,
} from './assetGroups';
export { xxh64, contentHashHex, contentHashOf } from './contentHash';
export { AsyncCache } from './AsyncCache';
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 50f3f9a3c..30e4e1641 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -71,6 +71,7 @@ export {
normalizeBundleMode,
ManifestModel,
resolveAssetGroup,
+ resolveAtlas,
activeRemoteRoot,
modeToDelivery,
folderGroupMode,
@@ -81,6 +82,8 @@ export {
ASSET_GROUP_MODES,
type AssetGroupMode,
type AssetGroupDef,
+ type AtlasDef,
+ type ResolvedAtlas,
type BuildProfile,
type AssetGroupsConfig,
type ResolvedAssetGroup,
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index e49b5fd45..122c0db41 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -503,6 +503,6 @@ export {
type GlyphVertexData,
} from './text/layout';
-export { ShelfPacker, type Packer, type PackPos } from './text/atlas-packer';
+export { ShelfPacker, type Packer, type PackPos } from '../util/shelfPack';
export { sdfFromAlpha } from './text/sdf';
export { submitTextBatch, TEXT_VERTEX_FLOATS } from './text/submit';
diff --git a/sdk/src/ui/text/atlas-packer.ts b/sdk/src/ui/text/atlas-packer.ts
deleted file mode 100644
index eecdbc409..000000000
--- a/sdk/src/ui/text/atlas-packer.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-/**
- * @file ui/text/atlas-packer.ts
- * @brief Rectangle packer for the runtime dynamic glyph atlas.
- *
- * Glyphs are packed into a fixed-size atlas page incrementally as they are first
- * seen. The packer is an interface so the heuristic is swappable; the default
- * ShelfPacker (row-based) is near-optimal here because glyphs of one font-size
- * share a height (especially CJK, whose em boxes are uniform), and it inserts in
- * O(rows) with no fragmentation bookkeeping.
- */
-
-export interface PackPos {
- x: number;
- y: number;
-}
-
-export interface Packer {
- /** Page dimensions in texels. */
- readonly width: number;
- readonly height: number;
- /** Reserve a `w`×`h` cell; returns its top-left, or null if the page is full. */
- pack(w: number, h: number): PackPos | null;
- /** Drop all reservations (e.g. when rebuilding a page). */
- reset(): void;
-}
-
-/**
- * Row ("shelf") packer: fills the current row left→right, opening a new row once
- * a glyph doesn't fit horizontally. Row height grows to the tallest glyph placed
- * in it. Returns null when a glyph fits in neither the current nor a new row.
- */
-export class ShelfPacker implements Packer {
- readonly width: number;
- readonly height: number;
- private shelfX = 0;
- private shelfY = 0;
- private shelfH = 0;
-
- constructor(width: number, height: number) {
- this.width = width;
- this.height = height;
- }
-
- pack(w: number, h: number): PackPos | null {
- if (w <= 0 || h <= 0 || w > this.width || h > this.height) return null;
-
- // Wrap to a new shelf if the glyph overflows the current row width.
- if (this.shelfX + w > this.width) {
- this.shelfY += this.shelfH;
- this.shelfX = 0;
- this.shelfH = 0;
- }
-
- // Out of vertical space on this page.
- if (this.shelfY + h > this.height) return null;
-
- const pos: PackPos = { x: this.shelfX, y: this.shelfY };
- this.shelfX += w;
- if (h > this.shelfH) this.shelfH = h;
- return pos;
- }
-
- reset(): void {
- this.shelfX = 0;
- this.shelfY = 0;
- this.shelfH = 0;
- }
-}
diff --git a/sdk/src/ui/text/glyph-atlas.ts b/sdk/src/ui/text/glyph-atlas.ts
index 13a05aa80..29164725f 100644
--- a/sdk/src/ui/text/glyph-atlas.ts
+++ b/sdk/src/ui/text/glyph-atlas.ts
@@ -16,7 +16,7 @@
* `sdfRenderSize`; the display size scales the quad at draw time. The cache key
* therefore carries no display size — only (font, codepoint, style).
*/
-import { ShelfPacker, type Packer } from './atlas-packer';
+import { ShelfPacker, type Packer } from '../../util/shelfPack';
/** A glyph rendered to an upload-ready bitmap plus its layout metrics (in render-size px). */
export interface RasterGlyph {
diff --git a/sdk/src/util/shelfPack.ts b/sdk/src/util/shelfPack.ts
new file mode 100644
index 000000000..c28f0fbfd
--- /dev/null
+++ b/sdk/src/util/shelfPack.ts
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file util/shelfPack.ts
+ * @brief Rectangle packing into a fixed page — the one implementation.
+ *
+ * There were two, and they disagreed on the heuristic. The runtime glyph atlas
+ * filled ONE shelf and opened a new one when a glyph overflowed it, abandoning
+ * whatever was left of the old row; the asset cook kept every shelf and placed
+ * into the first that fit. Same idea, different quality, and the better one was
+ * the one no font ever used.
+ *
+ * Pure geometry (no pixels, no assets), so it belongs to the foundation and both
+ * callers can have it: the cook composes pages from the placements, the glyph
+ * atlas uploads into them.
+ */
+
+export interface PackPos {
+ x: number;
+ y: number;
+}
+
+export interface Packer {
+ /** Page dimensions in texels. */
+ readonly width: number;
+ readonly height: number;
+ /** Reserve a `w`×`h` cell; returns its top-left, or null if the page is full. */
+ pack(w: number, h: number): PackPos | null;
+ /** Drop all reservations (e.g. when rebuilding a page). */
+ reset(): void;
+}
+
+/** A row opened at `y`, `height` tall, filled left→right to `x`. */
+interface Shelf {
+ y: number;
+ height: number;
+ x: number;
+}
+
+/**
+ * Row ("shelf") packer with first-fit across every open row: a cell goes into
+ * the first shelf tall enough with room left, and only opens a new row when none
+ * has either. Rows keep the height of whatever opened them, so height-descending
+ * input packs tightest — which is why the cook sorts before feeding it.
+ */
+export class ShelfPacker implements Packer {
+ readonly width: number;
+ readonly height: number;
+ private shelves: Shelf[] = [];
+ private yCursor = 0;
+
+ constructor(width: number, height: number) {
+ this.width = width;
+ this.height = height;
+ }
+
+ pack(w: number, h: number): PackPos | null {
+ if (w <= 0 || h <= 0 || w > this.width || h > this.height) return null;
+
+ for (const shelf of this.shelves) {
+ if (h <= shelf.height && shelf.x + w <= this.width) {
+ const pos: PackPos = { x: shelf.x, y: shelf.y };
+ shelf.x += w;
+ return pos;
+ }
+ }
+ if (this.yCursor + h > this.height) return null;
+ const pos: PackPos = { x: 0, y: this.yCursor };
+ this.shelves.push({ y: this.yCursor, height: h, x: w });
+ this.yCursor += h;
+ return pos;
+ }
+
+ reset(): void {
+ this.shelves = [];
+ this.yCursor = 0;
+ }
+}
diff --git a/sdk/tests/asset-groups.test.ts b/sdk/tests/asset-groups.test.ts
index cf4a7b4de..fa43df214 100644
--- a/sdk/tests/asset-groups.test.ts
+++ b/sdk/tests/asset-groups.test.ts
@@ -3,6 +3,7 @@
import { describe, it, expect } from 'vitest';
import {
resolveAssetGroup,
+ resolveAtlas,
activeRemoteRoot,
modeToDelivery,
folderGroupMode,
@@ -162,3 +163,40 @@ describe('activeRemoteRoot', () => {
expect(resolveAssetGroup('assets/plain/hero.png', cfg).alwaysInclude).toBe(false);
});
});
+
+describe('resolveAtlas — packing is its own axis, declared or by folder', () => {
+ const config: AssetGroupsConfig = {
+ version: '1.0',
+ groups: { cdn: { folder: 'assets/art', mode: 'remote' } },
+ atlases: { ui: { folder: 'assets/art/ui' } },
+ };
+
+ it('packs a texture into the atlas whose folder is the longest prefix', () => {
+ expect(resolveAtlas('assets/art/ui/button.png', config)).toEqual({ name: 'ui', folder: 'assets/art/ui' });
+ });
+
+ it('leaves a texture outside every declared folder standalone', () => {
+ expect(resolveAtlas('assets/art/background.png', config)).toBeNull();
+ });
+
+ // The two axes are independent: this texture is in the `cdn` DELIVERY group
+ // and the `ui` atlas at once, which a flag on the group could not express.
+ it('is orthogonal to the delivery group', () => {
+ expect(resolveAssetGroup('assets/art/ui/button.png', config).name).toBe('cdn');
+ expect(resolveAtlas('assets/art/ui/button.png', config)?.name).toBe('ui');
+ });
+
+ it('falls back to the <name>.atlas/ folder convention, keyed by directory', () => {
+ expect(resolveAtlas('assets/textures/sprites.atlas/player.png', null))
+ .toEqual({ name: 'assets/textures/sprites.atlas', folder: 'assets/textures/sprites.atlas' });
+ // Same-named dirs in different places stay distinct atlases.
+ expect(resolveAtlas('assets/hud/sprites.atlas/heart.png', null)?.name)
+ .toBe('assets/hud/sprites.atlas');
+ expect(resolveAtlas('assets/textures/player.png', null)).toBeNull();
+ });
+
+ it('prefers a declared atlas over a .atlas/ folder the file also sits in', () => {
+ const both: AssetGroupsConfig = { version: '1.0', atlases: { hud: { folder: 'assets/x.atlas' } } };
+ expect(resolveAtlas('assets/x.atlas/a.png', both)?.name).toBe('hud');
+ });
+});
diff --git a/sdk/tests/ui-atlas-packer.test.ts b/sdk/tests/shelf-pack.test.ts
similarity index 74%
rename from sdk/tests/ui-atlas-packer.test.ts
rename to sdk/tests/shelf-pack.test.ts
index e13bd3945..3faa8c3ac 100644
--- a/sdk/tests/ui-atlas-packer.test.ts
+++ b/sdk/tests/shelf-pack.test.ts
@@ -1,18 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file REARCH_GUI P1.1 — ShelfPacker (glyph atlas rectangle packer). Pure
- * logic; verifies row advance, wrapping, no overlaps, page-full + oversize
- * rejection, and reset.
+ * @file ShelfPacker — the one rectangle packer, shared by the glyph atlas and
+ * the asset cook. Verifies row advance, first-fit across open rows, no
+ * overlaps, page-full + oversize rejection, and reset.
*/
import { describe, it, expect } from 'vitest';
-import { ShelfPacker, type PackPos } from '../src/ui/text/atlas-packer';
+import { ShelfPacker, type PackPos } from '../src/util/shelfPack';
function overlaps(a: PackPos & { w: number; h: number }, b: PackPos & { w: number; h: number }): boolean {
return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
}
-describe('REARCH_GUI P1.1: ShelfPacker', () => {
+describe('ShelfPacker', () => {
it('advances along a row then wraps to the next shelf', () => {
const p = new ShelfPacker(100, 100);
expect(p.pack(40, 20)).toEqual({ x: 0, y: 0 });
@@ -59,6 +59,16 @@ describe('REARCH_GUI P1.1: ShelfPacker', () => {
expect(p.pack(1, 1)).toBeNull(); // no room left
});
+ // The behaviour the two implementations disagreed on: a row that a later,
+ // shorter rect still fits into is reused rather than abandoned.
+ it('fills an earlier row before opening a new one', () => {
+ const p = new ShelfPacker(100, 100);
+ expect(p.pack(60, 30)).toEqual({ x: 0, y: 0 }); // opens row 0, 30 tall
+ expect(p.pack(90, 10)).toEqual({ x: 0, y: 30 }); // too wide for row 0 → row 1
+ // Fits row 0's leftover (40 wide) AND row 0's height: it goes back up.
+ expect(p.pack(40, 10)).toEqual({ x: 60, y: 0 });
+ });
+
it('reset reclaims the whole page', () => {
const p = new ShelfPacker(32, 32);
p.pack(32, 32);
diff --git a/tools/check-golden.mjs b/tools/check-golden.mjs
index e04a42248..b65e2a9b6 100644
--- a/tools/check-golden.mjs
+++ b/tools/check-golden.mjs
@@ -105,15 +105,22 @@ for (const g of GOLDEN) {
if (g.runBy && !SCHEDULED.includes(g.runBy)) {
fail(`"${g.id}" is settled by \`${g.runBy}\`, which no release criterion runs — add it to releaseGate.mjs`);
}
- // A folder convention is only coverage while the folder is there: moving those
- // textures back out would take the claim with them, silently.
+ // Membership is only coverage while it is declared somewhere: moving those
+ // textures out, or dropping the atlases entry, would take the claim with them.
if (g.atlas) {
if (!(g.atlas.packed > 0)) fail(`"${g.id}" declares atlas without a positive packed count`);
- const dirs = existsSync(projectDir(g.id))
- ? readdirSync(path.join(projectDir(g.id), 'assets'), { withFileTypes: true, recursive: true })
- .filter((e) => e.isDirectory() && e.name.endsWith('.atlas'))
- : [];
- if (!dirs.length) fail(`"${g.id}" claims texture-atlas but has no <name>.atlas/ folder under assets/`);
+ const assets = path.join(projectDir(g.id), 'assets');
+ const byFolder = existsSync(assets)
+ && readdirSync(assets, { withFileTypes: true, recursive: true })
+ .some((e) => e.isDirectory() && e.name.endsWith('.atlas'));
+ let declared = false;
+ try {
+ const cfg = JSON.parse(readFileSync(path.join(projectDir(g.id), '.esengine', 'asset-groups.json'), 'utf8'));
+ declared = Object.keys(cfg.atlases ?? {}).length > 0;
+ } catch { declared = false; }
+ if (!byFolder && !declared) {
+ fail(`"${g.id}" claims texture-atlas with no atlas: no <name>.atlas/ folder and no \`atlases\` entry`);
+ }
}
const sa = g.safeArea;
if (sa) {