Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(forge): wire bbox fit into the GLB post-processing pipeline, fix async lods not binding

nirholas9e81778754e3
diff --git a/api/_lib/forge-job-options.js b/api/_lib/forge-job-options.js
index 4b4ea4522..67c693e09 100644
--- a/api/_lib/forge-job-options.js
+++ b/api/_lib/forge-job-options.js
@@ -1,15 +1,17 @@
-// Job → output-options binding for the /forge generation pipeline.
+// Job -> output-options binding for the /forge generation pipeline.
//
// normalizeForgeOptions() (forge-options.js) parses a request's optional output
-// controls (seed, output_format/compression, texture_size, target_polycount) in
-// the SAME serverless invocation that submits the job. An asynchronous lane
-// (Replicate/TRELLIS, Hunyuan3D, sketch, BYOK) completes in a LATER, separate
-// invocation of pollJob(), which only has the job handle — not the original
-// request body. This module remembers the request-affecting subset (the
-// post-generation compression choice, and whether the caller opted OUT of the
-// PBR material completion pass) against the job handle for the lifetime of a
+// controls (seed, output_format/compression, texture_size, target_polycount,
+// lods, bbox) in the SAME serverless invocation that submits the job. An
+// asynchronous lane (Replicate/TRELLIS, Hunyuan3D, sketch, BYOK) completes in a
+// LATER, separate invocation of pollJob(), which only has the job handle, not
+// the original request body. This module remembers the request-affecting
+// subset (the post-generation compression choice, whether the caller opted OUT
+// of the PBR material completion pass, whether an LOD variant was requested,
+// and the requested delivery bbox) against the job handle for the lifetime of a
// single poll cycle, so a completed async job still gets the caller's requested
-// output_format and material handling applied at materialize time.
+// output_format, material handling, LOD build, and bbox fit applied at
+// materialize time.
//
// Mirrors the bindJobToCacheKey/cacheKeyForJob idiom in forge-cache.js exactly:
// best-effort, short-TTL, fail-open without Redis (a cache/store outage just
@@ -37,10 +39,17 @@ export async function bindJobToOptions(jobHandle, opts, { redis } = {}) {
// derivePbr is opt-OUT, so only an explicit false is worth remembering: an
// unbound job takes the default-on path at materialize time either way.
const derivePbr = opts.derivePbr === false ? false : null;
- if (!compression && derivePbr === null) return; // default behavior needs no binding
+ // lods is opt-IN, mirroring compression: only an explicit true is worth
+ // remembering.
+ const lods = opts.lods === true ? true : null;
+ // bbox is opt-IN: a caller-supplied [x, y, z] fit box (forge-options.js).
+ const bbox = Array.isArray(opts.bbox) ? opts.bbox : null;
+ if (!compression && derivePbr === null && lods === null && !bbox) return; // default behavior needs no binding
const value = {
...(compression ? { compression } : {}),
...(derivePbr === false ? { derivePbr: false } : {}),
+ ...(lods === true ? { lods: true } : {}),
+ ...(bbox ? { bbox } : {}),
};
try {
await r.set(`${PREFIX}${jobHandle}`, JSON.stringify(value), { ex: TTL_S });
@@ -63,7 +72,9 @@ export async function optionsForJob(jobHandle, { redis } = {}) {
if (!value || typeof value !== 'object') return null;
const hasCompression = typeof value.compression === 'string';
const hasDerivePbr = value.derivePbr === false;
- return hasCompression || hasDerivePbr ? value : null;
+ const hasLods = value.lods === true;
+ const hasBbox = Array.isArray(value.bbox);
+ return hasCompression || hasDerivePbr || hasLods || hasBbox ? value : null;
} catch {
return null;
}
diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.js
index 6cce01a31..ceef9032f 100644
--- a/api/_lib/forge-store.js
+++ b/api/_lib/forge-store.js
@@ -23,6 +23,7 @@ import { recordDailyActivity, maybeAwardFirstCreation } from './streaks.js';
import { recordGenerationEvent } from './forge-events.js';
import { scoreGlbQuality } from './glb-quality.js';
import { stripFloorSlab } from './glb-floor-slab.js';
+import { fitBbox } from './glb-bbox-fit.js';
import { compressGlb, deliveryCompressionOptions } from './glb-compress.js';
import { classifyModelCategory } from './forge-classify.js';
import { cleanupGlb } from './glb-cleanup.js';
@@ -322,11 +323,12 @@ const COPY_TIMEOUT_MS = 120_000;
// (normal + packed occlusion/roughness/metallic + the class's measured
// extension layer); on by default, pass false to deliver the lane's own
// materials untouched.
-async function scoreAndCompress(buf, { computeQuality, compress, cleanup = false, derivePbr = false, prompt = '', tier = '', materialClass = '' }) {
+async function scoreAndCompress(buf, { computeQuality, compress, cleanup = false, derivePbr = false, bbox = null, prompt = '', tier = '', materialClass = '' }) {
let quality = null;
let compression = null;
let cleaned = null;
let pbr = null;
+ let fit = null;
let outBuf = buf;
// Cleanup FIRST: a welded, de-duplicated, decimated mesh both renders better
// and compresses better than the raw soup, so the codec below operates on the
@@ -363,7 +365,23 @@ async function scoreAndCompress(buf, { computeQuality, compress, cleanup = false
console.warn('[forge-store] floor slab strip failed, delivering as-is:', err?.message);
}
}
- // Material completion SECOND: it reads the albedo the lane baked and writes
+ // Bbox fit SECOND, still before material completion: it rescales and
+ // recenters the whole mesh (glb-bbox-fit.js), which must happen after the
+ // floor-slab strip settles the final geometry (fitting around a slab that is
+ // about to be cut would waste the fit) and before PBR derivation measures or
+ // bakes anything resolution-dependent on the final scale.
+ if (bbox) {
+ try {
+ const r = await fitBbox(outBuf, bbox);
+ if (r.fitted) {
+ outBuf = r.buffer;
+ fit = { bbox, scale: r.scale };
+ }
+ } catch (err) {
+ console.warn('[forge-store] bbox fit failed, delivering at native scale:', err?.message);
+ }
+ }
+ // Material completion THIRD: it reads the albedo the lane baked and writes
// derived maps onto the geometry cleanup just settled, so it has to run after
// cleanup and before the codec pass (a Draco/meshopt-encoded buffer would
// have to be decoded again to touch its materials) and before quality
@@ -412,7 +430,7 @@ async function scoreAndCompress(buf, { computeQuality, compress, cleanup = false
compression = { mode: compress, skipped: true, reason: 'compression_failed' };
}
}
- return { buf: outBuf, quality, compression, cleaned, pbr };
+ return { buf: outBuf, quality, compression, cleaned, pbr, fit };
}
// An upstream Content-Type ends up as the object's stored type, which the CDN
@@ -426,7 +444,7 @@ function mediaTypeOr(header, fallback) {
return STORABLE_TYPE_RE.test(type) ? type : fallback;
}
-async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null, cleanup = false, derivePbr = false, prompt = '', tier = '', materialClass = '', forceContentType = null, untrustedSource = false }) {
+async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, computeQuality = false, compress = null, cleanup = false, derivePbr = false, bbox = null, prompt = '', tier = '', materialClass = '', forceContentType = null, untrustedSource = false }) {
// fetchUpstream retries network errors and 408/425/429/5xx with jittered
// backoff and gives up immediately on 404/410 (the ephemeral asset has
// already expired; no retry can recover it), rejecting with an error that
@@ -451,19 +469,21 @@ async function copyToBucket({ sourceUrl, key, fallbackContentType, maxBytes, com
let compression = null;
let cleaned = null;
let pbr = null;
- if (computeQuality || compress || cleanup || derivePbr) {
- const scored = await scoreAndCompress(buf, { computeQuality, compress, cleanup, derivePbr, prompt, tier, materialClass });
+ let fit = null;
+ if (computeQuality || compress || cleanup || derivePbr || bbox) {
+ const scored = await scoreAndCompress(buf, { computeQuality, compress, cleanup, derivePbr, bbox, prompt, tier, materialClass });
buf = scored.buf;
quality = scored.quality;
compression = scored.compression;
cleaned = scored.cleaned;
pbr = scored.pbr;
+ fit = scored.fit;
}
await putObject({ key, body: buf, contentType, metadata: { source: 'forge' } });
// `buffer` is the bytes actually stored, post-cleanup and post-compression, so
// a caller that hashes or grades them is describing the asset users receive
// rather than the provider's original, and does it without a second fetch.
- return { bytes: buf.length, publicUrl: publicUrl(key), quality, compression, cleaned, pbr, buffer: buf };
+ return { bytes: buf.length, publicUrl: publicUrl(key), quality, compression, cleaned, pbr, fit, buffer: buf };
}
function imageExtFor(url) {
@@ -633,7 +653,7 @@ export function buildLodVariant({ buffer, creationId, keyPrefix }) {
// Off by default: it is real decimation work, worth its own opt-in
// exactly like forge-options.js documents. Fire-and-forget, same
// as the web-delivery variant it sits beside.
-export async function materializeCreation({ replicateJobId, clientKey, glbUrl, quality = false, compress = null, cleanup = true, derivePbr = true, lods = false }) {
+export async function materializeCreation({ replicateJobId, clientKey, glbUrl, quality = false, compress = null, cleanup = true, derivePbr = true, bbox = null, lods = false }) {
if (!forgeStoreEnabled() || !replicateJobId || !glbUrl) return null;
const existing = await findByJob({ replicateJobId, clientKey });
if (!existing) return null;
@@ -647,6 +667,7 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q
compression: null,
cleaned: null,
pbr: null,
+ fit: null,
};
}
@@ -661,6 +682,7 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q
compress,
cleanup,
derivePbr,
+ bbox,
// The row carries the words the material classifier reads and the tier
// that sets the derived maps' resolution, so no caller has to thread
// either through the poll path.
@@ -769,6 +791,7 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, q
compression: glb.compression ?? null,
cleaned: glb.cleaned ?? null,
pbr: glb.pbr ?? null,
+ fit: glb.fit ?? null,
};
} catch (err) {
// A 404/410 means the provider's ephemeral asset (e.g. a HuggingFace Space's
diff --git a/api/_lib/glb-bbox-fit.js b/api/_lib/glb-bbox-fit.js
new file mode 100644
index 000000000..c1cececb6
--- /dev/null
+++ b/api/_lib/glb-bbox-fit.js
@@ -0,0 +1,142 @@
+// Fit a delivered GLB inside a caller-requested [x, y, z] bounding box.
+//
+// Some integrations (a game engine's prop slot, an AR anchor, a print bed) need
+// the delivered mesh to occupy a known footprint rather than whatever scale the
+// generator happened to produce. forge-options.js's `bbox` field carries that
+// request in meters; this module performs the fit: the mesh is uniformly scaled
+// (never stretched: a non-uniform scale would distort the subject) so its
+// longest-relative-to-box axis exactly fills that axis of the box, then
+// recentered so it sits in the middle of X/Z and rests on the floor at Y=0,
+// matching the convention every other forge delivery already uses (see
+// glb-floor-slab.js).
+//
+// Pure, CPU-only and best-effort, same contract as glb-floor-slab.js: anything
+// this pass cannot read or decide returns the original bytes unchanged.
+
+import { Buffer } from 'node:buffer';
+
+function worldBounds(prim, matrix) {
+ const pos = prim.getAttribute('POSITION');
+ const n = pos.getCount();
+ const v = [0, 0, 0];
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+ for (let i = 0; i < n; i++) {
+ pos.getElement(i, v);
+ const x = matrix[0] * v[0] + matrix[4] * v[1] + matrix[8] * v[2] + matrix[12];
+ const y = matrix[1] * v[0] + matrix[5] * v[1] + matrix[9] * v[2] + matrix[13];
+ const z = matrix[2] * v[0] + matrix[6] * v[1] + matrix[10] * v[2] + matrix[14];
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ if (z < minZ) minZ = z;
+ if (z > maxZ) maxZ = z;
+ }
+ return { minX, minY, minZ, maxX, maxY, maxZ };
+}
+
+function mergeBounds(a, b) {
+ return {
+ minX: Math.min(a.minX, b.minX),
+ minY: Math.min(a.minY, b.minY),
+ minZ: Math.min(a.minZ, b.minZ),
+ maxX: Math.max(a.maxX, b.maxX),
+ maxY: Math.max(a.maxY, b.maxY),
+ maxZ: Math.max(a.maxZ, b.maxZ),
+ };
+}
+
+/**
+ * Compute the uniform scale and recentering translation that fits `bounds`
+ * inside `[bx, by, bz]` meters, preserving aspect ratio, centered on X/Z and
+ * floored at Y=0. Pure: takes world-space bounds, returns a transform.
+ *
+ * @param {{minX:number,minY:number,minZ:number,maxX:number,maxY:number,maxZ:number}} bounds
+ * @param {[number, number, number]} bbox
+ * @returns {{ fit: boolean, reason: string, scale?: number, translate?: [number, number, number] }}
+ */
+export function computeBboxFit(bounds, bbox) {
+ const sizeX = bounds.maxX - bounds.minX;
+ const sizeY = bounds.maxY - bounds.minY;
+ const sizeZ = bounds.maxZ - bounds.minZ;
+ if (!(sizeX > 0 || sizeY > 0 || sizeZ > 0)) return { fit: false, reason: 'no_extent' };
+ const [bx, by, bz] = bbox;
+ if (!(bx > 0 && by > 0 && bz > 0)) return { fit: false, reason: 'invalid_bbox' };
+ // Only the axes with real extent constrain the scale: a flat plane (sizeY
+ // near 0) would otherwise force an infinite scale trying to fill a height
+ // it has none of.
+ const ratios = [];
+ if (sizeX > 0) ratios.push(bx / sizeX);
+ if (sizeY > 0) ratios.push(by / sizeY);
+ if (sizeZ > 0) ratios.push(bz / sizeZ);
+ const scale = Math.min(...ratios);
+ if (!(scale > 0 && Number.isFinite(scale))) return { fit: false, reason: 'degenerate_scale' };
+ const centerX = (bounds.minX + bounds.maxX) / 2;
+ const centerZ = (bounds.minZ + bounds.maxZ) / 2;
+ return {
+ fit: true,
+ reason: 'fitted',
+ scale,
+ // Translate in the mesh's own (pre-scale) units: the root node applies
+ // scale then translate as separate TRS channels, so this offset must
+ // already be divided by `scale` to land the scaled mesh centered and
+ // floored once both transforms are composed.
+ translate: [-centerX, -bounds.minY, -centerZ],
+ };
+}
+
+/**
+ * Fit a GLB's content inside a caller-requested [x, y, z] box in meters, via a
+ * single wrapping root node (scale + translate), so the source geometry itself
+ * is never resampled. Returns the original bytes unchanged when there is
+ * nothing to fit or the request is degenerate.
+ *
+ * @param {Buffer|Uint8Array} buf - source GLB bytes
+ * @param {[number, number, number]} bbox - requested [x, y, z] in meters
+ * @returns {Promise<{ buffer: Buffer, fitted: boolean, reason: string, scale?: number }>}
+ */
+export async function fitBbox(buf, bbox) {
+ const input = Buffer.isBuffer(buf) ? buf : Buffer.from(buf);
+ const unchanged = (reason) => ({ buffer: input, fitted: false, reason });
+ if (!Array.isArray(bbox) || bbox.length !== 3) return unchanged('no_bbox_requested');
+
+ const { NodeIO } = await import('@gltf-transform/core');
+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const doc = await io.readBinary(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
+
+ const scene = doc.getRoot().listScenes()[0];
+ const topNodes = scene ? scene.listChildren() : doc.getRoot().listNodes().filter((n) => !n.getParentNode?.());
+ if (!topNodes.length) return unchanged('no_nodes');
+
+ let bounds = null;
+ for (const node of doc.getRoot().listNodes()) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const matrix = node.getWorldMatrix();
+ for (const prim of mesh.listPrimitives()) {
+ if (!prim.getAttribute('POSITION')) continue;
+ const b = worldBounds(prim, matrix);
+ bounds = bounds ? mergeBounds(bounds, b) : b;
+ }
+ }
+ if (!bounds) return unchanged('no_triangles');
+
+ const verdict = computeBboxFit(bounds, bbox);
+ if (!verdict.fit) return unchanged(verdict.reason);
+
+ // Wrap every top-level node under one new root that carries the scale and
+ // translation, rather than editing vertex data: cheap, lossless, and never
+ // fights an existing node hierarchy or skin.
+ const wrapper = doc.createNode('BboxFit').setScale([verdict.scale, verdict.scale, verdict.scale]);
+ wrapper.setTranslation(verdict.translate.map((v) => v * verdict.scale));
+ for (const node of topNodes) {
+ scene.removeChild(node);
+ wrapper.addChild(node);
+ }
+ if (scene) scene.addChild(wrapper);
+
+ const out = Buffer.from(await io.writeBinary(doc));
+ return { buffer: out, fitted: true, reason: 'fitted', scale: verdict.scale };
+}
diff --git a/api/forge.js b/api/forge.js
index 6f22c2a58..15ada74a6 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -670,6 +670,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
// One auto-retry on a flagged low-quality/degenerate output (CLAUDE.md: no
@@ -709,6 +710,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
if (retryDurable) {
durable = retryDurable;
@@ -750,6 +752,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;
},
@@ -982,6 +985,7 @@ async function runHfImageLane({
compress: wantCompress,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
// One auto-retry on a flagged low-quality/degenerate output. Only attempted
@@ -1027,6 +1031,7 @@ async function runHfImageLane({
compress: wantCompress,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
if (retryDurable) {
durable = retryDurable;
@@ -1078,6 +1083,7 @@ async function runHfImageLane({
glbUrl: rf.resultGlbUrl, quality: true, compress: wantCompress,
derivePbr: opts?.derivePbr !== false,
lods: opts?.lods === true,
+ bbox: opts?.bbox ?? null,
});
return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;
} finally {
@@ -1819,6 +1825,7 @@ async function startJobWithBody(req, res, body) {
compress: opts.compression !== 'none' ? opts.compression : null,
derivePbr: opts.derivePbr !== false,
lods: opts.lods === true,
+ bbox: opts.bbox ?? null,
});
return json(res, 200, {
job_id: null,
@@ -3265,6 +3272,7 @@ async function pollJob(req, res, jobId) {
quality: true,
compress: boundOpts?.compression || null,
derivePbr: boundOpts?.derivePbr !== false,
+ bbox: boundOpts?.bbox ?? null,
lods: boundOpts?.lods === true,
});
// Populate the result cache this job was bound to at submit time (text→3D,
diff --git a/tests/api/glb-bbox-fit.test.js b/tests/api/glb-bbox-fit.test.js
new file mode 100644
index 000000000..2ceca2374
--- /dev/null
+++ b/tests/api/glb-bbox-fit.test.js
@@ -0,0 +1,125 @@
+/**
+ * Bbox fit (api/_lib/glb-bbox-fit.js): a caller requests [x, y, z] meters
+ * (forge-options.js `bbox`) and the delivered mesh is uniformly rescaled to
+ * fit inside it, aspect ratio preserved, centered on X/Z and floored at Y=0.
+ * Built the same way tests/api/glb-floor-slab.test.js builds its fixtures:
+ * real GLBs assembled with the same @gltf-transform the pass reads them with.
+ */
+import { describe, it, expect } from 'vitest';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { fitBbox, computeBboxFit } from '../../api/_lib/glb-bbox-fit.js';
+
+function box(tris, x0, x1, y0, y1, z0, z1) {
+ const quad = (a, b, c, d) => tris.push([a, b, c], [a, c, d]);
+ quad([x0, y0, z0], [x1, y0, z0], [x1, y0, z1], [x0, y0, z1]);
+ quad([x0, y1, z0], [x1, y1, z0], [x1, y1, z1], [x0, y1, z1]);
+ quad([x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0]);
+ quad([x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1]);
+ quad([x0, y0, z0], [x0, y0, z1], [x0, y1, z1], [x0, y1, z0]);
+ quad([x1, y0, z0], [x1, y0, z1], [x1, y1, z1], [x1, y1, z0]);
+}
+
+async function toGlb(tris) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const positions = new Float32Array(tris.flat(2));
+ const indices = new Uint32Array(tris.length * 3).map((_, i) => i);
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(positions).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(indices).setBuffer(buffer));
+ const node = doc.createNode().setMesh(doc.createMesh().addPrimitive(prim));
+ doc.createScene().addChild(node);
+ return Buffer.from(await new NodeIO().writeBinary(doc));
+}
+
+// Independent of glb-bbox-fit.js's own bounds computation: reads the written
+// GLB back from scratch to verify what actually landed in the file.
+async function boundsOf(buf) {
+ const doc = await new NodeIO().readBinary(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
+ let minX = Infinity, minY = Infinity, minZ = Infinity;
+ let maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
+ const v = [0, 0, 0];
+ for (const node of doc.getRoot().listNodes()) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const m = node.getWorldMatrix();
+ for (const prim of mesh.listPrimitives()) {
+ const pos = prim.getAttribute('POSITION');
+ for (let i = 0; i < pos.getCount(); i++) {
+ pos.getElement(i, v);
+ const x = m[0] * v[0] + m[4] * v[1] + m[8] * v[2] + m[12];
+ const y = m[1] * v[0] + m[5] * v[1] + m[9] * v[2] + m[13];
+ const z = m[2] * v[0] + m[6] * v[1] + m[10] * v[2] + m[14];
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ if (z < minZ) minZ = z;
+ if (z > maxZ) maxZ = z;
+ }
+ }
+ }
+ return { minX, minY, minZ, maxX, maxY, maxZ };
+}
+
+describe('computeBboxFit', () => {
+ const bounds = { minX: -1, maxX: 1, minY: 0, maxY: 4, minZ: -2, maxZ: 2 };
+
+ it('scales by the most constraining axis and preserves aspect ratio', () => {
+ const v = computeBboxFit(bounds, [10, 10, 10]);
+ expect(v.fit).toBe(true);
+ // height (4) is the largest extent, so a 10m cube binds on Y: scale = 10/4.
+ expect(v.scale).toBeCloseTo(2.5, 5);
+ });
+
+ it('rejects a non-positive bbox dimension', () => {
+ expect(computeBboxFit(bounds, [10, 0, 10]).fit).toBe(false);
+ expect(computeBboxFit(bounds, [10, -1, 10]).fit).toBe(false);
+ });
+
+ it('rejects a mesh with no extent', () => {
+ const flat = { minX: 0, maxX: 0, minY: 0, maxY: 0, minZ: 0, maxZ: 0 };
+ expect(computeBboxFit(flat, [1, 1, 1]).fit).toBe(false);
+ });
+});
+
+describe('fitBbox', () => {
+ it('fits a tall box into a cube, centered on X/Z and floored at Y=0', async () => {
+ const tris = [];
+ box(tris, -1, 1, 0, 4, -2, 2);
+ const input = await toGlb(tris);
+ const r = await fitBbox(input, [10, 10, 10]);
+ expect(r.fitted).toBe(true);
+ expect(r.scale).toBeCloseTo(2.5, 5);
+
+ const b = await boundsOf(r.buffer);
+ expect(b.minY).toBeCloseTo(0, 3);
+ expect(b.maxY).toBeCloseTo(10, 3);
+ expect((b.minX + b.maxX) / 2).toBeCloseTo(0, 3);
+ expect((b.minZ + b.maxZ) / 2).toBeCloseTo(0, 3);
+ expect(b.maxX - b.minX).toBeCloseTo(5, 3); // 2m wide * 2.5
+ expect(b.maxZ - b.minZ).toBeCloseTo(10, 3); // 4m deep * 2.5
+ });
+
+ it('returns the original bytes unchanged when no bbox is requested', async () => {
+ const tris = [];
+ box(tris, -1, 1, 0, 1, -1, 1);
+ const input = await toGlb(tris);
+ const r = await fitBbox(input, null);
+ expect(r.fitted).toBe(false);
+ expect(r.buffer).toBe(input);
+ });
+
+ it('leaves an off-center mesh centered after the fit, not shifted by its original offset', async () => {
+ const tris = [];
+ box(tris, 5, 7, 0, 2, 100, 102); // same size, far from the origin
+ const input = await toGlb(tris);
+ const r = await fitBbox(input, [10, 10, 10]);
+ expect(r.fitted).toBe(true);
+ const b = await boundsOf(r.buffer);
+ expect((b.minX + b.maxX) / 2).toBeCloseTo(0, 3);
+ expect((b.minZ + b.maxZ) / 2).toBeCloseTo(0, 3);
+ expect(b.minY).toBeCloseTo(0, 3);
+ });
+});
diff --git a/tests/forge-job-options.test.js b/tests/forge-job-options.test.js
new file mode 100644
index 000000000..62878859b
--- /dev/null
+++ b/tests/forge-job-options.test.js
@@ -0,0 +1,51 @@
+// Job -> output-options binding (api/_lib/forge-job-options.js). An async lane
+// (Replicate/TRELLIS, Hunyuan3D, sketch, BYOK) completes in a later poll
+// invocation that only has the job handle, so every submit-time choice that
+// still matters at materialize time has to round-trip through this binding.
+//
+// Regression: bindJobToOptions recorded compression and derivePbr but silently
+// dropped lods, so a caller who requested `lods: true` on an async lane never
+// got an LOD variant: optionsForJob always resolved lods as undefined, and the
+// poll handler's `boundOpts?.lods === true` check was permanently false.
+
+import { describe, it, expect } from 'vitest';
+import { bindJobToOptions, optionsForJob } from '../api/_lib/forge-job-options.js';
+
+function fakeRedis() {
+ const store = new Map();
+ return {
+ async set(key, value) {
+ store.set(key, value);
+ },
+ async get(key) {
+ return store.has(key) ? store.get(key) : null;
+ },
+ };
+}
+
+describe('forge-job-options: bindJobToOptions / optionsForJob', () => {
+ it('round-trips an explicit lods:true request to the later poll invocation', async () => {
+ const redis = fakeRedis();
+ await bindJobToOptions('job-1', { lods: true }, { redis });
+ const bound = await optionsForJob('job-1', { redis });
+ expect(bound).toEqual({ lods: true });
+ });
+
+ it('round-trips compression, derivePbr:false, and lods together', async () => {
+ const redis = fakeRedis();
+ await bindJobToOptions('job-2', { compression: 'draco', derivePbr: false, lods: true }, { redis });
+ const bound = await optionsForJob('job-2', { redis });
+ expect(bound).toEqual({ compression: 'draco', derivePbr: false, lods: true });
+ });
+
+ it('does not bind anything when lods is absent or false and nothing else is non-default', async () => {
+ const redis = fakeRedis();
+ await bindJobToOptions('job-3', { lods: false }, { redis });
+ expect(await optionsForJob('job-3', { redis })).toBeNull();
+ });
+
+ it('resolves null for an unbound job handle', async () => {
+ const redis = fakeRedis();
+ expect(await optionsForJob('never-bound', { redis })).toBeNull();
+ });
+});