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.

Add the MaxRects atlas packer behind texture-atlas compiler v1.2

Matt Kissingera3081415daee
diff --git a/docs/plans/2026-10-15-game-delivery-contract.md b/docs/plans/2026-10-15-game-delivery-contract.md
index 58763267..8ac69863 100644
--- a/docs/plans/2026-10-15-game-delivery-contract.md
+++ b/docs/plans/2026-10-15-game-delivery-contract.md
@@ -254,3 +254,17 @@ from this scope and why. The owner's game session reads this log to monitor.
lint pass; `bun run test` 3695 pass, 2 skip, 21 fail = the 19 GNU-tar baseline failures
plus the two stale-bundle checks (`dist/mcp-engine.mjs`, `dist/cli.mjs`), which the item 4
gate rebuilds.
+- 2026-10-15 item 4 (solid diagnostics) done. Files: `src/geometry.ts` (`solid: { closed,
+ manifold, orientation, signedVolume }` from the existing edge analysis plus a direct signed
+ volume sum; `mixed` on any winding conflict or a zero volume), new `src/require-solid.ts`
+ (`requireSolid(part)` marks `userData.kilnRequireSolid`; `assertRequiredSolids` checks
+ every visible covered mesh before either converter runs and fails with `REQUIRE_SOLID`
+ naming the part and the failing facts), `src/render.ts`, `src/primitives.ts`,
+ `src/evaluator/authoring-diagnostic.ts` + `protocol.ts` (`REQUIRE_SOLID` closed advice),
+ Discovery (`requireSolid`; `geometryDiagnostics` documents `solid`), prompt-api snapshot.
+ Test: new `src/__tests__/solid-diagnostics.test.ts` (6, observed failing first). Gate after
+ `node scripts/build-runtime.mjs all` (exit 0): `bun run test:coverage` 3703 pass, 2 skip,
+ 19 fail (only the 19 GNU-tar baseline failures; both bundle checks pass);
+ `bun scripts/check-coverage.mjs` passed, functions 95.46% (min 94.00%), lines 93.10% (min
+ 92.10%); `bun run test:render-service` exit 0; `bun run check:skills` 6 conform, 2 copies
+ identical; typecheck and lint pass.
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index a8a2c0f4..304d0353 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -708,15 +708,20 @@ proceduralTexture({ schemaVersion: 2, size?: 4..1024 pow2, usage?, name?, layers
// e.g. const bark = proceduralTexture({ schemaVersion: 2, size: 256, usage: 'albedo', name:
// 'Bark', layers: [{ op: 'solid', color: 0x5a4632 }, { op: 'noise', colorA: 0x3d2f21, colorB:
// 0x7a6248, scale: 6, octaves: 4, blend: 'overlay' }] });
-await textureAtlas({ schemaVersion: 1, width, height, usage, sampler?, regions: [{ name, content: { x, y, width, height }, gutter?, edgeMode?, source, crop? }] })
+await textureAtlas({ schemaVersion: 1, width, height, usage, sampler?, pack?: { edge: 1024 | 2048, gutter?, algorithm?: 'maxrects' }, regions: [{ name, content?: { x, y, width, height }, gutter?, edgeMode?, source, crop? }] })
// Composes named, disjoint pixel regions from bounded procedural V3 recipes or exact pinned
// library maps without creating a mesh.
// NOTE: Coordinates are integer pixel edges from top left. Width/height 4..1024. Content
- // excludes gutter (default2); padded allocations must not overlap. copy-edge (default)
- // extrudes RGBA; mask-rgb-dilate preserves positive alpha and extends nearest donor RGB into
- // zero-alpha pixels without growing alpha, for albedo/emissive only. No packing, rotation or
- // resampling. An optional crop must exactly match content dimensions. Resource sources
- // require
+ // excludes gutter (default2); padded allocations must not overlap. With pack, width/height
+ // default to pack.edge (up to 2048, 128 regions, 32 sources; compiler
+ // kiln.texture-atlas.v1.2) and regions may omit content: MaxRects places them by area
+ // descending then name, around any explicit rectangles, at their source size (procedural spec
+ // size, crop, or a resource expected width/height); pack.gutter is the default gutter. The
+ // compiled spec records each placement (packed: true); read placements from the manifest
+ // regions. copy-edge (default) extrudes RGBA; mask-rgb-dilate preserves positive alpha and
+ // extends nearest donor RGB into zero-alpha pixels without growing alpha, for albedo/emissive
+ // only. No rotation or resampling. An optional crop must exactly match content dimensions.
+ // Resource sources require
// {kind:"resource",resourceId:exactMapId,pin:{resourceId:materialId,revisionId,sha256}} and a
// host-supplied exact dependency; paths, URLs, latest and approved non-library resources are
// unsupported. Default sampler is linear-mipmap-linear/linear/clamp-to-edge on both axes;
diff --git a/src/__tests__/texture-atlas-pack.test.ts b/src/__tests__/texture-atlas-pack.test.ts
new file mode 100644
index 00000000..cfcae924
--- /dev/null
+++ b/src/__tests__/texture-atlas-pack.test.ts
@@ -0,0 +1,238 @@
+/**
+ * Atlas packer (delivery contract item 5).
+ *
+ * `textureAtlas` accepts regions without `content` when the atlas sets
+ * `pack: { edge: 1024 | 2048, gutter?, algorithm?: 'maxrects' }`. Placement is deterministic
+ * (allocation area descending, then name), explicit rectangles stay where they are, packed
+ * specs carry compiler id `kiln.texture-atlas.v1.2` with raised limits, and the canonical spec
+ * records every resolved placement so a saved record re-validates without re-packing.
+ */
+import { describe, expect, test } from 'bun:test';
+import {
+ canonicalizeTextureAtlasSpecV1,
+ hashTextureAtlasSpecV1,
+ TEXTURE_ATLAS_COMPILER_ID,
+ TEXTURE_ATLAS_COMPILER_ID_V1_2,
+ TEXTURE_ATLAS_LIMITS_V1_2,
+ textureAtlasCompilerIdV1,
+ validateTextureAtlasManifestV1,
+} from '../texture-atlas-contract';
+import { compileTextureAtlasSpecV1 } from '../texture-atlas-pixels';
+import { remapUVToAtlas, textureAtlas } from '../texture-atlas';
+import { readAtlasTextureProvenance } from '../atlas-provenance';
+import * as THREE from 'three';
+
+const procedural = (size: number, rgba: [number, number, number, number]) => ({
+ kind: 'procedural' as const,
+ spec: { schemaVersion: 3, width: size, height: size, background: rgba, operations: [] },
+});
+const packed = (extra: Record<string, unknown> = {}) => ({
+ schemaVersion: 1,
+ usage: 'albedo',
+ pack: { edge: 1024 },
+ regions: [
+ { name: 'small', source: procedural(64, [10, 20, 30, 255]) },
+ { name: 'large', source: procedural(256, [200, 100, 50, 255]) },
+ { name: 'medium-b', source: procedural(128, [0, 255, 0, 255]) },
+ { name: 'medium-a', source: procedural(128, [0, 0, 255, 255]) },
+ ],
+ ...extra,
+});
+
+const overlaps = (
+ a: { x: number; y: number; width: number; height: number },
+ b: { x: number; y: number; width: number; height: number },
+) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
+
+describe('atlas packer', () => {
+ test('packs regions without content deterministically by area, then name', () => {
+ const spec = canonicalizeTextureAtlasSpecV1(packed());
+ expect(spec.width).toBe(1024);
+ expect(spec.height).toBe(1024);
+ expect(spec.pack).toEqual({ edge: 1024, gutter: 2, algorithm: 'maxrects' });
+ const byName = Object.fromEntries(spec.regions.map((r) => [r.name, r]));
+ // The largest allocation goes first, at the origin, inset by its gutter.
+ expect(byName.large!.content).toEqual({ x: 2, y: 2, width: 256, height: 256 });
+ expect(byName.large!.packed).toBe(true);
+ // Equal areas place in name order.
+ const a = byName['medium-a']!.content,
+ b = byName['medium-b']!.content;
+ expect(a.y < b.y || (a.y === b.y && a.x < b.x)).toBe(true);
+ for (const r of spec.regions)
+ expect(r.content.width).toBe(r.source.kind === 'procedural' ? r.source.spec.width : 0);
+ const allocations = spec.regions.map((r) => ({
+ x: r.content.x - r.gutter,
+ y: r.content.y - r.gutter,
+ width: r.content.width + 2 * r.gutter,
+ height: r.content.height + 2 * r.gutter,
+ }));
+ for (let i = 0; i < allocations.length; i++)
+ for (let j = i + 1; j < allocations.length; j++)
+ expect(overlaps(allocations[i]!, allocations[j]!)).toBe(false);
+ // Input order does not change the placement.
+ const shuffled = packed();
+ shuffled.regions.reverse();
+ expect(canonicalizeTextureAtlasSpecV1(shuffled)).toEqual(spec);
+ // The canonical record re-validates as-is: nothing re-packs.
+ expect(canonicalizeTextureAtlasSpecV1(spec)).toEqual(spec);
+ });
+
+ test('explicit rectangles stay fixed and packed regions avoid them', () => {
+ const spec = canonicalizeTextureAtlasSpecV1(
+ packed({
+ regions: [
+ {
+ name: 'fixed',
+ content: { x: 4, y: 4, width: 256, height: 256 },
+ gutter: 4,
+ source: procedural(256, [1, 2, 3, 255]),
+ },
+ { name: 'free', source: procedural(256, [9, 9, 9, 255]) },
+ ],
+ }),
+ );
+ const fixed = spec.regions.find((r) => r.name === 'fixed')!;
+ const free = spec.regions.find((r) => r.name === 'free')!;
+ expect(fixed.content).toEqual({ x: 4, y: 4, width: 256, height: 256 });
+ expect(fixed.packed).toBeUndefined();
+ expect(free.packed).toBe(true);
+ expect(free.gutter).toBe(2);
+ expect(
+ overlaps(
+ { x: 0, y: 0, width: 264, height: 264 },
+ { x: free.content.x - 2, y: free.content.y - 2, width: 260, height: 260 },
+ ),
+ ).toBe(false);
+ });
+
+ test('pack gutter is the default per region and a region gutter overrides it', () => {
+ const spec = canonicalizeTextureAtlasSpecV1(
+ packed({
+ pack: { edge: 1024, gutter: 8, algorithm: 'maxrects' },
+ regions: [
+ { name: 'a', source: procedural(32, [1, 1, 1, 255]) },
+ { name: 'b', gutter: 0, source: procedural(32, [2, 2, 2, 255]) },
+ ],
+ }),
+ );
+ expect(spec.regions.map((r) => r.gutter)).toEqual([8, 0]);
+ expect(spec.regions[0]!.content).toMatchObject({ x: 8, y: 8 });
+ });
+
+ test('packed specs use compiler v1.2 limits; unpacked specs keep v1.1 identities', () => {
+ expect(TEXTURE_ATLAS_COMPILER_ID).toBe('kiln.texture-atlas.v1.1');
+ expect(TEXTURE_ATLAS_COMPILER_ID_V1_2).toBe('kiln.texture-atlas.v1.2');
+ expect(TEXTURE_ATLAS_LIMITS_V1_2).toMatchObject({
+ edge: 2048,
+ outputTexels: 4_194_304,
+ sources: 32,
+ regions: 128,
+ });
+ const big = canonicalizeTextureAtlasSpecV1(packed({ pack: { edge: 2048 } }));
+ expect([big.width, big.height]).toEqual([2048, 2048]);
+ expect(textureAtlasCompilerIdV1(big)).toBe('kiln.texture-atlas.v1.2');
+ const explicit = {
+ schemaVersion: 1,
+ width: 64,
+ height: 64,
+ usage: 'albedo',
+ regions: [
+ {
+ name: 'one',
+ content: { x: 2, y: 2, width: 8, height: 8 },
+ source: procedural(8, [5, 5, 5, 255]),
+ },
+ ],
+ };
+ const canonical = canonicalizeTextureAtlasSpecV1(explicit);
+ expect(textureAtlasCompilerIdV1(canonical)).toBe('kiln.texture-atlas.v1.1');
+ expect('pack' in canonical).toBe(false);
+ expect('packed' in canonical.regions[0]!).toBe(false);
+ // Unpacked atlases still stop at the v1.1 edge; packed ones may name up to 128 regions.
+ expect(() => canonicalizeTextureAtlasSpecV1({ ...explicit, width: 2048 })).toThrow(/width/);
+ const many = Array.from({ length: 100 }, (_, i) => ({
+ name: `r${String(i).padStart(3, '0')}`,
+ source: procedural(16, [i % 30, 0, 0, 255]),
+ }));
+ expect(canonicalizeTextureAtlasSpecV1(packed({ regions: many })).regions).toHaveLength(100);
+ expect(() =>
+ canonicalizeTextureAtlasSpecV1({
+ ...explicit,
+ regions: many.map((r, i) => ({
+ ...r,
+ content: { x: (i % 8) * 20 + 2, y: Math.floor(i / 8) * 20 + 2, width: 16, height: 16 },
+ })),
+ }),
+ ).toThrow();
+ });
+
+ test('a packed region without a known size, an overfull pack and a bad edge fail closed', () => {
+ expect(() =>
+ canonicalizeTextureAtlasSpecV1({
+ schemaVersion: 1,
+ width: 64,
+ height: 64,
+ usage: 'albedo',
+ regions: [{ name: 'x', source: procedural(8, [1, 1, 1, 255]) }],
+ }),
+ ).toThrow(/content/);
+ expect(() => canonicalizeTextureAtlasSpecV1(packed({ pack: { edge: 512 } }))).toThrow(/edge/);
+ expect(() =>
+ canonicalizeTextureAtlasSpecV1(packed({ pack: { edge: 1024, algorithm: 'shelf' } })),
+ ).toThrow(/algorithm/);
+ expect(() =>
+ canonicalizeTextureAtlasSpecV1(
+ packed({
+ regions: Array.from({ length: 5 }, (_, i) => ({
+ name: `big${i}`,
+ source: procedural(512, [i, 0, 0, 255]),
+ })),
+ }),
+ ),
+ ).toThrow(/does not fit/);
+ expect(() =>
+ canonicalizeTextureAtlasSpecV1(
+ packed({
+ regions: [
+ {
+ name: 'pinned',
+ source: {
+ kind: 'resource',
+ resourceId: 'brick.basecolor',
+ pin: {
+ resourceId: 'brick',
+ revisionId: `sha256:${'a'.repeat(64)}`,
+ sha256: `sha256:${'a'.repeat(64)}`,
+ },
+ },
+ },
+ ],
+ }),
+ ),
+ ).toThrow(/size/);
+ });
+
+ test('compiles under v1.2, validates the manifest and survives provenance without re-packing', async () => {
+ const compiled = await compileTextureAtlasSpecV1(packed());
+ expect(compiled.manifest.compilerId).toBe('kiln.texture-atlas.v1.2');
+ expect(compiled.manifest.specHash).toBe(hashTextureAtlasSpecV1(compiled.spec));
+ expect(validateTextureAtlasManifestV1(compiled.manifest, compiled.spec)).toEqual(
+ compiled.manifest,
+ );
+ // The large region's top-left content texel carries its source colour.
+ const large = compiled.manifest.regions.find((r) => r.name === 'large')!;
+ const at = (large.content.y * compiled.spec.width + large.content.x) * 4;
+ expect([...compiled.pixels.slice(at, at + 4)]).toEqual([200, 100, 50, 255]);
+ const texture = await textureAtlas(packed());
+ const record = readAtlasTextureProvenance(texture)!;
+ expect(record.spec).toEqual(compiled.spec);
+ expect(record.manifest.regions.map((r) => r.content)).toEqual(
+ compiled.manifest.regions.map((r) => r.content),
+ );
+ const uv = remapUVToAtlas(new THREE.PlaneGeometry(), texture, 'large', {
+ inputOrigin: 'bottom-left',
+ mode: 'content-boundary',
+ });
+ expect(uv.userData.kilnAtlasBinding.content).toEqual(large.content);
+ });
+});
diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.ts
index 04de29b2..275428c1 100644
--- a/src/discovery/helper-contracts.ts
+++ b/src/discovery/helper-contracts.ts
@@ -2590,7 +2590,8 @@ define(
'Creates an owned texture and immutable-by-copy source snapshots; host map capability is never exposed to authored code.',
parameters: [
'schemaVersion1, width/height 4..1024, explicit usage and 1..64 named regions from at most16 distinct sources.',
- 'Each region has name, content rectangle and source; gutter defaults2 and edgeMode defaults copy-edge. Source crops and content dimensions must match without resampling.',
+ 'Optional pack { edge: 1024 | 2048, gutter?: 0..32 (default 2, the default region gutter), algorithm?: "maxrects" } selects compiler kiln.texture-atlas.v1.2: width/height default to edge (4..edge), 1..128 regions, at most 32 distinct sources, 4,194,304 output texels. Regions may then omit content and are placed deterministically (allocation area descending, then name; best short side fit; no rotation) around explicit rectangles. The canonical spec records the resolved content with packed: true, so a saved record re-validates without re-packing.',
+ 'Each region has name, content rectangle (optional when packing) and source; gutter defaults2 and edgeMode defaults copy-edge. Source crops and content dimensions must match without resampling.',
'Source is {kind:"procedural",spec:V3} or {kind:"resource",resourceId:exactMapId,pin:{resourceId:materialId,revisionId,sha256},expected?}. Pins are host-selected immutable library revisions; no arbitrary acquisition I/O.',
'Optional sampler specifies all four portable fields; default linear-mipmap-linear/linear/clamp-to-edge on both axes.',
],
@@ -2609,10 +2610,13 @@ define(
'src/texture-atlas.ts',
],
tags: ['texture', 'atlas', 'rgba', 'ownership'],
- aliases: ['named texture sheet', 'foliage atlas'],
- intents: ['compose reusable named pixel regions without a mesh'],
+ aliases: ['named texture sheet', 'foliage atlas', 'atlas packer', 'pack textures'],
+ intents: [
+ 'compose reusable named pixel regions without a mesh',
+ 'pack texture regions into one atlas automatically',
+ ],
limitations: [
- 'No automatic packing, rotation or resampling. Gutters reduce filtering bleed but cannot isolate every downsampled mip level.',
+ 'No rotation or resampling. Packing needs each region size before any load: a packed resource region needs a crop or expected width and height. Gutters reduce filtering bleed but cannot isolate every downsampled mip level.',
],
related: [{ name: 'remapUVToAtlas', relation: 'companion' }],
},
diff --git a/src/discovery/helper-specs.ts b/src/discovery/helper-specs.ts
index 1380652f..92f96577 100644
--- a/src/discovery/helper-specs.ts
+++ b/src/discovery/helper-specs.ts
@@ -1114,7 +1114,7 @@ const PRIMITIVES: HelperSpec[] = [
{
name: 'textureAtlas',
signature:
- 'await textureAtlas({ schemaVersion: 1, width, height, usage, sampler?, regions: [{ name, content: { x, y, width, height }, gutter?, edgeMode?, source, crop? }] })',
+ "await textureAtlas({ schemaVersion: 1, width, height, usage, sampler?, pack?: { edge: 1024 | 2048, gutter?, algorithm?: 'maxrects' }, regions: [{ name, content?: { x, y, width, height }, gutter?, edgeMode?, source, crop? }] })",
returns: 'Promise<THREE.DataTexture>',
category: 'textures',
description:
@@ -1122,7 +1122,7 @@ const PRIMITIVES: HelperSpec[] = [
example:
"const atlas = await textureAtlas({ schemaVersion: 1, width: 8, height: 8, usage: 'albedo', regions: [{ name: 'patch', content: { x: 2, y: 2, width: 4, height: 4 }, source: { kind: 'procedural', spec: { schemaVersion: 3, width: 4, height: 4, background: [70, 90, 40, 255], operations: [] } } }] });",
promptNotes:
- 'Coordinates are integer pixel edges from top left. Width/height 4..1024. Content excludes gutter (default2); padded allocations must not overlap. copy-edge (default) extrudes RGBA; mask-rgb-dilate preserves positive alpha and extends nearest donor RGB into zero-alpha pixels without growing alpha, for albedo/emissive only. No packing, rotation or resampling. An optional crop must exactly match content dimensions. Resource sources require {kind:"resource",resourceId:exactMapId,pin:{resourceId:materialId,revisionId,sha256}} and a host-supplied exact dependency; paths, URLs, latest and approved non-library resources are unsupported. Default sampler is linear-mipmap-linear/linear/clamp-to-edge on both axes; explicit samplers require all four fields. Gutters do not guarantee isolation at every mip level. Use remapUVToAtlas with an explicit input origin and mode; inspect at intended scene distance.',
+ 'Coordinates are integer pixel edges from top left. Width/height 4..1024. Content excludes gutter (default2); padded allocations must not overlap. With pack, width/height default to pack.edge (up to 2048, 128 regions, 32 sources; compiler kiln.texture-atlas.v1.2) and regions may omit content: MaxRects places them by area descending then name, around any explicit rectangles, at their source size (procedural spec size, crop, or a resource expected width/height); pack.gutter is the default gutter. The compiled spec records each placement (packed: true); read placements from the manifest regions. copy-edge (default) extrudes RGBA; mask-rgb-dilate preserves positive alpha and extends nearest donor RGB into zero-alpha pixels without growing alpha, for albedo/emissive only. No rotation or resampling. An optional crop must exactly match content dimensions. Resource sources require {kind:"resource",resourceId:exactMapId,pin:{resourceId:materialId,revisionId,sha256}} and a host-supplied exact dependency; paths, URLs, latest and approved non-library resources are unsupported. Default sampler is linear-mipmap-linear/linear/clamp-to-edge on both axes; explicit samplers require all four fields. Gutters do not guarantee isolation at every mip level. Use remapUVToAtlas with an explicit input origin and mode; inspect at intended scene distance.',
},
{
name: 'remapUVToAtlas',
diff --git a/src/material-authoring-schema.ts b/src/material-authoring-schema.ts
index f6224bcf..e30f47c3 100644
--- a/src/material-authoring-schema.ts
+++ b/src/material-authoring-schema.ts
@@ -16,7 +16,12 @@ import {
MAX_PROCEDURAL_V3_PALETTE,
PROCEDURAL_TEXTURE_V3_COMPILER_ID,
} from './procedural-texture-v3-contract';
-import { TEXTURE_ATLAS_COMPILER_ID, TEXTURE_ATLAS_LIMITS } from './texture-atlas-contract';
+import {
+ TEXTURE_ATLAS_COMPILER_IDS,
+ TEXTURE_ATLAS_LIMITS,
+ TEXTURE_ATLAS_LIMITS_V1_2,
+ TEXTURE_ATLAS_PACK_EDGES,
+} from './texture-atlas-contract';
import {
PORTABLE_MIN_FILTERS_V1,
PORTABLE_MAG_FILTERS_V1,
@@ -230,21 +235,47 @@ export function makeMaterialAuthoringSchemas<S extends z.ZodType<CanonicalProced
resourceSource,
]),
crop: atlasRectangleSchema.optional(),
+ packed: z.literal(true).optional(),
})
.strict();
+ // Packed atlases (compiler v1.2) raise the edge and counts; the canonicalizer applies the
+ // exact per-version limit.
const atlasBase = {
schemaVersion: z.literal(1),
- width: integer(4, TEXTURE_ATLAS_LIMITS.edge),
- height: integer(4, TEXTURE_ATLAS_LIMITS.edge),
+ width: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
+ height: integer(4, TEXTURE_ATLAS_LIMITS_V1_2.edge),
usage,
sampler: portableSamplerSchema,
};
+ const packEdge = z.union(
+ TEXTURE_ATLAS_PACK_EDGES.map((edge) => z.literal(edge)) as [
+ z.ZodLiteral<1024>,
+ z.ZodLiteral<2048>,
+ ],
+ );
const canonicalTextureAtlasSpecV1Schema = z
- .object({ ...atlasBase, regions: z.array(region).min(1).max(TEXTURE_ATLAS_LIMITS.regions) })
+ .object({
+ ...atlasBase,
+ regions: z.array(region).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
+ pack: z
+ .object({ edge: packEdge, gutter: integer(0, 32), algorithm: z.literal('maxrects') })
+ .strict()
+ .optional(),
+ })
.strict();
const textureAtlasSpecV1Schema = z
.object({
...atlasBase,
+ width: atlasBase.width.optional(),
+ height: atlasBase.height.optional(),
+ pack: z
+ .object({
+ edge: packEdge,
+ gutter: integer(0, 32).optional(),
+ algorithm: z.literal('maxrects').optional(),
+ })
+ .strict()
+ .optional(),
sampler: portableSamplerSchema.optional(),
regions: z
.array(
@@ -257,10 +288,10 @@ export function makeMaterialAuthoringSchemas<S extends z.ZodType<CanonicalProced
resourceSource,
]),
})
- .partial({ gutter: true, edgeMode: true }),
+ .partial({ content: true, gutter: true, edgeMode: true }),
)
.min(1)
- .max(TEXTURE_ATLAS_LIMITS.regions),
+ .max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
})
.strict();
const verifiedPinnedMaterialMapDescriptorSchema = z
@@ -302,7 +333,7 @@ export function makeMaterialAuthoringSchemas<S extends z.ZodType<CanonicalProced
const textureAtlasManifestV1Schema = z
.object({
version: z.literal('kiln.atlas-manifest.v1'),
- compilerId: z.literal(TEXTURE_ATLAS_COMPILER_ID),
+ compilerId: z.enum(TEXTURE_ATLAS_COMPILER_IDS),
width: atlasBase.width,
height: atlasBase.height,
usage,
@@ -312,7 +343,7 @@ export function makeMaterialAuthoringSchemas<S extends z.ZodType<CanonicalProced
layoutHash: hash,
decodedPixelHash: hash,
atlasPixelHash: hash,
- sources: z.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS.sources),
+ sources: z.array(sourceManifest).min(1).max(TEXTURE_ATLAS_LIMITS_V1_2.sources),
regions: z
.array(
z
@@ -326,7 +357,7 @@ export function makeMaterialAuthoringSchemas<S extends z.ZodType<CanonicalProced
.strict(),
)
.min(1)
- .max(TEXTURE_ATLAS_LIMITS.regions),
+ .max(TEXTURE_ATLAS_LIMITS_V1_2.regions),
manifestHash: hash,
})
.strict();
diff --git a/src/material-library-node.ts b/src/material-library-node.ts
index 8bef4d8f..9f17c46c 100644
--- a/src/material-library-node.ts
+++ b/src/material-library-node.ts
@@ -44,7 +44,6 @@ import {
PROCEDURAL_TEXTURE_V3_COMPILER_ID,
} from './procedural-texture-v3-contract';
import { admitTextureAtlasSpecV1, compileTextureAtlasSpecV1 } from './texture-atlas-pixels';
-import { TEXTURE_ATLAS_COMPILER_ID } from './texture-atlas-contract';
import type {
MaterialMapPinV1,
PinnedMaterialMapPortV1,
@@ -1243,7 +1242,7 @@ export async function createMaterialRecordV2(
);
recipe = {
kind: 'atlas',
- compilerId: TEXTURE_ATLAS_COMPILER_ID,
+ compilerId: compiled.manifest.compilerId,
spec: compiled.spec,
manifest: compiled.manifest,
encoder,
diff --git a/src/material-library.ts b/src/material-library.ts
index 6cebc8e8..af500d7e 100644
--- a/src/material-library.ts
+++ b/src/material-library.ts
@@ -13,7 +13,7 @@ import type { CanonicalPortableMaterialSpecV3 } from './procedural-material-v3';
import {
canonicalizeTextureAtlasSpecV1,
validateTextureAtlasManifestV1,
- TEXTURE_ATLAS_COMPILER_ID,
+ TEXTURE_ATLAS_COMPILER_IDS,
type CanonicalTextureAtlasSpecV1,
} from './texture-atlas-contract';
import type { TextureAtlasManifestV1 } from './texture-atlas-pixels';
@@ -585,7 +585,7 @@ const materialRecipeV2Schema = z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('atlas'),
- compilerId: z.literal(TEXTURE_ATLAS_COMPILER_ID),
+ compilerId: z.enum(TEXTURE_ATLAS_COMPILER_IDS),
spec: atlasSpecSchema,
manifest: atlasManifestSchema,
encoder: z.object({ name: z.literal('sharp'), version: text }).strict(),
@@ -594,6 +594,7 @@ const materialRecipeV2Schema = z.discriminatedUnion('kind', [
.superRefine((recipe, context) => {
try {
validateTextureAtlasManifestV1(recipe.manifest, recipe.spec);
+ if (recipe.compilerId !== recipe.manifest.compilerId) throw new Error('compiler id');
} catch {
context.addIssue({ code: 'custom', message: 'Invalid stored atlas manifest' });
}
diff --git a/src/primitives.ts b/src/primitives.ts
index 520e21df..02300125 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -85,7 +85,10 @@ export type { AtlasUVOptionsV1 } from './texture-atlas';
export {
TextureAtlasError,
TEXTURE_ATLAS_COMPILER_ID,
+ TEXTURE_ATLAS_COMPILER_ID_V1_2,
TEXTURE_ATLAS_LIMITS,
+ TEXTURE_ATLAS_LIMITS_V1_2,
+ textureAtlasCompilerIdV1,
canonicalizeTextureAtlasSpecV1,
canonicalTextureAtlasJsonV1,
hashTextureAtlasSpecV1,
@@ -97,6 +100,9 @@ export type {
TextureAtlasSourceV1,
TextureAtlasRegionV1,
TextureAtlasSpecV1,
+ TextureAtlasPackV1,
+ CanonicalTextureAtlasPackV1,
+ TextureAtlasCompilerIdV1,
CanonicalTextureAtlasSourceV1,
CanonicalTextureAtlasRegionV1,
CanonicalTextureAtlasSpecV1,
diff --git a/src/texture-atlas-contract.ts b/src/texture-atlas-contract.ts
index 214b1501..0319e392 100644
--- a/src/texture-atlas-contract.ts
+++ b/src/texture-atlas-contract.ts
@@ -16,7 +16,15 @@ import type { TextureAtlasManifestV1 } from './texture-atlas-pixels';
import { TEXTURE_USAGES, type TextureUsage } from './texture-contract';
import { AuthoringDiagnosticError } from './evaluator/authoring-diagnostic';
+/** Compiler id of an atlas without `pack`: its identities are unchanged since v1.1. */
export const TEXTURE_ATLAS_COMPILER_ID = 'kiln.texture-atlas.v1.1' as const;
+/** Compiler id of an atlas that sets `pack` (raised limits, packed placement). */
+export const TEXTURE_ATLAS_COMPILER_ID_V1_2 = 'kiln.texture-atlas.v1.2' as const;
+export const TEXTURE_ATLAS_COMPILER_IDS = Object.freeze([
+ TEXTURE_ATLAS_COMPILER_ID,
+ TEXTURE_ATLAS_COMPILER_ID_V1_2,
+] as const);
+export type TextureAtlasCompilerIdV1 = (typeof TEXTURE_ATLAS_COMPILER_IDS)[number];
export const TEXTURE_ATLAS_LIMITS = Object.freeze({
edge: 1024,
outputTexels: 1_048_576,
@@ -31,6 +39,41 @@ export const TEXTURE_ATLAS_LIMITS = Object.freeze({
uvVertices: 262_144,
uvAttributeBytes: 134_217_728,
});
+/**
+ * Limits of a packed (v1.2) atlas. Edge, output texels, sources and regions follow the
+ * delivery contract; work and allocation scale with the fourfold output so a full 2048 sheet
+ * can compile. Source-side budgets (decoded source texels, encoded bytes) are unchanged.
+ */
+export const TEXTURE_ATLAS_LIMITS_V1_2 = Object.freeze({
+ ...TEXTURE_ATLAS_LIMITS,
+ edge: 2048,
+ outputTexels: 4_194_304,
+ regions: 128,
+ sources: 32,
+ work: 192_000_000,
+ allocatedBytes: 134_217_728,
+});
+export type TextureAtlasLimitsV1 = typeof TEXTURE_ATLAS_LIMITS | typeof TEXTURE_ATLAS_LIMITS_V1_2;
+export const TEXTURE_ATLAS_PACK_EDGES = Object.freeze([1024, 2048] as const);
+/** Atlas packing request: regions without `content` are placed by MaxRects. */
+export interface TextureAtlasPackV1 {
+ edge: 1024 | 2048;
+ /** Default gutter of every region in a packed atlas (0..32, default 2). */
+ gutter?: number;
+ algorithm?: 'maxrects';
+}
+export interface CanonicalTextureAtlasPackV1 {
+ edge: 1024 | 2048;
+ gutter: number;
+ algorithm: 'maxrects';
+}
+/** The compiler id a canonical spec compiles under: v1.2 exactly when it sets `pack`. */
+export function textureAtlasCompilerIdV1(spec: { pack?: unknown }): TextureAtlasCompilerIdV1 {
+ return spec.pack === undefined ? TEXTURE_ATLAS_COMPILER_ID : TEXTURE_ATLAS_COMPILER_ID_V1_2;
+}
+export function textureAtlasLimitsV1(spec: { pack?: unknown }): TextureAtlasLimitsV1 {
+ return spec.pack === undefined ? TEXTURE_ATLAS_LIMITS : TEXTURE_ATLAS_LIMITS_V1_2;
+}
export interface AtlasRectangleV1 {
x: number;
y: number;
@@ -54,19 +97,24 @@ export type TextureAtlasSourceV1 =
};
export interface TextureAtlasRegionV1 {
name: string;
- content: AtlasRectangleV1;
+ /** Required unless the atlas sets `pack`; a packed region takes its source's size. */
+ content?: AtlasRectangleV1;
gutter?: number;
edgeMode?: AtlasEdgeModeV1;
source: TextureAtlasSourceV1;
crop?: AtlasRectangleV1;
+ /** Resolved-placement marker a canonical packed record carries; never set it by hand. */
+ packed?: true;
}
export interface TextureAtlasSpecV1 {
schemaVersion: 1;
- width: number;
- height: number;
+ /** Defaults to `pack.edge` when the atlas packs. */
+ width?: number;
+ height?: number;
usage: TextureUsage;
sampler?: PortableSamplerV1;
regions: TextureAtlasRegionV1[];
+ pack?: TextureAtlasPackV1;
}
export type CanonicalTextureAtlasSourceV1 =
| { kind: 'procedural'; spec: CanonicalProceduralTextureSpecV3 }
@@ -78,6 +126,8 @@ export interface CanonicalTextureAtlasRegionV1 {
edgeMode: AtlasEdgeModeV1;
source: CanonicalTextureAtlasSourceV1;
crop?: AtlasRectangleV1;
+ /** True when the packer placed this region; its content is the resolved placement. */
+ packed?: true;
}
export interface CanonicalTextureAtlasSpecV1 {
schemaVersion: 1;
@@ -86,6 +136,7 @@ export interface CanonicalTextureAtlasSpecV1 {
usage: TextureUsage;
sampler: CanonicalPortableSamplerV1;
regions: CanonicalTextureAtlasRegionV1[];
+ pack?: CanonicalTextureAtlasPackV1;
}
export class TextureAtlasError extends AuthoringDiagnosticError {
constructor(message: string) {
@@ -198,36 +249,160 @@ export function atlasSourceIdentityV1(source: CanonicalTextureAtlasSourceV1): st
? `procedural:${hashProceduralTextureSpecV3(source.spec)}`
: `resource:${source.pin.resourceId}:${source.pin.revisionId}:${source.resourceId}`;
}
+/** Packing order is allocation area descending, then name: deterministic for any input order. */
+interface PendingPackV1 {
+ region: CanonicalTextureAtlasRegionV1;
+ width: number;
+ height: number;
+}
+const rectsOverlap = (a: AtlasRectangleV1, b: AtlasRectangleV1): boolean =>
+ a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
+const rectContains = (outer: AtlasRectangleV1, inner: AtlasRectangleV1): boolean =>
+ inner.x >= outer.x &&
+ inner.y >= outer.y &&
+ inner.x + inner.width <= outer.x + outer.width &&
+ inner.y + inner.height <= outer.y + outer.height;
+/**
+ * MaxRects, best-short-side-fit, no rotation (UV remapping never rotates). Explicit allocations
+ * are carved out of the free space first; each packed region then takes the free rectangle
+ * with the smallest leftover short side, ties broken by long side, then y, then x. Integer
+ * arithmetic only, so the result is identical on every host.
+ */
+function packAtlasRegionsV1(
+ width: number,
+ height: number,
+ fixed: AtlasRectangleV1[],
+ pending: PendingPackV1[],
+): void {
+ let free: AtlasRectangleV1[] = [{ x: 0, y: 0, width, height }];
+ const occupy = (used: AtlasRectangleV1) => {
+ const next: AtlasRectangleV1[] = [];
+ for (const f of free) {
+ if (!rectsOverlap(f, used)) {
+ next.push(f);
+ continue;
+ }
+ if (used.x > f.x) next.push({ x: f.x, y: f.y, width: used.x - f.x, height: f.height });
+ if (used.x + used.width < f.x + f.width)
+ next.push({
+ x: used.x + used.width,
+ y: f.y,
+ width: f.x + f.width - used.x - used.width,
+ height: f.height,
+ });
+ if (used.y > f.y) next.push({ x: f.x, y: f.y, width: f.width, height: used.y - f.y });
+ if (used.y + used.height < f.y + f.height)
+ next.push({
+ x: f.x,
+ y: used.y + used.height,
+ width: f.width,
+ height: f.y + f.height - used.y - used.height,
+ });
+ }
+ // Drop rectangles contained in another; of two identical ones keep the first.
+ free = next.filter(
+ (a, i) =>
+ !next.some((b, j) => j !== i && rectContains(b, a) && (!rectContains(a, b) || j < i)),
+ );
+ if (free.length > 16_384) atlasFailure('pack: free-space bookkeeping budget exceeded.');
+ };
+ for (const allocation of fixed) occupy(allocation);
+ const order = [...pending].sort(
+ (a, b) =>
+ b.width * b.height - a.width * a.height ||
+ (a.region.name < b.region.name ? -1 : a.region.name > b.region.name ? 1 : 0),
+ );
+ for (const item of order) {
+ let best: AtlasRectangleV1 | undefined;
+ let bestScore: [number, number, number, number] | undefined;
+ for (const f of free) {
+ if (f.width < item.width || f.height < item.height) continue;
+ const dw = f.width - item.width,
+ dh = f.height - item.height;
+ const score: [number, number, number, number] = [
+ Math.min(dw, dh),
+ Math.max(dw, dh),
+ f.y,
+ f.x,
+ ];
+ if (
+ !bestScore ||
+ score[0] < bestScore[0] ||
+ (score[0] === bestScore[0] &&
+ (score[1] < bestScore[1] ||
+ (score[1] === bestScore[1] &&
+ (score[2] < bestScore[2] || (score[2] === bestScore[2] && score[3] < bestScore[3])))))
+ ) {
+ best = f;
+ bestScore = score;
+ }
+ }
+ if (!best)
+ atlasFailure(
+ `pack: region ${item.region.name} (${item.width}x${item.height} texels with its gutter) does not fit in the ${width}x${height} atlas beside the regions already placed.`,
+ );
+ item.region.content = {
+ x: best.x + item.region.gutter,
+ y: best.y + item.region.gutter,
+ width: item.region.content.width,
+ height: item.region.content.height,
+ };
+ occupy({ x: best.x, y: best.y, width: item.width, height: item.height });
+ }
+}
export function canonicalizeTextureAtlasSpecV1(input: unknown): CanonicalTextureAtlasSpecV1 {
preflight(input);
const r = record(
input,
- ['schemaVersion', 'width', 'height', 'usage', 'sampler', 'regions'],
+ ['schemaVersion', 'width', 'height', 'usage', 'sampler', 'regions', 'pack'],
'atlas',
);
if (r['schemaVersion'] !== 1) atlasFailure('schemaVersion must be 1.');
- const width = integer(r['width'], 4, TEXTURE_ATLAS_LIMITS.edge, 'width'),
- height = integer(r['height'], 4, TEXTURE_ATLAS_LIMITS.edge, 'height');
+ let pack: CanonicalTextureAtlasPackV1 | undefined;
+ if (r['pack'] !== undefined) {
+ const p = record(r['pack'], ['edge', 'gutter', 'algorithm'], 'pack');
+ if (!(TEXTURE_ATLAS_PACK_EDGES as readonly unknown[]).includes(p['edge']))
+ atlasFailure('pack.edge must be 1024 or 2048.');
+ if (p['algorithm'] !== undefined && p['algorithm'] !== 'maxrects')
+ atlasFailure("pack.algorithm must be 'maxrects'.");
+ pack = {
+ edge: p['edge'] as CanonicalTextureAtlasPackV1['edge'],
+ gutter: p['gutter'] === undefined ? 2 : integer(p['gutter'], 0, 32, 'pack.gutter'),
+ algorithm: 'maxrects',
+ };
+ }
+ const limits = pack ? TEXTURE_ATLAS_LIMITS_V1_2 : TEXTURE_ATLAS_LIMITS,
+ maxEdge = pack ? pack.edge : limits.edge;
+ const width =
+ pack && r['width'] === undefined ? pack.edge : integer(r['width'], 4, maxEdge, 'width'),
+ height =
+ pack && r['height'] === undefined ? pack.edge : integer(r['height'], 4, maxEdge, 'height');
+ if (width * height > limits.outputTexels) atlasFailure('output texel budget exceeded.');
if (!(TEXTURE_USAGES as readonly unknown[]).includes(r['usage']))
atlasFailure('usage must be a texture usage.');
const usage = r['usage'] as TextureUsage;
- if (
- !Array.isArray(r['regions']) ||
- !r['regions'].length ||
- r['regions'].length > TEXTURE_ATLAS_LIMITS.regions
- )
- atlasFailure('regions must contain 1..64 entries.');
+ if (!Array.isArray(r['regions']) || !r['regions'].length || r['regions'].length > limits.regions)
+ atlasFailure(`regions must contain 1..${limits.regions} entries.`);
+ const pending: PendingPackV1[] = [];
const regions = r['regions']
.map((value, i): CanonicalTextureAtlasRegionV1 => {
const q = record(
value,
- ['name', 'content', 'gutter', 'edgeMode', 'source', 'crop'],
+ ['name', 'content', 'gutter', 'edgeMode', 'source', 'crop', 'packed'],
`regions[${i}]`,
);
if (typeof q['name'] !== 'string' || !/^[a-z][a-z0-9_-]{0,79}$/.test(q['name']))
atlasFailure('region name must be a stable lowercase identifier.');
- const content = rect(q['content'], 'content'),
- gutter = q['gutter'] === undefined ? 2 : integer(q['gutter'], 0, 32, 'gutter');
+ const explicit = q['content'] !== undefined;
+ if (!explicit && !pack)
+ atlasFailure(`region ${q['name']}: content is required unless the atlas sets pack.`);
+ if (q['packed'] !== undefined && (q['packed'] !== true || !pack || !explicit))
+ atlasFailure(
+ 'packed is the resolved-placement marker: true, with content, in an atlas that sets pack.',
+ );
+ let content = explicit ? rect(q['content'], 'content') : undefined;
+ const gutter =
+ q['gutter'] === undefined ? (pack?.gutter ?? 2) : integer(q['gutter'], 0, 32, 'gutter');
const edgeMode = q['edgeMode'] === undefined ? 'copy-edge' : q['edgeMode'];
if (!['copy-edge', 'mask-rgb-dilate'].includes(edgeMode as string))
atlasFailure('unsupported edgeMode.');
@@ -243,6 +418,7 @@ export function canonicalizeTextureAtlasSpecV1(input: unknown): CanonicalTexture
atlasFailure('source usage does not match atlas usage.');
source = { kind: 'procedural', spec: admission.spec };
crop ??= { x: 0, y: 0, width: admission.spec.width, height: admission.spec.height };
+ content ??= { x: 0, y: 0, width: crop.width, height: crop.height };
assertAtlasCropV1(crop, content, admission.spec.width, admission.spec.height);
} else if (s['kind'] === 'resource') {
record(s, ['kind', 'resourceId', 'pin', 'expected'], 'resource source');
@@ -285,30 +461,59 @@ export function canonicalizeTextureAtlasSpecV1(input: unknown): CanonicalTexture
pin: { resourceId: p['resourceId'], revisionId, sha256 },
...(expected ? { expected } : {}),
};
+ if (!content) {
+ // A packed resource needs its size before any host load: a crop or expected size.
+ const size =
+ crop ??
+ (expected?.width !== undefined && expected.height !== undefined
+ ? { width: expected.width, height: expected.height }
+ : atlasFailure(
+ `region ${q['name']}: a packed resource region needs a crop or expected width and height (its size).`,
+ ));
+ content = { x: 0, y: 0, width: size.width, height: size.height };
+ }
if (crop && (crop.width !== content.width || crop.height !== content.height))
atlasFailure('source crop/content dimensions must match; resampling is unsupported.');
} else atlasFailure('source kind must be procedural or pinned resource.');
- const result = {
+ const result: CanonicalTextureAtlasRegionV1 = {
name: q['name'],
- content,
+ content: content!,
gutter,
edgeMode: edgeMode as AtlasEdgeModeV1,
source,
...(crop ? { crop } : {}),
+ ...(pack && (!explicit || q['packed'] === true) ? { packed: true as const } : {}),
};
- const allocation = atlasAllocationV1(result);
- if (
- allocation.x < 0 ||
- allocation.y < 0 ||
- allocation.x + allocation.width > width ||
- allocation.y + allocation.height > height
- )
- atlasFailure('padded allocation is out of bounds.');
+ if (!explicit)
+ pending.push({
+ region: result,
+ width: result.content.width + 2 * gutter,
+ height: result.content.height + 2 * gutter,
+ });
return result;
})
.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
if (new Set(regions.map((v) => v.name)).size !== regions.length)
atlasFailure('duplicate region name.');
+ if (pending.length) {
+ const placed = new Set(pending.map((p) => p.region));
+ packAtlasRegionsV1(
+ width,
+ height,
+ regions.filter((region) => !placed.has(region)).map((region) => atlasAllocationV1(region)),
+ pending,
+ );
+ }
+ for (const region of regions) {
+ const allocation = atlasAllocationV1(region);
+ if (
+ allocation.x < 0 ||
+ allocation.y < 0 ||
+ allocation.x + allocation.width > width ||
+ allocation.y + allocation.height > height
+ )
+ atlasFailure('padded allocation is out of bounds.');
+ }
for (let i = 0; i < regions.length; i++)
for (let j = i + 1; j < regions.length; j++) {
const a = atlasAllocationV1(regions[i]!),
@@ -321,10 +526,8 @@ export function canonicalizeTextureAtlasSpecV1(input: unknown): CanonicalTexture
)
atlasFailure(`padded allocations overlap: ${regions[i]!.name}, ${regions[j]!.name}.`);
}
- if (
- new Set(regions.map((v) => atlasSourceIdentityV1(v.source))).size > TEXTURE_ATLAS_LIMITS.sources
- )
- atlasFailure('distinct source budget exceeds 16.');
+ if (new Set(regions.map((v) => atlasSourceIdentityV1(v.source))).size > limits.sources)
+ atlasFailure(`distinct source budget exceeds ${limits.sources}.`);
let sampler: CanonicalPortableSamplerV1;
try {
sampler = canonicalizePortableSamplerV1(
@@ -347,6 +550,7 @@ export function canonicalizeTextureAtlasSpecV1(input: unknown): CanonicalTexture
usage,
sampler,
regions,
+ ...(pack ? { pack } : {}),
};
if (new TextEncoder().encode(JSON.stringify(spec)).length > TEXTURE_ATLAS_LIMITS.jsonBytes)
atlasFailure('canonical JSON byte budget exceeded.');
@@ -356,7 +560,8 @@ export function canonicalTextureAtlasJsonV1(input: unknown): string {
return JSON.stringify(canonicalizeTextureAtlasSpecV1(input));
}
export function hashTextureAtlasSpecV1(input: unknown): `sha256:${string}` {
- return `sha256:${sha256Hex(`${TEXTURE_ATLAS_COMPILER_ID}\n${canonicalTextureAtlasJsonV1(input)}`)}`;
+ const spec = canonicalizeTextureAtlasSpecV1(input);
+ return `sha256:${sha256Hex(`${textureAtlasCompilerIdV1(spec)}\n${JSON.stringify(spec)}`)}`;
}
/** Internal identity helper for bounded atlas metadata; stable across object property order. */
export function canonicalAtlasMetadataJsonV1(input: unknown): string {
@@ -406,7 +611,7 @@ export function validateTextureAtlasManifestV1(
);
if (
r['version'] !== 'kiln.atlas-manifest.v1' ||
- r['compilerId'] !== TEXTURE_ATLAS_COMPILER_ID ||
+ r['compilerId'] !== textureAtlasCompilerIdV1(spec) ||
r['width'] !== spec.width ||
r['height'] !== spec.height ||
r['usage'] !== spec.usage ||
@@ -514,7 +719,7 @@ export function validateTextureAtlasManifestV1(
integer(
d['encodedByteLength'],
1,
- TEXTURE_ATLAS_LIMITS.encodedSourceBytes,
+ textureAtlasLimitsV1(spec).encodedSourceBytes,
'manifest encodedByteLength',
);
if (d['decodedPixelHash'] !== undefined && d['decodedPixelHash'] !== s['decodedPixelHash'])
diff --git a/src/texture-atlas-pixels.ts b/src/texture-atlas-pixels.ts
index 0111fe91..ade0fa31 100644
--- a/src/texture-atlas-pixels.ts
+++ b/src/texture-atlas-pixels.ts
@@ -20,8 +20,10 @@ import {
canonicalizeTextureAtlasSpecV1,
canonicalAtlasMetadataJsonV1,
hashTextureAtlasSpecV1,
- TEXTURE_ATLAS_COMPILER_ID,
TEXTURE_ATLAS_LIMITS,
+ textureAtlasCompilerIdV1,
+ textureAtlasLimitsV1,
+ type TextureAtlasCompilerIdV1,
type AtlasRectangleV1,
type CanonicalTextureAtlasRegionV1,
type CanonicalTextureAtlasSourceV1,
@@ -73,7 +75,7 @@ export interface TextureAtlasRegionManifestV1 {
}
export interface TextureAtlasManifestV1 {
version: 'kiln.atlas-manifest.v1';
- compilerId: typeof TEXTURE_ATLAS_COMPILER_ID;
+ compilerId: TextureAtlasCompilerIdV1;
width: number;
height: number;
usage: CanonicalTextureAtlasSpecV1['usage'];
@@ -145,6 +147,7 @@ export function admitTextureAtlasSpecV1(
options: TextureAtlasCompileOptionsV1 = {},
): TextureAtlasAdmissionV1 {
const spec = canonicalizeTextureAtlasSpecV1(input),
+ limits = textureAtlasLimitsV1(spec),
unique = new Map<string, PreparedSource>(),
crops = new Map<string, AtlasRectangleV1>();
const outputTexels = spec.width * spec.height;
@@ -214,17 +217,17 @@ export function admitTextureAtlasSpecV1(
}
budget.workUnits += (spec.regions.length * (spec.regions.length - 1)) / 2;
budget.conservativePixelAllocationBytes += budget.dilationScratchBytes;
- if (budget.sourceTexels > TEXTURE_ATLAS_LIMITS.sourceTexels)
+ if (budget.sourceTexels > limits.sourceTexels)
atlasFailure(
'full decoded source texel budget exceeded; a small crop does not reduce source decode cost.',
);
- if (budget.encodedBytes > TEXTURE_ATLAS_LIMITS.encodedBytes)
+ if (budget.encodedBytes > limits.encodedBytes)
atlasFailure('aggregate encoded source byte budget exceeded.');
- if (budget.workUnits > TEXTURE_ATLAS_LIMITS.work)
- atlasFailure(`aggregate work budget ${budget.workUnits} exceeds ${TEXTURE_ATLAS_LIMITS.work}.`);
- if (budget.conservativePixelAllocationBytes > TEXTURE_ATLAS_LIMITS.allocatedBytes)
+ if (budget.workUnits > limits.work)
+ atlasFailure(`aggregate work budget ${budget.workUnits} exceeds ${limits.work}.`);
+ if (budget.conservativePixelAllocationBytes > limits.allocatedBytes)
atlasFailure(
- `aggregate pixel allocation budget ${budget.conservativePixelAllocationBytes} exceeds ${TEXTURE_ATLAS_LIMITS.allocatedBytes}.`,
+ `aggregate pixel allocation budget ${budget.conservativePixelAllocationBytes} exceeds ${limits.allocatedBytes}.`,
);
return {
spec,
@@ -424,7 +427,7 @@ export async function compileTextureAtlasSpecV1(
const atlasPixelHash = await pixelDigest(tagged);
const payload = {
version: 'kiln.atlas-manifest.v1' as const,
- compilerId: TEXTURE_ATLAS_COMPILER_ID,
+ compilerId: textureAtlasCompilerIdV1(spec),
width: spec.width,
height: spec.height,
usage: spec.usage,
diff --git a/src/texture-atlas.ts b/src/texture-atlas.ts
index 9e20ef9e..144f3e97 100644
--- a/src/texture-atlas.ts
+++ b/src/texture-atlas.ts
@@ -9,8 +9,10 @@ import {
import {
atlasFailure,
canonicalAtlasMetadataJsonV1,
- TEXTURE_ATLAS_COMPILER_ID,
+ TEXTURE_ATLAS_COMPILER_IDS,
+ TEXTURE_ATLAS_COMPILER_ID_V1_2,
TEXTURE_ATLAS_LIMITS,
+ TEXTURE_ATLAS_LIMITS_V1_2,
} from './texture-atlas-contract';
import { sha256Hex } from './procedural-material-v2';
import { remapUV } from './uv-shapes';
@@ -57,19 +59,23 @@ function manifestOf(atlas: THREE.Texture | TextureAtlasManifestV1): TextureAtlas
atlasFailure('an atlas texture or compiled manifest is required.');
canonicalAtlasMetadataJsonV1(value);
const manifest = value as TextureAtlasManifestV1;
+ const limits =
+ manifest.compilerId === TEXTURE_ATLAS_COMPILER_ID_V1_2
+ ? TEXTURE_ATLAS_LIMITS_V1_2
+ : TEXTURE_ATLAS_LIMITS;
if (
manifest.version !== 'kiln.atlas-manifest.v1' ||
- manifest.compilerId !== TEXTURE_ATLAS_COMPILER_ID ||
+ !(TEXTURE_ATLAS_COMPILER_IDS as readonly unknown[]).includes(manifest.compilerId) ||
manifest.origin !== 'top-left' ||
!Array.isArray(manifest.regions) ||
!manifest.regions.length ||
- manifest.regions.length > 64 ||
+ manifest.regions.length > limits.regions ||
!Number.isSafeInteger(manifest.width) ||
manifest.width < 4 ||
- manifest.width > 1024 ||
+ manifest.width > limits.edge ||
!Number.isSafeInteger(manifest.height) ||
manifest.height < 4 ||
- manifest.height > 1024
+ manifest.height > limits.edge
)
atlasFailure('invalid atlas manifest dimensions/version.');
const { manifestHash, ...payload } = manifest;