Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add extrude/tube geometry and physical PBR channels to the Three.js model schema (#3350)

[._.]/ Adam Eivya182a1a39af0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fe6abf6d76..09abfc1117 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -157,3 +157,7 @@
- **[issue-3335] Deleting a prompt stage now checks the source, not a hand-written list of ten.** `DELETE /api/prompts/:stage` force-guarded exactly the ten curated CoS/Brain/Memory stages, so removing `pipeline-series-concept-judge` (or roughly a hundred others PortOS resolves by literal key) succeeded with no warning and left the feature naming it throwing `Stage <key> not found` on its next run. Adding them all to the curated table was the wrong fix — the same table drives the Prompt Manager's `SYSTEM` badge and its "System only" filter, and badging ~100 of 127 rows makes both meaningless. Deletion protection is now a second, generated set: a checked-in manifest indexes every stage key a `server/` source names, including the ones reached only through an interpolated prefix like `pipeline-panel-${personaId}`, and a drift test fails until a new call site is regenerated into it. The badge and the filter still show the same ten stages; the delete dialog now names the files that reference the one you're about to remove.
- **[issue-3288] Video render submission is no longer a 717-line route handler — and a failed lookup mid-request stops orphaning your upload.** `POST /api/video-gen` did request validation, backend-pin resolution, model checks, durable staging for four upload kinds with rollback bookkeeping, IC-LoRA/keyframe/a2v validation, render-history lookups, LoRA normalization and chunk resolution inline, with twenty-plus throw sites sharing mutable cleanup state — so every new video-gen parameter meant editing the monolith and risking an unrelated validation branch. That whole region now lives in `services/videoGen/prepareParams.js`, mirroring what `imageGen` already did, and the route is a thin parse → prepare → enqueue → respond shell. Validation order and the exact cleanup-on-throw unwind are preserved verbatim, pinned by the existing route suite plus a new service suite. The extraction also closed a real leak (#3326): every *explicit* throw released the staged uploads, but a plain rejected `await` — a music-video project or track lookup, a render-history read, or the enqueue itself — bubbled straight past them, orphaning up to 100MB per request under `data/uploads` with no job to ever clean it up. One rollback guard now covers every rejection point at once and stays correct as new awaits are added, rethrowing the original error untouched.
- **[issue-3353] Client tests that type into a field and then submit no longer race the keystrokes.** A Stacker News save test failed on CI for a pull request whose entire diff was a dependency config file, and passed on the rerun. The cause is a shape that suite had in six places: `user.type` enters `20` as two separate events, and nothing between the last keystroke and the Save click asserted that the controlled input had actually reached `20` — so under load the click could send a payload built from the intermediate `2`, or from the post-clear empty string that `Number('')` turns into `0`. Waiting on the assertion cannot recover from that, because the call has already happened with the wrong argument and re-waiting never produces a second one. A shared `src/test/settledInput.js` helper now pins the settled input value between the keystrokes and whatever depends on them, and every instance of the shape now uses it — all six in the Stacker News suite plus ten more found by auditing the rest of the client tests, across the CoS agent card and reviewer picker, the sprite reference workflow, the media jobs queue, the duplicate-universe merge tab, and Media Collections. Two of those submitted with Enter typed as part of the same keystroke run, where a partially-typed `bad token!` would have been a *valid* username and quietly emitted; the Enter is now a separate press after the draft is pinned. One more asserted only the navigation that followed its submit, so a half-typed collection name could not have failed it — it now asserts the request it sent. The failure mode it replaces is an honest one — an input that never settles now fails saying so, rather than silently asserting against a half-typed value.
+
+## Three.js Models
+
+- **[issue-3350] Silhouettes with cutouts, bent details, and glass/cloth finishes no longer have to degrade into a coarse triangle mesh.** The scene schema could express primitives, a lathe, and a bounded custom mesh, so anything with a keyhole, a vent, a cable, or a bent handle either got flattened into a box stack or spent its budget on hand-authored triangles. Two schema-backed forms now cover that gap: `extrude` sweeps a closed 2D outline — with optional hole rings — to a depth with optional bevel, and `tube` sweeps a round profile along a Catmull-Rom path. Both are validated on the way in rather than trusted: a ring that encloses no area, a hole that falls outside its outline, a path that repeats a point consecutively, or a closed path that repeats its first point at the end are all rejected, because each renders as an empty face, a stray disjoint face, or NaN geometry rather than an error. `physical` materials also gained bounded `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, and `anisotropy`, so glass, gems, velvet, oil-slick, and brushed metal are material choices instead of approximations — parsed for every material type so a spec round-trips unchanged, but only handed to Three.js for physical ones. The generation prompt now says which form fits which subject and that custom triangles are the last resort, and the preview builds the new geometry through the same construction the downloaded standalone factory emits.
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsx
index 6489bf54f7..111c74f961 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { Canvas } from '@react-three/fiber';
import { Bounds, OrbitControls } from '@react-three/drei';
import * as THREE from 'three';
+import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from '../../lib/threejsSculpt';
const radians = (degrees = 0) => THREE.MathUtils.degToRad(degrees);
const rotation = (degrees = [0, 0, 0]) => degrees.map(radians);
@@ -25,20 +26,15 @@ const checkerboardStyle = {
backgroundPosition: '0 0, 0 8px, 8px -8px, -8px 0',
};
-function CustomGeometry({ definition }) {
- const geometry = useMemo(() => {
- const next = new THREE.BufferGeometry();
- next.setAttribute('position', new THREE.Float32BufferAttribute(definition.vertices, 3));
- next.setIndex(definition.indices);
- next.computeVertexNormals();
- next.computeBoundingSphere();
- return next;
- }, [definition]);
- useEffect(() => () => geometry.dispose(), [geometry]);
+function BufferGeometry({ definition }) {
+ const geometry = useMemo(() => createSculptBufferGeometry(definition), [definition]);
+ useEffect(() => () => geometry?.dispose(), [geometry]);
+ if (!geometry) return null;
return <primitive object={geometry} attach="geometry" />;
}
function Geometry({ definition }) {
+ if (needsSculptBufferGeometry(definition)) return <BufferGeometry definition={definition} />;
switch (definition.type) {
case 'box':
return <boxGeometry args={[definition.width, definition.height, definition.depth]} />;
@@ -54,44 +50,16 @@ function Geometry({ definition }) {
return <capsuleGeometry args={[definition.radius, definition.length, definition.capSegments, definition.radialSegments]} />;
case 'lathe':
return <latheGeometry args={[definition.points.map(([x, y]) => new THREE.Vector2(x, y)), definition.segments]} />;
- case 'custom':
- return <CustomGeometry definition={definition} />;
default:
return null;
}
}
function Material({ definition }) {
- const unlit = {
- color: definition.color,
- opacity: definition.opacity,
- transparent: definition.transparent,
- wireframe: definition.wireframe,
- };
- if (definition.type === 'basic') return <meshBasicMaterial {...unlit} />;
- const lit = {
- ...unlit,
- emissive: definition.emissive,
- emissiveIntensity: definition.emissiveIntensity,
- };
- if (definition.type === 'physical') {
- return (
- <meshPhysicalMaterial
- {...lit}
- metalness={definition.metalness}
- roughness={definition.roughness}
- clearcoat={definition.clearcoat}
- clearcoatRoughness={definition.clearcoatRoughness}
- />
- );
- }
- return (
- <meshStandardMaterial
- {...lit}
- metalness={definition.metalness}
- roughness={definition.roughness}
- />
- );
+ const props = sculptMaterialProps(definition);
+ if (definition.type === 'basic') return <meshBasicMaterial {...props} />;
+ if (definition.type === 'physical') return <meshPhysicalMaterial {...props} />;
+ return <meshStandardMaterial {...props} />;
}
function Part({ part, materials }) {
const transform = {
diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
index dd30b87449..b71d6cbf76 100644
--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx
@@ -9,6 +9,22 @@ vi.mock('@react-three/drei', () => ({
OrbitControls: () => null,
}));
+// r3f object props stringify to "[object Object]" under the DOM renderer, so the
+// only way to see WHICH geometry the preview attached is to record it as the real
+// builder hands it back.
+const built = vi.hoisted(() => []);
+vi.mock('../../lib/threejsSculpt', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ createSculptBufferGeometry: (definition) => {
+ const geometry = actual.createSculptBufferGeometry(definition);
+ built.push(geometry);
+ return geometry;
+ },
+ };
+});
+
import ThreejsModelPreview from './ThreejsModelPreview';
const SPEC = {
@@ -21,6 +37,40 @@ const SPEC = {
parts: [],
};
+const material = (overrides) => ({
+ type: 'standard',
+ color: '#8b5a2b',
+ metalness: 0,
+ roughness: 0.6,
+ emissive: '#000000',
+ emissiveIntensity: 0,
+ opacity: 1,
+ transparent: false,
+ wireframe: false,
+ clearcoat: 0,
+ clearcoatRoughness: 0,
+ ior: 1.5,
+ transmission: 0,
+ thickness: 0,
+ sheen: 0,
+ iridescence: 0,
+ anisotropy: 0,
+ ...overrides,
+});
+
+const part = (id, geometry, materialId) => ({
+ id,
+ name: id,
+ geometry,
+ material: materialId,
+ position: [0, 0, 0],
+ rotationDegrees: [0, 0, 0],
+ scale: [1, 1, 1],
+ castShadow: true,
+ receiveShadow: true,
+ children: [],
+});
+
describe('ThreejsModelPreview', () => {
it('offers preset and custom preview backgrounds without changing the scene spec', () => {
render(<ThreejsModelPreview spec={SPEC} />);
@@ -37,4 +87,65 @@ describe('ThreejsModelPreview', () => {
expect(screen.getByTestId('threejs-canvas')).toHaveAttribute('data-alpha', 'true');
expect(screen.getByLabelText('Custom preview background color')).toHaveValue('#000000');
});
+
+ it('renders extrude and tube parts as built buffer geometries', () => {
+ const { container } = render(<ThreejsModelPreview spec={{
+ ...SPEC,
+ materials: { body: material() },
+ parts: [
+ part('plate', {
+ type: 'extrude',
+ outline: [[-1, -1], [1, -1], [1, 1], [-1, 1]],
+ holes: [[[-0.3, -0.3], [0.3, -0.3], [0.3, 0.3], [-0.3, 0.3]]],
+ depth: 0.4,
+ bevelEnabled: false,
+ bevelThickness: 0.1,
+ bevelSize: 0.1,
+ bevelSegments: 2,
+ curveSegments: 8,
+ steps: 1,
+ }, 'body'),
+ part('cable', {
+ type: 'tube',
+ path: [[0, 0, 0], [0, 1, 0.5], [0.6, 1.6, 0]],
+ radius: 0.08,
+ tubularSegments: 24,
+ radialSegments: 8,
+ closed: false,
+ curveType: 'centripetal',
+ tension: 0.5,
+ }, 'body'),
+ ],
+ }} />);
+
+ expect(container.querySelectorAll('primitive[attach="geometry"]')).toHaveLength(2);
+ expect(built.map((geometry) => geometry.type)).toEqual(['ExtrudeGeometry', 'TubeGeometry']);
+ expect(built.every((geometry) => geometry.getAttribute('position').count > 0)).toBe(true);
+ });
+
+ it('forwards physical material channels only to physical materials', () => {
+ const { container } = render(<ThreejsModelPreview spec={{
+ ...SPEC,
+ materials: {
+ glass: material({ type: 'physical', ior: 1.45, transmission: 0.8, thickness: 0.6, sheen: 0.3, iridescence: 0.7, anisotropy: 0.9 }),
+ paint: material(),
+ },
+ parts: [
+ part('pane', { type: 'box', width: 1, height: 1, depth: 1 }, 'glass'),
+ part('frame', { type: 'box', width: 1, height: 1, depth: 1 }, 'paint'),
+ ],
+ }} />);
+
+ const physical = container.querySelector('meshPhysicalMaterial');
+ expect(physical.getAttribute('ior')).toBe('1.45');
+ expect(physical.getAttribute('transmission')).toBe('0.8');
+ expect(physical.getAttribute('thickness')).toBe('0.6');
+ expect(physical.getAttribute('sheen')).toBe('0.3');
+ expect(physical.getAttribute('iridescence')).toBe('0.7');
+ expect(physical.getAttribute('anisotropy')).toBe('0.9');
+
+ const standard = container.querySelector('meshStandardMaterial');
+ expect(standard.getAttribute('ior')).toBeNull();
+ expect(standard.getAttribute('transmission')).toBeNull();
+ });
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 37297ead07..d4fc9a2ae4 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -161,6 +161,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
+| `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`. Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. |
| `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. |
| `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |
| `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 1388e8f3f2..724f37f604 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -129,6 +129,7 @@ export * from './streakGlyph.js';
export * from './syncCounts.js';
export * from './tabNotation.js';
export * from './terminalTheme.js';
+export * from './threejsSculpt.js';
export * from './tribe.js';
export * from './tribeCadence.js';
export * from './universeBuilderExpand.js';
diff --git a/client/src/lib/threejsSculpt.js b/client/src/lib/threejsSculpt.js
new file mode 100644
index 0000000000..1b9e8c6722
--- /dev/null
+++ b/client/src/lib/threejsSculpt.js
@@ -0,0 +1,93 @@
+/**
+ * Three.js construction helpers for the validated procedural sculpt spec
+ * (`server/lib/threejsModel.js`).
+ *
+ * These mirror the `createGeometry` / `createMaterial` bodies that
+ * `buildThreejsFactorySource()` emits into the downloadable standalone factory,
+ * so the in-browser preview and the exported source render the same scene.
+ * Primitive geometries (box, sphere, cylinder, cone, torus, capsule, lathe) stay
+ * declarative r3f elements; only the forms that need an imperatively-built
+ * BufferGeometry live here.
+ */
+
+import * as THREE from 'three';
+
+const BUFFER_GEOMETRY_TYPES = new Set(['custom', 'extrude', 'tube']);
+
+/** True when the definition must be built with `createSculptBufferGeometry`. */
+export const needsSculptBufferGeometry = (definition) => BUFFER_GEOMETRY_TYPES.has(definition?.type);
+
+/**
+ * Build a BufferGeometry for the schema forms r3f has no direct element for.
+ * Returns null for primitive types, which the preview renders declaratively.
+ * Callers own disposal.
+ */
+export function createSculptBufferGeometry(definition) {
+ if (definition?.type === 'custom') {
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(definition.vertices, 3));
+ geometry.setIndex(definition.indices);
+ geometry.computeVertexNormals();
+ geometry.computeBoundingSphere();
+ return geometry;
+ }
+ if (definition?.type === 'extrude') {
+ const shape = new THREE.Shape(definition.outline.map(([x, y]) => new THREE.Vector2(x, y)));
+ for (const hole of definition.holes || []) {
+ shape.holes.push(new THREE.Path(hole.map(([x, y]) => new THREE.Vector2(x, y))));
+ }
+ return new THREE.ExtrudeGeometry(shape, {
+ depth: definition.depth,
+ bevelEnabled: definition.bevelEnabled,
+ bevelThickness: definition.bevelThickness,
+ bevelSize: definition.bevelSize,
+ bevelSegments: definition.bevelSegments,
+ curveSegments: definition.curveSegments,
+ steps: definition.steps,
+ });
+ }
+ if (definition?.type === 'tube') {
+ const curve = new THREE.CatmullRomCurve3(
+ definition.path.map(([x, y, z]) => new THREE.Vector3(x, y, z)),
+ definition.closed,
+ definition.curveType,
+ definition.tension,
+ );
+ return new THREE.TubeGeometry(curve, definition.tubularSegments, definition.radius, definition.radialSegments, definition.closed);
+ }
+ return null;
+}
+
+/**
+ * Map a validated material definition to the props for its Three.js material.
+ * Physical-only channels are dropped for standard/basic so an authored spec that
+ * carries schema defaults cannot leak unsupported props onto the wrong material.
+ */
+export function sculptMaterialProps(definition) {
+ const unlit = {
+ color: definition.color,
+ opacity: definition.opacity,
+ transparent: definition.transparent,
+ wireframe: definition.wireframe,
+ };
+ if (definition.type === 'basic') return unlit;
+ const lit = {
+ ...unlit,
+ metalness: definition.metalness,
+ roughness: definition.roughness,
+ emissive: definition.emissive,
+ emissiveIntensity: definition.emissiveIntensity,
+ };
+ if (definition.type !== 'physical') return lit;
+ return {
+ ...lit,
+ clearcoat: definition.clearcoat,
+ clearcoatRoughness: definition.clearcoatRoughness,
+ ior: definition.ior,
+ transmission: definition.transmission,
+ thickness: definition.thickness,
+ sheen: definition.sheen,
+ iridescence: definition.iridescence,
+ anisotropy: definition.anisotropy,
+ };
+}
diff --git a/client/src/lib/threejsSculpt.test.js b/client/src/lib/threejsSculpt.test.js
new file mode 100644
index 0000000000..7af0c69ad2
--- /dev/null
+++ b/client/src/lib/threejsSculpt.test.js
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest';
+import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from './threejsSculpt.js';
+
+const extrudeDefinition = (overrides = {}) => ({
+ type: 'extrude',
+ outline: [[-1, -1], [1, -1], [1, 1], [-1, 1]],
+ holes: [],
+ depth: 0.5,
+ bevelEnabled: false,
+ bevelThickness: 0.1,
+ bevelSize: 0.1,
+ bevelSegments: 2,
+ curveSegments: 8,
+ steps: 1,
+ ...overrides,
+});
+
+const tubeDefinition = (overrides = {}) => ({
+ type: 'tube',
+ path: [[0, 0, 0], [0, 1, 0.5], [0.6, 1.6, 0]],
+ radius: 0.1,
+ tubularSegments: 24,
+ radialSegments: 8,
+ closed: false,
+ curveType: 'centripetal',
+ tension: 0.5,
+ ...overrides,
+});
+
+describe('needsSculptBufferGeometry', () => {
+ it('claims only the imperatively built forms', () => {
+ expect(needsSculptBufferGeometry({ type: 'custom' })).toBe(true);
+ expect(needsSculptBufferGeometry({ type: 'extrude' })).toBe(true);
+ expect(needsSculptBufferGeometry({ type: 'tube' })).toBe(true);
+ expect(needsSculptBufferGeometry({ type: 'box' })).toBe(false);
+ expect(needsSculptBufferGeometry(undefined)).toBe(false);
+ });
+});
+
+describe('createSculptBufferGeometry', () => {
+ it('builds an indexed custom triangle mesh with normals', () => {
+ const geometry = createSculptBufferGeometry({
+ type: 'custom',
+ vertices: [0, 0, 0, 1, 0, 0, 0, 1, 0],
+ indices: [0, 1, 2],
+ });
+ expect(geometry.getAttribute('position').count).toBe(3);
+ expect(geometry.getAttribute('normal')).toBeTruthy();
+ expect(geometry.index.count).toBe(3);
+ });
+
+ it('extrudes a closed outline to the requested depth', () => {
+ const geometry = createSculptBufferGeometry(extrudeDefinition());
+ geometry.computeBoundingBox();
+ const { min, max } = geometry.boundingBox;
+ expect(max.z - min.z).toBeCloseTo(0.5, 5);
+ expect(max.x - min.x).toBeCloseTo(2, 5);
+ expect(geometry.getAttribute('position').count).toBeGreaterThan(0);
+ });
+
+ it('cuts holes out of the extruded outline', () => {
+ const solid = createSculptBufferGeometry(extrudeDefinition());
+ const perforated = createSculptBufferGeometry(extrudeDefinition({
+ holes: [[[-0.3, -0.3], [0.3, -0.3], [0.3, 0.3], [-0.3, 0.3]]],
+ }));
+ expect(perforated.getAttribute('position').count).toBeGreaterThan(solid.getAttribute('position').count);
+ });
+
+ it('sweeps a tube along the path without producing NaN positions', () => {
+ const geometry = createSculptBufferGeometry(tubeDefinition());
+ const positions = geometry.getAttribute('position').array;
+ expect(positions.length).toBeGreaterThan(0);
+ expect(Array.from(positions).every(Number.isFinite)).toBe(true);
+ geometry.computeBoundingBox();
+ expect(geometry.boundingBox.max.y).toBeGreaterThan(1.5);
+ });
+
+ it('returns null for primitives the preview renders declaratively', () => {
+ expect(createSculptBufferGeometry({ type: 'box', width: 1, height: 1, depth: 1 })).toBeNull();
+ });
+});
+
+describe('sculptMaterialProps', () => {
+ const definition = {
+ type: 'physical',
+ color: '#ffffff',
+ metalness: 0.2,
+ roughness: 0.4,
+ emissive: '#000000',
+ emissiveIntensity: 0,
+ opacity: 1,
+ transparent: false,
+ wireframe: false,
+ clearcoat: 0.5,
+ clearcoatRoughness: 0.1,
+ ior: 1.45,
+ transmission: 0.8,
+ thickness: 0.6,
+ sheen: 0.3,
+ iridescence: 0.7,
+ anisotropy: 0.9,
+ };
+
+ it('forwards physical channels for physical materials', () => {
+ expect(sculptMaterialProps(definition)).toMatchObject({
+ metalness: 0.2, roughness: 0.4, clearcoat: 0.5, clearcoatRoughness: 0.1,
+ ior: 1.45, transmission: 0.8, thickness: 0.6, sheen: 0.3, iridescence: 0.7, anisotropy: 0.9,
+ });
+ });
+
+ it('drops physical-only channels for standard materials', () => {
+ const props = sculptMaterialProps({ ...definition, type: 'standard' });
+ expect(props.metalness).toBe(0.2);
+ for (const key of ['clearcoat', 'ior', 'transmission', 'thickness', 'sheen', 'iridescence', 'anisotropy']) {
+ expect(props).not.toHaveProperty(key);
+ }
+ });
+
+ it('keeps basic materials unlit', () => {
+ const props = sculptMaterialProps({ ...definition, type: 'basic' });
+ expect(props).toEqual({ color: '#ffffff', opacity: 1, transparent: false, wireframe: false });
+ });
+});
diff --git a/docs/THREEJS_MODELS.md b/docs/THREEJS_MODELS.md
index fbab9884ed..980cf364fa 100644
--- a/docs/THREEJS_MODELS.md
+++ b/docs/THREEJS_MODELS.md
@@ -29,6 +29,29 @@ rendering it. The client maps that allowlist to Three.js primitives and bounded
`BufferGeometry`; it never evaluates provider-written JavaScript. Exported
source is produced deterministically from the validated spec.
+## Geometry vocabulary
+
+Alongside the primitives (box, sphere, cylinder, cone, torus, capsule, lathe)
+and the bounded `custom` triangle mesh, the schema carries two constructive
+forms so silhouette-defining shapes don't have to degrade into a coarse mesh:
+
+- `extrude` — a closed 2D outline (3–160 points) with optional hole rings,
+ swept to `depth` with optional bevel. Every ring must enclose real area and
+ each hole must lie inside the outline, so a degenerate or stray ring is
+ rejected instead of rendering as an empty or disjoint face.
+- `tube` — a round profile of `radius` swept along a 2–96 point Catmull-Rom
+ path. Consecutive points must differ and a `closed` path must not repeat its
+ first point, because either produces NaN frames in the centripetal/chordal
+ parameterizations.
+
+`type: "physical"` materials additionally carry bounded `ior`, `transmission`,
+`thickness`, `sheen`, `iridescence`, and `anisotropy` for glass, cloth,
+pearlescent, and brushed-metal finishes. Those channels are parsed for every
+material type so a spec round-trips unchanged, but only forwarded to Three.js
+for physical materials. `client/src/lib/threejsSculpt.js` mirrors the geometry
+and material construction the exported factory emits, so the preview and the
+downloaded source render the same scene.
+
## Provider behavior
API providers receive the gallery image as a multimodal image attachment. CLI
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 50af0dfb6d..dbece7be3e 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -67,6 +67,75 @@ const latheGeometrySchema = z.object({
segments: z.number().int().min(3).max(96).default(32),
});
+// Shoelace area — a closed outline whose points are coincident or collinear
+// extrudes to nothing, so it is rejected rather than rendered as an empty mesh.
+const MIN_RING_AREA = 1e-6;
+const ringArea = (ring) => {
+ let doubled = 0;
+ for (let index = 0; index < ring.length; index += 1) {
+ const [x1, y1] = ring[index];
+ const [x2, y2] = ring[(index + 1) % ring.length];
+ doubled += (x1 * y2) - (x2 * y1);
+ }
+ return Math.abs(doubled) / 2;
+};
+
+const ringBounds = (ring) => ring.reduce((bounds, [x, y]) => ({
+ minX: Math.min(bounds.minX, x),
+ maxX: Math.max(bounds.maxX, x),
+ minY: Math.min(bounds.minY, y),
+ maxY: Math.max(bounds.maxY, y),
+}), { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity });
+
+const outlineRingSchema = z.array(z.tuple([finite, finite])).min(3).max(160)
+ .refine((ring) => ringArea(ring) > MIN_RING_AREA, 'outline must enclose a non-zero area');
+
+const extrudeGeometrySchema = z.object({
+ type: z.literal('extrude'),
+ outline: outlineRingSchema,
+ holes: z.array(outlineRingSchema).max(12).default([]),
+ depth: positive,
+ bevelEnabled: z.boolean().default(false),
+ bevelThickness: z.number().finite().min(0).max(1_000).default(0.1),
+ bevelSize: z.number().finite().min(0).max(1_000).default(0.1),
+ bevelSegments: z.number().int().min(0).max(8).default(2),
+ curveSegments: z.number().int().min(1).max(24).default(8),
+ steps: z.number().int().min(1).max(32).default(1),
+}).superRefine((definition, ctx) => {
+ const bounds = ringBounds(definition.outline);
+ // A hole outside the outline is not a cutout — Three.js would silently emit a
+ // second disjoint face, so treat it as a malformed outline instead.
+ definition.holes.forEach((hole, index) => {
+ const outside = hole.some(([x, y]) => x < bounds.minX || x > bounds.maxX || y < bounds.minY || y > bounds.maxY);
+ if (outside) {
+ ctx.addIssue({ code: 'custom', message: `extrude hole ${index} falls outside the outline`, path: ['holes', index] });
+ }
+ });
+});
+
+const tubeGeometrySchema = z.object({
+ type: z.literal('tube'),
+ path: z.array(vec3Schema).min(2).max(96)
+ .refine(
+ (points) => points.every((point, index) => index === 0 || point.some((value, axis) => value !== points[index - 1][axis])),
+ 'tube path cannot repeat the same point consecutively',
+ ),
+ radius: positive,
+ tubularSegments: z.number().int().min(2).max(256).default(64),
+ radialSegments: z.number().int().min(3).max(32).default(12),
+ closed: z.boolean().default(false),
+ curveType: z.enum(['centripetal', 'chordal', 'catmullrom']).default('centripetal'),
+ tension: z.number().finite().min(0).max(1).default(0.5),
+}).superRefine((definition, ctx) => {
+ const first = definition.path[0];
+ const last = definition.path[definition.path.length - 1];
+ // A closed curve already joins the endpoints; repeating the seam point yields a
+ // zero-length segment and NaN frames in the centripetal/chordal parameterizations.
+ if (definition.closed && first.every((value, axis) => value === last[axis])) {
+ ctx.addIssue({ code: 'custom', message: 'a closed tube path must not repeat its first point at the end', path: ['path'] });
+ }
+});
+
const customGeometrySchema = z.object({
type: z.literal('custom'),
// 900 vertices / 2,700 coordinates is deliberately generous for a
@@ -85,6 +154,8 @@ export const threejsGeometrySchema = z.discriminatedUnion('type', [
torusGeometrySchema,
capsuleGeometrySchema,
latheGeometrySchema,
+ extrudeGeometrySchema,
+ tubeGeometrySchema,
customGeometrySchema,
]);
@@ -100,6 +171,15 @@ export const threejsMaterialSchema = z.object({
wireframe: z.boolean().default(false),
clearcoat: z.number().finite().min(0).max(1).default(0),
clearcoatRoughness: z.number().finite().min(0).max(1).default(0),
+ // Physical-only channels. They are parsed for every material type so a spec
+ // round-trips unchanged, but only `type: 'physical'` forwards them to Three.js.
+ // `ior` is bounded to the range MeshPhysicalMaterial itself clamps to.
+ ior: z.number().finite().min(1).max(2.333).default(1.5),
+ transmission: z.number().finite().min(0).max(1).default(0),
+ thickness: z.number().finite().min(0).max(1_000).default(0),
+ sheen: z.number().finite().min(0).max(1).default(0),
+ iridescence: z.number().finite().min(0).max(1).default(0),
+ anisotropy: z.number().finite().min(0).max(1).default(0),
});
let partSchema;
@@ -247,6 +327,30 @@ function createGeometry(definition) {
return new THREE.CapsuleGeometry(definition.radius, definition.length, definition.capSegments, definition.radialSegments);
case 'lathe':
return new THREE.LatheGeometry(definition.points.map(([x, y]) => new THREE.Vector2(x, y)), definition.segments);
+ case 'extrude': {
+ const shape = new THREE.Shape(definition.outline.map(([x, y]) => new THREE.Vector2(x, y)));
+ for (const hole of definition.holes) {
+ shape.holes.push(new THREE.Path(hole.map(([x, y]) => new THREE.Vector2(x, y))));
+ }
+ return new THREE.ExtrudeGeometry(shape, {
+ depth: definition.depth,
+ bevelEnabled: definition.bevelEnabled,
+ bevelThickness: definition.bevelThickness,
+ bevelSize: definition.bevelSize,
+ bevelSegments: definition.bevelSegments,
+ curveSegments: definition.curveSegments,
+ steps: definition.steps,
+ });
+ }
+ case 'tube': {
+ const curve = new THREE.CatmullRomCurve3(
+ definition.path.map(([x, y, z]) => new THREE.Vector3(x, y, z)),
+ definition.closed,
+ definition.curveType,
+ definition.tension
+ );
+ return new THREE.TubeGeometry(curve, definition.tubularSegments, definition.radius, definition.radialSegments, definition.closed);
+ }
case 'custom': {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(definition.vertices, 3));
@@ -282,6 +386,12 @@ function createMaterial(definition) {
...lit,
clearcoat: definition.clearcoat,
clearcoatRoughness: definition.clearcoatRoughness,
+ ior: definition.ior,
+ transmission: definition.transmission,
+ thickness: definition.thickness,
+ sheen: definition.sheen,
+ iridescence: definition.iridescence,
+ anisotropy: definition.anisotropy,
});
}
return new THREE.MeshStandardMaterial(lit);
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index a7a513831d..c5fb521fd6 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -1,5 +1,18 @@
import { describe, expect, it } from 'vitest';
-import { buildThreejsFactorySource, threejsSculptSpecSchema } from './threejsModel.js';
+import { buildThreejsFactorySource, threejsGeometrySchema, threejsSculptSpecSchema } from './threejsModel.js';
+
+const squareOutline = [[-1, -1], [1, -1], [1, 1], [-1, 1]];
+const validExtrude = () => ({
+ type: 'extrude',
+ outline: squareOutline,
+ holes: [[[-0.3, -0.3], [0.3, -0.3], [0.3, 0.3], [-0.3, 0.3]]],
+ depth: 0.4,
+});
+const validTube = () => ({
+ type: 'tube',
+ path: [[0, 0, 0], [0, 1, 0.5], [0.6, 1.6, 0]],
+ radius: 0.08,
+});
const validSpec = () => ({
schemaVersion: 1,
@@ -76,6 +89,78 @@ describe('threejsSculptSpecSchema', () => {
expect(result.success).toBe(false);
expect(result.error.issues.some((issue) => issue.message.includes('exceeds vertex count'))).toBe(true);
});
+
+ it('accepts extrude and tube parts and fills their construction defaults', () => {
+ const spec = validSpec();
+ spec.parts[0].geometry = validExtrude();
+ spec.parts[0].children[0].geometry = validTube();
+ const parsed = threejsSculptSpecSchema.parse(spec);
+ expect(parsed.parts[0].geometry).toMatchObject({
+ bevelEnabled: false, bevelSegments: 2, curveSegments: 8, steps: 1,
+ });
+ expect(parsed.parts[0].children[0].geometry).toMatchObject({
+ tubularSegments: 64, radialSegments: 12, closed: false, curveType: 'centripetal', tension: 0.5,
+ });
+ });
+
+ it('fills physical material channel defaults', () => {
+ const parsed = threejsSculptSpecSchema.parse(validSpec());
+ expect(parsed.materials.trim).toMatchObject({
+ ior: 1.5, transmission: 0, thickness: 0, sheen: 0, iridescence: 0, anisotropy: 0,
+ });
+ });
+
+ it('rejects out-of-range physical material channels', () => {
+ const spec = validSpec();
+ spec.materials.trim.ior = 4;
+ spec.materials.trim.transmission = 1.5;
+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);
+ });
+});
+
+describe('threejsGeometrySchema extrude/tube validation', () => {
+ it('rejects an outline or hole that encloses no area', () => {
+ const collinear = [[0, 0], [1, 0], [2, 0], [3, 0]];
+ expect(threejsGeometrySchema.safeParse({ ...validExtrude(), outline: collinear }).success).toBe(false);
+ expect(threejsGeometrySchema.safeParse({ ...validExtrude(), holes: [collinear] }).success).toBe(false);
+ });
+
+ it('rejects an outline with fewer than three points', () => {
+ expect(threejsGeometrySchema.safeParse({ ...validExtrude(), outline: [[0, 0], [1, 1]] }).success).toBe(false);
+ });
+
+ it('rejects a hole that falls outside the outline', () => {
+ const result = threejsGeometrySchema.safeParse({
+ ...validExtrude(),
+ holes: [[[5, 5], [6, 5], [6, 6], [5, 6]]],
+ });
+ expect(result.success).toBe(false);
+ expect(result.error.issues.some((issue) => issue.message.includes('falls outside the outline'))).toBe(true);
+ });
+
+ it('rejects a tube path that repeats a point consecutively', () => {
+ const result = threejsGeometrySchema.safeParse({
+ ...validTube(),
+ path: [[0, 0, 0], [0, 0, 0], [1, 0, 0]],
+ });
+ expect(result.success).toBe(false);
+ expect(result.error.issues.some((issue) => issue.message.includes('repeat the same point consecutively'))).toBe(true);
+ });
+
+ it('rejects a closed tube path that repeats its first point at the end', () => {
+ const result = threejsGeometrySchema.safeParse({
+ type: 'tube',
+ radius: 0.1,
+ closed: true,
+ path: [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 0, 0]],
+ });
+ expect(result.success).toBe(false);
+ expect(result.error.issues.some((issue) => issue.message.includes('must not repeat its first point'))).toBe(true);
+ });
+
+ it('accepts a closed tube path with distinct endpoints', () => {
+ expect(threejsGeometrySchema.safeParse({ ...validTube(), closed: true }).success).toBe(true);
+ });
});
describe('buildThreejsFactorySource', () => {
it('exports a deterministic Group factory from validated data', () => {
@@ -86,4 +171,18 @@ describe('buildThreejsFactorySource', () => {
expect(source).toContain("case 'custom'");
expect(source).toContain('new THREE.MeshBasicMaterial(unlit)');
});
+
+ it('emits extrude, tube, and physical-channel construction', () => {
+ const spec = validSpec();
+ spec.parts[0].geometry = validExtrude();
+ spec.parts[0].children[0].geometry = validTube();
+ const source = buildThreejsFactorySource(spec);
+ expect(source).toContain('new THREE.ExtrudeGeometry(shape');
+ expect(source).toContain('shape.holes.push(new THREE.Path(');
+ expect(source).toContain('new THREE.CatmullRomCurve3(');
+ expect(source).toContain('new THREE.TubeGeometry(curve');
+ for (const channel of ['ior', 'transmission', 'thickness', 'sheen', 'iridescence', 'anisotropy']) {
+ expect(source).toContain(`${channel}: definition.${channel},`);
+ }
+ });
});
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index 8f3818d58f..c3857ba482 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -14,7 +14,15 @@ Allowed geometry definitions:
- {"type":"torus","radius":n,"tube":n,"radialSegments":3..64,"tubularSegments":6..128,"arcDegrees":1..360}
- {"type":"capsule","radius":n,"length":n,"capSegments":2..32,"radialSegments":3..64}
- {"type":"lathe","points":[[x,y],...],"segments":3..96}
+- {"type":"extrude","outline":[[x,y],...],"holes":[[[x,y],...],...],"depth":n,"bevelEnabled":false,"bevelThickness":n,"bevelSize":n,"bevelSegments":0..8,"curveSegments":1..24,"steps":1..32} (a closed 2D outline of 3..160 points swept along +Z; \`holes\` are closed rings cut out of it. Every ring must enclose real area and every hole must lie inside the outline.)
+- {"type":"tube","path":[[x,y,z],...],"radius":n,"tubularSegments":2..256,"radialSegments":3..32,"closed":false,"curveType":"centripetal"|"chordal"|"catmullrom","tension":0..1} (a round profile swept along a smooth 2..96 point curve. Consecutive path points must differ, and a closed path must not repeat its first point at the end.)
- {"type":"custom","vertices":[x,y,z,...],"indices":[a,b,c,...]} (triangle mesh; use only when primitives cannot express an identity-defining silhouette)
+
+Choosing between them:
+- extrude — flat or plate-like parts whose identity is their silhouette: badges, logos, letters, signs, panels with cutouts, keyholes, vents, window frames, gears, brackets, star/cross/gem profiles.
+- tube — anything sweeping a constant round section along a path: cables, hoses, wires, handles, pipes, straps, springs, antennae, bent rods, rope, rims.
+- lathe — profiles that are rotationally symmetric about the Y axis.
+- custom triangles — a last resort, only after none of the above can express the silhouette.
`;
const outputContract = `
@@ -33,7 +41,9 @@ Return one raw JSON object and nothing else. It must have exactly this top-level
"color":"#RRGGBB","metalness":0..1,"roughness":0..1,
"emissive":"#RRGGBB","emissiveIntensity":0..20,
"opacity":0..1,"transparent":false,"wireframe":false,
- "clearcoat":0..1,"clearcoatRoughness":0..1
+ "clearcoat":0..1,"clearcoatRoughness":0..1,
+ "ior":1..2.333,"transmission":0..1,"thickness":n,
+ "sheen":0..1,"iridescence":0..1,"anisotropy":0..1
}
},
"lights": [{
@@ -90,16 +100,17 @@ WORKFLOW:
2. Classify the subject as object, character, or hybrid.
3. Inventory every identity-defining visible detail: silhouette, proportions, bevels/rounding, seams, trim, controls, fasteners, facial landmarks, limbs, wear, gloss, emissive regions, and attachment points.
4. Build from a clear parent/child hierarchy. Put moving or attachable pieces in their own named parts. Add sockets for meaningful pivots/attachments.
-5. Use primitive composition first. Use custom triangles only for silhouettes primitives cannot reproduce.
-6. Use physically coherent PBR material channels. Do not use textures, external meshes, URLs, downloaded assets, or JavaScript.
+5. Use primitive composition first, then the schema-backed extrude/tube/lathe forms for silhouettes, cutouts, and swept details. Use custom triangles only when no other allowed form can reproduce the shape.
+6. Use physically coherent PBR material channels. Reach for "physical" with ior/transmission/thickness for glass, gems, liquid, and clear plastic, sheen for cloth and velvet, iridescence for oil-slick/soap-film/pearlescent finishes, and anisotropy for brushed metal or spun discs. Do not use textures, external meshes, URLs, downloaded assets, or JavaScript.
7. Center the subject near the origin, keep dimensions internally consistent, and choose a camera that frames the whole model.
8. Be honest about unseen sides in limitations. Infer conservatively; never claim exact hidden geometry.
-9. Ensure every detailInventory item points to real part ids, every material reference exists, every socket parent exists, all ids are unique, and custom indices are in range.
+9. Ensure every detailInventory item points to real part ids, every material reference exists, every socket parent exists, all ids are unique, custom indices are in range, extrude rings enclose real area with holes inside the outline, and tube paths never repeat a point.
QUALITY GATE:
- A compound subject must not collapse into one primitive.
- Major visible attachments may not float or be omitted.
- Identity-priority details must be represented by actual geometry/material choices.
+- Do not spend custom triangles on a shape extrude, tube, or lathe already expresses.
- Include useful ambient/hemisphere fill plus at least one directional/key light.
- Keep the full hierarchy at 160 parts or fewer.