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(workbench): add the Workbench viewport with view modes and undo, plus in-browser decimate and Taubin smoothing

nirholas89f798d36ec7
diff --git a/src/workbench/mesh-tools.js b/src/workbench/mesh-tools.js
new file mode 100644
index 000000000..f4e2c18a7
--- /dev/null
+++ b/src/workbench/mesh-tools.js
@@ -0,0 +1,285 @@
+// In-browser mesh operations for the Workbench viewport.
+//
+// Both tools work on the live three.js scene, so they run instantly on any GLB
+// the user generated or imported, with no upload and no queue:
+// • decimate : meshoptimizer edge-collapse simplification (the same library
+// the server-side cleanup in api/_lib/glb-cleanup.js uses),
+// followed by a vertex compaction so the export really shrinks.
+// • smooth : Taubin lambda/mu smoothing over position-welded vertices, so
+// UV seams never tear and the mesh does not shrink the way plain
+// Laplacian smoothing does.
+//
+// Generated GLBs arrive meshopt-quantized (Int16/Int8 normalized attributes).
+// Every operation first rewrites the touched geometry to plain Float32 so the
+// math runs on real coordinates; the exporter writes Float32 back out.
+
+import { BufferAttribute } from 'three';
+
+let simplifierPromise = null;
+
+function loadSimplifier() {
+ if (!simplifierPromise) {
+ simplifierPromise = import('meshoptimizer/simplifier').then(async ({ MeshoptSimplifier }) => {
+ await MeshoptSimplifier.ready;
+ return MeshoptSimplifier;
+ });
+ }
+ return simplifierPromise;
+}
+
+/** Every mesh in a scene graph that carries triangle geometry. */
+export function collectMeshes(root) {
+ const meshes = [];
+ root.traverse((o) => {
+ if (o.isMesh && o.geometry?.attributes?.position) meshes.push(o);
+ });
+ return meshes;
+}
+
+/** Triangle and vertex totals for a scene graph. */
+export function countScene(root) {
+ let tris = 0;
+ let verts = 0;
+ for (const m of collectMeshes(root)) {
+ const g = m.geometry;
+ verts += g.attributes.position.count;
+ tris += (g.index ? g.index.count : g.attributes.position.count) / 3;
+ }
+ return { tris: Math.round(tris), verts };
+}
+
+function toFloatAttribute(attr) {
+ const size = attr.itemSize;
+ const out = new Float32Array(attr.count * size);
+ const getters = ['getX', 'getY', 'getZ', 'getW'];
+ for (let i = 0; i < attr.count; i++) {
+ for (let c = 0; c < size; c++) out[i * size + c] = attr[getters[c]](i);
+ }
+ return new BufferAttribute(out, size, false);
+}
+
+/**
+ * Rewrite a geometry so every attribute is a plain, non-interleaved Float32
+ * array (skin indices stay integral) and it carries an explicit Uint32 index.
+ */
+function normalizeGeometry(geometry) {
+ for (const name of Object.keys(geometry.attributes)) {
+ const attr = geometry.attributes[name];
+ if (name === 'skinIndex') {
+ if (attr.isInterleavedBufferAttribute) {
+ const arr = new Uint16Array(attr.count * attr.itemSize);
+ for (let i = 0; i < attr.count; i++) {
+ arr[i * 4] = attr.getX(i);
+ arr[i * 4 + 1] = attr.getY(i);
+ arr[i * 4 + 2] = attr.getZ(i);
+ arr[i * 4 + 3] = attr.getW(i);
+ }
+ geometry.setAttribute(name, new BufferAttribute(arr, attr.itemSize));
+ }
+ continue;
+ }
+ if (attr.isInterleavedBufferAttribute || attr.normalized || !(attr.array instanceof Float32Array)) {
+ geometry.setAttribute(name, toFloatAttribute(attr));
+ }
+ }
+ for (const name of Object.keys(geometry.morphAttributes)) {
+ geometry.morphAttributes[name] = geometry.morphAttributes[name].map((a) =>
+ a.isInterleavedBufferAttribute || a.normalized || !(a.array instanceof Float32Array) ? toFloatAttribute(a) : a,
+ );
+ }
+ const count = geometry.attributes.position.count;
+ const index = new Uint32Array(geometry.index ? geometry.index.count : count);
+ if (geometry.index) for (let i = 0; i < index.length; i++) index[i] = geometry.index.getX(i);
+ else for (let i = 0; i < count; i++) index[i] = i;
+ geometry.setIndex(new BufferAttribute(index, 1));
+ return geometry;
+}
+
+function remapAttribute(attr, remap, unique) {
+ const size = attr.itemSize;
+ const Ctor = attr.array.constructor;
+ const out = new Ctor(unique * size);
+ for (let i = 0; i < remap.length; i++) {
+ const to = remap[i];
+ if (to === 0xffffffff) continue;
+ for (let c = 0; c < size; c++) out[to * size + c] = attr.array[i * size + c];
+ }
+ return new BufferAttribute(out, size, attr.normalized);
+}
+
+/** Drop vertices no triangle references; rewrites the index in place. */
+function compactGeometry(geometry, simplifier, indices) {
+ const [remap, unique] = simplifier.compactMesh(indices);
+ for (const name of Object.keys(geometry.attributes)) {
+ geometry.setAttribute(name, remapAttribute(geometry.attributes[name], remap, unique));
+ }
+ for (const name of Object.keys(geometry.morphAttributes)) {
+ geometry.morphAttributes[name] = geometry.morphAttributes[name].map((a) => remapAttribute(a, remap, unique));
+ }
+ geometry.setIndex(new BufferAttribute(indices, 1));
+ geometry.clearGroups();
+ geometry.computeBoundingBox();
+ geometry.computeBoundingSphere();
+}
+
+/**
+ * Simplify every mesh under `root` to `ratio` of its triangles.
+ * Geometry shared between meshes is simplified once.
+ * @returns {Promise<{before:{tris:number,verts:number}, after:{tris:number,verts:number}}>}
+ */
+export async function decimateScene(root, ratio) {
+ const simplifier = await loadSimplifier();
+ const before = countScene(root);
+ const done = new Set();
+ for (const mesh of collectMeshes(root)) {
+ const g = mesh.geometry;
+ if (done.has(g)) continue;
+ done.add(g);
+ normalizeGeometry(g);
+ const index = g.index.array;
+ if (index.length < 3 * 64) continue;
+ const target = Math.max(3 * 32, Math.floor((index.length * ratio) / 3) * 3);
+ const [simplified] = simplifier.simplify(index, g.attributes.position.array, 3, target, 0.05, []);
+ if (simplified.length >= index.length) continue;
+ compactGeometry(g, simplifier, simplified);
+ if (g.attributes.normal) recomputeWeldedNormals(g, simplifier);
+ }
+ return { before, after: countScene(root) };
+}
+
+/**
+ * Taubin smoothing (lambda = 0.5, mu = -0.53) over position-welded vertices.
+ * @param {number} iterations lambda/mu pairs to apply
+ */
+export async function smoothScene(root, iterations = 4) {
+ const simplifier = await loadSimplifier();
+ const done = new Set();
+ for (const mesh of collectMeshes(root)) {
+ const g = mesh.geometry;
+ if (done.has(g)) continue;
+ done.add(g);
+ normalizeGeometry(g);
+ smoothGeometry(g, simplifier, iterations);
+ }
+ return countScene(root);
+}
+
+function smoothGeometry(geometry, simplifier, iterations) {
+ const pos = geometry.attributes.position.array;
+ const count = pos.length / 3;
+ // Vertices that share a position (UV or normal seams) move together.
+ const canon = simplifier.generatePositionRemap(pos, 3);
+ const index = geometry.index.array;
+
+ // Unique undirected edges between canonical vertices, as CSR adjacency.
+ const degree = new Uint32Array(count);
+ const edgeSet = new Set();
+ const edges = [];
+ const addEdge = (a, b) => {
+ if (a === b) return;
+ const lo = a < b ? a : b;
+ const hi = a < b ? b : a;
+ const key = lo * count + hi;
+ if (edgeSet.has(key)) return;
+ edgeSet.add(key);
+ edges.push(lo, hi);
+ degree[lo]++;
+ degree[hi]++;
+ };
+ for (let t = 0; t < index.length; t += 3) {
+ const a = canon[index[t]];
+ const b = canon[index[t + 1]];
+ const c = canon[index[t + 2]];
+ addEdge(a, b);
+ addEdge(b, c);
+ addEdge(c, a);
+ }
+ const offsets = new Uint32Array(count + 1);
+ for (let i = 0; i < count; i++) offsets[i + 1] = offsets[i] + degree[i];
+ const neighbors = new Uint32Array(offsets[count]);
+ const fill = offsets.slice(0, count);
+ for (let e = 0; e < edges.length; e += 2) {
+ neighbors[fill[edges[e]]++] = edges[e + 1];
+ neighbors[fill[edges[e + 1]]++] = edges[e];
+ }
+
+ const work = Float32Array.from(pos);
+ const next = new Float32Array(pos.length);
+ const step = (factor) => {
+ next.set(work);
+ for (let v = 0; v < count; v++) {
+ const n = offsets[v + 1] - offsets[v];
+ if (n === 0 || canon[v] !== v) continue;
+ let x = 0;
+ let y = 0;
+ let z = 0;
+ for (let k = offsets[v]; k < offsets[v + 1]; k++) {
+ const u = neighbors[k] * 3;
+ x += work[u];
+ y += work[u + 1];
+ z += work[u + 2];
+ }
+ const o = v * 3;
+ next[o] = work[o] + factor * (x / n - work[o]);
+ next[o + 1] = work[o + 1] + factor * (y / n - work[o + 1]);
+ next[o + 2] = work[o + 2] + factor * (z / n - work[o + 2]);
+ }
+ work.set(next);
+ };
+ for (let i = 0; i < iterations; i++) {
+ step(0.5);
+ step(-0.53);
+ }
+ // Seam duplicates take their canonical vertex's new position.
+ for (let v = 0; v < count; v++) {
+ const c = canon[v] * 3;
+ pos[v * 3] = work[c];
+ pos[v * 3 + 1] = work[c + 1];
+ pos[v * 3 + 2] = work[c + 2];
+ }
+ geometry.attributes.position.needsUpdate = true;
+ if (geometry.attributes.normal) recomputeWeldedNormals(geometry, simplifier, canon);
+ geometry.computeBoundingBox();
+ geometry.computeBoundingSphere();
+}
+
+/**
+ * Area-weighted vertex normals summed across every vertex sharing a position,
+ * so UV seams shade continuously instead of showing a hard crease.
+ */
+function recomputeWeldedNormals(geometry, simplifier, canon = null) {
+ const pos = geometry.attributes.position.array;
+ const index = geometry.index.array;
+ const count = pos.length / 3;
+ const map = canon || simplifier.generatePositionRemap(pos, 3);
+ const acc = new Float32Array(count * 3);
+ for (let t = 0; t < index.length; t += 3) {
+ const a = index[t] * 3;
+ const b = index[t + 1] * 3;
+ const c = index[t + 2] * 3;
+ const e1x = pos[b] - pos[a];
+ const e1y = pos[b + 1] - pos[a + 1];
+ const e1z = pos[b + 2] - pos[a + 2];
+ const e2x = pos[c] - pos[a];
+ const e2y = pos[c + 1] - pos[a + 1];
+ const e2z = pos[c + 2] - pos[a + 2];
+ const nx = e1y * e2z - e1z * e2y;
+ const ny = e1z * e2x - e1x * e2z;
+ const nz = e1x * e2y - e1y * e2x;
+ for (const v of [index[t], index[t + 1], index[t + 2]]) {
+ const o = map[v] * 3;
+ acc[o] += nx;
+ acc[o + 1] += ny;
+ acc[o + 2] += nz;
+ }
+ }
+ const normals = new Float32Array(count * 3);
+ for (let v = 0; v < count; v++) {
+ const o = map[v] * 3;
+ const len = Math.hypot(acc[o], acc[o + 1], acc[o + 2]) || 1;
+ normals[v * 3] = acc[o] / len;
+ normals[v * 3 + 1] = acc[o + 1] / len;
+ normals[v * 3 + 2] = acc[o + 2] / len;
+ }
+ geometry.setAttribute('normal', new BufferAttribute(normals, 3));
+}
diff --git a/src/workbench/viewport.js b/src/workbench/viewport.js
new file mode 100644
index 000000000..fecad728b
--- /dev/null
+++ b/src/workbench/viewport.js
@@ -0,0 +1,387 @@
+// The Workbench 3D viewport: renderer, camera, fading floor grid, lighting,
+// view modes (shaded, wireframe, normals, clay), turntable, framing,
+// screenshot, and a bounded undo/redo stack over mesh geometry.
+//
+// three.js and its addons load lazily from mountViewport() so the workflow
+// panel paints before the WebGL bundle arrives.
+
+import { getDecoders } from '../viewer/internal.js';
+import { collectMeshes, countScene } from './mesh-tools.js';
+
+const HISTORY_LIMIT = 6;
+
+const GRID_VERT = /* glsl */ `
+varying vec3 vWorld;
+void main() {
+ vec4 w = modelMatrix * vec4(position, 1.0);
+ vWorld = w.xyz;
+ gl_Position = projectionMatrix * viewMatrix * w;
+}`;
+
+const GRID_FRAG = /* glsl */ `
+uniform vec3 uColor;
+uniform float uMinor;
+uniform float uMajor;
+uniform float uFade;
+varying vec3 vWorld;
+float gridLine(float size) {
+ vec2 c = vWorld.xz / size;
+ vec2 g = abs(fract(c - 0.5) - 0.5) / fwidth(c);
+ return 1.0 - min(min(g.x, g.y), 1.0);
+}
+void main() {
+ float minor = gridLine(uMinor) * 0.35;
+ float major = gridLine(uMajor) * 0.7;
+ float d = length(vWorld.xz - cameraPosition.xz);
+ float fade = 1.0 - smoothstep(uFade * 0.35, uFade, d);
+ float a = max(minor, major) * fade;
+ if (a <= 0.003) discard;
+ gl_FragColor = vec4(uColor, a);
+}`;
+
+export async function mountViewport(container, { onStats, onHistory } = {}) {
+ const [THREE, { OrbitControls }, { GLTFLoader }, { RoomEnvironment }] = await Promise.all([
+ import('three'),
+ import('three/addons/controls/OrbitControls.js'),
+ import('three/addons/loaders/GLTFLoader.js'),
+ import('three/addons/environments/RoomEnvironment.js'),
+ ]);
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: false });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.0;
+ container.appendChild(renderer.domElement);
+ renderer.domElement.setAttribute('aria-label', '3D viewport. Drag to orbit, scroll to zoom, right-drag to pan.');
+ renderer.domElement.setAttribute('role', 'img');
+
+ const scene = new THREE.Scene();
+ const bg = getComputedStyle(container).getPropertyValue('--wb-viewport-bg').trim() || '#17171a';
+ scene.background = new THREE.Color(bg);
+
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const envTexture = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ scene.environment = envTexture;
+ const key = new THREE.DirectionalLight(0xffffff, 1.4);
+ key.position.set(3, 6, 4);
+ scene.add(key, new THREE.HemisphereLight(0xffffff, 0x222233, 0.35));
+
+ const camera = new THREE.PerspectiveCamera(40, 1, 0.01, 1000);
+ camera.position.set(2.6, 1.7, 3.4);
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.08;
+ controls.autoRotateSpeed = 1.6;
+
+ const grid = new THREE.Mesh(
+ new THREE.PlaneGeometry(400, 400).rotateX(-Math.PI / 2),
+ new THREE.ShaderMaterial({
+ vertexShader: GRID_VERT,
+ fragmentShader: GRID_FRAG,
+ transparent: true,
+ depthWrite: false,
+ extensions: { derivatives: true },
+ uniforms: {
+ uColor: { value: new THREE.Color(0x8a8a99) },
+ uMinor: { value: 0.25 },
+ uMajor: { value: 1 },
+ uFade: { value: 18 },
+ },
+ }),
+ );
+ grid.renderOrder = -1;
+ scene.add(grid);
+
+ const stage = new THREE.Group();
+ scene.add(stage);
+
+ let model = null;
+ let mode = 'shaded';
+ let originalMaterials = new Map();
+ const overrideMaterials = {
+ wireframe: new THREE.MeshBasicMaterial({ color: 0xb59cff, wireframe: true }),
+ normals: new THREE.MeshNormalMaterial(),
+ clay: new THREE.MeshStandardMaterial({ color: 0xbdbdc6, roughness: 0.85, metalness: 0 }),
+ };
+ const undoStack = [];
+ const redoStack = [];
+
+ const resize = () => {
+ const w = container.clientWidth || 1;
+ const h = container.clientHeight || 1;
+ renderer.setSize(w, h, false);
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ };
+ const ro = new ResizeObserver(resize);
+ ro.observe(container);
+ resize();
+
+ let running = true;
+ renderer.setAnimationLoop(() => {
+ if (!running) return;
+ controls.update();
+ renderer.render(scene, camera);
+ });
+
+ const emitStats = () => onStats?.(model ? countScene(model) : null);
+ const emitHistory = () => onHistory?.({ canUndo: undoStack.length > 0, canRedo: redoStack.length > 0 });
+
+ function frame() {
+ if (!model) return;
+ const box = new THREE.Box3().setFromObject(model);
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const radius = Math.max(size.length() / 2, 0.001);
+ const dist = radius / Math.sin((camera.fov * Math.PI) / 360);
+ const dir = new THREE.Vector3(0.62, 0.42, 0.66).normalize();
+ controls.target.copy(center);
+ camera.position.copy(center).addScaledVector(dir, dist * 1.05);
+ camera.near = dist / 200;
+ camera.far = dist * 50;
+ camera.updateProjectionMatrix();
+ controls.update();
+ }
+
+ // Normalize any model to stand on the grid at roughly two units tall, so
+ // the grid scale reads the same for a 2 cm scan and a 40 m building.
+ function placeOnGrid(root) {
+ const box = new THREE.Box3().setFromObject(root);
+ const size = box.getSize(new THREE.Vector3());
+ const maxDim = Math.max(size.x, size.y, size.z) || 1;
+ const s = 2 / maxDim;
+ root.scale.multiplyScalar(s);
+ root.updateMatrixWorld(true);
+ const placed = new THREE.Box3().setFromObject(root);
+ const center = placed.getCenter(new THREE.Vector3());
+ root.position.x -= center.x;
+ root.position.z -= center.z;
+ root.position.y -= placed.min.y;
+ }
+
+ function disposeObject(root) {
+ const geos = new Set();
+ const mats = new Set();
+ root.traverse((o) => {
+ if (o.geometry) geos.add(o.geometry);
+ const m = o.material;
+ if (Array.isArray(m)) m.forEach((x) => mats.add(x));
+ else if (m) mats.add(m);
+ });
+ for (const m of originalMaterials.values()) {
+ if (Array.isArray(m)) m.forEach((x) => mats.add(x));
+ else mats.add(m);
+ }
+ geos.forEach((g) => g.dispose());
+ for (const m of mats) {
+ if (Object.values(overrideMaterials).includes(m)) continue;
+ for (const v of Object.values(m)) if (v && v.isTexture) v.dispose();
+ m.dispose();
+ }
+ }
+
+ function clearHistory() {
+ for (const snap of [...undoStack, ...redoStack]) snap.forEach((g) => g.dispose());
+ undoStack.length = 0;
+ redoStack.length = 0;
+ emitHistory();
+ }
+
+ function setModel(root) {
+ if (model) {
+ applyMode('shaded');
+ stage.remove(model);
+ disposeObject(model);
+ }
+ clearHistory();
+ originalMaterials = new Map();
+ model = root;
+ if (root) {
+ placeOnGrid(root);
+ stage.add(root);
+ frame();
+ applyMode(mode);
+ }
+ emitStats();
+ }
+
+ function applyMode(next) {
+ mode = next;
+ if (!model) return;
+ for (const mesh of collectMeshes(model)) {
+ if (!originalMaterials.has(mesh)) originalMaterials.set(mesh, mesh.material);
+ mesh.material = next === 'shaded' ? originalMaterials.get(mesh) : overrideMaterials[next];
+ }
+ }
+
+ async function loadGLB(source) {
+ const { dracoLoader, ktx2Loader, meshoptDecoder } = await getDecoders();
+ const loader = new GLTFLoader()
+ .setDRACOLoader(dracoLoader)
+ .setKTX2Loader(ktx2Loader.detectSupport(renderer))
+ .setMeshoptDecoder(meshoptDecoder);
+ const gltf =
+ typeof source === 'string'
+ ? await loader.loadAsync(source)
+ : await loader.parseAsync(source, '');
+ const root = gltf.scene || gltf.scenes?.[0];
+ if (!root) throw new Error('The file has no scene to display.');
+ setModel(root);
+ return root;
+ }
+
+ async function loadFile(file) {
+ const ext = (file.name.split('.').pop() || '').toLowerCase();
+ const buf = await file.arrayBuffer();
+ if (ext === 'glb' || ext === 'gltf') return loadGLB(buf);
+ let root;
+ if (ext === 'obj') {
+ const { OBJLoader } = await import('three/addons/loaders/OBJLoader.js');
+ root = new OBJLoader().parse(new TextDecoder().decode(buf));
+ } else if (ext === 'stl' || ext === 'ply') {
+ const mod =
+ ext === 'stl'
+ ? new (await import('three/addons/loaders/STLLoader.js')).STLLoader()
+ : new (await import('three/addons/loaders/PLYLoader.js')).PLYLoader();
+ const geometry = mod.parse(buf);
+ if (!geometry.attributes.normal) geometry.computeVertexNormals();
+ const material = new THREE.MeshStandardMaterial({
+ color: 0xc9c9d2,
+ roughness: 0.7,
+ vertexColors: Boolean(geometry.attributes.color),
+ });
+ root = new THREE.Group();
+ root.add(new THREE.Mesh(geometry, material));
+ } else if (ext === 'fbx') {
+ const { FBXLoader } = await import('three/addons/loaders/FBXLoader.js');
+ root = new FBXLoader().parse(buf, '');
+ } else {
+ throw new Error(`Unsupported file type ".${ext}". Use GLB, glTF, OBJ, STL, PLY or FBX.`);
+ }
+ setModel(root);
+ return root;
+ }
+
+ function snapshot() {
+ return new Map(collectMeshes(model).map((m) => [m, m.geometry.clone()]));
+ }
+
+ function restore(snap) {
+ for (const [mesh, geometry] of snap) {
+ mesh.geometry.dispose();
+ mesh.geometry = geometry;
+ }
+ }
+
+ /** Run a geometry-mutating operation with undo support. */
+ async function mutate(op) {
+ if (!model) throw new Error('Load or generate a model first.');
+ const before = snapshot();
+ try {
+ const result = await op(model);
+ undoStack.push(before);
+ while (undoStack.length > HISTORY_LIMIT) undoStack.shift().forEach((g) => g.dispose());
+ for (const snap of redoStack) snap.forEach((g) => g.dispose());
+ redoStack.length = 0;
+ emitHistory();
+ emitStats();
+ return result;
+ } catch (err) {
+ before.forEach((g) => g.dispose());
+ throw err;
+ }
+ }
+
+ function step(from, to) {
+ if (!model || !from.length) return false;
+ to.push(snapshot());
+ restore(from.pop());
+ emitHistory();
+ emitStats();
+ return true;
+ }
+
+ async function exportAs(format) {
+ if (!model) throw new Error('Nothing to export yet.');
+ applyMode('shaded');
+ try {
+ if (format === 'glb') {
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
+ const ab = await new GLTFExporter().parseAsync(model, { binary: true, onlyVisible: true });
+ return new Blob([ab], { type: 'model/gltf-binary' });
+ }
+ if (format === 'obj') {
+ const { OBJExporter } = await import('three/addons/exporters/OBJExporter.js');
+ return new Blob([new OBJExporter().parse(model)], { type: 'text/plain' });
+ }
+ if (format === 'stl') {
+ const { STLExporter } = await import('three/addons/exporters/STLExporter.js');
+ return new Blob([new STLExporter().parse(model, { binary: true })], { type: 'model/stl' });
+ }
+ if (format === 'ply') {
+ const { PLYExporter } = await import('three/addons/exporters/PLYExporter.js');
+ const ab = await new Promise((resolve) =>
+ new PLYExporter().parse(model, resolve, { binary: true }),
+ );
+ return new Blob([ab], { type: 'application/octet-stream' });
+ }
+ throw new Error(`Unknown export format ${format}`);
+ } finally {
+ applyMode(mode);
+ }
+ }
+
+ function screenshot() {
+ renderer.render(scene, camera);
+ return new Promise((resolve) => renderer.domElement.toBlob(resolve, 'image/png'));
+ }
+
+ return {
+ THREE,
+ get model() {
+ return model;
+ },
+ get mode() {
+ return mode;
+ },
+ loadGLB,
+ loadFile,
+ setModel,
+ setMode: applyMode,
+ frame,
+ mutate,
+ undo: () => step(undoStack, redoStack),
+ redo: () => step(redoStack, undoStack),
+ exportAs,
+ screenshot,
+ setGrid: (on) => (grid.visible = on),
+ get gridVisible() {
+ return grid.visible;
+ },
+ setEnvironment: (on) => {
+ scene.environment = on ? envTexture : null;
+ },
+ get environmentOn() {
+ return scene.environment !== null;
+ },
+ setAutoRotate: (on) => (controls.autoRotate = on),
+ get autoRotate() {
+ return controls.autoRotate;
+ },
+ /** Drop the model, its history and its GPU buffers. */
+ free() {
+ setModel(null);
+ renderer.renderLists.dispose();
+ },
+ destroy() {
+ running = false;
+ renderer.setAnimationLoop(null);
+ ro.disconnect();
+ if (model) disposeObject(model);
+ pmrem.dispose();
+ envTexture.dispose();
+ renderer.dispose();
+ },
+ };
+}