Skip to content

3D engine that AI agents drive

Render 3D models as 2D icons in one job (#2031)

Nguyen Xuan An4b2750dec6a3
diff --git a/changes/2031.md b/changes/2031.md
new file mode 100644
index 00000000..f3de52e6
--- /dev/null
+++ b/changes/2031.md
@@ -0,0 +1 @@
+- `scene_render_submit` takes `kind: "icons"`: render up to 256 GLBs as matching transparent icons (clean or toon, fit or relative scale), with an atlas and `icons.json`, in one job (#2031)
diff --git a/changes/2031.size.md b/changes/2031.size.md
new file mode 100644
index 00000000..8013b7e1
--- /dev/null
+++ b/changes/2031.size.md
@@ -0,0 +1,2 @@
+- tool:scene_render_submit: the `icons` job kind adds `items`, `size`, `style`, `viewpoint`, `scale` and `padding` so an agent can ask for a whole icon set in one call; the detail stays in `scene_capabilities` topic `jobs` under `icons`, and the new code sits in the MCP server bundle only.
+- tool-total: the same 1125 bytes, all in `scene_render_submit`; no new tool.
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index 9a494584..c54dbb25 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -181,6 +181,40 @@ Passes in these formats are drawn into half-float targets, so albedo, normal and
The path tracer writes an 8-bit PNG of the whole frame: `transparent`, `format` and `region` are refused with `renderer`. H.264 has no alpha, so `transparent` and `format` are refused for video. 16-bit and EXR output need `EXT_color_buffer_float`; without it the job fails with a message that says to use `png`.
A `png16` or `exr` frame is up to four times the 8-bit frame limit (48 MiB). A region with the browser H.264 encoder (`encoder: "nvenc"`) uses screenshot frames instead.
+## Icons {since 0.22.0}
+
+`kind: "icons"` renders a set of GLBs as matching transparent square icons in one job, for inventories, asset browsers and docs. It is a job kind of `scene_render_submit`, so status, result and release work as for any job. The scene you submit it with is not drawn (any open scene will do, for instance an empty one).
+
+```json
+{ "kind": "icons", "items": ["sword.glb", "chest.glb", "coin.glb"], "size": 256, "style": "toon", "scale": "relative" }
+```
+
+| Field | Meaning |
+| --- | --- |
+| `items` | 1 to 256 catalog GLB names (as `scene_asset_catalog` lists them, inside `--assets` or `--packs`) or 64 character asset ids. Names are pinned to their asset id at submit. No paths outside the catalog and no URLs. |
+| `size` | 64, 128, 256 (default) or 512 pixels per icon side. The atlas side is at most 4096 px, so 512 takes up to 64 items. |
+| `style` | `clean` (default, the shaded render) or `toon` (outlines and three light bands, from [line art](line-art.md)). `sketch` is refused until it ships. |
+| `viewpoint` | `"three-quarter"` (default: azimuth 35, elevation 25 degrees) or `{ azimuth, elevation }` in degrees, from the front of the model (+Z in glTF). |
+| `scale` | `fit` (default): every item fills its icon. `relative`: one view height for the set, so the largest item fills its icon and a sword stays smaller than a chest. |
+| `padding` | The empty border as a fraction of the icon side, 0.02 to 0.4 (default 0.08), the same for every item. |
+
+The camera is orthographic, so an item's size does not depend on its distance, and the light is a fixed three-point rig that turns with the view, so every icon is lit from the same side. There is no ground and no sky: the background is transparent.
+
+Framing fits the silhouette, not the bounding sphere. The job draws the item once from a bounding sphere, measures the alpha box of what was drawn and moves the camera until that box is centred and spans the icon minus its padding (up to four draws per item). A thin or flat item such as a sword or a coin therefore fills its icon instead of drawing small. An item that draws nothing, or cannot be framed in four draws, fails the job and names the item.
+
+Output, all in the job's folder: `icon-0.png` to `icon-<n-1>.png` (one per item, in order), `atlas.png` (a near square grid, row by row, transparent where unused) and `icons.json`:
+
+```json
+{ "version": 1, "size": 256, "style": "toon", "scale": "relative", "padding": 0.08, "viewpoint": { "azimuth": 35, "elevation": 25 },
+ "atlas": { "file": "atlas.png", "width": 512, "height": 512, "columns": 2, "rows": 2 },
+ "icons": [{ "name": "sword", "file": "icon-0.png", "source": "sword.glb", "asset": "<id>", "angle": 35,
+ "rect": { "x": 0, "y": 0, "width": 256, "height": 256 }, "bounds": { "x": 70, "y": 21, "width": 116, "height": 214 }, "viewHeight": 2.1 }] }
+```
+
+`rect` is the icon's cell in the atlas, `bounds` the box of its pixels inside the icon, and `viewHeight` the metres the icon's height spans. The JSON is plain, so Godot, Unity, Phaser and web code read it without a converter. The same items and settings give byte-identical files on the `cpu` backend.
+
+Not in this release: `style: "sketch"`, turnaround sheets (`angles`), the `breakdown` strip, HDRI lighting, `background` and `outline` (issue #2031; each is refused by name), and scene node ids as items. `scene_capabilities` topic `jobs` lists the limits under `icons`. `node scripts/smoke-icons.mjs --assets <folder> --out <folder> --style toon` renders a folder of GLBs and checks every icon's frame.
+
## Path tracer
An `image`, `stills` or `video` job can ask for the offline [path tracer](https://github.com/codepawl/crucible/blob/main/docs/path-tracer.md) with `settings.renderer`:
diff --git a/scripts/agent-icon-job.mjs b/scripts/agent-icon-job.mjs
new file mode 100644
index 00000000..262d32bb
--- /dev/null
+++ b/scripts/agent-icon-job.mjs
@@ -0,0 +1,102 @@
+// The `icons` render job: draws each item as a transparent square icon, frames its silhouette, and writes one PNG per item,
+// an atlas of all of them and icons.json. The browser side is passed in as `openItem`, so the loop runs without a page.
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
+
+import { ICON_ARTIFACTS, alphaBounds, cameraForFraming, iconArtifactName, iconManifest, isFramed, layoutAtlas, refineFraming, relativeScale, sphereFraming } from '../src/icon-sheet.js';
+import { blankImage, copyIntoAtlas, decodePng, encodePng } from './agent-icon-png.mjs';
+
+/** Draws and measures at most this many times per item: the sphere guess, then up to three refinements. */
+const MAXIMUM_DRAWS = 4;
+const PNG_MIME = 'image/png';
+
+function drewNothingError(settings, index) {
+ const { source } = settings.items[index];
+ return new Error(`items[${index}] (${source}) drew no pixels. Check that the GLB has visible, opaque geometry in front of the camera.`);
+}
+
+function tooSmallForRelativeError(settings, index, sizeRatio) {
+ const { source } = settings.items[index];
+ return new Error(`items[${index}] (${source}) is too small for scale "relative": the largest item of the set is about ${Math.round(sizeRatio)} times its size, so it draws under one pixel. Use scale "fit", or give the set consistent units.`);
+}
+
+function notFramedError(settings, index, box) {
+ const { source } = settings.items[index];
+ return new Error(`items[${index}] (${source}) could not be framed in ${MAXIMUM_DRAWS} draws: its silhouette spans ${box.left},${box.top} to ${box.right},${box.bottom} of ${settings.size} px. Try a smaller padding or another view.`);
+}
+
+/**
+ * Draws one item until its silhouette is centred and inside the icon: a first guess from the bounding sphere, then each measured
+ * box moves the camera. With `fixedScale` the view height stays, so a set keeps one scale.
+ */
+async function frameItem({ item, index, settings, startFraming, fixedScale, signal }) {
+ const { size, viewpoint: view, padding } = settings;
+ let framing = startFraming;
+ for (let draw = 1; draw <= MAXIMUM_DRAWS; draw++) {
+ signal.throwIfAborted();
+ const image = decodePng(await item.draw(cameraForFraming(framing, view)));
+ if (image.width !== size || image.height !== size) throw new Error(`items[${index}] was drawn at ${image.width}x${image.height}, not ${size}x${size}. The render budget may have reduced the frame; raise --memory.`);
+ const box = alphaBounds(image.data, size, size);
+ if (!box) throw fixedScale === undefined ? drewNothingError(settings, index) : tooSmallForRelativeError(settings, index, fixedScale / startFraming.fittedScale);
+ if (isFramed(box, { size, padding, fit: fixedScale === undefined })) return { framing, image, box };
+ if (draw === MAXIMUM_DRAWS) throw notFramedError(settings, index, box);
+ framing = refineFraming(framing, box, { size, view, padding, fixedScale });
+ }
+ throw notFramedError(settings, index, { left: 0, top: 0, right: 0, bottom: 0 });
+}
+
+function entryOf({ framing, box }) {
+ return { bounds: { x: box.left, y: box.top, width: box.right - box.left, height: box.bottom - box.top }, viewHeight: Number(framing.orthoScale.toPrecision(7)) };
+}
+
+/**
+ * Runs the job. `openItem(item, index)` resolves to `{ bounds, draw(camera), close() }`: the item's world bounds, a function that
+ * draws it with a camera and returns a transparent PNG of the icon size, and a release. Returns the runner result the job store reads.
+ */
+export async function renderIconJob({ settings, directory, signal, progress, openItem }) {
+ const layout = layoutAtlas(settings.items.length, settings.size);
+ const atlas = blankImage(layout.width, layout.height);
+ const artifacts = [];
+ const entries = [];
+ const fitted = [];
+
+ async function withItem(index, work) {
+ const item = await openItem(settings.items[index], index);
+ try { return await work(item); }
+ finally { await item.close(); }
+ }
+
+ async function keep(index, image, framed) {
+ copyIntoAtlas(atlas, image, layout.rectangles[index].x, layout.rectangles[index].y);
+ const filename = iconArtifactName(index);
+ await writeFile(join(directory, `${filename}.partial`), encodePng(image), { flag: 'wx' });
+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: PNG_MIME });
+ entries[index] = entryOf(framed);
+ }
+
+ for (let index = 0; index < settings.items.length; index++) {
+ signal.throwIfAborted();
+ const framed = await withItem(index, async item => frameItem({ item, index, settings, startFraming: sphereFraming(item.bounds), signal }));
+ fitted[index] = framed.framing;
+ if (settings.scale === 'fit') await keep(index, framed.image, framed);
+ await progress({ frames: index + 1, maximumPendingFrames: 0 });
+ }
+
+ if (settings.scale === 'relative') {
+ const fixedScale = relativeScale(fitted.map(framing => framing.orthoScale));
+ for (let index = 0; index < settings.items.length; index++) {
+ signal.throwIfAborted();
+ const startFraming = { ...fitted[index], fittedScale: fitted[index].orthoScale, orthoScale: fixedScale };
+ const framed = await withItem(index, item => frameItem({ item, index, settings, startFraming, fixedScale, signal }));
+ await keep(index, framed.image, framed);
+ }
+ }
+
+ const atlasName = ICON_ARTIFACTS.atlas;
+ await writeFile(join(directory, `${atlasName}.partial`), encodePng(atlas), { flag: 'wx' });
+ artifacts.push({ temporary: `${atlasName}.partial`, filename: atlasName, mimeType: PNG_MIME });
+ const manifestName = ICON_ARTIFACTS.manifest;
+ await writeFile(join(directory, `${manifestName}.partial`), `${JSON.stringify(iconManifest({ settings, layout, entries }), null, 2)}\n`, { flag: 'wx' });
+ artifacts.push({ temporary: `${manifestName}.partial`, filename: manifestName, mimeType: 'application/json' });
+ return { artifacts, metrics: { icons: settings.items.length, atlasWidth: layout.width, atlasHeight: layout.height } };
+}
diff --git a/scripts/agent-icon-page.mjs b/scripts/agent-icon-page.mjs
new file mode 100644
index 00000000..053b467e
--- /dev/null
+++ b/scripts/agent-icon-page.mjs
@@ -0,0 +1,59 @@
+// The browser side of the `icons` job: one scene per item in the job page, drawn through the same preview API as every other job.
+import { iconRecipe } from '../src/icon-sheet.js';
+import { renderIconJob } from './agent-icon-job.mjs';
+
+const SCREENSHOT_OPTIONS = { fromSurface: true, format: 'png', optimizeForSpeed: true };
+
+/**
+ * Draws every item of an icons job in `jobPage` (already on the preview page and sized to the icon) and writes the job's files.
+ * `assetData(recipe)` returns the catalog bytes the recipe places, in the form `create` reads them.
+ */
+export async function renderIconsInPage({ jobPage, jobId, settings, directory, signal, progress, assetData, memoryBudgetMiB, backend, tier }) {
+ const cdp = await jobPage.context().newCDPSession(jobPage);
+ // A transparent canvas shows the page behind it in a screenshot, so the page and the browser's default are made clear.
+ await cdp.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
+ await jobPage.evaluate(() => {
+ document.documentElement.style.background = 'transparent';
+ document.body.style.background = 'transparent';
+ });
+ const metrics = { backend, requestedWidth: settings.size, requestedHeight: settings.size, drawCount: 0 };
+
+ async function openItem(item, index) {
+ if (!item.asset) throw new Error(`items[${index}] (${item.source}) has no pinned asset id. The runtime pins catalog names when the job is submitted.`);
+ const recipe = iconRecipe({ assetId: item.asset, style: settings.style, view: settings.viewpoint, size: settings.size });
+ const input = { sessionId: jobId, recipe, memoryBudgetMiB, backend, transparent: true, ...(tier ? { tier } : {}), ...(await assetData(recipe)) };
+ const created = await jobPage.evaluate(createInput => window.__agentPreview.create(createInput), input)
+ .catch(error => { throw new Error(`items[${index}] (${item.source}) could not be loaded: ${String(error.message).split('\n')[0]}`); });
+ try {
+ if (created.render.width < settings.size || created.render.height < settings.size) {
+ throw new Error(`The render budget reduced the frame to ${created.render.width}x${created.render.height}, below the ${settings.size} px icon. Start the server with a larger --memory or ask for a smaller size.`);
+ }
+ const inspected = await jobPage.evaluate(sessionId => window.__agentPreview.inspect({ sessionId }), jobId);
+ const bounds = inspected.assets?.[0]?.bounds;
+ if (!bounds) throw new Error(`items[${index}] (${item.source}) placed no geometry. Check that the GLB holds meshes.`);
+ return {
+ bounds,
+ async draw(camera) {
+ signal.throwIfAborted();
+ const frame = await jobPage.evaluate(drawInput => window.__agentPreview.frame(drawInput), { sessionId: jobId, camera });
+ if (backend === 'cpu' && !/swiftshader/i.test(frame.graphics)) throw new Error('CPU job did not select SwiftShader.');
+ metrics.graphics = frame.graphics;
+ metrics.drawCount++;
+ metrics.width = frame.width;
+ metrics.height = frame.height;
+ const captured = await cdp.send('Page.captureScreenshot', SCREENSHOT_OPTIONS);
+ return Buffer.from(captured.data, 'base64');
+ },
+ async close() {
+ await jobPage.evaluate(sessionId => window.__agentPreview.dispose({ sessionId }), jobId);
+ },
+ };
+ } catch (error) {
+ await jobPage.evaluate(sessionId => window.__agentPreview.dispose({ sessionId }), jobId).catch(() => {});
+ throw error;
+ }
+ }
+
+ const result = await renderIconJob({ settings, directory, signal, progress, openItem });
+ return { artifacts: result.artifacts, metrics: { ...metrics, ...result.metrics } };
+}
diff --git a/scripts/agent-icon-png.mjs b/scripts/agent-icon-png.mjs
new file mode 100644
index 00000000..3d1a6bf3
--- /dev/null
+++ b/scripts/agent-icon-png.mjs
@@ -0,0 +1,111 @@
+// 8-bit RGBA PNG reading and writing for the icons job: decode a browser screenshot, copy icons into an atlas, encode both.
+// The encoder is plain deflate at a fixed level, so the same pixels always give the same bytes.
+import { deflateSync, inflateSync } from 'node:zlib';
+
+const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+const MAXIMUM_PIXELS = 4096 * 4096;
+const CRC_TABLE = (() => {
+ const table = new Uint32Array(256);
+ for (let byte = 0; byte < 256; byte++) {
+ let value = byte;
+ for (let bit = 0; bit < 8; bit++) value = value & 1 ? 0xedb88320 ^ value >>> 1 : value >>> 1;
+ table[byte] = value >>> 0;
+ }
+ return table;
+})();
+
+function crc32(bytes) {
+ let crc = 0xffffffff;
+ for (const byte of bytes) crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type, data) {
+ const output = Buffer.alloc(12 + data.length);
+ output.writeUInt32BE(data.length, 0);
+ output.write(type, 4, 'latin1');
+ data.copy(output, 8);
+ output.writeUInt32BE(crc32(output.subarray(4, 8 + data.length)), 8 + data.length);
+ return output;
+}
+
+function paeth(left, up, upLeft) {
+ const estimate = left + up - upLeft;
+ const distanceLeft = Math.abs(estimate - left);
+ const distanceUp = Math.abs(estimate - up);
+ const distanceUpLeft = Math.abs(estimate - upLeft);
+ if (distanceLeft <= distanceUp && distanceLeft <= distanceUpLeft) return left;
+ return distanceUp <= distanceUpLeft ? up : upLeft;
+}
+
+/** The pixels of an 8-bit RGB or RGBA PNG without interlacing, as RGBA bytes row by row. Anything else throws. */
+export function decodePng(bytes) {
+ if (!Buffer.isBuffer(bytes) || bytes.length < 33 || !bytes.subarray(0, 8).equals(SIGNATURE)) throw new Error('Not a PNG file.');
+ const width = bytes.readUInt32BE(16);
+ const height = bytes.readUInt32BE(20);
+ const bitDepth = bytes[24];
+ const colorType = bytes[25];
+ const interlace = bytes[28];
+ if (bitDepth !== 8 || (colorType !== 6 && colorType !== 2) || interlace !== 0) {
+ throw new Error(`The icons job reads 8-bit RGB or RGBA PNGs without interlacing; got bit depth ${bitDepth}, colour type ${colorType}, interlace ${interlace}.`);
+ }
+ if (!width || !height || width * height > MAXIMUM_PIXELS) throw new Error(`PNG size ${width}x${height} is outside the icons job limit.`);
+ const data = [];
+ for (let offset = 8; offset < bytes.length;) {
+ const length = bytes.readUInt32BE(offset);
+ if (bytes.toString('latin1', offset + 4, offset + 8) === 'IDAT') data.push(bytes.subarray(offset + 8, offset + 8 + length));
+ offset += 12 + length;
+ }
+ const channels = colorType === 6 ? 4 : 3;
+ const raw = inflateSync(Buffer.concat(data));
+ const stride = width * channels;
+ if (raw.length !== (stride + 1) * height) throw new Error('PNG pixel data has the wrong length.');
+ const rgba = Buffer.alloc(width * height * 4, 255);
+ const previous = Buffer.alloc(stride);
+ const current = Buffer.alloc(stride);
+ for (let row = 0; row < height; row++) {
+ const filter = raw[row * (stride + 1)];
+ for (let index = 0; index < stride; index++) {
+ const value = raw[row * (stride + 1) + 1 + index];
+ const left = index >= channels ? current[index - channels] : 0;
+ const up = previous[index];
+ const upLeft = index >= channels ? previous[index - channels] : 0;
+ const predicted = filter === 0 ? 0 : filter === 1 ? left : filter === 2 ? up : filter === 3 ? (left + up) >> 1 : paeth(left, up, upLeft);
+ if (filter > 4) throw new Error(`PNG row ${row} has the unknown filter ${filter}.`);
+ current[index] = (value + predicted) & 255;
+ }
+ for (let column = 0; column < width; column++) {
+ for (let channel = 0; channel < channels; channel++) rgba[(row * width + column) * 4 + channel] = current[column * channels + channel];
+ }
+ current.copy(previous);
+ }
+ return { width, height, data: rgba };
+}
+
+/** An 8-bit RGBA PNG of the pixels. The same pixels always give the same bytes. */
+export function encodePng({ width, height, data }) {
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width, 0);
+ header.writeUInt32BE(height, 4);
+ header[8] = 8;
+ header[9] = 6;
+ const stride = width * 4;
+ const raw = Buffer.alloc((stride + 1) * height);
+ for (let row = 0; row < height; row++) {
+ raw[row * (stride + 1)] = 0;
+ Buffer.from(data.buffer, data.byteOffset + row * stride, stride).copy(raw, row * (stride + 1) + 1);
+ }
+ return Buffer.concat([SIGNATURE, chunk('IHDR', header), chunk('IDAT', deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
+}
+
+/** Copies `source` into `atlas` with its top left corner at (x, y). */
+export function copyIntoAtlas(atlas, source, x, y) {
+ for (let row = 0; row < source.height; row++) {
+ const from = row * source.width * 4;
+ source.data.copy(atlas.data, ((y + row) * atlas.width + x) * 4, from, from + source.width * 4);
+ }
+}
+
+export function blankImage(width, height) {
+ return { width, height, data: Buffer.alloc(width * height * 4) };
+}
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 1063b68e..31f92bbf 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -10,6 +10,7 @@ import { recipeAssetNeeds } from '../src/agent-scene-assets.js';
import { normalizeFilmTimeline, filmTimelineDuration, videoFrameCount } from '../src/film-timeline.js';
import { OIDN_DEFAULT_SAMPLES, PATH_TRACER_DENOISERS, PATH_TRACER_JOB_LIMITS } from '../src/path-tracer-capabilities.js';
import { AGENT_ASSET_LIMITS, describeAssetBytes } from '../src/agent-asset-limits.js';
+import { iconArtifactNames, normalizeIconSettings } from '../src/icon-sheet.js';
const UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
const STATES = ['queued', 'running', 'finalizing', 'completed', 'cancelling', 'cancelled', 'failed', 'interrupted'];
@@ -109,8 +110,9 @@ export function normalizeJobSettings(input, clips, recipe) {
}
function settingsFrom(input, clips = [], recipe) {
+ if (input?.kind === 'icons') return normalizeIconSettings(input);
objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes', 'renderer', 'timeline', 'audio', 'encoder', 'transparent', 'format', 'multilayer', 'region', 'quality', 'stillCount'], 'settings');
- if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');
+ if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills, video or icons.');
const largeFrame = input.kind === 'image';
const maximumSide = largeFrame ? MAXIMUM_JOB_SIDE : MAXIMUM_SEQUENCE_JOB_SIDE;
const maximumPixels = largeFrame ? MAXIMUM_JOB_PIXELS : MAXIMUM_SEQUENCE_JOB_PIXELS;
@@ -304,14 +306,17 @@ function passesFrom(passes, kind) {
/** Every artifact filename of a job, lit image first and then each requested pass, frame by frame. */
export function artifactNames(kind, passes = [], format = 'png', multilayer = false, stillCount = 8) {
if (kind === 'video') return ['render.mp4'];
+ // An icons job has one frame per item, so its frame count is its item count.
+ if (kind === 'icons') return iconArtifactNames(stillCount);
const extension = format === 'exr' ? 'exr' : 'png';
const stems = kind === 'image' ? ['render'] : Array.from({ length: stillCount }, (_, index) => `frame-${index}`);
if (multilayer) return stems.map(stem => `${stem}.${extension}`);
return stems.flatMap(stem => [`${stem}.${extension}`, ...passes.map(pass => `${stem}-${pass}.${extension}`)]);
}
-function artifactMimeType(settings) {
+function artifactMimeType(settings, filename = '') {
if (settings.kind === 'video') return 'video/mp4';
+ if (settings.kind === 'icons' && filename.endsWith('.json')) return 'application/json';
return settings.format === 'exr' ? 'image/x-exr' : 'image/png';
}
@@ -341,14 +346,15 @@ export function frameByteLimitFor(width, height, baseBytes) {
}
function artifactByteLimit(settings, limits) {
- if (settings.kind === 'video') return limits.maxOutputBytes;
+ // The atlas of a full icon set is the largest file; the combined output limit still caps the whole job.
+ if (settings.kind === 'video' || settings.kind === 'icons') return limits.maxOutputBytes;
const frameBytes = frameByteLimitFor(settings.width, settings.height, limits.maxFrameBytes);
return settings.format === undefined ? frameBytes : frameBytes * HIGH_PRECISION_FRAME_FACTOR;
}
function allowedFile(name) {
const passNames = RENDER_PASS_NAMES.join('|');
- const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:render|frame-\\d{1,3})(?:-(?:${passNames}))?\\.(?:png|exr))(?:\\.partial)?$`);
+ const artifact = new RegExp(`^(?:render\\.(?:png|mp4|exr)|(?:icon-\\d{1,3}|atlas)\\.png|icons\\.json|(?:render|frame-\\d{1,3})(?:-(?:${passNames}))?\\.(?:png|exr))(?:\\.partial)?$`);
return INTERNAL_FILES.has(name) || artifact.test(name);
}
@@ -844,7 +850,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inp
if (!namesAllowed.includes(artifact.filename) || seen.has(artifact.filename)) throw new Error('Invalid persisted artifact name.');
seen.add(artifact.filename);
const actual = await hashFile(join(directory, artifact.filename), artifactByteLimit(settings, limits));
- if (artifact.mimeType !== artifactMimeType(settings) || artifact.bytes !== actual.bytes || artifact.sha256 !== actual.sha256) throw new Error('Persisted artifact integrity failed.');
+ if (artifact.mimeType !== artifactMimeType(settings, artifact.filename) || artifact.bytes !== actual.bytes || artifact.sha256 !== actual.sha256) throw new Error('Persisted artifact integrity failed.');
}
if (record.state === 'completed' && record.artifacts.length !== namesAllowed.length) throw new Error('Completed job is missing its artifacts.');
const job = { record, persistence: Promise.resolve(), settled: Promise.resolve() };
@@ -928,7 +934,7 @@ export async function createAgentRenderJobs({ root, run, acquireGpu, limits: inp
let outputBytes = 0;
for (const output of completed.artifacts) {
objectKeys(output, ['temporary', 'filename', 'mimeType'], 'runner artifact');
- if (!expected.includes(output.filename) || seen.has(output.filename) || output.temporary !== `${output.filename}.partial` || output.mimeType !== artifactMimeType(record.settings)) throw new Error('Runner artifact must use the fixed filename and MIME type.');
+ if (!expected.includes(output.filename) || seen.has(output.filename) || output.temporary !== `${output.filename}.partial` || output.mimeType !== artifactMimeType(record.settings, output.filename)) throw new Error('Runner artifact must use the fixed filename and MIME type.');
seen.add(output.filename);
const artifact = { filename: output.filename, mimeType: output.mimeType, ...await hashFile(join(directory, output.temporary), artifactByteLimit(record.settings, limits)) };
outputBytes += artifact.bytes;
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 2b1a1a8a..aad0a3e9 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -44,6 +44,8 @@ import { RENDER_QUALITY_NOTE, applyQuality, tierReport } from './agent-render-qu
import { RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget } from './agent-render-budget.mjs';
import { RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, pathTraceTriangleProblem, renderReport, sceneSizeFrom } from './agent-render-estimate.mjs';
import { objectIdMetrics } from './agent-object-id-metrics.mjs';
+import { renderIconsInPage } from './agent-icon-page.mjs';
+import { ICON_CAPABILITIES } from '../src/icon-sheet.js';
import { encodeRenderOutput, encodeMultilayerExr } from './render-output-encoders.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
import { DEFAULT_PAGE_ENCODER_QUANTIZER, createFrameReceiver, startVideoEncoderInPage } from './gpu-frame-reader.mjs';
@@ -422,6 +424,24 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
await assertPlacedAssetsFitBeforeReading({}, [], recipe);
}
+ /**
+ * Pins each item of an icons job to its catalog asset id, so the job holds the content hash and a re-exported file cannot change
+ * a render in flight. An item is a catalog GLB name or an asset id; the original text stays as `source` for icons.json.
+ */
+ async function pinIconItems(settings) {
+ if (!Array.isArray(settings.items)) return settings;
+ const readyCatalog = await catalog();
+ const items = await Promise.all(settings.items.map(async item => {
+ if (typeof item !== 'string') return item;
+ if (/^[0-9a-f]{64}$/.test(item)) {
+ await readyCatalog.size(item);
+ return { source: item, asset: item };
+ }
+ return { source: item, asset: readyCatalog.resolveName(item) };
+ }));
+ return { ...settings, items };
+ }
+
/** Bytes of the catalog assets a recipe or edit list places, base64 by asset id, for the page that decodes them. */
async function placedAssetData(value) {
await assertPlacedAssetsFitBeforeReading(value);
@@ -847,6 +867,13 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
jobPage.setDefaultTimeout(15000);
await jobPage.goto(origin);
await jobPage.waitForFunction(() => Boolean(window.__agentPreview));
+ if (settings.kind === 'icons') {
+ // Each icon is its own scene, created and disposed inside the job, so the shared dispose below has nothing left to release.
+ const icons = await renderIconsInPage({ jobPage, jobId, settings, directory, signal, progress, assetData: placedAssetData, memoryBudgetMiB: memory, backend, tier: settings.quality });
+ metrics.renderSeconds = (performance.now() - started) / 1000;
+ metrics.elapsedSeconds = metrics.renderSeconds;
+ return { artifacts: icons.artifacts, metrics: { ...metrics, ...icons.metrics } };
+ }
const input = { sessionId: jobId, recipe: snapshot.recipe, memoryBudgetMiB: memory, backend, ...(settings.transparent ? { transparent: true } : {}), ...(settings.quality ? { tier: settings.quality } : {}),
...(snapshot.assetBytes ? { data: snapshot.assetBytes.toString('base64'), ...(await motionSources([snapshot.recipe.motion])) } : await placedAssetData(snapshot.recipe)) };
const created = await jobPage.evaluate(({ method, input }) => window.__agentPreview[method](input),
@@ -1129,7 +1156,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
finally {
try {
if (jobPage && !jobPage.isClosed()) {
- try { await jobPage.evaluate(sessionId => window.__agentPreview.dispose({ sessionId }), jobId); }
+ try { if (settings.kind !== 'icons') await jobPage.evaluate(sessionId => window.__agentPreview.dispose({ sessionId }), jobId); }
finally { await jobPage.close(); }
}
}
@@ -1199,7 +1226,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
maximumFileBytes: MAXIMUM_PACK_FILE_BYTES, maximumJsonBytes: MAXIMUM_PACK_JSON_BYTES, maximumItemsPerKind: MAXIMUM_PACK_ITEMS_PER_KIND,
use: 'scene_asset_catalog lists packs: name, version, license, author, description and item ids. GLBs, images, looks and environments carry assetId values that work in scene_create_asset, look, hdri and texture fields. Materials and recipes are read with scene_asset_catalog { pack, material } or { pack, recipe }: pass a recipe to scene_create, and a material as a materials entry or a scene_apply set-material. Packs are installed by the user (unzip into the --packs folder); a tool call never downloads one. Invalid packs are skipped and listed under packs.rejected with the reason.',
},
- jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1, estimate: RENDER_ESTIMATE_NOTE, budget: RENDER_BUDGET_NOTE, quality: RENDER_QUALITY_NOTE, tiers: await deviceTiers(),
+ jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video', 'icons'], icons: ICON_CAPABILITIES, passes: RENDER_PASS_NAMES, pathTracer: PATH_TRACER_CAPABILITIES, maximumActiveJobs: 1, estimate: RENDER_ESTIMATE_NOTE, budget: RENDER_BUDGET_NOTE, quality: RENDER_QUALITY_NOTE, tiers: await deviceTiers(),
maximumWidth: MAXIMUM_JOB_SIDE, maximumHeight: MAXIMUM_JOB_SIDE, maximumPixels: MAXIMUM_JOB_PIXELS, maximumSequenceWidth: MAXIMUM_SEQUENCE_JOB_SIDE, maximumSequenceHeight: MAXIMUM_SEQUENCE_JOB_SIDE, maximumSequencePixels: MAXIMUM_SEQUENCE_JOB_PIXELS, maximumSquareSide: MAXIMUM_SQUARE_JOB_SIDE, maximumSquareSequenceSide: MAXIMUM_SQUARE_SEQUENCE_JOB_SIDE,
maximumDuration: MAXIMUM_VIDEO_SECONDS, maximumFps: MAXIMUM_JOB_FPS, maximumFrames: MAXIMUM_JOB_FRAMES, maximumStills: 8, maximumStillCount: MAXIMUM_STILLS_FRAMES, stillCountNote: 'a stills job with stillCount (2 to maximumStillCount) and fps writes frame-0.png and on, one per 1 / fps s of the motion clock from motion.start; with transparent each is RGBA. Without stillCount it is 8 spread over duration.',
encoder: 'H.264', encoders: VIDEO_ENCODERS, audio: Boolean(audioRoot), timeline: true, previewSuspendedDuringJob: true,
@@ -1623,6 +1650,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return enqueue(async () => {
await requirePreviewRenderer();
const controller = await jobs();
+ if (settings?.kind === 'icons') settings = await pinIconItems(settings);
if (settings?.audio) {
if (!audioLibrary) throw new Error('Configure --audio with an absolute folder before submitting a job with audio.');
await audioLibrary.resolve(settings.audio.file);
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 753e222a..5a14a528 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -866,9 +866,15 @@ function jobKeysHint(toolName, acceptedKeys) {
: undefined);
}
const renderSettings = z.strictObject({
- kind: z.enum(['image', 'stills', 'video']),
- width: z.number().int().min(64).max(MAXIMUM_JOB_SIDE),
- height: z.number().int().min(64).max(MAXIMUM_JOB_SIDE),
+ kind: z.enum(['image', 'stills', 'video', 'icons']),
+ width: z.number().int().min(64).max(MAXIMUM_JOB_SIDE).optional().describe('Not for icons, which use size.'),
+ height: z.number().int().min(64).max(MAXIMUM_JOB_SIDE).optional(),
+ items: z.array(z.string().max(260)).min(1).max(256).optional().describe('icons: 1 to 256 catalog GLB names or asset ids; one transparent PNG each, plus atlas.png and icons.json. scene_capabilities jobs.icons.'),
+ size: z.union([z.literal(64), z.literal(128), z.literal(256), z.literal(512)]).optional().describe('icons: pixels per icon side (default 256).'),
+ style: z.enum(['clean', 'toon', 'sketch']).optional().describe('icons: clean (default) or toon; sketch is coming.'),
+ viewpoint: z.union([z.literal('three-quarter'), z.strictObject({ azimuth: z.number().optional(), elevation: z.number().optional() })]).optional().describe('icons: three-quarter (default) or azimuth and elevation in degrees.'),
+ scale: z.enum(['fit', 'relative']).optional().describe('icons: fit fills every icon; relative keeps one scale for the set.'),
+ padding: z.number().optional().describe('icons: border as a fraction of the icon, 0.02 to 0.4 (default 0.08).'),
fps: z.number().int().min(1).max(MAXIMUM_JOB_FPS).optional(),
duration: z.number().min(0.1).max(60).optional(),
animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),
diff --git a/scripts/smoke-icons.mjs b/scripts/smoke-icons.mjs
new file mode 100644
index 00000000..e786eb9f
--- /dev/null
+++ b/scripts/smoke-icons.mjs
@@ -0,0 +1,82 @@
+// Renders every GLB of a folder as icons through the MCP server on the cpu backend and copies the files to --out.
+// node scripts/smoke-icons.mjs --assets <folder of .glb files> --out <folder> [--style clean|toon] [--scale fit|relative] [--size 128] [--twice]
+// Checks each icon's alpha box against the frame (inside it, centred) and, with --twice, that a second job writes the same bytes.
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { copyFile, mkdir, readdir, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+import { mkdtemp } from 'node:fs/promises';
+
+const argumentsGiven = process.argv.slice(2);
+function option(name, fallback) {
+ const index = argumentsGiven.indexOf(`--${name}`);
+ return index < 0 ? fallback : argumentsGiven[index + 1];
+}
+const assets = resolve(option('assets', ''));
+const output = resolve(option('out', 'artifacts/icons'));
+const style = option('style', 'clean');
+const scale = option('scale', 'fit');
+const size = Number(option('size', 128));
+const runTwice = argumentsGiven.includes('--twice');
+const names = (await readdir(assets)).filter(name => name.endsWith('.glb')).sort();
+assert.ok(names.length, `No .glb files in ${assets}.`);
+const jobs = join(await mkdtemp(join(tmpdir(), 'crucible-icons-')), 'jobs');
+const cli = resolve('bin/crucible-mcp.mjs');
+const transport = new StdioClientTransport({ command: process.execPath, args: [cli, '--backend', 'cpu', '--memory', '256', '--assets', assets, '--jobs', jobs], stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-4096); });
+const client = new Client({ name: 'crucible-icons-proof', version: '1' });
+
+async function call(name, argumentsValue = {}) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 600000 });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result.structuredContent;
+}
+
+async function runJob() {
+ const created = await call('scene_create', { recipe: { format: 'crucible.scene', schemaVersion: 1, geometries: [{ id: 'g', type: 'box' }], materials: [{ id: 'm' }], nodes: [{ id: 'n', geometry: 'g', material: 'm' }] } });
+ const submitted = await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: 0, settings: { kind: 'icons', items: names, size, style, scale } });
+ const deadline = Date.now() + 580000;
+ for (;;) {
+ const record = await call('scene_render_status', { jobId: submitted.jobId });
+ if (['completed', 'failed', 'cancelled'].includes(record.state)) {
+ assert.equal(record.state, 'completed', record.reason);
+ break;
+ }
+ assert.ok(Date.now() < deadline, 'The icons job did not finish in time.');
+ await new Promise(done => setTimeout(done, 500));
+ }
+ const result = await call('scene_render_result', { jobId: submitted.jobId });
+ return { jobId: submitted.jobId, artifacts: result.artifacts };
+}
+
+const digest = async path => createHash('sha256').update(await readFile(path)).digest('hex');
+try {
+ await client.connect(transport);
+ const first = await runJob();
+ await mkdir(output, { recursive: true });
+ for (const artifact of first.artifacts) await copyFile(artifact.path, join(output, artifact.filename));
+ const manifest = JSON.parse(await readFile(join(output, 'icons.json'), 'utf8'));
+ for (const icon of manifest.icons) {
+ const { x, y, width, height } = icon.bounds;
+ assert.ok(x >= 1 && y >= 1 && x + width <= size - 1 && y + height <= size - 1, `${icon.name} touches the frame edge: ${JSON.stringify(icon.bounds)}`);
+ console.log(icon.name.padEnd(28), JSON.stringify(icon.bounds), `view height ${icon.viewHeight}`);
+ }
+ if (runTwice) {
+ const second = await runJob();
+ for (const artifact of first.artifacts) {
+ const other = second.artifacts.find(candidate => candidate.filename === artifact.filename);
+ assert.equal(await digest(artifact.path), await digest(other.path), `${artifact.filename} differs between two runs`);
+ }
+ console.log(`${first.artifacts.length} files are byte-identical across two jobs`);
+ }
+ console.log(`wrote ${first.artifacts.length} files to ${output}`);
+} catch (error) {
+ console.error(error.message, diagnostics);
+ process.exitCode = 1;
+} finally {
+ await client.close();
+}
diff --git a/src/icon-sheet.js b/src/icon-sheet.js
new file mode 100644
index 00000000..ead1f800
--- /dev/null
+++ b/src/icon-sheet.js
@@ -0,0 +1,287 @@
+// Icon sheets: the pure part of the `icons` render job (docs/agent-render-jobs.md, "Icons"). Validation of the job settings, the camera
+// and light rig, the framing arithmetic that fits one silhouette, the atlas layout and the icons.json manifest. No browser, no files.
+import { invalidField } from './field-error.js';
+
+export const ICON_LIMITS = Object.freeze({
+ maximumItems: 256,
+ sizes: Object.freeze([64, 128, 256, 512]),
+ styles: Object.freeze(['clean', 'toon']),
+ scales: Object.freeze(['fit', 'relative']),
+ maximumAtlasSide: 4096,
+ minimumPadding: 0.02,
+ maximumPadding: 0.4,
+ defaultPadding: 0.08,
+ defaultView: Object.freeze({ azimuth: 35, elevation: 25 }),
+ maximumElevation: 89,
+});
+
+/** What `icons` leaves out of this release, named so an error can say it is coming and not that it is unknown. */
+const COMING_FIELDS = Object.freeze({
+ angles: 'turnaround sheets (angles 4 or 8)',
+ breakdown: 'the step-by-step strip',
+ lighting: 'an HDRI rig (the three-point rig is fixed)',
+ background: 'a background colour (icons are transparent)',
+ outline: 'an outline colour and width',
+});
+
+const ASSET_ID = /^[0-9a-f]{64}$/;
+const URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
+const DERIVED_FIELDS = ['width', 'height', 'fps', 'duration', 'transparent'];
+const SETTING_FIELDS = ['kind', 'items', 'size', 'style', 'viewpoint', 'scale', 'padding', ...DERIVED_FIELDS];
+const MAXIMUM_ITEM_LENGTH = 260;
+
+export const ICON_ARTIFACTS = Object.freeze({ atlas: 'atlas.png', manifest: 'icons.json' });
+
+export function iconArtifactName(index) {
+ return `icon-${index}.png`;
+}
+
+/** Every artifact of an icons job, in the order the runner writes them: one PNG per item, the atlas, then icons.json. */
+export function iconArtifactNames(itemCount) {
+ return [...Array.from({ length: itemCount }, (_, index) => iconArtifactName(index)), ICON_ARTIFACTS.atlas, ICON_ARTIFACTS.manifest];
+}
+
+/** How many items fit one atlas at this size: a square grid no wider than the atlas limit. */
+export function atlasCapacity(size) {
+ return (ICON_LIMITS.maximumAtlasSide / size) ** 2;
+}
+
+function itemFrom(item, position) {
+ const label = `items[${position}]`;
+ if (typeof item === 'string') item = { source: item };
+ if (!item || Object.getPrototypeOf(item) !== Object.prototype || typeof item.source !== 'string') {
+ throw invalidField(label, typeof item, 'a catalog GLB name from scene_asset_catalog, such as "sword.glb", or its 64 hexadecimal asset id', TypeError);
+ }
+ const source = item.source;
+ if (!source || source.length > MAXIMUM_ITEM_LENGTH) {
+ throw invalidField(label, `${source.length} characters`, `a catalog GLB name of 1 to ${MAXIMUM_ITEM_LENGTH} characters`, RangeError);
+ }
+ if (URL_SCHEME.test(source)) {
+ throw invalidField(label, source.slice(0, 60), 'a catalog GLB name from scene_asset_catalog (inside --assets or --packs); remote URLs are not accepted', RangeError);
+ }
+ if (item.asset !== undefined && (typeof item.asset !== 'string' || !ASSET_ID.test(item.asset))) {
+ throw invalidField(`${label}.asset`, String(item.asset).slice(0, 20), 'the 64 hexadecimal characters of a catalog asset id', RangeError);
+ }
+ return item.asset === undefined ? { source } : { source, asset: item.asset };
+}
+
+function viewFrom(view) {
+ if (view === undefined || view === 'three-quarter') return { ...ICON_LIMITS.defaultView };
+ if (!view || Object.getPrototypeOf(view) !== Object.prototype) {
+ throw invalidField('viewpoint', typeof view, '"three-quarter" or { azimuth, elevation } in degrees', TypeError);
+ }
+ for (const key of Object.keys(view)) {
+ if (!['azimuth', 'elevation'].includes(key)) throw invalidField(`viewpoint.${key}`, 'an unknown field', 'only azimuth and elevation, in degrees', TypeError);
+ }
+ const azimuth = view.azimuth ?? ICON_LIMITS.defaultView.azimuth;
+ const elevation = view.elevation ?? ICON_LIMITS.defaultView.elevation;
+ if (!Number.isFinite(azimuth) || azimuth < -180 || azimuth > 180) throw invalidField('viewpoint.azimuth', azimuth, 'degrees from -180 to 180', RangeError);
+ if (!Number.isFinite(elevation) || Math.abs(elevation) > ICON_LIMITS.maximumElevation) {
+ throw invalidField('viewpoint.elevation', elevation, `degrees from -${ICON_LIMITS.maximumElevation} to ${ICON_LIMITS.maximumElevation}`, RangeError);
+ }
+ return { azimuth, elevation };
+}
+
+/**
+ * The settings of an icons job as the store keeps them, every default filled in and every limit checked. `items` may be bare
+ * strings (the caller's form) or `{ source, asset }` (the pinned form the runtime stores, where `asset` is the catalog id).
+ * It also fills the frame fields the rest of the job store reads (width, height, fps, duration), so an icons job has a size
+ * and a frame count like any other job: one frame per item.
+ */
+export function normalizeIconSettings(input) {
+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw new TypeError('settings must be a plain object.');
+ for (const key of Object.keys(input)) {
+ if (COMING_FIELDS[key] !== undefined) {
+ throw invalidField(`settings.${key}`, 'a field the first icons release leaves out', `no ${key}: ${COMING_FIELDS[key]} is coming (issue #2031)`, RangeError);
+ }
+ if (!SETTING_FIELDS.includes(key)) {
+ throw new TypeError(`Unknown settings field: ${key}. Allowed fields for kind icons: ${SETTING_FIELDS.filter(field => !DERIVED_FIELDS.includes(field)).join(', ')}.`);
+ }
+ }
+ if (!Array.isArray(input.items) || input.items.length < 1 || input.items.length > ICON_LIMITS.maximumItems) {
+ throw invalidField('items', Array.isArray(input.items) ? input.items.length : typeof input.items, `a list of 1 to ${ICON_LIMITS.maximumItems} catalog GLB names (the count of items it holds is shown when it is a list)`, RangeError);
+ }
+ const size = input.size ?? 256;
+ if (!ICON_LIMITS.sizes.includes(size)) throw invalidField('size', size, `one of ${ICON_LIMITS.sizes.join(', ')} (pixels per icon side)`, RangeError);
+ const capacity = atlasCapacity(size);
+ if (input.items.length > capacity) {
+ throw invalidField('items', input.items.length, `at most ${capacity} items at size ${size} (the atlas side is capped at ${ICON_LIMITS.maximumAtlasSide} px), or a smaller size`, RangeError);
+ }
+ const style = input.style ?? 'clean';
+ if (style === 'sketch') throw invalidField('style', 'sketch', 'clean or toon: the sketch style is coming (issue #2031)', RangeError);
+ if (!ICON_LIMITS.styles.includes(style)) throw invalidField('style', String(style), `one of ${ICON_LIMITS.styles.join(', ')}`, RangeError);
+ const scale = input.scale ?? 'fit';
+ if (!ICON_LIMITS.scales.includes(scale)) throw invalidField('scale', String(scale), `fit (every item fills its frame) or relative (one scale for the set)`, RangeError);
+ const padding = input.padding ?? ICON_LIMITS.defaultPadding;
+ if (!Number.isFinite(padding) || padding < ICON_LIMITS.minimumPadding || padding > ICON_LIMITS.maximumPadding) {
+ throw invalidField('padding', padding, `a fraction of the icon side from ${ICON_LIMITS.minimumPadding} to ${ICON_LIMITS.maximumPadding}`, RangeError);
+ }
+ const items = input.items.map(itemFrom);
+ return { kind: 'icons', size, width: size, height: size, fps: 1, duration: 1, frameCount: items.length, transparent: true, items, style, viewpoint: viewFrom(input.viewpoint), scale, padding };
+}
+
+/** The lowercase unit vector from the subject toward the camera, and the camera's right and up axes, for a azimuth and elevation in degrees. */
+export function cameraBasis({ azimuth, elevation }) {
+ const azimuthRadians = azimuth * Math.PI / 180;
+ const elevationRadians = elevation * Math.PI / 180;
+ const toCamera = [Math.sin(azimuthRadians) * Math.cos(elevationRadians), Math.sin(elevationRadians), Math.cos(azimuthRadians) * Math.cos(elevationRadians)];
+ const right = [Math.cos(azimuthRadians), 0, -Math.sin(azimuthRadians)];
+ const up = [
+ toCamera[1] * right[2] - toCamera[2] * right[1],
+ toCamera[2] * right[0] - toCamera[0] * right[2],
+ toCamera[0] * right[1] - toCamera[1] * right[0],
+ ];
+ return { toCamera, right, up };
+}
+
+/** A framing that holds the whole bounding sphere: the first guess, before any silhouette is measured. */
+export function sphereFraming(bounds) {
+ const center = [0, 1, 2].map(axis => (bounds.min[axis] + bounds.max[axis]) / 2);
+ const radius = Math.max(1e-6, Math.hypot(...[0, 1, 2].map(axis => (bounds.max[axis] - bounds.min[axis]) / 2)));
+ return { center, radius, orthoScale: radius * 2 };
+}
+
+/** The orthographic camera of a framing: square view, `orthoScale` metres tall, looking at the center along the view direction. */
+export function cameraForFraming(framing, view) {
+ const { toCamera } = cameraBasis(view);
+ const distance = framing.radius * 3;
+ return {
+ eye: framing.center.map((value, axis) => value + toCamera[axis] * distance),
+ target: [...framing.center],
+ up: [0, 1, 0],
+ projection: 'orthographic',
+ orthoScale: framing.orthoScale,
+ near: Math.max(0.001, distance - framing.radius * 1.1),
+ far: distance + framing.radius * 1.1,
+ };
+}
+
+/**
+ * The fixed three-point rig: a key from above the camera's left, a fill and a rim from the studio's two fill lights, and a soft
+ * ambient term. The key direction follows the view, so every icon of a set is lit from the same side of its own picture.
+ */
+export function lightRigEnvironment(view) {
+ const { toCamera, right, up } = cameraBasis(view);
+ const lightDirection = [0, 1, 2].map(axis => -right[axis] * 0.55 + up[axis] * 0.7 + toCamera[axis] * 0.6);
+ const length = Math.hypot(...lightDirection);
+ // No ground and no sky: an icon is the item alone on a transparent background.
+ return { ground: false, world: false, lightDirection: lightDirection.map(value => value / length), keyIntensity: 1, fillIntensity: 0.6, ambientIntensity: 0.7 };
+}
+
+/** The line width of the toon style in output pixels: the same share of the picture at every size. */
+export function toonLineWidth(size) {
+ return Math.max(0.75, size / 128);
+}
+
+/** The scene recipe that draws one catalog asset as an icon: the asset at the origin, the light rig, and line art for toon. */
+export function iconRecipe({ assetId, style, view, size }) {
+ const environment = lightRigEnvironment(view);
+ if (style === 'toon') environment.lines = { width: toonLineWidth(size), toon: 3 };
+ return { format: 'crucible.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [{ id: 'icon', asset: { id: assetId } }], environment };
+}
+
+/** The pixel box of the pixels whose alpha passes `threshold`, with exclusive right and bottom, or null when nothing is drawn. */
+export function alphaBounds(rgba, width, height, threshold = 1) {
+ let left = width;
+ let top = height;
+ let right = -1;
+ let bottom = -1;
+ for (let row = 0; row < height; row++) {
+ for (let column = 0; column < width; column++) {
+ if (rgba[(row * width + column) * 4 + 3] < threshold) continue;
+ if (column < left) left = column;
+ if (column > right) right = column;
+ if (row < top) top = row;
+ if (row > bottom) bottom = row;
+ }
+ }
+ return right < 0 ? null : { left, top, right: right + 1, bottom: bottom + 1 };
+}
+
+/**
+ * The framing that puts a measured silhouette in the middle of its icon. `fixedScale` keeps the view height (the relative
+ * scale of a set); without it the view height changes so the longer side of the silhouette spans the icon minus its padding.
+ * The view is orthographic, so a box measured in the picture maps back to the view plane by a plain ratio.
+ */
+export function refineFraming(framing, box, { size, view, padding, fixedScale }) {
+ const metresPerPixel = framing.orthoScale / size;
+ const { right, up } = cameraBasis(view);
+ const shiftRight = ((box.left + box.right) / 2 - size / 2) * metresPerPixel;
+ const shiftUp = -((box.top + box.bottom) / 2 - size / 2) * metresPerPixel;
+ const center = framing.center.map((value, axis) => value + right[axis] * shiftRight + up[axis] * shiftUp);
+ const extent = Math.max(box.right - box.left, box.bottom - box.top);
+ const fitScale = framing.orthoScale * extent / (size * (1 - 2 * padding));
+ return { center, radius: framing.radius, orthoScale: Math.max(framing.radius * 0.02, fixedScale ?? fitScale) };
+}
+
+/** Whether a silhouette sits in its frame: centred within a pixel, inside the edges, and (for `fit`) spanning the padded side within 2 pixels. */
+export function isFramed(box, { size, padding, fit = true }) {
+ const centeredColumn = Math.abs((box.left + box.right) / 2 - size / 2) <= 1;
+ const centeredRow = Math.abs((box.top + box.bottom) / 2 - size / 2) <= 1;
+ const inside = box.left >= 1 && box.top >= 1 && box.right <= size - 1 && box.bottom <= size - 1;
+ if (!inside || !centeredColumn || !centeredRow) return false;
+ if (!fit) return true;
+ const extent = Math.max(box.right - box.left, box.bottom - box.top);
+ return Math.abs(extent - size * (1 - 2 * padding)) <= 2;
+}
+
+/** The view height of the whole set at one scale: the largest fitted view height, so the biggest item fills its icon and the rest stay smaller. */
+export function relativeScale(fittedScales) {
+ return Math.max(...fittedScales);
+}
+
+/** A square grid of cells, row by row: the atlas rectangle of every item. */
+export function layoutAtlas(count, size) {
+ const columns = Math.ceil(Math.sqrt(count));
+ const rows = Math.ceil(count / columns);
+ const rectangles = Array.from({ length: count }, (_, index) => ({ x: index % columns * size, y: Math.floor(index / columns) * size, width: size, height: size }));
+ return { columns, rows, width: columns * size, height: rows * size, rectangles };
+}
+
+/** Unique, file-safe names for the items: the file name without folder or extension, with the item number added to a repeat. */
+export function iconNames(sources) {
+ const bases = sources.map(source => (source.split(/[\\/]/).pop() ?? source).replace(/\.glb$/i, '').replace(/[^A-Za-z0-9._-]+/g, '-') || 'item');
+ const counts = new Map();
+ for (const base of bases) counts.set(base, (counts.get(base) ?? 0) + 1);
+ return bases.map((base, index) => (counts.get(base) > 1 ? `${base}-${index}` : base));
+}
+
+/** The icons.json document: plain JSON a game engine or web page reads without a converter. */
+export function iconManifest({ settings, layout, entries }) {
+ const names = iconNames(settings.items.map(item => item.source));
+ return {
+ version: 1,
+ size: settings.size,
+ style: settings.style,
+ scale: settings.scale,
+ padding: settings.padding,
+ viewpoint: settings.viewpoint,
+ atlas: { file: ICON_ARTIFACTS.atlas, width: layout.width, height: layout.height, columns: layout.columns, rows: layout.rows },
+ icons: settings.items.map((item, index) => ({
+ name: names[index],
+ file: iconArtifactName(index),
+ source: item.source,
+ asset: item.asset,
+ angle: settings.viewpoint.azimuth,
+ rect: layout.rectangles[index],
+ bounds: entries[index].bounds,
+ viewHeight: entries[index].viewHeight,
+ })),
+ };
+}
+
+/** What `scene_capabilities` jobs reports for kind icons: the limits the validator enforces and the files a job writes. */
+export const ICON_CAPABILITIES = Object.freeze({
+ kind: 'icons',
+ note: 'settings.kind icons draws each item (a catalog GLB name or asset id from scene_asset_catalog) as a transparent square icon with an orthographic three-quarter view, a fixed three-point light rig and a silhouette fit. Writes icon-<n>.png per item, atlas.png and icons.json (name, atlas rect, source, bounds). The submitted scene is not drawn.',
+ maximumItems: ICON_LIMITS.maximumItems,
+ sizes: ICON_LIMITS.sizes,
+ styles: ICON_LIMITS.styles,
+ comingStyles: Object.freeze(['sketch']),
+ scales: ICON_LIMITS.scales,
+ viewpoint: Object.freeze({ default: 'three-quarter', azimuth: ICON_LIMITS.defaultView.azimuth, elevation: ICON_LIMITS.defaultView.elevation, maximumElevation: ICON_LIMITS.maximumElevation }),
+ padding: Object.freeze({ default: ICON_LIMITS.defaultPadding, minimum: ICON_LIMITS.minimumPadding, maximum: ICON_LIMITS.maximumPadding }),
+ maximumAtlasSide: ICON_LIMITS.maximumAtlasSide,
+ itemsPerSize: Object.freeze(Object.fromEntries(ICON_LIMITS.sizes.map(size => [size, Math.min(ICON_LIMITS.maximumItems, atlasCapacity(size))]))),
+ notYet: Object.freeze(Object.keys(COMING_FIELDS)),
+});
diff --git a/tests/agent-icon-job.test.js b/tests/agent-icon-job.test.js
new file mode 100644
index 00000000..5fc2c865
--- /dev/null
+++ b/tests/agent-icon-job.test.js
@@ -0,0 +1,168 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { renderIconJob } from '../scripts/agent-icon-job.mjs';
+import { decodePng, encodePng } from '../scripts/agent-icon-png.mjs';
+import { alphaBounds, normalizeIconSettings } from '../src/icon-sheet.js';
+import { artifactNames, normalizeJobSettings } from '../scripts/agent-render-jobs.mjs';
+
+const subtract = (a, b) => a.map((value, axis) => value - b[axis]);
+const dot = (a, b) => a.reduce((sum, value, axis) => sum + value * b[axis], 0);
+const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+const normalize = a => a.map(value => value / Math.hypot(...a));
+
+/** A stand-in for the page: draws an axis aligned box as the filled screen box of its eight corners, through its own orthographic projection. */
+function boxItem(dimensions, size, centerOffset = [0, 0, 0]) {
+ const bounds = { min: centerOffset.map((value, axis) => value - dimensions[axis] / 2), max: centerOffset.map((value, axis) => value + dimensions[axis] / 2) };
+ return {
+ bounds,
+ async draw(camera) {
+ const forward = normalize(subtract(camera.target, camera.eye));
+ const right = normalize(cross(forward, camera.up));
+ const up = cross(right, forward);
+ const corners = Array.from({ length: 8 }, (_, corner) => [0, 1, 2].map(axis => (corner & (1 << axis) ? bounds.max[axis] : bounds.min[axis])));
+ const screen = corners.map(point => {
+ const offset = subtract(point, camera.target);
+ return [size / 2 + dot(offset, right) / camera.orthoScale * size, size / 2 - dot(offset, up) / camera.orthoScale * size];
+ });
+ const left = Math.min(...screen.map(point => point[0]));
+ const right2 = Math.max(...screen.map(point => point[0]));
+ const top = Math.min(...screen.map(point => point[1]));
+ const bottom = Math.max(...screen.map(point => point[1]));
+ const data = Buffer.alloc(size * size * 4);
+ for (let row = 0; row < size; row++) {
+ for (let column = 0; column < size; column++) {
+ if (column + 0.5 < left || column + 0.5 > right2 || row + 0.5 < top || row + 0.5 > bottom) continue;
+ data.set([200, 90, 40, 255], (row * size + column) * 4);
+ }
+ }
+ return encodePng({ width: size, height: size, data });
+ },
+ async close() {},
+ };
+}
+
+const SHAPES = { coin: [0.5, 0.04, 0.5], sword: [0.08, 1.6, 0.03], chest: [2.4, 1.8, 1.6] };
+
+async function runJob(sources, overrides = {}) {
+ const size = overrides.size ?? 128;
+ const settings = normalizeIconSettings({ kind: 'icons', items: sources, size, ...overrides });
+ const directory = await mkdtemp(join(tmpdir(), 'crucible-icons-test-'));
+ const progressCalls = [];
+ const result = await renderIconJob({
+ settings, directory, signal: new AbortController().signal,
+ progress: async update => { progressCalls.push(update.frames); },
+ openItem: async item => boxItem(SHAPES[item.source], size),
+ });
+ const files = {};
+ for (const artifact of result.artifacts) files[artifact.filename] = await readFile(join(directory, artifact.temporary));
+ await rm(directory, { recursive: true, force: true });
+ return { settings, result, files, progressCalls };
+}
+
+function iconBox(png) {
+ const image = decodePng(png);
+ return alphaBounds(image.data, image.width, image.height);
+}
+
+test('a thin flat item fills its icon and no item is clipped, measured on the alpha box', async () => {
+ const { files, settings } = await runJob(['coin', 'sword', 'chest']);
+ for (const [index, name] of ['coin', 'sword', 'chest'].entries()) {
+ const box = iconBox(files[`icon-${index}.png`]);
+ const extent = Math.max(box.right - box.left, box.bottom - box.top);
+ assert.ok(box.left >= 1 && box.top >= 1 && box.right <= settings.size - 1 && box.bottom <= settings.size - 1, `${name} is clipped: ${JSON.stringify(box)}`);
+ assert.ok(extent >= settings.size * (1 - 2 * settings.padding) - 2, `${name} is drawn small: ${extent} px of ${settings.size}`);
+ assert.ok(Math.abs((box.left + box.right) / 2 - settings.size / 2) <= 1, `${name} is off centre horizontally`);
+ assert.ok(Math.abs((box.top + box.bottom) / 2 - settings.size / 2) <= 1, `${name} is off centre vertically`);
+ }
+});
+
+test('every item uses the same padding at any size', async () => {
+ for (const size of [64, 256]) {
+ const { files, settings } = await runJob(['coin', 'sword'], { size, padding: 0.12 });
+ for (const index of [0, 1]) {
+ const box = iconBox(files[`icon-${index}.png`]);
+ const extent = Math.max(box.right - box.left, box.bottom - box.top);
+ assert.ok(Math.abs(extent - size * (1 - 2 * settings.padding)) <= 2, `size ${size} icon ${index} spans ${extent}`);
+ }
+ }
+});
+
+test('relative scale keeps the size order of the set: coin, then sword, then chest', async () => {
+ const { files, result } = await runJob(['coin', 'sword', 'chest'], { scale: 'relative' });
+ const extents = [0, 1, 2].map(index => {
+ const box = iconBox(files[`icon-${index}.png`]);
+ return Math.max(box.right - box.left, box.bottom - box.top);
+ });
+ const manifest = JSON.parse(files['icons.json']);
+ assert.equal(new Set(manifest.icons.map(icon => icon.viewHeight)).size, 1, 'one view height for the whole set');
+ assert.ok(extents[0] < extents[1], `coin ${extents[0]} px is smaller than sword ${extents[1]} px`);
+ assert.ok(extents[1] < extents[2], `sword ${extents[1]} px is smaller than chest ${extents[2]} px`);
+ assert.ok(extents[2] >= 128 * 0.84 - 2, 'the largest item still fills its icon');
+ assert.equal(result.artifacts.length, 5);
+});
+
+test('relative scale names an item that is under one pixel next to the largest, and fit still draws it', async () => {
+ SHAPES.speck = [0.001, 0.001, 0.001];
+ try {
+ await assert.rejects(runJob(['speck', 'chest'], { scale: 'relative' }), /items\[0\] \(speck\) is too small for scale "relative".*Use scale "fit"/);
+ const fitted = await runJob(['speck', 'chest']);
+ assert.ok(iconBox(fitted.files['icon-0.png']));
+ } finally {
+ delete SHAPES.speck;
+ }
+});
+
+test('fit scale gives each item its own view height', async () => {
+ const { files } = await runJob(['coin', 'sword', 'chest']);
+ const manifest = JSON.parse(files['icons.json']);
+ assert.equal(new Set(manifest.icons.map(icon => icon.viewHeight)).size, 3);
+});
+
+test('the atlas holds every icon at its rectangle, and icons.json describes the layout', async () => {
+ const { files, settings, progressCalls } = await runJob(['coin', 'sword', 'chest']);
+ const manifest = JSON.parse(files['icons.json']);
+ const atlas = decodePng(files['atlas.png']);
+ assert.deepEqual(manifest.atlas, { file: 'atlas.png', width: 256, height: 256, columns: 2, rows: 2 });
+ assert.equal(atlas.width, 256);
+ assert.equal(atlas.height, 256);
+ assert.deepEqual(manifest.icons.map(icon => icon.name), ['coin', 'sword', 'chest']);
+ assert.deepEqual(manifest.icons.map(icon => icon.rect), [{ x: 0, y: 0, width: 128, height: 128 }, { x: 128, y: 0, width: 128, height: 128 }, { x: 0, y: 128, width: 128, height: 128 }]);
+ for (const [index, icon] of manifest.icons.entries()) {
+ const picture = decodePng(files[icon.file]);
+ for (let row = 0; row < settings.size; row++) {
+ const fromAtlas = atlas.data.subarray(((icon.rect.y + row) * atlas.width + icon.rect.x) * 4, ((icon.rect.y + row) * atlas.width + icon.rect.x + settings.size) * 4);
+ assert.ok(fromAtlas.equals(picture.data.subarray(row * settings.size * 4, (row + 1) * settings.size * 4)), `icon ${index} row ${row} differs in the atlas`);
+ }
+ assert.deepEqual(icon.bounds, (({ left, top, right, bottom }) => ({ x: left, y: top, width: right - left, height: bottom - top }))(iconBox(files[icon.file])));
+ }
+ assert.deepEqual(progressCalls, [1, 2, 3]);
+ const cell = atlas.data.subarray((200 * atlas.width + 200) * 4, (200 * atlas.width + 200) * 4 + 4);
+ assert.deepEqual([...cell], [0, 0, 0, 0], 'the unused fourth cell is transparent');
+});
+
+test('the same input writes byte-identical files', async () => {
+ const first = await runJob(['coin', 'sword', 'chest'], { scale: 'relative' });
+ const second = await runJob(['coin', 'sword', 'chest'], { scale: 'relative' });
+ assert.deepEqual(Object.keys(first.files), Object.keys(second.files));
+ for (const name of Object.keys(first.files)) assert.ok(first.files[name].equals(second.files[name]), `${name} differs between runs`);
+});
+
+test('an item that draws nothing fails naming the item', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'crucible-icons-test-'));
+ const settings = normalizeIconSettings({ kind: 'icons', items: ['empty'], size: 64 });
+ const openItem = async () => ({ bounds: { min: [0, 0, 0], max: [1, 1, 1] }, draw: async () => encodePng({ width: 64, height: 64, data: Buffer.alloc(64 * 64 * 4) }), close: async () => {} });
+ await assert.rejects(renderIconJob({ settings, directory, signal: new AbortController().signal, progress: async () => {}, openItem }), /items\[0\] \(empty\) drew no pixels/);
+ await rm(directory, { recursive: true, force: true });
+});
+
+test('the job store knows the icons settings and artifact names', () => {
+ const settings = normalizeJobSettings({ kind: 'icons', items: ['a.glb', 'b.glb'], size: 64 }, [], {});
+ assert.equal(settings.frameCount, 2);
+ assert.equal(settings.width, 64);
+ assert.deepEqual(artifactNames('icons', [], 'png', false, settings.frameCount), ['icon-0.png', 'icon-1.png', 'atlas.png', 'icons.json']);
+ const { frameCount, ...stored } = settings;
+ assert.deepEqual(normalizeJobSettings(stored, [], {}), settings, 'stored settings normalise to themselves');
+});
diff --git a/tests/icon-sheet.test.js b/tests/icon-sheet.test.js
new file mode 100644
index 00000000..c8f66e4d
--- /dev/null
+++ b/tests/icon-sheet.test.js
@@ -0,0 +1,109 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { ICON_CAPABILITIES, ICON_LIMITS, atlasCapacity, cameraBasis, cameraForFraming, iconNames, iconRecipe, layoutAtlas, lightRigEnvironment, normalizeIconSettings, sphereFraming } from '../src/icon-sheet.js';
+
+const valid = { kind: 'icons', items: ['sword.glb'] };
+
+test('defaults: 256 px, clean, fit, three-quarter view and the padding', () => {
+ const settings = normalizeIconSettings(valid);
+ assert.deepEqual({ size: settings.size, style: settings.style, scale: settings.scale, padding: settings.padding, viewpoint: settings.viewpoint },
+ { size: 256, style: 'clean', scale: 'fit', padding: 0.08, viewpoint: { azimuth: 35, elevation: 25 } });
+ assert.deepEqual(settings.items, [{ source: 'sword.glb' }]);
+ assert.equal(settings.frameCount, 1);
+ assert.equal(settings.transparent, true);
+});
+
+test('sketch is refused as coming, not as unknown', () => {
+ assert.throws(() => normalizeIconSettings({ ...valid, style: 'sketch' }), /style: got "sketch"; expected clean or toon: the sketch style is coming/);
+ assert.throws(() => normalizeIconSettings({ ...valid, style: 'pencil' }), /style: got "pencil"; expected one of clean, toon/);
+});
+
+test('fields left for later releases say they are coming', () => {
+ for (const field of ['angles', 'breakdown', 'lighting', 'background', 'outline']) {
+ assert.throws(() => normalizeIconSettings({ ...valid, [field]: 4 }), new RegExp(`settings.${field}: .*is coming`));
+ }
+ assert.throws(() => normalizeIconSettings({ ...valid, bogus: 1 }), /Unknown settings field: bogus/);
+});
+
+test('every field is checked and the error names it and what to pass', () => {
+ const cases = [
+ [{ items: [] }, /items: got 0; expected a list of 1 to 256/],
+ [{ items: 'sword.glb' }, /items: got "string"; expected a list of 1 to 256/],
+ [{ items: [7] }, /items\[0\]: got "number"; expected a catalog GLB name/],
+ [{ items: ['https://example.com/a.glb'] }, /remote URLs are not accepted/],
+ [{ items: ['a'.repeat(300)] }, /items\[0\]: got .* expected a catalog GLB name of 1 to 260/],
+ [{ items: [{ source: 'a.glb', asset: 'xyz' }] }, /items\[0\]\.asset: got "xyz"; expected the 64 hexadecimal/],
+ [{ size: 100 }, /size: got 100; expected one of 64, 128, 256, 512/],
+ [{ scale: 'huge' }, /scale: got "huge"; expected fit/],
+ [{ padding: 0.9 }, /padding: got 0.9; expected a fraction of the icon side from 0.02 to 0.4/],
+ [{ padding: 0 }, /padding: got 0;/],
+ [{ viewpoint: 'top' }, /viewpoint: got "string"; expected "three-quarter" or \{ azimuth, elevation \}/],
+ [{ viewpoint: { azimuth: 200 } }, /viewpoint.azimuth: got 200; expected degrees from -180 to 180/],
+ [{ viewpoint: { elevation: 90 } }, /viewpoint.elevation: got 90; expected degrees from -89 to 89/],
+ [{ viewpoint: { roll: 1 } }, /viewpoint.roll/],
+ ];
+ for (const [overrides, pattern] of cases) assert.throws(() => normalizeIconSettings({ ...valid, ...overrides }), pattern, JSON.stringify(overrides).slice(0, 60));
+});
+
+test('the item count is bounded by 256 and by the atlas for the size', () => {
+ const items = count => Array.from({ length: count }, (_, index) => `item-${index}.glb`);
+ assert.equal(normalizeIconSettings({ kind: 'icons', items: items(256), size: 256 }).frameCount, 256);
+ assert.throws(() => normalizeIconSettings({ kind: 'icons', items: items(257) }), /items: got 257; expected a list of 1 to 256/);
+ assert.equal(atlasCapacity(512), 64);
+ assert.throws(() => normalizeIconSettings({ kind: 'icons', items: items(65), size: 512 }), /items: got 65; expected at most 64 items at size 512/);
+ assert.equal(normalizeIconSettings({ kind: 'icons', items: items(64), size: 512 }).frameCount, 64);
+});
+
+test('a view override replaces azimuth and elevation and keeps the other default', () => {
+ assert.deepEqual(normalizeIconSettings({ ...valid, viewpoint: { azimuth: -45 } }).viewpoint, { azimuth: -45, elevation: 25 });
+ assert.deepEqual(normalizeIconSettings({ ...valid, viewpoint: 'three-quarter' }).viewpoint, ICON_LIMITS.defaultView);
+});
+
+test('stored settings with the pinned item form normalise to themselves', () => {
+ const asset = 'ab'.repeat(32);
+ const settings = normalizeIconSettings({ ...valid, items: [{ source: 'sword.glb', asset }] });
+ assert.deepEqual(settings.items, [{ source: 'sword.glb', asset }]);
+ // The job store re-reads its records without the frame count, which it checks separately.
+ const { frameCount, ...stored } = settings;
+ assert.deepEqual(normalizeIconSettings(stored), settings);
+});
+
+test('the camera looks at the item from the view direction with an orthographic square frame', () => {
+ const { toCamera, right, up } = cameraBasis({ azimuth: 0, elevation: 0 });
+ const rounded = vector => vector.map(value => Math.round(value) + 0);
+ assert.deepEqual(rounded(toCamera), [0, 0, 1]);
+ assert.deepEqual(rounded(right), [1, 0, 0]);
+ assert.deepEqual(rounded(up), [0, 1, 0]);
+ const framing = sphereFraming({ min: [-1, 0, -1], max: [1, 2, 1] });
+ assert.deepEqual(framing.center, [0, 1, 0]);
+ const camera = cameraForFraming(framing, { azimuth: 35, elevation: 25 });
+ assert.equal(camera.projection, 'orthographic');
+ assert.equal(camera.orthoScale, framing.radius * 2);
+ assert.ok(camera.near > 0 && camera.far > camera.near);
+});
+
+test('the light rig and toon lines come from the recipe, never from the caller', () => {
+ const clean = iconRecipe({ assetId: 'ab'.repeat(32), style: 'clean', view: { azimuth: 35, elevation: 25 }, size: 256 });
+ const toon = iconRecipe({ assetId: 'ab'.repeat(32), style: 'toon', view: { azimuth: 35, elevation: 25 }, size: 256 });
+ assert.equal(clean.environment.lines, undefined);
+ assert.deepEqual(toon.environment.lines, { width: 2, toon: 3 });
+ assert.equal(clean.environment.ground, false);
+ assert.equal(clean.environment.world, false);
+ assert.deepEqual(lightRigEnvironment({ azimuth: 35, elevation: 25 }), clean.environment);
+ assert.ok(Math.abs(Math.hypot(...clean.environment.lightDirection) - 1) < 1e-9);
+ assert.deepEqual(clean.nodes, [{ id: 'icon', asset: { id: 'ab'.repeat(32) } }]);
+});
+
+test('the atlas is a near square grid and names stay unique', () => {
+ const layout = layoutAtlas(9, 64);
+ assert.deepEqual([layout.columns, layout.rows, layout.width, layout.height], [3, 3, 192, 192]);
+ assert.deepEqual(layout.rectangles[4], { x: 64, y: 64, width: 64, height: 64 });
+ assert.deepEqual(iconNames(['kenney/sword.glb', 'other\\sword.glb', 'chest.GLB']), ['sword-0', 'sword-1', 'chest']);
+});
+
+test('scene_capabilities reports the limits the validator enforces', () => {
+ assert.equal(ICON_CAPABILITIES.maximumItems, 256);
+ assert.deepEqual(ICON_CAPABILITIES.styles, ['clean', 'toon']);
+ assert.deepEqual(ICON_CAPABILITIES.itemsPerSize, { 64: 256, 128: 256, 256: 256, 512: 64 });
+ assert.ok(ICON_CAPABILITIES.notYet.includes('breakdown'));
+});