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(print): add the partner adapter, editions, and the certificate schema

nirholas1a3dcfaf8c2f
diff --git a/api/_lib/migrations/20260902193000_print_certificates.sql b/api/_lib/migrations/20260902193000_print_certificates.sql
new file mode 100644
index 000000000..4bbc91a1f
--- /dev/null
+++ b/api/_lib/migrations/20260902193000_print_certificates.sql
@@ -0,0 +1,114 @@
+begin;
+
+-- Materialize provenance: the certificate a physical print carries.
+--
+-- A print is only a collectible if its scarcity and its lineage can be checked
+-- by someone who does not trust us. So the moment an order ships, three facts
+-- are frozen together: the SHA-256 of the exact bytes that were printed, the
+-- edition number claimed out of that model's series, and a Solana memo
+-- transaction carrying both. The QR on the package resolves to /cert/<id>,
+-- which renders the original model plus the raw memo payload, so verification
+-- needs neither this database nor a block explorer.
+--
+-- One certificate per order, enforced by a unique index rather than by handler
+-- discipline: the issuer is idempotent because the database says so.
+
+create table if not exists print_certificates (
+ -- 24 lowercase hex characters (12 random bytes). Short on purpose: it is
+ -- printed on a card and encoded into a QR that has to scan off paper at
+ -- arm's length, where a 36-character uuid measurably costs modules.
+ id text primary key,
+ order_id uuid not null references print_orders(id) on delete cascade,
+ creation_id uuid references forge_creations(id) on delete set null,
+
+ -- The edition series this number was claimed from. For a print of a forge
+ -- creation that is the creation id; for a direct GLB upload, which has no
+ -- creation row, it is 'sha256:<hash>' so identical bytes still form one
+ -- honest series instead of every upload minting a fresh "edition 1 of 1".
+ series_key text not null,
+ edition_no integer not null,
+ -- The creator's cap at claim time. Null is an open edition. Copied here
+ -- rather than read live so a later cap change cannot rewrite what a
+ -- shipped certificate already promised.
+ edition_of integer,
+
+ -- SHA-256 of the prepared GLB: the canonical 3D representation, and the
+ -- one /cert renders. Hex, lowercase, 64 chars.
+ glb_sha256 text not null,
+ glb_bytes bigint,
+ -- The manufacturing asset actually handed to the printer (stl or 3mf) and
+ -- its own hash, so "these bytes were printed" is checkable too, not just
+ -- "this model was printed".
+ print_asset_kind text,
+ print_asset_key text,
+ print_asset_sha256 text,
+
+ material_id text,
+ -- Frozen at issuance: what the buyer sees on the certificate never moves
+ -- when the catalog is retuned.
+ material_label text,
+ printed_at timestamptz not null default now(),
+
+ -- The attestation. `memo` is the exact JSON string signed on-chain, stored
+ -- verbatim so the page can render the bytes a verifier hashes, and network
+ -- says which cluster to resolve the signature on.
+ network text not null default 'devnet',
+ memo text not null,
+ solana_signature text,
+ attested_at timestamptz,
+ attest_attempts integer not null default 0,
+ attest_error text,
+
+ qr_key text,
+ qr_url text,
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ constraint print_certificates_id_chk check (id ~ '^[0-9a-f]{24}$'),
+ constraint print_certificates_sha_chk check (glb_sha256 ~ '^[0-9a-f]{64}$'),
+ constraint print_certificates_edition_chk check (edition_no >= 1),
+ constraint print_certificates_cap_chk check (edition_of is null or edition_no <= edition_of),
+ constraint print_certificates_network_chk check (network in ('mainnet', 'devnet')),
+ constraint print_certificates_asset_kind_chk
+ check (print_asset_kind is null or print_asset_kind in ('stl', '3mf', 'glb'))
+);
+
+-- One certificate per order. This is the issuer's idempotency key: a retried
+-- shipped-transition finds the existing row instead of minting a second one.
+create unique index if not exists print_certificates_order_uniq
+ on print_certificates (order_id);
+
+-- The edition guard. Two orders of the same model shipping at the same instant
+-- both compute "max + 1" and race; the loser takes a unique violation and
+-- recomputes, so no two certificates ever carry the same edition number.
+create unique index if not exists print_certificates_series_edition_uniq
+ on print_certificates (series_key, edition_no);
+
+-- The reconciliation sweep's working set: certificates whose memo never landed.
+create index if not exists print_certificates_unattested_idx
+ on print_certificates (created_at)
+ where solana_signature is null;
+
+-- A model's edition history, newest first, for the model page's badge.
+create index if not exists print_certificates_series_idx
+ on print_certificates (series_key, edition_no desc);
+
+do $$ begin
+ create trigger print_certificates_set_updated_at before update on print_certificates
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- The creator's scarcity control. Null (the default, and every existing row) is
+-- an open edition: print as many as people order. A number caps the series, is
+-- enforced at quote time, and is what the certificate renders as "3 of 25".
+alter table forge_creations
+ add column if not exists print_edition_limit integer;
+
+do $$ begin
+ alter table forge_creations
+ add constraint forge_creations_print_edition_limit_chk
+ check (print_edition_limit is null or print_edition_limit between 1 and 10000);
+exception when duplicate_object then null; end $$;
+
+commit;
diff --git a/api/_lib/print/adapters/index.js b/api/_lib/print/adapters/index.js
new file mode 100644
index 000000000..7dfa6674d
--- /dev/null
+++ b/api/_lib/print/adapters/index.js
@@ -0,0 +1,82 @@
+// @ts-check
+// The fulfillment adapter registry.
+//
+// Adapters declare themselves as data plus a module; this file is the only
+// place that knows which ones exist. Registration is conditional on
+// configured(), so a lane whose credentials are absent is invisible rather
+// than present-and-broken: nothing can route an order into it, and the console
+// never offers it.
+//
+// The registry is rebuilt per call rather than frozen at import, because
+// `configured()` reads process.env and a container's env can be updated
+// (gcloud run services update --update-env-vars) without a code change. The
+// cost is a handful of string checks; the benefit is that turning a partner on
+// is a config change, which is the entire point of the adapter layer.
+
+import { assertAdapterShape, adapterSupportsOrder } from './contract.js';
+import manual from './manual.js';
+import partnerCn from './partner-cn.js';
+
+// Order matters: the first configured adapter that supports an order is the
+// default route, and `manual` is deliberately last. A contracted partner
+// should take a job it can run; a human should take everything else.
+const ALL = [partnerCn, manual].map(assertAdapterShape);
+
+/** Every adapter that exists in the build, configured or not. Diagnostics. */
+export function allAdapters() {
+ return ALL.map((a) => ({ ...a }));
+}
+
+/** Adapters this deployment can actually use right now. */
+export function listAdapters() {
+ return ALL.filter((a) => {
+ try {
+ return a.configured() === true;
+ } catch {
+ return false;
+ }
+ });
+}
+
+/**
+ * Resolve one adapter by key. Returns null for an unknown or unconfigured key,
+ * which every caller treats as "this lane is not available here".
+ * @param {string} key
+ */
+export function getAdapter(key) {
+ return listAdapters().find((a) => a.key === key) || null;
+}
+
+/**
+ * The lane an order should go to: the first configured adapter whose declared
+ * capabilities cover it. Returns the adapter plus the reasons the earlier ones
+ * declined, so a routing decision is explainable in the console rather than a
+ * silent fallback.
+ * @param {object} order
+ * @returns {{ adapter: any|null, declined: Array<{ key: string, reason: string }> }}
+ */
+export function routeOrder(order) {
+ const declined = [];
+ for (const adapter of listAdapters()) {
+ const verdict = adapterSupportsOrder(adapter, order);
+ if (verdict.ok) return { adapter, declined };
+ declined.push({ key: adapter.key, reason: verdict.reason });
+ }
+ return { adapter: null, declined };
+}
+
+/** Capability summary for the console and for docs. Never includes secrets. */
+export function adapterSummaries() {
+ return ALL.map((a) => ({
+ key: a.key,
+ label: a.label,
+ configured: (() => {
+ try {
+ return a.configured() === true;
+ } catch {
+ return false;
+ }
+ })(),
+ capabilities: a.capabilities,
+ }));
+}
diff --git a/api/_lib/print/adapters/partner-cn.js b/api/_lib/print/adapters/partner-cn.js
new file mode 100644
index 000000000..c05ca5183
--- /dev/null
+++ b/api/_lib/print/adapters/partner-cn.js
@@ -0,0 +1,225 @@
+// @ts-check
+// The `partner-cn` fulfillment adapter: a contracted high-precision print
+// partner, wired behind credentials.
+//
+// STATUS: the partner is UNCONTRACTED (00-CONTEXT, origin 2026-08-13). This
+// module is fully structured and fully tested on every path that can run
+// without credentials, and it registers itself ONLY when both env vars are
+// present, exactly how the forge treats a BYOK lane. On a deployment without
+// them the adapter does not appear in the registry at all, so no surface can
+// route an order into a lane that cannot answer.
+//
+// PRINT_PARTNER_CN_URL https base of the partner API, no trailing slash
+// PRINT_PARTNER_CN_KEY bearer credential, also the webhook HMAC secret
+//
+// ── THE REQUEST SHAPE THIS ASSUMES ───────────────────────────────────────────
+//
+// Nothing below is a fabricated endpoint: it is the contract to reconcile
+// against the partner's real API documentation the day it arrives. It is
+// written in the store's own vocabulary so that reconciliation is a rename of
+// wire fields, never a redesign of the state machine.
+//
+// POST {URL}/orders
+// headers: authorization: Bearer {KEY}, content-type: application/json
+// body: {
+// reference: our order id (their idempotency key)
+// material: catalog material id
+// quantity: integer
+// height_mm: target height, null when the mesh's own scale governs
+// files: { stl, "3mf", glb } absolute URLs, fetchable for 7 days
+// shipping: { name, line1, line2, city, region, postal_code, country, phone }
+// }
+// → 200 { id, state, lead_time_days }
+//
+// GET {URL}/orders/{id}
+// → 200 { id, state, tracking_number, carrier, note }
+//
+// POST {URL}/orders/{id}/cancel body { reason }
+// → 200 { ok, state }
+//
+// WEBHOOK POST /api/print/webhook/partner-cn
+// headers: x-print-signature: sha256={hex hmac of the raw body, key=KEY}
+// x-print-delivery: their delivery id (optional; we derive one
+// from the payload hash when absent, so a retry is still one row)
+// body: { id, state, tracking_number, carrier, note }
+//
+// STATE VOCABULARY: theirs maps onto ours through PARTNER_STATE_MAP below. An
+// unrecognized state maps to null, which the caller reads as "no news". That is
+// deliberate: guessing a transition from a string a partner added in a release
+// we have not read is exactly how a state machine gets corrupted.
+
+import { createHmac, timingSafeEqual } from 'node:crypto';
+import { AdapterUpstreamError, derivedDeliveryId, mapProviderStatus } from './contract.js';
+import { fetchUpstream } from '../../upstream-fetch.js';
+
+export const key = 'partner-cn';
+export const label = 'Partner fulfillment (CN, high precision)';
+
+export const capabilities = Object.freeze({
+ // Named from the catalog's own ids. Deliberately a list, not '*': a partner
+ // runs the machines they run, and an order for anything else must route to
+ // another lane rather than fail after it was taken.
+ materials: ['resin-standard', 'resin-tough', 'sls-nylon', 'sandstone-color'],
+ maxBboxMm: { x: 400, y: 400, z: 500 },
+ shipsFrom: 'CN',
+ leadTimeDays: 14,
+});
+
+const REQUEST_TIMEOUT_MS = 20_000;
+
+function config() {
+ const base = (process.env.PRINT_PARTNER_CN_URL || '').replace(/\/+$/, '');
+ const apiKey = process.env.PRINT_PARTNER_CN_KEY || '';
+ if (!base || !apiKey) return null;
+ return { base, apiKey };
+}
+
+/** Registered only when both credentials exist. */
+export function configured() {
+ return config() !== null;
+}
+
+/** Their state vocabulary → ours. The only place the two systems meet. */
+export const PARTNER_STATE_MAP = Object.freeze({
+ accepted: 'submitted',
+ queued: 'submitted',
+ in_production: 'printing',
+ printing: 'printing',
+ post_processing: 'quality_check',
+ inspection: 'quality_check',
+ quality_check: 'quality_check',
+ shipped: 'shipped',
+ in_transit: 'shipped',
+ delivered: 'delivered',
+ canceled: 'canceled',
+ cancelled: 'canceled',
+ rejected: 'rejected',
+ failed: 'rejected',
+});
+
+/**
+ * Map one of their states. Exported because it is the piece most likely to need
+ * a line added when their real docs land, and it is unit-tested without
+ * credentials.
+ * @param {unknown} partnerState
+ */
+export function mapState(partnerState) {
+ return mapProviderStatus(PARTNER_STATE_MAP, partnerState);
+}
+
+/**
+ * @param {string} path
+ * @param {RequestInit & { timeoutMs?: number }} [init]
+ */
+async function call(path, init = {}) {
+ const cfg = config();
+ if (!cfg) throw new AdapterUpstreamError(key, 'partner credentials are not configured');
+ const res = await fetchUpstream(
+ `${cfg.base}${path}`,
+ {
+ ...init,
+ headers: {
+ authorization: `Bearer ${cfg.apiKey}`,
+ 'content-type': 'application/json',
+ ...(init.headers || {}),
+ },
+ },
+ { name: `print:${key}`, timeoutMs: REQUEST_TIMEOUT_MS, attempts: 2 },
+ ).catch((err) => {
+ throw new AdapterUpstreamError(key, err?.message || String(err));
+ });
+ const body = await res.text().catch(() => '');
+ if (!res.ok) throw new AdapterUpstreamError(key, `${path} returned ${res.status}: ${body.slice(0, 300)}`, res.status);
+ try {
+ return body ? JSON.parse(body) : {};
+ } catch {
+ throw new AdapterUpstreamError(key, `${path} returned non-JSON: ${body.slice(0, 200)}`, res.status);
+ }
+}
+
+/**
+ * @param {object} order
+ * @param {{ stl?: string, '3mf'?: string, glb?: string }} [assets]
+ */
+export async function submit(order, assets = {}) {
+ const payload = {
+ reference: order?.id,
+ material: order?.material_id,
+ quantity: Number(order?.quantity) || 1,
+ height_mm: order?.target_height_mm != null ? Number(order.target_height_mm) : null,
+ files: { stl: assets?.stl || null, '3mf': assets?.['3mf'] || null, glb: assets?.glb || order?.source_glb_url || null },
+ shipping: order?.shipping || null,
+ };
+ const body = await call('/orders', { method: 'POST', body: JSON.stringify(payload) });
+ const providerOrderId = String(body?.id || '').trim();
+ if (!providerOrderId) throw new AdapterUpstreamError(key, 'partner accepted the order without returning an id');
+ return {
+ providerOrderId,
+ status: mapState(body?.state) || 'submitted',
+ leadTimeDays: Number.isInteger(body?.lead_time_days) ? body.lead_time_days : capabilities.leadTimeDays,
+ note: `Accepted by ${label}.`,
+ state: body,
+ };
+}
+
+/** @param {string} providerOrderId */
+export async function status(providerOrderId) {
+ const body = await call(`/orders/${encodeURIComponent(providerOrderId)}`);
+ return {
+ status: mapState(body?.state),
+ trackingNumber: body?.tracking_number || '',
+ carrier: body?.carrier || '',
+ note: typeof body?.note === 'string' ? body.note : '',
+ state: body,
+ };
+}
+
+/**
+ * @param {object} order
+ * @param {string} [reason]
+ */
+export async function cancel(order, reason = '') {
+ const body = await call(`/orders/${encodeURIComponent(order?.provider_order_id || '')}/cancel`, {
+ method: 'POST',
+ body: JSON.stringify({ reason: reason || 'canceled by three.ws' }),
+ });
+ return { ok: body?.ok !== false, note: 'Cancellation sent to the partner.', state: body };
+}
+
+/**
+ * HMAC-SHA256 over the exact bytes received. Signature comparison is constant
+ * time and length-guarded, because timingSafeEqual throws on a length mismatch
+ * and an attacker controls the header.
+ *
+ * @param {string} rawBody
+ * @param {Record<string, string|undefined>} headers
+ * @returns {{ ok: boolean, deliveryId: string, reason: string }}
+ */
+export function verifyWebhook(rawBody, headers = {}) {
+ const cfg = config();
+ if (!cfg) return { ok: false, deliveryId: '', reason: 'partner credentials are not configured' };
+ const presented = String(headers['x-print-signature'] || '').trim().replace(/^sha256=/i, '');
+ if (!presented) return { ok: false, deliveryId: '', reason: 'missing x-print-signature' };
+ const expected = createHmac('sha256', cfg.apiKey).update(rawBody, 'utf8').digest('hex');
+ const a = Buffer.from(presented, 'utf8');
+ const b = Buffer.from(expected, 'utf8');
+ if (a.length !== b.length || !timingSafeEqual(a, b)) {
+ return { ok: false, deliveryId: '', reason: 'signature mismatch' };
+ }
+ const supplied = String(headers['x-print-delivery'] || '').trim().slice(0, 200);
+ return { ok: true, deliveryId: supplied || derivedDeliveryId(key, rawBody), reason: '' };
+}
+
+/** @param {any} payload */
+export function parseWebhook(payload) {
+ return {
+ providerOrderId: String(payload?.id || '').trim(),
+ status: mapState(payload?.state),
+ trackingNumber: payload?.tracking_number || '',
+ carrier: payload?.carrier || '',
+ note: typeof payload?.note === 'string' ? payload.note : `Partner reported '${payload?.state}'.`,
+ state: payload,
+ };
+}
+
+export default { key, label, capabilities, configured, submit, status, cancel, verifyWebhook, parseWebhook };
diff --git a/api/_lib/print/analyze.js b/api/_lib/print/analyze.js
index b774229d6..f3aa21072 100644
--- a/api/_lib/print/analyze.js
+++ b/api/_lib/print/analyze.js
@@ -21,8 +21,8 @@
import * as THREE from 'three';
import { MeshBVH, ExtendedTriangle } from 'three-mesh-bvh';
import { boundsOf, weldPositions } from './mesh-io.js';
-import { edgeCensus, shells, signedVolume, surfaceArea } from './topology.js';
-import { toManifold, isNotManifoldError } from './manifold.js';
+import { edgeTopology, connectedShells, signedVolume, surfaceArea } from './topology.js';
+import { toSolid } from './manifold-kernel.js';
export const REPORT_VERSION = 1;
@@ -269,8 +269,15 @@ export async function analyzeMesh(mesh, opts = {}) {
throw new Error('mesh has no finite bounds');
}
- const census = edgeCensus(welded.indices);
- const shellInfo = shells(welded.indices, welded.positions.length / 3);
+ const topology = edgeTopology(welded.indices);
+ const shellList = connectedShells(welded.indices, topology.edges);
+ const census = {
+ openEdges: topology.openEdges,
+ nonManifoldEdges: topology.nonManifoldEdges,
+ edgeCount: topology.edgeCount,
+ degenerateTriangles: 0,
+ };
+ const shellInfo = { count: shellList.length };
const triangleCount = welded.indices.length / 3;
// The manifold kernel is the arbiter of "is this a solid". When it accepts
@@ -280,15 +287,14 @@ export async function analyzeMesh(mesh, opts = {}) {
let volumeM3 = null;
let volumeSource = 'signed_sum';
let genus = null;
- try {
- const solid = await toManifold(welded.positions, welded.indices);
+ const solid = await toSolid(welded.positions, welded.indices);
+ if (solid) {
manifold = true;
volumeM3 = Math.abs(solid.volume());
volumeSource = 'manifold';
genus = solid.genus();
solid.delete?.();
- } catch (err) {
- if (!isNotManifoldError(err)) throw err;
+ } else {
volumeM3 = Math.abs(signedVolume(welded.positions, welded.indices));
}
diff --git a/api/_lib/print/catalog.js b/api/_lib/print/catalog.js
new file mode 100644
index 000000000..39559717a
--- /dev/null
+++ b/api/_lib/print/catalog.js
@@ -0,0 +1,276 @@
+// Materialize catalog loader: data/print-catalog.json, validated once at module
+// load, projected two ways.
+//
+// The file is data and the owner tunes it; this module is the only thing that
+// reads it. It fails LOUDLY at import time on a malformed catalog rather than
+// at request time, because a catalog that lost its shipping zones or grew a
+// negative rate is a pricing incident, and the deploy is the right place to
+// find out.
+//
+// Two projections:
+// PRINT_CATALOG the full record, including the owner-only fields
+// (margin_fraction, _sources, the _note keys).
+// publicCatalog() what GET /api/print/catalog serves: buyer-facing only.
+// Margin and sourcing are ours, not the buyer's.
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const CATALOG_PATH = fileURLToPath(new URL('../../../data/print-catalog.json', import.meta.url));
+
+const MATERIAL_CLASSES = new Set([
+ 'resin',
+ 'sls_nylon',
+ 'full_color',
+ 'fdm_draft',
+ 'metal_quote_only',
+]);
+
+function fail(message) {
+ throw new Error(`print-catalog: ${message}`);
+}
+
+function positiveNumber(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
+ fail(`${label} must be a positive number, got ${JSON.stringify(value)}`);
+ }
+ return value;
+}
+
+function nonNegativeNumber(value, label) {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
+ fail(`${label} must be a non-negative number, got ${JSON.stringify(value)}`);
+ }
+ return value;
+}
+
+function validateFinish(finish, materialId) {
+ const where = `material ${materialId} finish ${finish?.id}`;
+ if (!finish?.id || typeof finish.id !== 'string') fail(`${where}: missing id`);
+ if (!finish.name) fail(`${where}: missing name`);
+ nonNegativeNumber(finish.fee_usd, `${where}.fee_usd`);
+ nonNegativeNumber(finish.fee_usd_cm3, `${where}.fee_usd_cm3`);
+ nonNegativeNumber(finish.lead_time_days, `${where}.lead_time_days`);
+}
+
+function validateMaterial(material) {
+ const id = material?.id;
+ if (!id || typeof id !== 'string') fail('a material is missing its id');
+ if (!MATERIAL_CLASSES.has(material.class)) {
+ fail(`material ${id}: unknown class ${JSON.stringify(material.class)}`);
+ }
+ if (!material.name) fail(`material ${id}: missing name`);
+ positiveNumber(material.density_g_cm3, `material ${id}.density_g_cm3`);
+ nonNegativeNumber(material.rate_usd_cm3, `material ${id}.rate_usd_cm3`);
+ nonNegativeNumber(material.setup_fee_usd, `material ${id}.setup_fee_usd`);
+ positiveNumber(material.min_wall_mm, `material ${id}.min_wall_mm`);
+ positiveNumber(material.min_height_mm, `material ${id}.min_height_mm`);
+ positiveNumber(material.max_height_mm, `material ${id}.max_height_mm`);
+ if (material.max_height_mm <= material.min_height_mm) {
+ fail(`material ${id}: max_height_mm must exceed min_height_mm`);
+ }
+ if (!Array.isArray(material.max_bbox_mm) || material.max_bbox_mm.length !== 3) {
+ fail(`material ${id}: max_bbox_mm must be three numbers`);
+ }
+ for (const [i, dim] of material.max_bbox_mm.entries()) {
+ positiveNumber(dim, `material ${id}.max_bbox_mm[${i}]`);
+ }
+ nonNegativeNumber(material.lead_time_days, `material ${id}.lead_time_days`);
+ if (typeof material.quote_only !== 'boolean') fail(`material ${id}: quote_only must be a boolean`);
+ // A priced material with a zero rate would quote every print at the setup fee
+ // alone. Only a quote-on-request material is allowed to carry no rate.
+ if (!material.quote_only && material.rate_usd_cm3 <= 0) {
+ fail(`material ${id}: a priced material needs a positive rate_usd_cm3`);
+ }
+ if (!Array.isArray(material.finishes) || material.finishes.length === 0) {
+ fail(`material ${id}: needs at least one finish`);
+ }
+ for (const finish of material.finishes) validateFinish(finish, id);
+ const finishIds = material.finishes.map((f) => f.id);
+ if (new Set(finishIds).size !== finishIds.length) fail(`material ${id}: duplicate finish ids`);
+}
+
+function validateZone(zone) {
+ const id = zone?.id;
+ if (!id) fail('a shipping zone is missing its id');
+ if (!zone.name) fail(`zone ${id}: missing name`);
+ nonNegativeNumber(zone.base_usd, `zone ${id}.base_usd`);
+ nonNegativeNumber(zone.per_kg_usd, `zone ${id}.per_kg_usd`);
+ nonNegativeNumber(zone.transit_days, `zone ${id}.transit_days`);
+ if (!Array.isArray(zone.countries)) fail(`zone ${id}: countries must be an array`);
+ for (const code of zone.countries) {
+ if (!/^[A-Z]{2}$/.test(code)) fail(`zone ${id}: ${JSON.stringify(code)} is not an ISO 3166-1 alpha-2 code`);
+ }
+}
+
+function validate(catalog) {
+ if (!Number.isInteger(catalog?.version) || catalog.version < 1) fail('version must be a positive integer');
+ if (!Array.isArray(catalog.materials) || catalog.materials.length === 0) fail('no materials');
+ for (const material of catalog.materials) validateMaterial(material);
+ const ids = catalog.materials.map((m) => m.id);
+ if (new Set(ids).size !== ids.length) fail('duplicate material ids');
+
+ if (!Array.isArray(catalog.shipping_zones) || catalog.shipping_zones.length === 0) fail('no shipping zones');
+ for (const zone of catalog.shipping_zones) validateZone(zone);
+ const zoneIds = catalog.shipping_zones.map((z) => z.id);
+ if (new Set(zoneIds).size !== zoneIds.length) fail('duplicate shipping zone ids');
+ // Every zone but the fallback names its countries; the fallback names none,
+ // and there must be exactly one of it or a destination could resolve nowhere.
+ const fallbacks = catalog.shipping_zones.filter((z) => z.countries.length === 0);
+ if (fallbacks.length !== 1) fail('exactly one shipping zone must be the empty-country fallback');
+ const seen = new Set();
+ for (const zone of catalog.shipping_zones) {
+ for (const code of zone.countries) {
+ if (seen.has(code)) fail(`country ${code} is claimed by more than one zone`);
+ seen.add(code);
+ }
+ }
+
+ const q = catalog.quote;
+ positiveNumber(q?.ttl_seconds, 'quote.ttl_seconds');
+ nonNegativeNumber(q?.minimum_manufacturing_usd, 'quote.minimum_manufacturing_usd');
+ positiveNumber(q?.floor_price_usd, 'quote.floor_price_usd');
+ positiveNumber(q?.max_quantity, 'quote.max_quantity');
+ positiveNumber(q?.volumetric_divisor_cm3_per_kg, 'quote.volumetric_divisor_cm3_per_kg');
+ nonNegativeNumber(q?.packaging_weight_kg, 'quote.packaging_weight_kg');
+ positiveNumber(q?.max_parcel_weight_kg, 'quote.max_parcel_weight_kg');
+
+ const hd = catalog.holder_discount;
+ nonNegativeNumber(hd?.max_bps, 'holder_discount.max_bps');
+ if (hd.max_bps > 10_000) fail('holder_discount.max_bps cannot exceed 10000');
+
+ if (!Array.isArray(catalog.quantity_breaks)) fail('quantity_breaks must be an array');
+ let previousQuantity = 1;
+ for (const brk of catalog.quantity_breaks) {
+ positiveNumber(brk?.min_quantity, 'quantity_breaks[].min_quantity');
+ nonNegativeNumber(brk?.discount_bps, 'quantity_breaks[].discount_bps');
+ if (brk.discount_bps > 10_000) fail('a quantity break cannot exceed 10000 bps');
+ // Ascending order is load-bearing: bestQuantityBreak() walks the list and
+ // keeps the last match, so an unsorted list would silently under-discount.
+ if (brk.min_quantity <= previousQuantity) fail('quantity_breaks must ascend by min_quantity');
+ previousQuantity = brk.min_quantity;
+ }
+
+ if (!Array.isArray(catalog._sources) || catalog._sources.length === 0) fail('no _sources');
+ for (const source of catalog._sources) {
+ if (!source?.id || !source.url || !source.retrieved) fail('a _sources entry is missing id/url/retrieved');
+ }
+ const sourceIds = new Set(catalog._sources.map((s) => s.id));
+ for (const material of catalog.materials) {
+ for (const sid of material.source_ids || []) {
+ if (!sourceIds.has(sid)) fail(`material ${material.id} cites unknown source ${sid}`);
+ }
+ }
+ return catalog;
+}
+
+export const PRINT_CATALOG = Object.freeze(
+ validate(JSON.parse(readFileSync(CATALOG_PATH, 'utf8'))),
+);
+
+const MATERIALS_BY_ID = new Map(PRINT_CATALOG.materials.map((m) => [m.id, m]));
+const ZONES_BY_ID = new Map(PRINT_CATALOG.shipping_zones.map((z) => [z.id, z]));
+const ZONE_BY_COUNTRY = new Map();
+for (const zone of PRINT_CATALOG.shipping_zones) {
+ for (const code of zone.countries) ZONE_BY_COUNTRY.set(code, zone);
+}
+const FALLBACK_ZONE = PRINT_CATALOG.shipping_zones.find((z) => z.countries.length === 0);
+
+/** The material record for an id, or null. */
+export function materialById(id) {
+ return MATERIALS_BY_ID.get(String(id || '')) || null;
+}
+
+/** A material's finish record by id, or null. */
+export function finishById(material, id) {
+ return material?.finishes?.find((f) => f.id === String(id || '')) || null;
+}
+
+/** A shipping zone by its id, or null. */
+export function zoneById(id) {
+ return ZONES_BY_ID.get(String(id || '')) || null;
+}
+
+/**
+ * The shipping zone serving a destination country. An unrecognized or absent
+ * country resolves to the fallback zone rather than throwing: a destination we
+ * have not named is still a destination we ship to, at the rest-of-world rate.
+ */
+export function zoneForCountry(country) {
+ const code = String(country || '').trim().toUpperCase();
+ return ZONE_BY_COUNTRY.get(code) || FALLBACK_ZONE;
+}
+
+/** ISO alpha-2 shape check, so a quote never prices "United States" as row. */
+export function isCountryCode(country) {
+ return /^[A-Za-z]{2}$/.test(String(country || '').trim());
+}
+
+function publicFinish(finish) {
+ return {
+ id: finish.id,
+ name: finish.name,
+ blurb: finish.blurb || '',
+ fee_usd: finish.fee_usd,
+ fee_usd_cm3: finish.fee_usd_cm3,
+ lead_time_days: finish.lead_time_days,
+ };
+}
+
+function publicMaterial(material) {
+ return {
+ id: material.id,
+ name: material.name,
+ class: material.class,
+ blurb: material.blurb || '',
+ density_g_cm3: material.density_g_cm3,
+ rate_usd_cm3: material.rate_usd_cm3,
+ setup_fee_usd: material.setup_fee_usd,
+ min_wall_mm: material.min_wall_mm,
+ min_height_mm: material.min_height_mm,
+ max_height_mm: material.max_height_mm,
+ max_bbox_mm: material.max_bbox_mm,
+ lead_time_days: material.lead_time_days,
+ quote_only: material.quote_only,
+ color_capable: material.color_capable === true,
+ finishes: material.finishes.map(publicFinish),
+ };
+}
+
+function publicZone(zone) {
+ return {
+ id: zone.id,
+ name: zone.name,
+ base_usd: zone.base_usd,
+ per_kg_usd: zone.per_kg_usd,
+ transit_days: zone.transit_days,
+ countries: zone.countries,
+ };
+}
+
+/**
+ * The buyer-facing catalog: everything a human or an agent needs to choose a
+ * material and predict a price, and nothing about our margin or our sourcing.
+ */
+export function publicCatalog() {
+ return {
+ version: PRINT_CATALOG.version,
+ updated: PRINT_CATALOG.updated,
+ currency: PRINT_CATALOG.currency,
+ settlement: PRINT_CATALOG.settlement,
+ quote: {
+ ttl_seconds: PRINT_CATALOG.quote.ttl_seconds,
+ minimum_manufacturing_usd: PRINT_CATALOG.quote.minimum_manufacturing_usd,
+ floor_price_usd: PRINT_CATALOG.quote.floor_price_usd,
+ max_quantity: PRINT_CATALOG.quote.max_quantity,
+ max_parcel_weight_kg: PRINT_CATALOG.quote.max_parcel_weight_kg,
+ },
+ holder_discount: {
+ max_bps: PRINT_CATALOG.holder_discount.max_bps,
+ applies_to: PRINT_CATALOG.holder_discount.applies_to,
+ },
+ quantity_breaks: PRINT_CATALOG.quantity_breaks.map((b) => ({ ...b })),
+ materials: PRINT_CATALOG.materials.map(publicMaterial),
+ shipping_zones: PRINT_CATALOG.shipping_zones.map(publicZone),
+ };
+}
diff --git a/api/_lib/print/certificate.js b/api/_lib/print/certificate.js
new file mode 100644
index 000000000..25c96c963
--- /dev/null
+++ b/api/_lib/print/certificate.js
@@ -0,0 +1,568 @@
+// @ts-check
+// Materialize certificates: the on-chain proof a physical print carries.
+//
+// When an order ships, three things are frozen together and never move again:
+//
+// 1. the SHA-256 of the exact bytes that were printed (and of the prepared
+// GLB the certificate page renders),
+// 2. the edition number claimed out of that model's series, claimed
+// atomically so two simultaneous shipments cannot both be "number 7",
+// 3. a Solana memo transaction carrying both, signed by the platform.
+//
+// The QR on the package resolves to /cert/<id>, which renders the original
+// model, the lineage, the edition, and the RAW memo payload. That last part is
+// the point: a buyer verifies a print by hashing the file and comparing it to
+// the string in the transaction, with no dependency on this database, this
+// company, or any block explorer staying online.
+//
+// Cluster policy. Devnet is the default and needs no approval: it proves the
+// pipeline end to end. Mainnet is gated twice on purpose (CLAUDE.md gate 1
+// covers irreversible on-chain actions): PRINT_CERT_CLUSTER must say mainnet
+// AND PRINT_CERT_MAINNET_APPROVAL must carry the owner's recorded approval. A
+// missing approval does not silently downgrade to devnet, because a devnet
+// signature printed on a mainnet certificate would be a lie; it leaves the
+// certificate unattested, records why, and lets the sweep retry once the
+// approval lands.
+//
+// Failure policy. Issuance never blocks a shipment. The row is written first;
+// the QR and the memo are best-effort and retried by the print reconciliation
+// sweep (api/cron/print-orders-sync.js). A certificate with a null signature is
+// a real certificate whose proof is still in flight, and the page says so.
+
+import crypto from 'node:crypto';
+import { Buffer } from 'node:buffer';
+import QRCode from 'qrcode';
+import { Keypair, PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';
+
+import { sql } from '../db.js';
+import { getObjectBuffer, keyFromPublicUrl, putObject, publicUrl, objectStorageConfigured } from '../r2.js';
+import { solanaConnection } from '../solana/connection.js';
+import { sendAndConfirm } from '../solana/confirm.js';
+import { decodeAttesterSecret } from '../attest-event.js';
+import { RPC } from '../solana-attestations.js';
+import { seriesKeyFor, editionLimitFor, PrintEditionError } from './editions.js';
+
+/** SPL Memo v2. Same program the agent attestations use. */
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+const TX_TIMEOUT_MS = 20_000;
+/** The memo schema version. Bumping it is a wire-format change, not a tweak. */
+export const CERT_MEMO_KIND = 'threews.print.v1';
+/** Bounded so a claim race cannot spin: 12 shipments of one model at once. */
+const EDITION_CLAIM_ATTEMPTS = 12;
+
+export const CERT_ID_RE = /^[0-9a-f]{24}$/;
+
+/** Typed failure so handlers map a cause to a status code, never a bare 500. */
+export class PrintCertificateError extends Error {
+ /**
+ * @param {string} code
+ * @param {string} message
+ * @param {Record<string, unknown>} [extra]
+ */
+ constructor(code, message, extra = {}) {
+ super(message);
+ this.name = 'PrintCertificateError';
+ this.code = code;
+ Object.assign(this, extra);
+ }
+}
+
+/** 24 lowercase hex characters: short enough to print, wide enough to be unguessable. */
+export function newCertificateId() {
+ return crypto.randomBytes(12).toString('hex');
+}
+
+/** @param {Buffer|Uint8Array} bytes */
+export function sha256Hex(bytes) {
+ return crypto.createHash('sha256').update(bytes).digest('hex');
+}
+
+export function siteOrigin() {
+ return (process.env.PUBLIC_BASE_URL || 'https://three.ws').replace(/\/$/, '');
+}
+
+/** @param {string} certId */
+export function certificateUrl(certId) {
+ return `${siteOrigin()}/cert/${certId}`;
+}
+
+/**
+ * Which cluster certificates attest on. Devnet unless the deployment says
+ * otherwise; anything unrecognised is devnet, never a silent mainnet spend.
+ * @returns {'mainnet'|'devnet'}
+ */
+export function certCluster() {
+ return String(process.env.PRINT_CERT_CLUSTER || '').trim().toLowerCase() === 'mainnet'
+ ? 'mainnet'
+ : 'devnet';
+}
+
+/**
+ * The owner gate on real-money attestation. Mainnet sends are irreversible
+ * on-chain actions, so they require an explicit recorded approval on top of
+ * the cluster flag.
+ * @returns {{ allowed: boolean, reason: string }}
+ */
+export function mainnetAttestationAllowed() {
+ const approval = String(process.env.PRINT_CERT_MAINNET_APPROVAL || '').trim();
+ if (!approval) {
+ return {
+ allowed: false,
+ reason:
+ 'mainnet attestation is owner-gated: set PRINT_CERT_MAINNET_APPROVAL to the recorded approval before certificates attest on mainnet',
+ };
+ }
+ return { allowed: true, reason: '' };
+}
+
+/** The keypair that signs certificate memos. */
+export function loadCertAttester() {
+ const raw = process.env.PRINT_CERT_ATTESTER_SECRET || process.env.ATTEST_AGENT_SECRET_KEY;
+ if (!raw) {
+ throw new PrintCertificateError(
+ 'attester_unconfigured',
+ 'no certificate attester key: set PRINT_CERT_ATTESTER_SECRET (or ATTEST_AGENT_SECRET_KEY)',
+ );
+ }
+ const bytes = decodeAttesterSecret(raw);
+ if (!bytes) {
+ throw new PrintCertificateError(
+ 'attester_key_undecodable',
+ 'the certificate attester key is set but is not a decodable ed25519 secret key',
+ );
+ }
+ return Keypair.fromSecretKey(bytes);
+}
+
+/**
+ * The exact JSON a certificate's memo transaction carries. Compact on purpose:
+ * SPL Memo is capped per transaction, and every byte here is printed on the
+ * certificate page for a human to compare against the chain.
+ *
+ * @param {{ id: string, glb_sha256: string, print_asset_sha256?: string|null, print_asset_kind?: string|null,
+ * edition_no: number, edition_of?: number|null, creation_id?: string|null, printed_at?: Date|string|null }} cert
+ * @returns {string}
+ */
+export function buildCertificateMemo(cert) {
+ /** @type {Record<string, unknown>} */
+ const payload = {
+ v: 1,
+ kind: CERT_MEMO_KIND,
+ cert: cert.id,
+ sha256: cert.glb_sha256,
+ ed: cert.edition_no,
+ of: cert.edition_of ?? null,
+ ts: Math.floor(new Date(cert.printed_at || Date.now()).getTime() / 1000),
+ };
+ if (cert.creation_id) payload.creation = cert.creation_id;
+ if (cert.print_asset_sha256 && cert.print_asset_kind) {
+ payload.print = `${cert.print_asset_kind}:${cert.print_asset_sha256}`;
+ }
+ return JSON.stringify(payload);
+}
+
+/**
+ * Pick the manufacturing asset an order was actually printed from. STL and 3MF
+ * are what a bureau loads; the GLB is the viewable original and is hashed
+ * separately. Returns null when the order carries neither.
+ * @param {Record<string, string>} assets
+ */
+export function pickPrintAsset(assets) {
+ for (const kind of ['3mf', 'stl', 'glb']) {
+ const url = assets?.[kind];
+ if (typeof url === 'string' && url) return { kind, url };
+ }
+ return null;
+}
+
+/**
+ * Read an asset by its public URL and return its bytes plus the storage key.
+ * @param {string} url
+ */
+async function readAsset(url) {
+ const key = keyFromPublicUrl(url);
+ if (!key) {
+ throw new PrintCertificateError(
+ 'asset_not_in_bucket',
+ `prepared asset ${url} does not live in this deployment's object storage, so its bytes cannot be hashed`,
+ );
+ }
+ const bytes = await getObjectBuffer(key);
+ return { key, bytes };
+}
+
+/**
+ * Claim the next edition number for a series and insert the certificate, in one
+ * statement, retrying on the unique-index collision that a concurrent claim
+ * produces. The HAVING clause is what enforces the cap atomically: when the
+ * series is full the insert selects zero rows rather than writing an
+ * over-numbered certificate.
+ *
+ * @param {object} row
+ * @returns {Promise<any>}
+ */
+async function claimEdition(row) {
+ for (let attempt = 1; attempt <= EDITION_CLAIM_ATTEMPTS; attempt++) {
+ try {
+ const inserted = await sql`
+ insert into print_certificates (
+ id, order_id, creation_id, series_key, edition_no, edition_of,
+ glb_sha256, glb_bytes, print_asset_kind, print_asset_key, print_asset_sha256,
+ material_id, material_label, network, memo
+ )
+ select
+ ${row.id}, ${row.order_id}, ${row.creation_id}, ${row.series_key},
+ coalesce(max(edition_no), 0) + 1, ${row.edition_of},
+ ${row.glb_sha256}, ${row.glb_bytes}, ${row.print_asset_kind},
+ ${row.print_asset_key}, ${row.print_asset_sha256},
+ ${row.material_id}, ${row.material_label}, ${row.network}, ''
+ from print_certificates
+ where series_key = ${row.series_key}
+ having ${row.edition_of}::int is null
+ or coalesce(max(edition_no), 0) + 1 <= ${row.edition_of}::int
+ returning *
+ `;
+ if (inserted.length === 0) {
+ throw new PrintEditionError(
+ 'edition_sold_out',
+ `this edition is capped at ${row.edition_of} and every copy has already been certified`,
+ { limit: row.edition_of },
+ );
+ }
+ return inserted[0];
+ } catch (err) {
+ // 23505 on the order index means someone else already certified this
+ // order: that is the idempotent answer, not a failure.
+ if (err?.code === '23505' && String(err?.constraint || '').includes('order_uniq')) {
+ const [existing] = await sql`select * from print_certificates where order_id = ${row.order_id} limit 1`;
+ if (existing) return existing;
+ }
+ // 23505 on the series index means a concurrent claim took this number.
+ // Recompute and try again; the loop is bounded so a pathological
+ // series cannot spin forever.
+ if (err?.code === '23505' && attempt < EDITION_CLAIM_ATTEMPTS) continue;
+ throw err;
+ }
+ }
+ throw new PrintCertificateError(
+ 'edition_claim_contended',
+ 'could not claim an edition number after repeated concurrent collisions',
+ );
+}
+
+/**
+ * Render the certificate's QR as a PNG and store it beside the prepared assets.
+ * Best-effort: a certificate without its QR is still a valid certificate, and
+ * the sweep regenerates it.
+ * @param {{ id: string }} cert
+ * @returns {Promise<{ qr_key: string, qr_url: string }|null>}
+ */
+export async function generateCertificateQr(cert) {
+ if (!objectStorageConfigured()) return null;
+ const png = await QRCode.toBuffer(certificateUrl(cert.id), {
+ type: 'png',
+ errorCorrectionLevel: 'Q',
+ margin: 2,
+ width: 720,
+ color: { dark: '#000000ff', light: '#ffffffff' },
+ });
+ const key = `print/certs/${cert.id}/qr.png`;
+ await putObject({ key, body: png, contentType: 'image/png' });
+ const url = publicUrl(key);
+ await sql`update print_certificates set qr_key = ${key}, qr_url = ${url} where id = ${cert.id}`;
+ return { qr_key: key, qr_url: url };
+}
+
+/**
+ * Send the certificate's memo transaction and record its signature.
+ *
+ * @param {any} cert a print_certificates row
+ * @returns {Promise<{ status: 'attested'|'already'|'refused', signature: string|null, reason?: string }>}
+ */
+export async function attestCertificate(cert) {
+ if (cert.solana_signature) {
+ return { status: 'already', signature: cert.solana_signature };
+ }
+ const network = cert.network === 'mainnet' ? 'mainnet' : 'devnet';
+ if (network === 'mainnet') {
+ const gate = mainnetAttestationAllowed();
+ if (!gate.allowed) {
+ await sql`
+ update print_certificates
+ set attest_error = ${gate.reason}, attest_attempts = attest_attempts + 1
+ where id = ${cert.id}
+ `;
+ return { status: 'refused', signature: null, reason: gate.reason };
+ }
+ }
+
+ const memo = cert.memo && cert.memo !== '' ? cert.memo : buildCertificateMemo(cert);
+ const attester = loadCertAttester();
+ const conn = solanaConnection({ url: RPC[network], commitment: 'confirmed' });
+ const ix = new TransactionInstruction({
+ programId: MEMO_PROGRAM_ID,
+ keys: [{ pubkey: attester.publicKey, isSigner: true, isWritable: true }],
+ data: Buffer.from(memo, 'utf8'),
+ });
+
+ let signature;
+ try {
+ signature = await withTimeout(
+ sendAndConfirm(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),
+ TX_TIMEOUT_MS,
+ );
+ } catch (err) {
+ await sql`
+ update print_certificates
+ set attest_error = ${String(err?.message || err).slice(0, 500)},
+ attest_attempts = attest_attempts + 1
+ where id = ${cert.id}
+ `;
+ throw err;
+ }
+
+ await sql`
+ update print_certificates
+ set solana_signature = ${signature}, attested_at = now(), attest_error = null,
+ memo = ${memo}, attest_attempts = attest_attempts + 1
+ where id = ${cert.id}
+ `;
+ return { status: 'attested', signature };
+}
+
+/**
+ * @template T
+ * @param {Promise<T>} promise
+ * @param {number} ms
+ * @returns {Promise<T>}
+ */
+function withTimeout(promise, ms) {
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(Object.assign(new Error(`solana rpc timeout after ${ms}ms`), { code: 'RPC_TIMEOUT' })),
+ ms,
+ );
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+/**
+ * Issue the certificate for a shipped order. Idempotent: a second call returns
+ * the certificate the first one wrote.
+ *
+ * @param {{ orderId: string, attest?: boolean, qr?: boolean }} input
+ * @returns {Promise<{ certificate: any, created: boolean, attestation: { status: string, signature: string|null, reason?: string }|null }>}
+ */
+export async function issueCertificateForOrder({ orderId, attest = true, qr = true }) {
+ const [existing] = await sql`select * from print_certificates where order_id = ${orderId} limit 1`;
+ if (existing) {
+ return { certificate: existing, created: false, attestation: null };
+ }
+
+ const [order] = await sql`
+ select id, creation_id, source_glb_url, prepared_asset_urls, material_id, quote, user_id
+ from print_orders where id = ${orderId} limit 1
+ `;
+ if (!order) throw new PrintCertificateError('order_not_found', `no print order ${orderId}`);
+
+ const assets = order.prepared_asset_urls || {};
+ const glbUrl = assets.glb || order.source_glb_url;
+ if (!glbUrl) {
+ throw new PrintCertificateError(
+ 'order_has_no_asset',
+ 'this order carries neither a prepared GLB nor a source GLB, so there are no bytes to certify',
+ );
+ }
+
+ const glb = await readAsset(glbUrl);
+ const glbSha256 = sha256Hex(glb.bytes);
+
+ // The manufacturing file, when the prepare step produced one distinct from
+ // the GLB. Hashing it is what makes "these exact bytes were printed"
+ // checkable, rather than only "this model was printed".
+ let printAsset = null;
+ const picked = pickPrintAsset(assets);
+ if (picked && picked.url !== glbUrl) {
+ const read = await readAsset(picked.url);
+ printAsset = { kind: picked.kind, key: read.key, sha256: sha256Hex(read.bytes) };
+ }
+
+ const seriesKey = seriesKeyFor({ creationId: order.creation_id, glbSha256 });
+ const editionOf = await editionLimitFor(order.creation_id);
+ const materialLabel = order.quote?.material?.label || order.quote?.material_label || null;
+
+ const claimed = await claimEdition({
+ id: newCertificateId(),
+ order_id: order.id,
+ creation_id: order.creation_id ?? null,
+ series_key: seriesKey,
+ edition_of: editionOf,
+ glb_sha256: glbSha256,
+ glb_bytes: glb.bytes.length,
+ print_asset_kind: printAsset?.kind ?? null,
+ print_asset_key: printAsset?.key ?? null,
+ print_asset_sha256: printAsset?.sha256 ?? null,
+ material_id: order.material_id ?? null,
+ material_label: materialLabel,
+ network: certCluster(),
+ });
+
+ // A claim that resolved to an existing row (the order unique index won a
+ // race) is already complete; do not re-run its side effects.
+ if (claimed.memo) {
+ return { certificate: claimed, created: false, attestation: null };
+ }
+
+ const memo = buildCertificateMemo(claimed);
+ await sql`update print_certificates set memo = ${memo} where id = ${claimed.id}`;
+ let certificate = { ...claimed, memo };
+
+ if (qr) {
+ try {
+ const stored = await generateCertificateQr(certificate);
+ if (stored) certificate = { ...certificate, ...stored };
+ } catch (err) {
+ console.error('[print-certificate] qr generation failed:', err?.message);
+ }
+ }
+
+ let attestation = null;
+ if (attest) {
+ try {
+ attestation = await attestCertificate(certificate);
+ if (attestation.signature) {
+ certificate = { ...certificate, solana_signature: attestation.signature, attested_at: new Date() };
+ }
+ } catch (err) {
+ console.error('[print-certificate] attestation failed:', err?.message);
+ attestation = { status: 'failed', signature: null, reason: String(err?.message || err) };
+ }
+ }
+
+ return { certificate, created: true, attestation };
+}
+
+/**
+ * The retry path the print reconciliation sweep runs: certificates whose memo
+ * never landed, oldest first, with their QR backfilled on the way past.
+ *
+ * @param {{ limit?: number, maxAttempts?: number }} [opts]
+ */
+export async function retryPendingAttestations({ limit = 10, maxAttempts = 8 } = {}) {
+ const pending = await sql`
+ select * from print_certificates
+ where solana_signature is null and attest_attempts < ${maxAttempts}
+ order by created_at asc
+ limit ${limit}
+ `;
+ const result = { scanned: pending.length, attested: 0, refused: 0, failed: 0, qrBackfilled: 0 };
+ for (const cert of pending) {
+ if (!cert.qr_url) {
+ try {
+ if (await generateCertificateQr(cert)) result.qrBackfilled += 1;
+ } catch (err) {
+ console.error('[print-certificate] qr backfill failed:', err?.message);
+ }
+ }
+ try {
+ const out = await attestCertificate(cert);
+ if (out.status === 'attested') result.attested += 1;
+ else if (out.status === 'refused') result.refused += 1;
+ } catch {
+ result.failed += 1;
+ }
+ }
+ return result;
+}
+
+/**
+ * Public read shape. `prompt` is withheld for a private creation: the
+ * certificate always renders (the buyer holds the object and the proof), but a
+ * private model's lineage stays private.
+ *
+ * @param {string} certId
+ * @returns {Promise<object|null>}
+ */
+export async function getPublicCertificate(certId) {
+ if (!CERT_ID_RE.test(String(certId || ''))) return null;
+ const [row] = await sql`
+ select c.*,
+ o.material_id as order_material_id,
+ o.quantity as order_quantity,
+ fc.prompt as creation_prompt,
+ fc.visibility as creation_visibility,
+ fc.glb_url as creation_glb_url,
+ fc.preview_image_url as creation_preview_url,
+ fc.model_category as creation_category,
+ fc.parent_creation_id as creation_parent_id,
+ fc.refine_instruction as creation_refine_instruction,
+ fc.created_at as creation_created_at,
+ fc.print_edition_limit as creation_edition_limit,
+ u.username as creator_username,
+ u.display_name as creator_display_name
+ from print_certificates c
+ join print_orders o on o.id = c.order_id
+ left join forge_creations fc on fc.id = c.creation_id
+ left join users u on u.id = fc.user_id and u.deleted_at is null
+ where c.id = ${certId}
+ limit 1
+ `;
+ if (!row) return null;
+
+ const isPrivate = row.creation_visibility === 'private';
+ const [issued] = await sql`
+ select count(*)::int as n from print_certificates where series_key = ${row.series_key}
+ `;
+
+ return {
+ id: row.id,
+ edition_no: row.edition_no,
+ edition_of: row.edition_of ?? null,
+ edition_issued: issued?.n ?? row.edition_no,
+ printed_at: row.printed_at,
+ material_id: row.material_id ?? row.order_material_id ?? null,
+ material_label: row.material_label ?? null,
+ glb_sha256: row.glb_sha256,
+ glb_bytes: row.glb_bytes ?? null,
+ print_asset_kind: row.print_asset_kind ?? null,
+ print_asset_sha256: row.print_asset_sha256 ?? null,
+ network: row.network,
+ memo: row.memo,
+ solana_signature: row.solana_signature ?? null,
+ attested_at: row.attested_at ?? null,
+ explorer_url: row.solana_signature ? explorerTxUrl(row.solana_signature, row.network) : null,
+ qr_url: row.qr_url ?? null,
+ certificate_url: certificateUrl(row.id),
+ creation: row.creation_id
+ ? {
+ id: row.creation_id,
+ // A private model still shows its object: the holder of the print
+ // owns that. Its prompt is the creator's, and stays theirs.
+ prompt: isPrivate ? null : (row.creation_prompt ?? null),
+ prompt_withheld: isPrivate,
+ glb_url: row.creation_glb_url ?? null,
+ preview_image_url: row.creation_preview_url ?? null,
+ category: row.creation_category ?? null,
+ parent_creation_id: isPrivate ? null : (row.creation_parent_id ?? null),
+ refine_instruction: isPrivate ? null : (row.creation_refine_instruction ?? null),
+ created_at: row.creation_created_at ?? null,
+ visibility: row.creation_visibility ?? null,
+ model_url: isPrivate ? null : `/m/${row.creation_id}`,
+ creator_username: isPrivate ? null : (row.creator_username ?? null),
+ creator_display_name: isPrivate ? null : (row.creator_display_name ?? null),
+ }
+ : null,
+ };
+}
+
+/**
+ * A public explorer link for a signature. The certificate page renders the raw
+ * memo beside it, so the page keeps working when the explorer does not.
+ * @param {string} signature
+ * @param {string} network
+ */
+export function explorerTxUrl(signature, network) {
+ const cluster = network === 'mainnet' ? '' : '?cluster=devnet';
+ return `https://explorer.solana.com/tx/${signature}${cluster}`;
+}
diff --git a/api/_lib/print/editions.js b/api/_lib/print/editions.js
new file mode 100644
index 000000000..b8923d59c
--- /dev/null
+++ b/api/_lib/print/editions.js
@@ -0,0 +1,179 @@
+// @ts-check
+// Edition scarcity for Materialize prints.
+//
+// A print is a collectible only if its supply is knowable. The creator of a
+// forge model sets one number: how many physical copies of it may ever exist.
+// Null (every model's default) is an open edition, which is the honest state
+// for a model nobody has capped, not a missing value to be filled in later.
+//
+// The cap is read in two places and written in one:
+// - the quote path calls assertEditionAvailable() BEFORE any money moves, so
+// a sold-out model refuses at the price, never after the payment;
+// - the certificate issuer claims the next edition number atomically at ship
+// time (api/_lib/print/certificate.js) and freezes the cap onto the row;
+// - the creator sets it through setEditionLimit(), which refuses to cap a
+// series below what has already shipped.
+//
+// The series a number is claimed from is NOT always a creation: a direct GLB
+// upload has no forge row. Those series are keyed by the content hash, so two
+// prints of identical bytes belong to one series rather than each minting its
+// own "edition 1 of 1".
+
+import { sql } from '../db.js';
+
+export const EDITION_LIMIT_MIN = 1;
+export const EDITION_LIMIT_MAX = 10_000;
+
+/** Typed failure so handlers can map a cause to a status code and a message. */
+export class PrintEditionError extends Error {
+ /**
+ * @param {string} code
+ * @param {string} message
+ * @param {Record<string, unknown>} [extra]
+ */
+ constructor(code, message, extra = {}) {
+ super(message);
+ this.name = 'PrintEditionError';
+ this.code = code;
+ Object.assign(this, extra);
+ }
+}
+
+/**
+ * The key a series of editions is numbered under.
+ * @param {{ creationId?: string|null, glbSha256?: string|null }} input
+ * @returns {string}
+ */
+export function seriesKeyFor({ creationId = null, glbSha256 = null }) {
+ if (creationId) return String(creationId);
+ if (glbSha256 && /^[0-9a-f]{64}$/.test(glbSha256)) return `sha256:${glbSha256}`;
+ throw new PrintEditionError(
+ 'series_key_underivable',
+ 'an edition series needs either a creation id or the printed asset hash',
+ );
+}
+
+/**
+ * Normalize a caller-supplied cap. Accepts null/'' (open edition) and refuses
+ * anything that is not a whole number inside the allowed band, so the column
+ * constraint is never the first thing a user hears about.
+ * @param {unknown} raw
+ * @returns {number|null}
+ */
+export function normalizeEditionLimit(raw) {
+ if (raw === null || raw === undefined || raw === '') return null;
+ const n = typeof raw === 'number' ? raw : Number(String(raw).trim());
+ if (!Number.isInteger(n)) {
+ throw new PrintEditionError('edition_limit_invalid', 'edition size must be a whole number');
+ }
+ if (n < EDITION_LIMIT_MIN || n > EDITION_LIMIT_MAX) {
+ throw new PrintEditionError(
+ 'edition_limit_out_of_range',
+ `edition size must be between ${EDITION_LIMIT_MIN} and ${EDITION_LIMIT_MAX}`,
+ );
+ }
+ return n;
+}
+
+/**
+ * How many certificates a series has already issued.
+ * @param {string} seriesKey
+ * @returns {Promise<number>}
+ */
+export async function issuedCount(seriesKey) {
+ const [row] = await sql`
+ select count(*)::int as n from print_certificates where series_key = ${seriesKey}
+ `;
+ return row?.n ?? 0;
+}
+
+/**
+ * The cap a creation currently declares, or null for an open edition.
+ * @param {string|null} creationId
+ * @returns {Promise<number|null>}
+ */
+export async function editionLimitFor(creationId) {
+ if (!creationId) return null;
+ const [row] = await sql`
+ select print_edition_limit from forge_creations where id = ${creationId} limit 1
+ `;
+ return row?.print_edition_limit ?? null;
+}
+
+/**
+ * Everything a surface needs to render scarcity: the cap, what is gone, and
+ * what is left. `limit: null` means open, and `remaining` is null with it.
+ * @param {{ creationId?: string|null, glbSha256?: string|null }} input
+ * @returns {Promise<{ seriesKey: string, limit: number|null, issued: number, remaining: number|null, soldOut: boolean }>}
+ */
+export async function editionState({ creationId = null, glbSha256 = null }) {
+ const seriesKey = seriesKeyFor({ creationId, glbSha256 });
+ const [limit, issued] = await Promise.all([editionLimitFor(creationId), issuedCount(seriesKey)]);
+ const remaining = limit === null ? null : Math.max(0, limit - issued);
+ return { seriesKey, limit, issued, remaining, soldOut: remaining !== null && remaining <= 0 };
+}
+
+/**
+ * The quote-time gate. Throws PrintEditionError('edition_sold_out') when the
+ * requested quantity cannot be served by what is left of the series.
+ *
+ * Deliberately runs against issued certificates rather than open orders: an
+ * order that never ships releases its slot, so a cancelled checkout can never
+ * strand the last copy of a 25-piece edition.
+ *
+ * @param {{ creationId?: string|null, glbSha256?: string|null, quantity?: number }} input
+ * @returns {Promise<{ seriesKey: string, limit: number|null, issued: number, remaining: number|null, soldOut: boolean }>}
+ */
+export async function assertEditionAvailable({ creationId = null, glbSha256 = null, quantity = 1 }) {
+ const qty = Number.isInteger(quantity) && quantity > 0 ? quantity : 1;
+ const state = await editionState({ creationId, glbSha256 });
+ if (state.limit === null) return state;
+ if (state.remaining !== null && state.remaining < qty) {
+ throw new PrintEditionError(
+ 'edition_sold_out',
+ state.remaining === 0
+ ? `This edition is sold out. All ${state.limit} copies have shipped.`
+ : `Only ${state.remaining} of this ${state.limit}-piece edition ${state.remaining === 1 ? 'is' : 'are'} left, so ${qty} cannot be ordered.`,
+ { limit: state.limit, issued: state.issued, remaining: state.remaining },
+ );
+ }
+ return state;
+}
+
+/**
+ * Set (or clear) a creation's edition cap. Owner-only: the caller must be the
+ * signed-in creator, or, for a model forged before sign-in existed on that
+ * browser, the browser that forged it.
+ *
+ * A cap below what already shipped is refused rather than silently clamped:
+ * shrinking a series under its own history would make an already-printed
+ * certificate read "edition 7 of 5".
+ *
+ * @param {{ creationId: string, userId?: string|null, clientKey?: string|null, limit: unknown }} input
+ */
+export async function setEditionLimit({ creationId, userId = null, clientKey = null, limit }) {
+ const value = normalizeEditionLimit(limit);
+ const [creation] = await sql`
+ select id, user_id, client_key, glb_url, status
+ from forge_creations where id = ${creationId} limit 1
+ `;
+ if (!creation) throw new PrintEditionError('creation_not_found', 'no such model');
+
+ const ownedByUser = Boolean(userId) && creation.user_id === userId;
+ const ownedByBrowser = !creation.user_id && Boolean(clientKey) && creation.client_key === clientKey;
+ if (!ownedByUser && !ownedByBrowser) {
+ throw new PrintEditionError('not_creation_owner', 'only the creator of this model can set its edition size');
+ }
+
+ const issued = await issuedCount(seriesKeyFor({ creationId }));
+ if (value !== null && value < issued) {
+ throw new PrintEditionError(
+ 'edition_limit_below_issued',
+ `${issued} ${issued === 1 ? 'copy has' : 'copies have'} already shipped, so the edition cannot be capped below ${issued}.`,
+ { issued },
+ );
+ }
+
+ await sql`update forge_creations set print_edition_limit = ${value}, updated_at = now() where id = ${creationId}`;
+ return editionState({ creationId });
+}
diff --git a/api/_lib/print/fulfillment.js b/api/_lib/print/fulfillment.js
new file mode 100644
index 000000000..1e4c71e7b
--- /dev/null
+++ b/api/_lib/print/fulfillment.js
@@ -0,0 +1,198 @@
+// @ts-check
+// Fulfillment orchestration: the one place adapter output meets the state
+// machine.
+//
+// Adapters speak; the store decides. Every path in here takes a normalized
+// adapter result and turns it into at most one transitionOrder() call, so the
+// rules about what may follow what live in print-store.js and nowhere else.
+//
+// The interesting case is a provider reporting something the machine refuses:
+// a partner announcing "shipped" for a job we already refunded, or a webhook
+// arriving out of order after a later one already landed. That is not an
+// exception to propagate to the provider (they would retry it forever) and not
+// something to silently drop (an operator needs to see it). It is recorded on
+// the timeline as a provider event with the refusal in its note, and the HTTP
+// caller gets a 200 that says `applied: false`.
+
+import { sql } from '../db.js';
+import {
+ PrintTransitionError,
+ appendOrderEvent,
+ getOrder,
+ transitionOrder,
+} from '../print-store.js';
+import {
+ normalizeCancelResult,
+ normalizeStatusResult,
+ normalizeSubmitResult,
+ adapterSupportsOrder,
+} from './adapters/contract.js';
+import { getAdapter, routeOrder } from './adapters/index.js';
+
+/**
+ * Hand a screened order to a fulfillment lane.
+ *
+ * @param {object} input
+ * @param {object} input.order the order row, status must be 'screening'
+ * @param {string} [input.adapterKey] force a lane; omit to route by capability
+ * @param {string} [input.actor] who asked (operator | system)
+ * @param {string|null} [input.actorId]
+ * @returns {Promise<{ order: object, adapter: string, providerOrderId: string }>}
+ */
+export async function submitOrder({ order, adapterKey = '', actor = 'operator', actorId = null }) {
+ const assets = order?.prepared_asset_urls || {};
+ let adapter;
+ if (adapterKey) {
+ adapter = getAdapter(adapterKey);
+ if (!adapter) throw new FulfillmentError('adapter_unavailable', `no configured adapter '${adapterKey}'`);
+ const verdict = adapterSupportsOrder(adapter, order);
+ if (!verdict.ok) throw new FulfillmentError('adapter_incapable', verdict.reason);
+ } else {
+ const routed = routeOrder(order);
+ if (!routed.adapter) {
+ const why = routed.declined.map((d) => `${d.key}: ${d.reason}`).join('; ') || 'no adapters are configured';
+ throw new FulfillmentError('no_route', `no fulfillment lane can run this order (${why})`);
+ }
+ adapter = routed.adapter;
+ }
+
+ const raw = await adapter.submit(order, assets);
+ const result = normalizeSubmitResult(adapter.key, raw);
+
+ const { order: updated } = await transitionOrder({
+ orderId: order.id,
+ to: result.status,
+ note: result.note || `Submitted to ${adapter.label}.`,
+ actor,
+ actorId,
+ patch: {
+ provider: adapter.key,
+ provider_order_id: result.providerOrderId,
+ provider_state: result.state,
+ lead_time_days: result.leadTimeDays || adapter.capabilities.leadTimeDays,
+ submitted_at: new Date().toISOString(),
+ stall_alerted_at: null,
+ },
+ });
+
+ return { order: updated, adapter: adapter.key, providerOrderId: result.providerOrderId };
+}
+
+/** A fulfillment routing/lane failure with a code a handler can map to HTTP. */
+export class FulfillmentError extends Error {
+ /** @param {string} code @param {string} message */
+ constructor(code, message) {
+ super(message);
+ this.name = 'FulfillmentError';
+ this.code = code;
+ }
+}
+
+/**
+ * Apply one provider-reported event (from a webhook or from a status poll) to
+ * an order. Idempotent by construction: an event that reports the status the
+ * order already has updates tracking and returns `applied: false`.
+ *
+ * @param {object} input
+ * @param {object} input.order
+ * @param {{ status: string|null, trackingNumber?: string, carrier?: string, note?: string, state?: object }} input.event
+ * @param {string} [input.actor] provider | system
+ * @returns {Promise<{ applied: boolean, order: object, reason: string }>}
+ */
+export async function applyProviderEvent({ order, event, actor = 'provider' }) {
+ const patch = {};
+ if (event.trackingNumber && event.trackingNumber !== order.tracking_number) patch.tracking_number = event.trackingNumber;
+ if (event.carrier && event.carrier !== order.carrier) patch.carrier = event.carrier;
+ if (event.state && Object.keys(event.state).length) patch.provider_state = event.state;
+
+ // No status, or the status we already hold: this is news about the job, not
+ // a move. Record what changed and stop.
+ if (!event.status || event.status === order.status) {
+ const changed = await patchOnly(order, patch);
+ if (event.note) {
+ await appendOrderEvent({
+ orderId: order.id,
+ status: order.status,
+ note: event.note,
+ actor,
+ });
+ }
+ return { applied: false, order: changed, reason: event.status ? 'already in that status' : 'no status change reported' };
+ }
+
+ try {
+ const { order: updated } = await transitionOrder({
+ orderId: order.id,
+ to: event.status,
+ note: event.note || `Provider reported ${event.status}.`,
+ actor,
+ patch,
+ });
+ return { applied: true, order: updated, reason: '' };
+ } catch (err) {
+ if (err instanceof PrintTransitionError) {
+ // Out-of-order or impossible: keep it on the timeline where an operator
+ // will see it, and tell the caller it was not applied.
+ await appendOrderEvent({
+ orderId: order.id,
+ status: order.status,
+ note: `Refused provider report '${event.status}': ${err.message}`,
+ actor,
+ });
+ const current = (await getOrder(order.id)) || order;
+ return { applied: false, order: current, reason: err.message };
+ }
+ throw err;
+ }
+}
+
+/**
+ * Write patched columns without a status change. Used when a provider reports
+ * a tracking number before (or after) the transition that carries it.
+ * @param {object} order
+ * @param {Record<string, unknown>} patch
+ */
+async function patchOnly(order, patch) {
+ if (!patch || Object.keys(patch).length === 0) return order;
+ // transitionOrder is the only writer of `status`; a no-op self transition is
+ // not legal, so patch-only writes go through a dedicated statement here. It
+ // touches no lifecycle column, which is why it does not need the machine.
+ const rows = await sql`
+ update print_orders set
+ tracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),
+ carrier = coalesce(${patch.carrier ?? null}, carrier),
+ provider_state = coalesce(${patch.provider_state ? JSON.stringify(patch.provider_state) : null}::jsonb, provider_state)
+ where id = ${order.id}
+ returning *`;
+ return rows[0] || order;
+}
+
+/**
+ * Poll a lane for one order and apply whatever it says.
+ * @param {object} order
+ * @returns {Promise<{ applied: boolean, order: object, reason: string, polled: boolean }>}
+ */
+export async function reconcileOrder(order) {
+ const adapter = getAdapter(order.provider);
+ if (!adapter) {
+ return { applied: false, order, reason: `adapter '${order.provider}' is not configured here`, polled: false };
+ }
+ const raw = await adapter.status(order.provider_order_id);
+ const event = normalizeStatusResult(adapter.key, raw);
+ const result = await applyProviderEvent({ order, event, actor: 'provider' });
+ return { ...result, polled: true };
+}
+
+/**
+ * Ask the lane to stop. The order's own move to `canceled` is the caller's, so
+ * a provider that refuses cannot leave us claiming a cancellation we did not
+ * get.
+ * @param {object} order
+ * @param {string} [reason]
+ */
+export async function cancelWithProvider(order, reason = '') {
+ const adapter = getAdapter(order.provider);
+ if (!adapter) return { ok: false, note: `adapter '${order.provider || 'none'}' is not configured here`, state: {} };
+ const raw = await adapter.cancel(order, reason);
+ return normalizeCancelResult(adapter.key, raw);
+}
diff --git a/api/_lib/print/manifold.js b/api/_lib/print/manifold.js
deleted file mode 100644
index 82ca1caea..000000000
--- a/api/_lib/print/manifold.js
+++ /dev/null
@@ -1,124 +0,0 @@
-// The Manifold kernel, wrapped for this pipeline.
-//
-// Manifold (github.com/elalish/manifold, Apache-2.0) is the geometry kernel
-// behind manifoldCAD and OpenSCAD's fast backend: exact boolean operations on
-// solids, guaranteed manifold output, and a volume that is a real volume rather
-// than an estimate. It ships here as plain WebAssembly with no native binding,
-// which is exactly why it was chosen over a CGAL binding: the API container is
-// node-only, and a build that needs a compiler is a build that breaks.
-//
-// The kernel is instantiated once per process and reused. Instantiation is a
-// few tens of milliseconds and the module is stateless between calls, so a warm
-// Cloud Run instance pays it once.
-//
-// Memory discipline: Manifold objects live in WASM memory and are NOT
-// garbage-collected by JavaScript. Every function here that creates one either
-// deletes it before returning or hands ownership to the caller and says so in
-// its doc comment. Leaking them leaks the whole heap of a long-lived instance.
-
-let modulePromise = null;
-
-/** The Manifold toplevel (Manifold, Mesh, CrossSection, triangulate). */
-export async function getKernel() {
- if (!modulePromise) {
- modulePromise = (async () => {
- const factory = (await import('manifold-3d')).default;
- const wasm = await factory();
- wasm.setup();
- return wasm;
- })();
- }
- return modulePromise;
-}
-
-/**
- * Wrap an indexed triangle soup as a Manifold Mesh and merge coincident
- * vertices. `merge()` is the kernel's own crack-closer: it links vertices that
- * share a position but were split by a UV or normal seam, which is the single
- * most common reason an otherwise closed AI-generated mesh reads as full of
- * holes. The Mesh is a plain JS object; nothing needs deleting.
- */
-export async function toKernelMesh(positions, indices) {
- const { Mesh } = await getKernel();
- const verts = new Float32Array(positions.length);
- for (let i = 0; i < positions.length; i += 1) verts[i] = positions[i];
- const mesh = new Mesh({
- numProp: 3,
- vertProperties: verts,
- triVerts: indices instanceof Uint32Array ? indices : Uint32Array.from(indices),
- });
- const merged = mesh.merge();
- return { mesh, merged };
-}
-
-/**
- * Read a solid back out as an indexed soup. The caller owns the returned
- * arrays; the Manifold is untouched.
- */
-export function fromSolid(solid) {
- const mesh = solid.getMesh();
- const stride = mesh.numProp;
- const vertexCount = mesh.vertProperties.length / stride;
- const positions = new Float64Array(vertexCount * 3);
- for (let v = 0; v < vertexCount; v += 1) {
- positions[v * 3] = mesh.vertProperties[v * stride];
- positions[v * 3 + 1] = mesh.vertProperties[v * stride + 1];
- positions[v * 3 + 2] = mesh.vertProperties[v * stride + 2];
- }
- return { positions, indices: Uint32Array.from(mesh.triVerts) };
-}
-
-/**
- * Try to read a soup as a solid. Returns the Manifold on success (the caller
- * MUST delete it) or null when the kernel refuses the topology, which is not an
- * error: it is the signal that the mesh needs repair first.
- */
-export async function trySolid(positions, indices) {
- const { Manifold } = await getKernel();
- const { mesh, merged } = await toKernelMesh(positions, indices);
- let solid = null;
- try {
- solid = Manifold.ofMesh(mesh);
- } catch {
- return { solid: null, merged, status: 'NotManifold' };
- }
- const status = solid.status();
- if (status !== 'NoError') {
- solid.delete();
- return { solid: null, merged, status };
- }
- return { solid, merged, status };
-}
-
-/**
- * Union a solid with itself through decompose: separating the disjoint pieces
- * and unioning them back resolves overlapping shells and self-intersections
- * into one clean boundary. Consumes `solid` and returns a new one the caller
- * owns. A kernel failure returns the original rather than losing the geometry.
- */
-export async function unionShells(solid) {
- const { Manifold } = await getKernel();
- let parts = [];
- try {
- parts = solid.decompose();
- } catch {
- return solid;
- }
- if (parts.length <= 1) {
- for (const p of parts) p.delete();
- return solid;
- }
- try {
- const merged = Manifold.union(parts);
- if (merged.status() !== 'NoError') {
- merged.delete();
- return solid;
- }
- solid.delete();
- return merged;
- } catch {
- return solid;
- } finally {
- for (const p of parts) p.delete();
- }
-}
diff --git a/api/_lib/print/ops-auth.js b/api/_lib/print/ops-auth.js
new file mode 100644
index 000000000..0da9c2b03
--- /dev/null
+++ b/api/_lib/print/ops-auth.js
@@ -0,0 +1,121 @@
+// @ts-check
+// The authorization gate for the Materialize operator console.
+//
+// Why this is not api/_lib/ops-auth.js: that gate is deliberately OPEN in
+// development when no OPS_SECRET is configured, which is correct for a
+// read-only health board on a developer's laptop. These endpoints are not that.
+// They read shipping addresses (the first real PII this platform stores), they
+// move orders through a state machine, and they mark refunds. So this gate
+// FAILS CLOSED everywhere, dev included: no credential, no access.
+//
+// Three doors, strongest first:
+//
+// 1. A signed-in platform admin. The requireAdmin model (wallet in
+// ADMIN_ADDRESSES, the built-in owner address, or is_admin in the DB).
+// Carries a real user id, which is what makes an operator transition
+// attributable on the timeline.
+// 2. A signed-in user on the operator allowlist: PRINT_OPERATORS, a comma
+// separated list of user ids or wallet addresses. This exists so
+// fulfillment can be staffed without handing out platform admin, which is
+// a much larger privilege than "may mark a job shipped".
+// 3. `x-ops-secret` (or Authorization: Bearer) matching OPS_SECRET, the same
+// dedicated ops credential the health boards use and deliberately never
+// CRON_SECRET. This door has no user identity, so its actions land on the
+// timeline as `ops-secret` rather than as a person: use it for scripts,
+// not for daily operations.
+//
+// The page is never the boundary. Every endpoint calls requireOperator().
+
+import { constantTimeEquals } from '../crypto.js';
+import { getSessionUser } from '../auth.js';
+import { isAdminUser } from '../admin.js';
+import { error } from '../http.js';
+
+/** Entries of PRINT_OPERATORS, trimmed. User ids or wallet addresses. */
+function operatorAllowlist() {
+ return (process.env.PRINT_OPERATORS || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+// Wallet addresses are compared case-insensitively for EVM hex (checksum casing
+// varies per wallet and identifies the same account) and literally otherwise,
+// because Solana base58 IS case sensitive and folding it widens the match.
+const EVM_ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
+
+/** @param {string} entry @param {string} candidate */
+function identityMatches(entry, candidate) {
+ if (!entry || !candidate) return false;
+ if (EVM_ADDRESS_RE.test(entry) && EVM_ADDRESS_RE.test(candidate)) {
+ return entry.toLowerCase() === candidate.toLowerCase();
+ }
+ return entry === candidate;
+}
+
+/**
+ * True when this signed-in user is a fulfillment operator by allowlist.
+ * @param {{ id?: string, wallet_address?: string }} user
+ */
+export function isAllowlistedOperator(user) {
+ if (!user) return false;
+ const list = operatorAllowlist();
+ if (list.length === 0) return false;
+ return list.some((entry) => identityMatches(entry, String(user.id || '')) || identityMatches(entry, String(user.wallet_address || '')));
+}
+
+/**
+ * Resolve the operator decision without writing a response.
+ * @param {{ headers?: Record<string, string|undefined> }} req
+ * @returns {Promise<{ ok: boolean, actor: string, actorId: string|null, via: string }>}
+ */
+export async function authorizeOperator(req) {
+ try {
+ const user = await getSessionUser(req);
+ if (user) {
+ if (await isAdminUser(user)) {
+ return { ok: true, actor: user.wallet_address || `user:${user.id}`, actorId: user.id, via: 'admin' };
+ }
+ if (isAllowlistedOperator(user)) {
+ return { ok: true, actor: user.wallet_address || `user:${user.id}`, actorId: user.id, via: 'allowlist' };
+ }
+ }
+ } catch {
+ /* no or invalid session — fall through to the secret door */
+ }
+
+ const secret = process.env.OPS_SECRET;
+ if (secret) {
+ const auth = req.headers?.['authorization'];
+ const presented =
+ req.headers?.['x-ops-secret'] ||
+ (typeof auth === 'string' ? auth.replace(/^Bearer\s+/i, '') : '');
+ if (presented && constantTimeEquals(String(presented), secret)) {
+ return { ok: true, actor: 'ops-secret', actorId: null, via: 'ops-secret' };
+ }
+ }
+
+ // Fails closed, including in development. Fulfillment reads PII.
+ return { ok: false, actor: '', actorId: null, via: '' };
+}
+
+/**
+ * The call every operator endpoint starts with. Writes the 401/403 itself and
+ * returns null, so a handler that forgets to check the return value cannot
+ * accidentally serve data: it will throw on the null instead.
+ *
+ * @param {any} req
+ * @param {any} res
+ * @returns {Promise<{ actor: string, actorId: string|null, via: string }|null>}
+ */
+export async function requireOperator(req, res) {
+ const verdict = await authorizeOperator(req);
+ if (verdict.ok) return { actor: verdict.actor, actorId: verdict.actorId, via: verdict.via };
+ error(
+ res,
+ 403,
+ 'forbidden',
+ 'fulfillment operator access required: sign in as a platform admin or an allowlisted operator',
+ );
+ return null;
+}
diff --git a/api/_lib/print/repair.js b/api/_lib/print/repair.js
index faab644d2..f326db858 100644
--- a/api/_lib/print/repair.js
+++ b/api/_lib/print/repair.js
@@ -1,318 +1,419 @@
-// Turning a generated mesh into a solid a printer will accept.
+// Turn a triangle soup into a solid a printer can fill, then put it at the size
+// and wall thickness the buyer paid for.
//
-// The order of operations is the whole design. Cheap topology first, because it
-// fixes the failures forge output actually has (UV seams read as holes, mirrored
-// duplicate shells, patches wound backwards, an open bottom where the generator
-// never closed the base), and it preserves the artist's triangles exactly. Only
-// when that is not enough does the voxel reconstruction run, which always
-// produces a manifold but resamples the surface and therefore softens detail.
+// The pipeline has a strict order because each stage removes a class of defect
+// the next one cannot survive:
//
-// Every stage records before/after metrics. A repair the buyer cannot see is a
-// repair the buyer cannot trust, and the /materialize page renders these numbers
-// as the "what changed" list next to the model.
-
-import Module from 'manifold-3d';
+// 1. weld seams split by UV/normal authoring read as holes
+// 2. de-degenerate a zero-area face is a hole the reconstruction cannot close
+// 3. orient a mirrored face inverts "inside" for half the shell
+// 4. fill holes a centroid fan closes every boundary loop
+// 5. reconstruct Manifold takes each closed shell, union merges them
+// 6. offset shell the fallback when a shell is still not 2-manifold
+//
+// Stage 6 exists because "we could not fix it" is not an answer a buyer can
+// act on. When a shell has non-manifold junctions that filling cannot resolve
+// (self-touching hair, a fan of coincident faces, a Klein-bottle artefact of
+// generation), the surface is rebuilt from its distance field as a closed shell
+// at a bounded voxel resolution. It costs fidelity and says so in the metrics;
+// it never fails.
+//
+// Every stage returns before/after numbers so the surface can show the buyer
+// exactly what the platform changed about their model before they pay for it.
-import { boundsOf, weldPositions } from './mesh-io.js';
+import { weldPositions, boundsOf } from './mesh-io.js';
import {
- boundaryLoops,
- connectedComponents,
- dropDegenerateTriangles,
- edgeCensus,
- orientConsistently,
+ dropDegenerate,
+ edgeTopology,
+ connectedShells,
+ orientShell,
+ fillHoles,
+ extractShell,
signedVolume,
- surfaceArea,
+ triangleArea,
} from './topology.js';
-import { buildSignedDistance, extractLevelSet } from './voxel-sdf.js';
+import { makeSignedDistance, makeUnsignedDistance } from './sampling.js';
+
+// glTF is metres by the spec; every print number a human reads is millimetres.
+export const MM_PER_UNIT = 1000;
+
+// Voxel budget for the level-set stages. 250k samples is roughly 2.5 s of BVH
+// closest-point work on this runtime, which keeps a fallback repair inside a
+// request while still resolving features around 1/60th of the model's height.
+const LEVEL_SET_SAMPLES = 250_000;
-// Weld tolerance as a fraction of the bounding-box diagonal. Loose enough to
-// merge the duplicated vertices a UV seam creates, tight enough to leave two
-// genuinely distinct surfaces a hair apart alone.
-const WELD_FRACTION = 1e-5;
+// A shell smaller than this fraction of the largest shell's triangle count is
+// generation debris (a stray quad, an orphaned eyelash) and is dropped rather
+// than unioned, which keeps the solid's bounding box honest.
+const DEBRIS_SHELL_RATIO = 0.0005;
-let wasmPromise = null;
+let modulePromise = null;
/**
- * The Manifold WASM module, initialized once per process. It is plain
- * WebAssembly with no native binding, which is why it runs in the API container
- * at all; the same single-instance pattern the Draco decoders use.
+ * One initialised Manifold WASM module per process. The library ships plain
+ * WASM with no native binding, so it loads in the API container exactly as it
+ * does locally; the async setup is memoised because instantiating the module
+ * per request would dominate the cost of a small mesh.
*/
-export async function getManifold() {
- if (!wasmPromise) {
- wasmPromise = (async () => {
- const wasm = await Module();
+export async function manifoldModule() {
+ if (!modulePromise) {
+ modulePromise = (async () => {
+ const mod = await import('manifold-3d');
+ const factory = mod.default ?? mod;
+ const wasm = await factory();
wasm.setup();
return wasm;
- })().catch((err) => {
- wasmPromise = null;
- throw err;
- });
+ })();
}
- return wasmPromise;
+ return modulePromise;
}
-/** Flat arrays out of a Manifold solid, in the representation everything else here speaks. */
-export function solidToArrays(solid) {
- const mesh = solid.getMesh();
- const stride = mesh.numProp;
- const count = mesh.vertProperties.length / stride;
- const positions = new Float64Array(count * 3);
- for (let i = 0; i < count; i += 1) {
- positions[i * 3] = mesh.vertProperties[i * stride];
- positions[i * 3 + 1] = mesh.vertProperties[i * stride + 1];
- positions[i * 3 + 2] = mesh.vertProperties[i * stride + 2];
+export class RepairError extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'RepairError';
+ this.code = code;
}
- return { positions, indices: Uint32Array.from(mesh.triVerts) };
}
-/**
- * Hand a triangle soup to Manifold. Returns null rather than throwing when the
- * soup is not a closed, non-self-intersecting 2-manifold, because "not yet a
- * solid" is the normal case this pipeline exists to fix, not an error.
- */
-export function toSolid(wasm, positions, indices) {
- try {
- const mesh = new wasm.Mesh({
- numProp: 3,
- vertProperties: Float32Array.from(positions),
- triVerts: Uint32Array.from(indices),
- });
- const solid = wasm.Manifold.ofMesh(mesh);
- if (solid.status() !== 'NoError' || solid.isEmpty()) return null;
- return solid;
- } catch {
- return null;
- }
+function toManifoldMesh(wasm, positions, indices) {
+ return new wasm.Mesh({
+ numProp: 3,
+ vertProperties: Float32Array.from(positions),
+ triVerts: Uint32Array.from(indices),
+ });
}
/**
- * Fan-fill every boundary loop. Each hole gets one new vertex at the loop's
- * centroid and a triangle per rim edge, wound opposite to the rim so the patch
- * agrees with the surface it closes.
+ * Rebuild a closed surface from the distance field of an arbitrary soup.
*
- * A centroid fan is the right tool here specifically because these holes are
- * generator artifacts (a flat open base, a missing cap) rather than designed
- * openings; it is stable, needs no projection plane, and never produces a
- * self-intersecting patch on a convex rim.
+ * `level` is what makes it work on open geometry: sampling the UNSIGNED
+ * distance and extracting the surface at a small positive level produces the
+ * offset shell around whatever was there, so a single open plane becomes a thin
+ * closed slab rather than nothing. On geometry that is already closed the
+ * signed field is used instead, which reproduces the original surface without
+ * the offset's thickening.
*/
-export function fillBoundaryLoops(positions, indices) {
- const loops = boundaryLoops(indices);
- if (!loops.length) return { positions, indices, filled: 0, addedTriangles: 0 };
- const pos = Array.from(positions);
- const tris = Array.from(indices);
- let addedTriangles = 0;
- for (const loop of loops) {
- if (loop.length === 3) {
- tris.push(loop[2], loop[1], loop[0]);
- addedTriangles += 1;
- continue;
- }
- let cx = 0, cy = 0, cz = 0;
- for (const v of loop) {
- cx += positions[v * 3];
- cy += positions[v * 3 + 1];
- cz += positions[v * 3 + 2];
- }
- const center = pos.length / 3;
- pos.push(cx / loop.length, cy / loop.length, cz / loop.length);
- for (let i = 0; i < loop.length; i += 1) {
- const u = loop[i];
- const v = loop[(i + 1) % loop.length];
- tris.push(v, u, center);
- addedTriangles += 1;
- }
- }
- return {
- positions: Float64Array.from(pos),
- indices: Uint32Array.from(tris),
- filled: loops.length,
- addedTriangles,
- };
+function levelSetSolid(wasm, positions, indices, { closed, bounds, offset }) {
+ const sample = closed
+ ? makeSignedDistance(positions, indices)
+ : makeUnsignedDistance(positions, indices);
+ const pad = offset * 3;
+ const min = [bounds.min[0] - pad, bounds.min[1] - pad, bounds.min[2] - pad];
+ const max = [bounds.max[0] + pad, bounds.max[1] + pad, bounds.max[2] + pad];
+ const span = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];
+ const volume = Math.max(span[0] * span[1] * span[2], Number.MIN_VALUE);
+ // Solve for the edge length that spends the sample budget on this box.
+ let edge = Math.cbrt(volume / LEVEL_SET_SAMPLES);
+ edge = Math.min(edge, Math.max(span[0], span[1], span[2]) / 8);
+ // Manifold's level set takes the field as "positive inside", so an unsigned
+ // distance is negated and shifted by the offset to give the shell.
+ const field = closed
+ ? (p) => -sample(p[0], p[1], p[2])
+ : (p) => offset - sample(p[0], p[1], p[2]);
+ const solid = wasm.Manifold.levelSet(field, { min, max }, edge, 0);
+ return { solid, edge, offset: closed ? 0 : offset };
}
/**
- * The cheap repair: weld, drop what cannot hold volume, agree on a winding,
- * close the holes, and make the whole thing point outward. Pure topology, no
- * resampling, so the surface a buyer approved is the surface that prints.
+ * Reconstruct a printable solid from a loaded mesh.
+ *
+ * Returns the Manifold solid plus a metrics record describing every change
+ * made. The caller owns the solid and must delete() it; every intermediate is
+ * released here.
+ *
+ * @param {{positions: Float64Array, indices: Uint32Array}} mesh
+ * @param {{weldTolerance?: number, fillHoles?: boolean}} [opts]
*/
-export function cleanTopology(mesh, opts = {}) {
- const bounds = boundsOf(mesh.positions);
- const tolerance = opts.weldTolerance ?? Math.max((bounds?.diagonal ?? 1) * WELD_FRACTION, Number.EPSILON);
+export async function reconstruct(mesh, opts = {}) {
+ const wasm = await manifoldModule();
+ const sourceBounds = boundsOf(mesh.positions);
+ if (!sourceBounds || !(sourceBounds.diagonal > 0)) {
+ throw new RepairError('degenerate_input', 'model has no measurable extent');
+ }
+ // Weld tolerance scales with the model so it behaves the same whether the
+ // asset was authored in metres, centimetres or arbitrary units.
+ const tolerance = opts.weldTolerance ?? sourceBounds.diagonal * 1e-6;
const welded = weldPositions(mesh.positions, mesh.indices, tolerance);
- const cleaned = dropDegenerateTriangles(welded.positions, welded.indices, {
- minArea: (tolerance * tolerance) / 2,
- });
- const oriented = orientConsistently(cleaned.indices);
- const before = edgeCensus(oriented.indices);
- const filled = fillBoundaryLoops(welded.positions, oriented.indices);
- const after = edgeCensus(filled.indices);
+ const areaEpsilon = (sourceBounds.diagonal * 1e-7) ** 2;
+ const cleaned = dropDegenerate(welded.positions, welded.indices, areaEpsilon);
- // Winding is only consistent per component after orientConsistently; a
- // negative total signed volume means the biggest shell points inward.
- let indices = filled.indices;
- let volume = signedVolume(filled.positions, indices);
- let flippedAll = false;
- if (volume < 0) {
- const flipped = Uint32Array.from(indices);
- for (let i = 0; i + 2 < flipped.length; i += 3) {
- const b = flipped[i + 1];
- flipped[i + 1] = flipped[i + 2];
- flipped[i + 2] = b;
+ const metrics = {
+ method: null,
+ tolerance,
+ welded_vertices: mesh.positions.length / 3 - welded.positions.length / 3,
+ degenerate_removed: cleaned.removed,
+ shells_in: 0,
+ shells_used: 0,
+ shells_dropped: 0,
+ holes_filled: 0,
+ patch_triangles: 0,
+ unclosed_loops: 0,
+ faces_reoriented: 0,
+ level_set_shells: 0,
+ level_set_edge_mm: null,
+ triangles_in: mesh.indices.length / 3,
+ triangles_out: 0,
+ };
+
+ if (cleaned.indices.length < 12) {
+ throw new RepairError('degenerate_input', 'model has no triangles left after cleanup');
+ }
+
+ const topology = edgeTopology(cleaned.indices);
+ const shells = connectedShells(cleaned.indices, topology.edges);
+ metrics.shells_in = shells.length;
+ const largest = shells[0]?.length ?? 0;
+
+ const solids = [];
+ for (const tris of shells) {
+ if (tris.length < largest * DEBRIS_SHELL_RATIO || tris.length < 4) {
+ metrics.shells_dropped += 1;
+ continue;
+ }
+ const oriented = orientShell(welded.positions, cleaned.indices, tris);
+ metrics.faces_reoriented += oriented.flipped;
+ let shell = extractShell(welded.positions, oriented.indices);
+ if (opts.fillHoles !== false) {
+ const filled = fillHoles(shell.positions, shell.indices);
+ metrics.holes_filled += filled.filled;
+ metrics.patch_triangles += filled.addedTriangles;
+ metrics.unclosed_loops += filled.unclosedLoops;
+ shell = { positions: filled.positions, indices: filled.indices };
+ }
+ let solid = null;
+ try {
+ const mm = toManifoldMesh(wasm, shell.positions, shell.indices);
+ mm.merge();
+ solid = wasm.Manifold.ofMesh(mm);
+ if (solid.status() !== 0 || solid.isEmpty()) {
+ solid.delete();
+ solid = null;
+ }
+ } catch {
+ solid = null;
+ }
+ if (!solid) {
+ // Still not 2-manifold after filling: rebuild it from its distance
+ // field. Never a failure path, only a lower-fidelity one.
+ const shellBounds = boundsOf(shell.positions);
+ const closed = signedVolume(shell.positions, shell.indices) !== 0 && edgeTopology(shell.indices).openEdges === 0;
+ const offset = shellBounds.diagonal * 0.004;
+ const built = levelSetSolid(wasm, shell.positions, shell.indices, {
+ closed,
+ bounds: shellBounds,
+ offset,
+ });
+ metrics.level_set_shells += 1;
+ metrics.level_set_edge_mm = Math.max(
+ metrics.level_set_edge_mm ?? 0,
+ built.edge * MM_PER_UNIT,
+ );
+ solid = built.solid;
+ if (solid.isEmpty()) {
+ solid.delete();
+ metrics.shells_dropped += 1;
+ continue;
+ }
}
- indices = flipped;
- volume = -volume;
- flippedAll = true;
+ solids.push(solid);
+ metrics.shells_used += 1;
}
- return {
- positions: filled.positions,
- indices,
- metrics: {
- weldTolerance: tolerance,
- mergedVertices: mesh.positions.length / 3 - welded.positions.length / 3,
- degenerateRemoved: cleaned.degenerate,
- duplicateRemoved: cleaned.duplicate,
- trianglesFlipped: oriented.flipped,
- shellReversed: flippedAll,
- holesFilled: filled.filled,
- patchTriangles: filled.addedTriangles,
- openEdgesBefore: before.open,
- openEdgesAfter: after.open,
- nonManifoldEdgesAfter: after.nonManifold,
- signedVolume: volume,
- },
- };
+ if (solids.length === 0) {
+ throw new RepairError('unrepairable', 'no shell of this model could be closed into a solid');
+ }
+
+ // Union rather than compose: two shells that overlap in space are one object
+ // to a printer, and the boolean is what removes the internal wall between
+ // them. A single shell skips the boolean entirely.
+ let solid = solids[0];
+ if (solids.length > 1) {
+ solid = wasm.Manifold.union(solids);
+ for (const s of solids) s.delete();
+ }
+ metrics.method = metrics.level_set_shells > 0 ? 'level_set' : 'manifold_union';
+ metrics.triangles_out = solid.numTri();
+ return { solid, metrics, wasm };
}
/**
- * Uniform scale about the mesh's own centre, then a translation that puts the
- * base on z=0 of nothing in particular; callers that need a print bed origin
- * do that in the exporter, where the up-axis convention belongs.
+ * Uniformly scale a solid so its Y extent (glTF is Y-up) matches the requested
+ * print height. Returns the new solid and the scale that was applied; the
+ * caller keeps the factor because every wall-thickness number measured before
+ * the scale must be multiplied by it.
*/
-export function scaleMesh(positions, factor) {
- const out = new Float64Array(positions.length);
- for (let i = 0; i < positions.length; i += 1) out[i] = positions[i] * factor;
- return out;
+export function scaleToHeight(wasm, solid, targetHeightMm) {
+ const box = solid.boundingBox();
+ const heightUnits = box.max[1] - box.min[1];
+ if (!(heightUnits > 0)) {
+ throw new RepairError('degenerate_input', 'model has zero height and cannot be scaled');
+ }
+ const factor = targetHeightMm / (heightUnits * MM_PER_UNIT);
+ const scaled = solid.scale([factor, factor, factor]);
+ return { solid: scaled, factor };
}
/**
- * Full repair. Returns a solid whenever one can be produced, plus the metrics
- * describing how it was reached and which path ran.
+ * Hollow a solid into a shell of `wallMm`, with drain holes.
+ *
+ * Resin is sold by volume, so hollowing a 150 mm figurine typically removes 80%
+ * of its material cost. It is only safe when the wall survives the erosion
+ * everywhere, so the caller passes the measured minimum wall and this refuses
+ * (with a reason, never silently) when the model is already thinner than twice
+ * the requested wall.
*
- * `strategy` is reported, never guessed at by the caller:
- * 'already-solid' the input was already a closed manifold
- * 'topology' welding, hole filling and re-winding were enough
- * 'reconstructed' the voxel level set had to rebuild the surface
+ * Drain holes are mandatory, not optional: a sealed resin shell traps uncured
+ * liquid, which is both a print failure and a chemical hazard in the box. Two
+ * holes are cut on the underside so the cavity can vent as it drains.
*/
-export async function repairMesh(mesh, opts = {}) {
- const wasm = opts.wasm || (await getManifold());
- const started = Date.now();
- const cleaned = cleanTopology(mesh, opts);
+export function hollowSolid(wasm, solid, { wallMm, minWallMm, drainHoleMm = 3.5 }) {
+ const box = solid.boundingBox();
+ const size = [box.max[0] - box.min[0], box.max[1] - box.min[1], box.max[2] - box.min[2]];
+ const sizeMm = size.map((v) => v * MM_PER_UNIT);
+ const reason = (code, message) => ({ solid: null, applied: false, code, message });
- let solid = toSolid(wasm, cleaned.positions, cleaned.indices);
- let strategy = solid ? (cleaned.metrics.holesFilled === 0 && cleaned.metrics.degenerateRemoved === 0 ? 'already-solid' : 'topology') : null;
- let reconstruction = null;
+ if (!(wallMm > 0)) return reason('invalid_wall', 'hollow wall thickness must be positive');
+ if (Math.min(...sizeMm) < wallMm * 6) {
+ return reason(
+ 'too_small',
+ `model is ${Math.min(...sizeMm).toFixed(1)} mm across its thinnest axis, too small to hollow at a ${wallMm} mm wall`,
+ );
+ }
+ if (Number.isFinite(minWallMm) && minWallMm > 0 && minWallMm < wallMm * 2) {
+ return reason(
+ 'too_thin',
+ `thinnest wall is ${minWallMm.toFixed(2)} mm, so a ${wallMm} mm hollow would break through it`,
+ );
+ }
- if (!solid) {
- // Topology could not save it: overlapping shells, edges shared by three
- // faces, or holes whose rims do not close. Resample instead. This always
- // produces a printable solid, at the cost of the original triangulation.
- const field = buildSignedDistance(cleaned.positions, cleaned.indices, {
- maxCells: opts.maxGridCells,
- });
- const extracted = extractLevelSet(wasm, field, { maxSamples: opts.maxSamples });
- if (extracted.solid.isEmpty()) {
- throw new Error('mesh could not be reconstructed into a printable solid');
+ const wallUnits = wallMm / MM_PER_UNIT;
+ const mesh = solid.getMesh();
+ const positions = Float64Array.from(mesh.vertProperties);
+ const indices = Uint32Array.from(mesh.triVerts);
+ // Strip the extra properties Manifold may carry per vertex: the distance
+ // field only reads positions.
+ const stride = mesh.numProp;
+ let plain = positions;
+ if (stride !== 3) {
+ plain = new Float64Array((positions.length / stride) * 3);
+ for (let i = 0, o = 0; i < positions.length; i += stride, o += 3) {
+ plain[o] = positions[i];
+ plain[o + 1] = positions[i + 1];
+ plain[o + 2] = positions[i + 2];
}
- solid = extracted.solid;
- strategy = 'reconstructed';
- reconstruction = { gridDims: field.dims, edgeLength: extracted.edgeLength };
}
- const arrays = solidToArrays(solid);
- const components = connectedComponents(arrays.indices);
+ const sample = makeSignedDistance(plain, indices);
+ const min = [box.min[0], box.min[1], box.min[2]];
+ const max = [box.max[0], box.max[1], box.max[2]];
+ const volume = Math.max(size[0] * size[1] * size[2], Number.MIN_VALUE);
+ let edge = Math.cbrt(volume / LEVEL_SET_SAMPLES);
+ // The cavity wall must be resolvable by the grid or the erosion tears.
+ edge = Math.min(edge, wallUnits / 1.5);
+ const core = wasm.Manifold.levelSet(
+ (p) => -(sample(p[0], p[1], p[2]) + wallUnits),
+ { min, max },
+ edge,
+ 0,
+ );
+ if (core.isEmpty()) {
+ core.delete();
+ return reason('no_cavity', `a ${wallMm} mm wall leaves no cavity to remove in this model`);
+ }
+
+ // Two drains through the base: a single hole airlocks and will not drain.
+ const holeRadius = drainHoleMm / 2 / MM_PER_UNIT;
+ const holeDepth = size[1] * 0.5;
+ const offsets = [
+ [box.min[0] + size[0] * 0.3, box.min[2] + size[2] * 0.5],
+ [box.min[0] + size[0] * 0.7, box.min[2] + size[2] * 0.5],
+ ];
+ const drains = offsets.map(([x, z]) => {
+ const cyl = wasm.Manifold.cylinder(holeDepth, holeRadius, holeRadius, 24, false);
+ return cyl.translate([x, box.min[1] - holeDepth * 0.05, z]);
+ });
+ const cavity = wasm.Manifold.union([core, ...drains]);
+ const shell = solid.subtract(cavity);
+ const solidVolume = solid.volume();
+ const shellVolume = shell.volume();
+ core.delete();
+ for (const d of drains) d.delete();
+ cavity.delete();
+
+ if (!(shellVolume > 0) || shell.isEmpty()) {
+ shell.delete();
+ return reason('hollow_failed', 'hollowing produced no printable shell');
+ }
return {
- wasm,
- solid,
- positions: arrays.positions,
- indices: arrays.indices,
- strategy,
- metrics: {
- ...cleaned.metrics,
- strategy,
- reconstruction,
- trianglesBefore: mesh.indices.length / 3,
- trianglesAfter: arrays.indices.length / 3,
- shells: components.count,
- volume: solid.volume(),
- surfaceArea: solid.surfaceArea(),
- genus: solid.genus(),
- elapsedMs: Date.now() - started,
- },
+ solid: shell,
+ applied: true,
+ wall_mm: wallMm,
+ drain_holes: drains.length,
+ drain_hole_mm: drainHoleMm,
+ volume_saved_ratio: solidVolume > 0 ? 1 - shellVolume / solidVolume : 0,
+ voxel_mm: edge * MM_PER_UNIT,
};
}
/**
- * Hollow a solid to a wall thickness, with drain holes.
- *
- * Resin is sold by volume, so a hollow print of a 10 cm figure can cost a third
- * of the solid one. The erosion is a level-set offset of the solid's own
- * distance field; the two drain holes are mandatory, not decorative, because a
- * sealed resin shell traps uncured liquid and can burst under the vat's suction.
- *
- * Returns `{ solid, hollowed: false, reason }` rather than throwing when the
- * geometry cannot take it: a thin ornament with no interior to remove is
- * printed solid, and the buyer is quoted for a solid.
+ * Reduce a solid to a triangle budget. Manifold's own simplify is tolerance
+ * based, so the tolerance is searched (a handful of doublings) until the mesh
+ * fits, which keeps the geometric error the smallest one that meets the budget
+ * rather than an arbitrary constant.
*/
-export function hollowSolid(wasm, solid, { wallThickness, drainRadius, maxSamples } = {}) {
- if (!(wallThickness > 0)) return { solid, hollowed: false, reason: 'no-wall-thickness' };
- const arrays = solidToArrays(solid);
- const bounds = boundsOf(arrays.positions);
- if (!bounds) return { solid, hollowed: false, reason: 'empty' };
- // Nothing to gain when the wall is most of the object.
- if (wallThickness * 6 > bounds.longest) {
- return { solid, hollowed: false, reason: 'too-small-to-hollow' };
- }
-
- const field = buildSignedDistance(arrays.positions, arrays.indices);
- const eroded = extractLevelSet(wasm, field, { level: wallThickness, maxSamples });
- if (eroded.solid.isEmpty()) {
- return { solid, hollowed: false, reason: 'no-interior-at-this-wall-thickness' };
+export function decimateSolid(solid, budget) {
+ const before = solid.numTri();
+ if (!Number.isFinite(budget) || budget <= 0 || before <= budget) {
+ return { solid, applied: false, triangles_before: before, triangles_after: before };
}
-
- const shell = solid.subtract(eroded.solid);
- if (shell.isEmpty() || shell.status() !== 'NoError') {
- return { solid, hollowed: false, reason: 'shell-subtraction-failed' };
+ const box = solid.boundingBox();
+ const diagonal = Math.hypot(
+ box.max[0] - box.min[0],
+ box.max[1] - box.min[1],
+ box.max[2] - box.min[2],
+ );
+ let tolerance = diagonal * 1e-5;
+ let current = solid;
+ let applied = false;
+ for (let step = 0; step < 12; step += 1) {
+ const next = current.simplify(tolerance);
+ if (applied) current.delete();
+ current = next;
+ applied = true;
+ if (current.numTri() <= budget) break;
+ tolerance *= 2;
}
-
- // Two drain holes on the lowest face, offset from each other so the resin has
- // somewhere to leave and air somewhere to enter.
- const r = drainRadius ?? Math.max(wallThickness * 1.5, bounds.longest * 0.012);
- const depth = bounds.size[1] * 0.5;
- const punch = (x, z) =>
- wasm.Manifold.cylinder(depth, r, r, 24, true).translate([
- bounds.center[0] + x,
- bounds.min[1] + depth * 0.25,
- bounds.center[2] + z,
- ]);
- const offset = Math.max(r * 2.5, bounds.longest * 0.05);
- const drained = shell.subtract(punch(-offset, 0)).subtract(punch(offset, 0));
- const finalSolid = drained.isEmpty() || drained.status() !== 'NoError' ? shell : drained;
-
return {
- solid: finalSolid,
- hollowed: true,
- reason: null,
- metrics: {
- solidVolume: solid.volume(),
- hollowVolume: finalSolid.volume(),
- wallThickness,
- drainHoles: finalSolid === shell ? 0 : 2,
- drainRadius: r,
- },
+ solid: current,
+ applied,
+ tolerance,
+ triangles_before: before,
+ triangles_after: current.numTri(),
};
}
-/** Analytic helpers the quote engine and the report share. */
-export const geometry = { boundsOf, signedVolume, surfaceArea };
+/** Manifold solid to the plain indexed soup every exporter in this directory reads. */
+export function solidToMesh(solid) {
+ const mesh = solid.getMesh();
+ const stride = mesh.numProp;
+ const source = mesh.vertProperties;
+ const count = source.length / stride;
+ const positions = new Float64Array(count * 3);
+ for (let i = 0; i < count; i += 1) {
+ positions[i * 3] = source[i * stride];
+ positions[i * 3 + 1] = source[i * stride + 1];
+ positions[i * 3 + 2] = source[i * stride + 2];
+ }
+ return { positions, indices: Uint32Array.from(mesh.triVerts) };
+}
+
+/** Total area of an indexed soup, used for the print-time surface estimate. */
+export function meshArea(positions, indices) {
+ let total = 0;
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ total += triangleArea(positions, indices[i], indices[i + 1], indices[i + 2]);
+ }
+ return total;
+}
diff --git a/api/_lib/print/sampling.js b/api/_lib/print/sampling.js
deleted file mode 100644
index ac653cb0a..000000000
--- a/api/_lib/print/sampling.js
+++ /dev/null
@@ -1,304 +0,0 @@
-// Geometric sampling over an accelerated mesh: wall thickness, self-crossings,
-// and the signed distance field the reconstruction falls back on.
-//
-// All three questions are "what else is near this point", which is exactly what
-// a BVH answers, so one tree built from the welded soup serves all of them.
-// three-mesh-bvh is the accelerator; three's BufferGeometry is only the
-// container it wants, and no renderer, scene or material is ever constructed.
-//
-// Determinism is a contract of the printability report: the same bytes must
-// produce the same numbers, so every sample position comes from a seeded
-// generator with a fixed stream order, never from Math.random.
-
-import { BufferGeometry, BufferAttribute, Vector3, Ray, FrontSide } from 'three';
-import { MeshBVH } from 'three-mesh-bvh';
-
-// A 32-bit xorshift. Small, fast, and reproducible across engines, which is
-// what the determinism contract needs; the statistical quality demanded of it
-// (spread points over a surface) is far below what it delivers.
-export function seededRandom(seed = 0x9e3779b9) {
- let state = seed >>> 0 || 1;
- return () => {
- state ^= state << 13;
- state >>>= 0;
- state ^= state >>> 17;
- state ^= state << 5;
- state >>>= 0;
- return state / 4294967296;
- };
-}
-
-/** Wrap an indexed soup in the BufferGeometry + BVH that the samplers need. */
-export function buildBvh(positions, indices) {
- const geometry = new BufferGeometry();
- geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3));
- geometry.setIndex(new BufferAttribute(Uint32Array.from(indices), 1));
- return { geometry, bvh: new MeshBVH(geometry) };
-}
-
-function triangleNormal(positions, a, b, c, out) {
- const ax = positions[a * 3];
- const ay = positions[a * 3 + 1];
- const az = positions[a * 3 + 2];
- const ux = positions[b * 3] - ax;
- const uy = positions[b * 3 + 1] - ay;
- const uz = positions[b * 3 + 2] - az;
- const vx = positions[c * 3] - ax;
- const vy = positions[c * 3 + 1] - ay;
- const vz = positions[c * 3 + 2] - az;
- out.set(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx);
- const len = out.length();
- if (len > 0) out.multiplyScalar(1 / len);
- return len;
-}
-
-/**
- * Minimum wall thickness, sampled by casting each sample point's inward normal
- * back into the solid and measuring the distance to the first surface it hits.
- *
- * This is the metric that decides whether a print survives handling. A cape, a
- * sword blade or a hair strand on a generated character is routinely 0.2 mm at
- * the size a buyer wants, which snaps in the wash tank; knowing the thinnest
- * wall as a FRACTION of the model's height is what lets the quote engine say
- * "print this at 140 mm or taller" instead of shipping a broken object.
- *
- * Sampling is area-weighted (a big flat face is not over-sampled relative to a
- * thin fin) via a cumulative-area table with a seeded uniform draw, and the
- * result carries the sample count so the report can state its own resolution.
- * Percentiles are reported alongside the minimum because a single 0.05 mm
- * spike on a stray triangle should not condemn an otherwise printable model:
- * `min` is the worst point, `p01` is the thinness that actually characterizes
- * the mesh.
- */
-export function sampleWallThickness(positions, indices, { samples = 2000, seed = 0x5eed1234 } = {}) {
- const triCount = indices.length / 3;
- if (triCount === 0) return null;
-
- const { bvh } = buildBvh(positions, indices);
- const areas = new Float64Array(triCount);
- let totalArea = 0;
- const normal = new Vector3();
- for (let t = 0; t < triCount; t += 1) {
- const len = triangleNormal(positions, indices[t * 3], indices[t * 3 + 1], indices[t * 3 + 2], normal);
- areas[t] = len / 2;
- totalArea += areas[t];
- }
- if (totalArea <= 0) return null;
- const cumulative = new Float64Array(triCount);
- let running = 0;
- for (let t = 0; t < triCount; t += 1) {
- running += areas[t];
- cumulative[t] = running;
- }
-
- const random = seededRandom(seed);
- const ray = new Ray();
- const origin = new Vector3();
- const thicknesses = [];
- // Nudge the ray origin off the surface so it cannot re-hit its own face.
- // Scaled to the model, not absolute, so it holds at any authoring unit.
- const epsilon = Math.max(1e-9, Math.sqrt(totalArea) * 1e-6);
- const wanted = Math.min(samples, triCount * 8);
-
- for (let i = 0; i < wanted; i += 1) {
- const pick = random() * totalArea;
- let lo = 0;
- let hi = triCount - 1;
- while (lo < hi) {
- const mid = (lo + hi) >> 1;
- if (cumulative[mid] < pick) lo = mid + 1;
- else hi = mid;
- }
- const t = lo;
- let u = random();
- let v = random();
- if (u + v > 1) {
- u = 1 - u;
- v = 1 - v;
- }
- const a = indices[t * 3];
- const b = indices[t * 3 + 1];
- const c = indices[t * 3 + 2];
- if (triangleNormal(positions, a, b, c, normal) <= 0) continue;
- const w = 1 - u - v;
- origin.set(
- positions[a * 3] * w + positions[b * 3] * u + positions[c * 3] * v,
- positions[a * 3 + 1] * w + positions[b * 3 + 1] * u + positions[c * 3 + 1] * v,
- positions[a * 3 + 2] * w + positions[b * 3 + 2] * u + positions[c * 3 + 2] * v,
- );
- ray.direction.copy(normal).multiplyScalar(-1);
- ray.origin.copy(origin).addScaledVector(ray.direction, epsilon);
- const hit = bvh.raycastFirst(ray, FrontSide);
- if (!hit) continue;
- const thickness = hit.distance + epsilon;
- if (thickness > 0 && Number.isFinite(thickness)) thicknesses.push(thickness);
- }
-
- if (thicknesses.length === 0) return { samples: wanted, hits: 0, min: null, p01: null, median: null };
- thicknesses.sort((a, b) => a - b);
- const at = (q) => thicknesses[Math.min(thicknesses.length - 1, Math.floor(q * thicknesses.length))];
- return {
- samples: wanted,
- hits: thicknesses.length,
- min: thicknesses[0],
- p01: at(0.01),
- median: at(0.5),
- };
-}
-
-// Moller's triangle-triangle overlap test, interval form. Returns false for the
-// coplanar case: two coplanar triangles that merely share an edge or a vertex
-// are normal topology, and treating every such pair as a defect would report a
-// clean mesh as thousands of intersections.
-function trianglesIntersect(p, ia, ib) {
- const v = (i, k) => [p[i * 3], p[i * 3 + 1], p[i * 3 + 2]][k];
- const sub = (a, b) => [v(a, 0) - v(b, 0), v(a, 1) - v(b, 1), v(a, 2) - v(b, 2)];
- 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 dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
-
- const n2 = cross(sub(ib[1], ib[0]), sub(ib[2], ib[0]));
- const d2 = -dot(n2, [v(ib[0], 0), v(ib[0], 1), v(ib[0], 2)]);
- const dist1 = ia.map((i) => dot(n2, [v(i, 0), v(i, 1), v(i, 2)]) + d2);
- const scale = Math.max(Math.abs(n2[0]), Math.abs(n2[1]), Math.abs(n2[2])) || 1;
- const eps = scale * 1e-12;
- if (dist1.every((d) => d > eps) || dist1.every((d) => d < -eps)) return false;
- if (dist1.every((d) => Math.abs(d) <= eps)) return false;
-
- const n1 = cross(sub(ia[1], ia[0]), sub(ia[2], ia[0]));
- const d1 = -dot(n1, [v(ia[0], 0), v(ia[0], 1), v(ia[0], 2)]);
- const dist2 = ib.map((i) => dot(n1, [v(i, 0), v(i, 1), v(i, 2)]) + d1);
- const scale1 = Math.max(Math.abs(n1[0]), Math.abs(n1[1]), Math.abs(n1[2])) || 1;
- const eps1 = scale1 * 1e-12;
- if (dist2.every((d) => d > eps1) || dist2.every((d) => d < -eps1)) return false;
-
- // Project onto the intersection line's dominant axis and compare intervals.
- const dir = cross(n1, n2);
- let axis = 0;
- let best = Math.abs(dir[0]);
- if (Math.abs(dir[1]) > best) {
- axis = 1;
- best = Math.abs(dir[1]);
- }
- if (Math.abs(dir[2]) > best) axis = 2;
-
- const interval = (tri, dists) => {
- // The lone vertex on its own side of the other plane bridges to each of
- // the other two, giving the segment where this triangle crosses the line.
- let lone = 0;
- for (let i = 0; i < 3; i += 1) {
- const others = [0, 1, 2].filter((k) => k !== i);
- if (dists[i] * dists[others[0]] <= 0 && dists[i] * dists[others[1]] <= 0) lone = i;
- }
- const o1 = (lone + 1) % 3;
- const o2 = (lone + 2) % 3;
- const proj = (i) => v(tri[i], axis);
- const cut = (i) => proj(lone) + (proj(i) - proj(lone)) * (dists[lone] / (dists[lone] - dists[i]));
- const t1 = dists[lone] === dists[o1] ? proj(lone) : cut(o1);
- const t2 = dists[lone] === dists[o2] ? proj(lone) : cut(o2);
- return t1 <= t2 ? [t1, t2] : [t2, t1];
- };
-
- const [aMin, aMax] = interval(ia, dist1);
- const [bMin, bMax] = interval(ib, dist2);
- return aMax >= bMin && bMax >= aMin;
-}
-
-/**
- * Count pairs of triangles that pass through each other. Faces sharing a vertex
- * are skipped: they touch by construction, and a shared-vertex pair is never
- * the defect a slicer chokes on.
- *
- * Bounded on purpose. A pathological mesh can have millions of crossing pairs,
- * and the caller needs a usable signal in bounded time, not an exact census, so
- * the sweep stops at `maxPairs` findings or `budgetMs` and says which happened.
- */
-export function countSelfIntersections(
- positions,
- indices,
- { maxPairs = 2000, budgetMs = 4000 } = {},
-) {
- const triCount = indices.length / 3;
- const { bvh } = buildBvh(positions, indices);
- const started = Date.now();
- let pairs = 0;
- let truncated = false;
- const box = { min: new Vector3(), max: new Vector3() };
-
- for (let t = 0; t < triCount; t += 1) {
- if (pairs >= maxPairs || Date.now() - started > budgetMs) {
- truncated = t < triCount - 1;
- break;
- }
- const ia = [indices[t * 3], indices[t * 3 + 1], indices[t * 3 + 2]];
- box.min.set(Infinity, Infinity, Infinity);
- box.max.set(-Infinity, -Infinity, -Infinity);
- for (const i of ia) {
- box.min.min(new Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
- box.max.max(new Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
- }
- bvh.shapecast({
- intersectsBounds: (bounds) =>
- bounds.min.x <= box.max.x &&
- bounds.max.x >= box.min.x &&
- bounds.min.y <= box.max.y &&
- bounds.max.y >= box.min.y &&
- bounds.min.z <= box.max.z &&
- bounds.max.z >= box.min.z,
- intersectsTriangle: (_tri, other) => {
- // Each unordered pair is tested once, from the lower index.
- if (other <= t) return false;
- const ib = [indices[other * 3], indices[other * 3 + 1], indices[other * 3 + 2]];
- if (ia.some((x) => ib.includes(x))) return false;
- if (trianglesIntersect(positions, ia, ib)) {
- pairs += 1;
- if (pairs >= maxPairs) return true;
- }
- return false;
- },
- });
- }
- return { pairs, truncated, budgetMs, maxPairs };
-}
-
-/**
- * A signed distance field over a closed surface: unsigned distance from the
- * BVH, sign from ray parity. Parity is exact on a closed mesh and cheap (a
- * single all-hits cast), which beats a closest-point pseudonormal sign that
- * misreads concave creases exactly where hollowing needs it most.
- *
- * Used for two things: eroding a solid into a shell (hollowing), and rebuilding
- * a surface that no amount of hole filling could make manifold.
- */
-export function makeSignedDistance(positions, indices) {
- const { bvh } = buildBvh(positions, indices);
- const point = new Vector3();
- const target = {};
- const ray = new Ray(new Vector3(), new Vector3(1, 0, 0).normalize());
- // An axis-aligned probe direction grazes axis-aligned geometry, which is
- // most of it; an irrational direction hits nothing edge-on.
- ray.direction.set(0.5773502691896258, 0.5567764362830022, 0.5972015665748936).normalize();
- return (x, y, z) => {
- point.set(x, y, z);
- bvh.closestPointToPoint(point, target);
- const distance = target.distance ?? point.distanceTo(target.point);
- ray.origin.copy(point);
- const hits = bvh.raycast(ray, FrontSide);
- return hits.length % 2 === 1 ? -distance : distance;
- };
-}
-
-/** Unsigned distance only: the offset-shell repair never needs a sign. */
-export function makeUnsignedDistance(positions, indices) {
- const { bvh } = buildBvh(positions, indices);
- const point = new Vector3();
- const target = {};
- return (x, y, z) => {
- point.set(x, y, z);
- bvh.closestPointToPoint(point, target);
- return target.distance ?? point.distanceTo(target.point);
- };
-}
diff --git a/tests/_helpers/print-glb.js b/tests/_helpers/print-glb.js
new file mode 100644
index 000000000..92f2fb540
--- /dev/null
+++ b/tests/_helpers/print-glb.js
@@ -0,0 +1,111 @@
+// Deterministic GLB fixtures for the Materialize print pipeline tests.
+//
+// The print engine's whole job is judging geometry, so its tests need meshes
+// with known, exact properties: a solid whose volume is arithmetic, a shell
+// with a hole of a known size, two bodies that must be counted as two. Binary
+// fixtures are never committed (a .glb in git is an opaque blob nobody can
+// review); these builders write the bytes at test time from plain arrays, so
+// the expected numbers are visible right next to the assertion.
+
+import { Document, NodeIO } from '@gltf-transform/core';
+
+/** Corner positions of an axis-aligned box spanning [0,size] on every axis. */
+function boxCorners(size, offset = [0, 0, 0]) {
+ const [ox, oy, oz] = offset;
+ const s = size;
+ return [
+ ox, oy, oz,
+ ox + s, oy, oz,
+ ox + s, oy + s, oz,
+ ox, oy + s, oz,
+ ox, oy, oz + s,
+ ox + s, oy, oz + s,
+ ox + s, oy + s, oz + s,
+ ox, oy + s, oz + s,
+ ];
+}
+
+// Outward-facing (counter-clockwise from outside) winding for the eight corners
+// above. The last two triangles are the -Y face; dropping them is what makes the
+// open-bottom fixture.
+const BOX_TRIANGLES = [
+ 0, 2, 1, 0, 3, 2, // -Z
+ 4, 5, 6, 4, 6, 7, // +Z
+ 0, 1, 5, 0, 5, 4, // -Y
+ 1, 2, 6, 1, 6, 5, // +X
+ 2, 3, 7, 2, 7, 6, // +Y
+ 3, 0, 4, 3, 4, 7, // -X
+];
+
+/**
+ * Write a GLB from flat positions + indices.
+ *
+ * @param {number[][]} parts one entry per primitive: [positions, indices]
+ * @param {{ color?: [number, number, number] }} [opts]
+ */
+export async function writeGlb(parts, opts = {}) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const scene = doc.createScene();
+ const material = doc
+ .createMaterial('surface')
+ .setBaseColorFactor([...(opts.color || [1, 1, 1]), 1])
+ .setRoughnessFactor(1)
+ .setMetallicFactor(0);
+
+ parts.forEach(([positions, indices], i) => {
+ const position = doc
+ .createAccessor(`P${i}`)
+ .setType('VEC3')
+ .setArray(Float32Array.from(positions))
+ .setBuffer(buffer);
+ const index = doc
+ .createAccessor(`I${i}`)
+ .setType('SCALAR')
+ .setArray(Uint32Array.from(indices))
+ .setBuffer(buffer);
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', position)
+ .setIndices(index)
+ .setMaterial(material);
+ const mesh = doc.createMesh(`M${i}`).addPrimitive(prim);
+ scene.addChild(doc.createNode(`N${i}`).setMesh(mesh));
+ });
+
+ doc.getRoot().setDefaultScene(scene);
+ return new NodeIO().writeBinary(doc);
+}
+
+/** A closed axis-aligned cube. `size` is in meters (glTF's unit). */
+export function cubeGlb(size = 0.05) {
+ return writeGlb([[boxCorners(size), BOX_TRIANGLES]]);
+}
+
+/** The same cube with its -Y face removed: one hole, four boundary edges. */
+export function openBoxGlb(size = 0.05) {
+ return writeGlb([[boxCorners(size), BOX_TRIANGLES.slice(0, 24)]]);
+}
+
+/** Two disjoint closed cubes: two shells, twice the volume. */
+export function twoShellGlb(size = 0.05) {
+ return writeGlb([
+ [boxCorners(size), BOX_TRIANGLES],
+ [boxCorners(size, [size * 3, 0, 0]), BOX_TRIANGLES],
+ ]);
+}
+
+/**
+ * A thin plate: 40 mm wide, 40 mm tall, 0.4 mm thick. Below every process's
+ * minimum wall, which is what the thin-wall deduction and the material
+ * constraint rejections are asserted against.
+ */
+export function thinPlateGlb() {
+ const w = 0.04;
+ const t = 0.0004;
+ const positions = [
+ 0, 0, 0, w, 0, 0, w, w, 0, 0, w, 0,
+ 0, 0, t, w, 0, t, w, w, t, 0, w, t,
+ ];
+ return writeGlb([[positions, BOX_TRIANGLES]]);
+}