scadify 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.js ADDED
@@ -0,0 +1,97 @@
1
+ // openscad-wasm-prebuilt wrapper: recipe -> mesh. A fresh WASM instance per part keeps compiles hermetic.
2
+ import { createHash } from 'node:crypto';
3
+ import { createOpenSCAD } from 'openscad-wasm-prebuilt';
4
+ import { toScadParts, defineArgs, declareHeader, partTint, recipeHash } from './recipe.js';
5
+
6
+ const cache = new Map();
7
+
8
+ async function compilePart(source, defs) {
9
+ const log = [];
10
+ const o = await createOpenSCAD({ print: (t) => log.push(t), printErr: (t) => log.push(t) });
11
+ const inst = o.getInstance();
12
+ inst.FS.writeFile('/in.scad', source);
13
+ let code = 0;
14
+ try {
15
+ code = inst.callMain(['/in.scad', '--backend=manifold', ...defs, '-o', '/out.stl']);
16
+ } catch (e) {
17
+ code = typeof e?.status === 'number' ? e.status : 1;
18
+ log.push(String(e?.message ?? e));
19
+ }
20
+ let off = null;
21
+ try { off = inst.FS.readFile('/out.stl', { encoding: 'utf8' }); } catch { /* not produced */ }
22
+ if (code !== 0 || !off) {
23
+ const msg = log.filter((l) => /ERROR|error|Parser/.test(l)).join('\n') || log.slice(-5).join('\n');
24
+ throw new Error(`openscad failed: ${msg || 'no output (empty geometry?)'}`);
25
+ }
26
+ return parseStl(off);
27
+ }
28
+
29
+ // ASCII STL (always triangles; OFF can carry concave polygons). Vertices are welded by exact printed value.
30
+ function parseStl(text) {
31
+ const pos = []; const idx = []; const seen = new Map();
32
+ const re = /vertex\s+(\S+)\s+(\S+)\s+(\S+)/g; let m; let corner = 0; const tri = [];
33
+ while ((m = re.exec(text))) {
34
+ const key = `${m[1]} ${m[2]} ${m[3]}`;
35
+ let i = seen.get(key);
36
+ if (i === undefined) { i = pos.length / 3; seen.set(key, i); pos.push(+m[1], +m[2], +m[3]); }
37
+ tri.push(i);
38
+ if (++corner === 3) { corner = 0; if (tri[0] !== tri[1] && tri[1] !== tri[2] && tri[0] !== tri[2]) idx.push(...tri); tri.length = 0; }
39
+ }
40
+ if (!idx.length) throw new Error('empty geometry');
41
+ return { positions: Float32Array.from(pos), indices: Uint32Array.from(idx) };
42
+ }
43
+
44
+ /** Compile a normalized recipe -> { parts:[{name,tint,positions,indices}], checksum }. */
45
+ export async function compile(recipe) {
46
+ const key = recipeHash(recipe);
47
+ if (cache.has(key)) return cache.get(key);
48
+ const { program, partCode } = toScadParts(recipe);
49
+ const defs = defineArgs(recipe);
50
+ const parts = [];
51
+ for (const name of Object.keys(recipe.parts)) {
52
+ const m = await compilePart(`${declareHeader(recipe)}\n${program}\n${partCode[name]}\n`, defs);
53
+ parts.push({ name, tint: partTint(recipe, name), ...m });
54
+ }
55
+ const mesh = { parts, checksum: meshChecksum(parts) };
56
+ cache.set(key, mesh);
57
+ return mesh;
58
+ }
59
+
60
+ export function meshChecksum(parts) {
61
+ const h = createHash('sha256');
62
+ for (const p of parts) {
63
+ h.update(p.name);
64
+ h.update(Buffer.from(p.positions.buffer, p.positions.byteOffset, p.positions.byteLength));
65
+ h.update(Buffer.from(p.indices.buffer, p.indices.byteOffset, p.indices.byteLength));
66
+ }
67
+ return h.digest('hex');
68
+ }
69
+
70
+ export function measure(mesh) {
71
+ const total = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
72
+ let volume = 0, area = 0, tris = 0;
73
+ const parts = mesh.parts.map((p) => {
74
+ const bb = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
75
+ const P = p.positions;
76
+ for (let i = 0; i < P.length; i += 3) for (let a = 0; a < 3; a++) {
77
+ bb.min[a] = Math.min(bb.min[a], P[i + a]); bb.max[a] = Math.max(bb.max[a], P[i + a]);
78
+ }
79
+ let v = 0, ar = 0;
80
+ for (let t = 0; t < p.indices.length; t += 3) {
81
+ const a = p.indices[t] * 3, b = p.indices[t + 1] * 3, c = p.indices[t + 2] * 3;
82
+ const ux = P[b] - P[a], uy = P[b + 1] - P[a + 1], uz = P[b + 2] - P[a + 2];
83
+ const vx = P[c] - P[a], vy = P[c + 1] - P[a + 1], vz = P[c + 2] - P[a + 2];
84
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
85
+ ar += Math.hypot(nx, ny, nz) / 2;
86
+ v += (P[a] * (P[b + 1] * P[c + 2] - P[b + 2] * P[c + 1]) - P[a + 1] * (P[b] * P[c + 2] - P[b + 2] * P[c]) + P[a + 2] * (P[b] * P[c + 1] - P[b + 1] * P[c])) / 6;
87
+ }
88
+ for (let a = 0; a < 3; a++) { total.min[a] = Math.min(total.min[a], bb.min[a]); total.max[a] = Math.max(total.max[a], bb.max[a]); }
89
+ volume += v; area += ar; tris += p.indices.length / 3;
90
+ return { name: p.name, bbox: { min: bb.min.map(round), max: bb.max.map(round) }, volume_mm3: round(v), triangles: p.indices.length / 3 };
91
+ });
92
+ return {
93
+ bbox: { min: total.min.map(round), max: total.max.map(round) }, size: total.max.map((m, i) => round(m - total.min[i])),
94
+ volume_mm3: round(volume), surface_area_mm2: round(area), triangles: tris, parts, checksum: mesh.checksum,
95
+ };
96
+ }
97
+ const round = (x) => Math.round(x * 1e4) / 1e4;
package/src/mcp.js ADDED
@@ -0,0 +1,128 @@
1
+ // Hand-rolled stdio MCP server (newline-delimited JSON-RPC 2.0). No SDK.
2
+ import { writeFileSync, mkdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ import { createInterface } from 'node:readline';
6
+ import { Store, defaultOutDir, checkRef } from './store.js';
7
+ import { compile, measure } from './engine.js';
8
+ import { emitGLB, emitGLTF } from './emitters/glb.js';
9
+ import { emitSTL } from './emitters/stl.js';
10
+ import { emit3MF } from './emitters/threemf.js';
11
+ import { emitUSDA, emitUSDZ } from './emitters/usd.js';
12
+ import { emitSCAD } from './emitters/scad.js';
13
+ import { renderTurntable, renderFrame, renderStandard, encodePNG, parseBackground, STUDIO_BG, STANDARD_PANELS } from './raster.js';
14
+ import { canonical } from './recipe.js';
15
+
16
+ const VERSION = '0.1.0';
17
+ export const FORMATS = {
18
+ glb: emitGLB, gltf: emitGLTF, stl: emitSTL, '3mf': emit3MF, usdz: emitUSDZ, usda: emitUSDA, scad: emitSCAD,
19
+ json: (recipe) => JSON.stringify(JSON.parse(canonical(recipe)), null, 2) + '\n',
20
+ };
21
+
22
+ const recipeSchema = {
23
+ type: 'object', description: 'Recipe: {kind:"scad"|"csg", title, units:"mm|cm|dm|m" (default dm), seed, params, program+parts (scad) | tree/parts (csg), tints}',
24
+ properties: { kind: { enum: ['scad', 'csg'] }, title: { type: 'string' }, units: { enum: ['mm', 'cm', 'dm', 'm'] }, seed: { type: 'integer' }, program: { type: 'string' }, parts: { type: 'object' }, tree: { type: 'object' }, params: { type: 'object' }, tints: { type: 'object' } },
25
+ };
26
+ const refProp = { ref: { type: 'string', description: 'Solid ref returned by mint_solid' } };
27
+
28
+ export const TOOLS = [
29
+ { name: 'mint_solid', description: 'Store a recipe (the source of truth; meshes are never stored). Returns { ref }.', inputSchema: { type: 'object', properties: { recipe: recipeSchema }, required: ['recipe'] } },
30
+ { name: 'list_solids', description: 'List stored solid refs and titles.', inputSchema: { type: 'object', properties: {} } },
31
+ { name: 'get_solid', description: 'Return the stored recipe JSON.', inputSchema: { type: 'object', properties: refProp, required: ['ref'] } },
32
+ { name: 'update_solid', description: 'Edit a stored recipe in place: params merge; program/parts/tree/title/seed/tints replace.', inputSchema: { type: 'object', properties: { ...refProp, params: { type: 'object' }, program: { type: 'string' }, parts: { type: 'object' }, tree: { type: 'object' }, title: { type: 'string' }, seed: { type: 'integer' }, tints: { type: 'object' } }, required: ['ref'] } },
33
+ { name: 'export_solid', description: 'Compile deterministically and write a file. Returns { path, format, sizeBytes, sha256, ref }.', inputSchema: { type: 'object', properties: { ...refProp, format: { enum: Object.keys(FORMATS) } }, required: ['ref', 'format'] } },
34
+ { name: 'render_turntable', description: 'Render 3-36 turntable PNG frames in-process (software rasterizer). Returns frame paths.', inputSchema: { type: 'object', properties: { ...refProp, frames: { type: 'integer', minimum: 3, maximum: 36 }, size: { type: 'integer', minimum: 32, maximum: 1024 }, elevation_deg: { type: 'number' } }, required: ['ref'] } },
35
+ { name: 'render_shot', description: 'Render exactly one PNG from a chosen azimuth + elevation (software rasterizer). angle_deg 0 = the model front (-y); positive turns the camera around +z. Returns { path, size }.', inputSchema: { type: 'object', properties: { ...refProp, angle_deg: { type: 'number' }, elevation_deg: { type: 'number', minimum: -89, maximum: 89 }, size: { type: 'integer', minimum: 32, maximum: 1024 }, background: { type: 'string', description: "#rrggbb or 'transparent' (default #0C1019)" } }, required: ['ref'] } },
36
+ { name: 'render_standard', description: 'Standard preview: one square PNG with a front-on shot (left) and an angled-high shot (right) side by side on the studio background. Returns { path, size, panels }.', inputSchema: { type: 'object', properties: { ...refProp, size: { type: 'integer', minimum: 64, maximum: 2048 }, background: { type: 'string', description: "#rrggbb or 'transparent' (default #0C1019)" } }, required: ['ref'] } },
37
+ { name: 'measure_solid', description: 'Bounding box, volume, area and mesh checksum of the compiled solid (determinism gate).', inputSchema: { type: 'object', properties: refProp, required: ['ref'] } },
38
+ ];
39
+
40
+ const sha = (b) => createHash('sha256').update(b).digest('hex');
41
+
42
+ export function makeHandlers({ store = new Store(), outDir = defaultOutDir() } = {}) {
43
+ const load = async (ref) => { const recipe = store.get(checkRef(ref)); return { recipe, mesh: await compile(recipe) }; };
44
+ return {
45
+ async mint_solid({ recipe }) { const m = store.mint(recipe); return { ref: m.ref, title: m.recipe.title }; },
46
+ async list_solids() { return { solids: store.list() }; },
47
+ async get_solid({ ref }) { return store.get(checkRef(ref)); },
48
+ async update_solid({ ref, ...patch }) { return { ref, recipe: store.update(checkRef(ref), patch) }; },
49
+ async export_solid({ ref, format }) {
50
+ const emit = FORMATS[format]; if (!emit) throw new Error(`unknown format: ${format} (use ${Object.keys(FORMATS).join('|')})`);
51
+ checkRef(ref);
52
+ const recipe = store.get(ref);
53
+ const data = format === 'json' || format === 'scad' ? emit(recipe) : emit(recipe, (await compile(recipe)));
54
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
55
+ mkdirSync(outDir, { recursive: true });
56
+ const path = join(outDir, `${ref}.${format}`);
57
+ writeFileSync(path, buf);
58
+ return { path, format, sizeBytes: buf.length, sha256: sha(buf), ref };
59
+ },
60
+ async render_turntable({ ref, frames = 8, size = 256, elevation_deg = 25 }) {
61
+ if (!Number.isInteger(frames) || frames < 3 || frames > 36) throw new Error('frames must be an integer 3..36');
62
+ if (!Number.isInteger(size) || size < 32 || size > 1024) throw new Error('size must be an integer 32..1024');
63
+ const { mesh } = await load(ref);
64
+ const pngs = renderTurntable(mesh, { frames, size, elevation: (elevation_deg * Math.PI) / 180 });
65
+ const dir = join(outDir, `${ref}-turntable`); mkdirSync(dir, { recursive: true });
66
+ const paths = pngs.map((b, i) => { const p = join(dir, `frame-${String(i).padStart(2, '0')}.png`); writeFileSync(p, b); return p; });
67
+ return { ref, frames: paths.length, size, paths };
68
+ },
69
+ async render_shot({ ref, angle_deg = 0, elevation_deg = 26, size = 512, background = STUDIO_BG }) {
70
+ if (!Number.isFinite(angle_deg)) throw new Error('angle_deg must be a number');
71
+ if (!Number.isFinite(elevation_deg) || Math.abs(elevation_deg) > 89) throw new Error('elevation_deg must be within -89..89');
72
+ if (!Number.isInteger(size) || size < 32 || size > 1024) throw new Error('size must be an integer 32..1024');
73
+ const { mesh } = await load(ref);
74
+ const rad = Math.PI / 180;
75
+ const png = encodePNG(size, size, renderFrame(mesh, { size, angle: angle_deg * rad, elevation: elevation_deg * rad, background: parseBackground(background) }));
76
+ mkdirSync(outDir, { recursive: true });
77
+ const path = join(outDir, `${ref}-shot-${angle_deg}-${elevation_deg}.png`);
78
+ writeFileSync(path, png);
79
+ return { path, size };
80
+ },
81
+ async render_standard({ ref, size = 1024, background = STUDIO_BG }) {
82
+ if (!Number.isInteger(size) || size < 64 || size > 2048) throw new Error('size must be an integer 64..2048');
83
+ const bg = parseBackground(background);
84
+ const { mesh } = await load(ref);
85
+ mkdirSync(outDir, { recursive: true });
86
+ const path = join(outDir, `${ref}-standard.png`);
87
+ writeFileSync(path, renderStandard(mesh, { size, background: bg }));
88
+ const d = (k) => `angle_deg=${STANDARD_PANELS[k].angle_deg} elevation_deg=${STANDARD_PANELS[k].elevation_deg}`;
89
+ return { path, size, panels: { front: `front-on ${d('front')}`, high: `angled-high ${d('high')}` } };
90
+ },
91
+ async measure_solid({ ref }) { return measure((await load(ref)).mesh); },
92
+ };
93
+ }
94
+
95
+ export async function callTool(handlers, name, args) {
96
+ if (!Object.hasOwn(handlers, name)) throw new Error(`unknown tool: ${name}`);
97
+ return handlers[name](args ?? {});
98
+ }
99
+
100
+ export function serve({ input = process.stdin, output = process.stdout, handlers = makeHandlers() } = {}) {
101
+ const send = (m) => output.write(JSON.stringify(m) + '\n');
102
+ const ok = (id, result) => send({ jsonrpc: '2.0', id, result });
103
+ const err = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } });
104
+ const rl = createInterface({ input });
105
+ let chain = Promise.resolve(); // handle messages in order (WASM compiles are heavy; keep it simple)
106
+ rl.on('line', (line) => { if (line.trim()) chain = chain.then(() => handle(line)).catch(() => {}); });
107
+ async function handle(line) {
108
+ let msg;
109
+ try { msg = JSON.parse(line); } catch { return err(null, -32700, 'parse error'); }
110
+ const { id, method, params } = msg;
111
+ const isNote = id === undefined;
112
+ if (typeof method !== 'string') return isNote ? undefined : err(id, -32600, 'invalid request');
113
+ switch (method) {
114
+ case 'initialize': return ok(id, { protocolVersion: params?.protocolVersion ?? '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'scadify', version: VERSION } });
115
+ case 'ping': return ok(id, {});
116
+ case 'tools/list': return ok(id, { tools: TOOLS });
117
+ case 'tools/call':
118
+ try {
119
+ const result = await callTool(handlers, params?.name, params?.arguments);
120
+ return ok(id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: result, isError: false });
121
+ } catch (e) {
122
+ return ok(id, { content: [{ type: 'text', text: String(e?.message ?? e) }], isError: true });
123
+ }
124
+ default: if (!isNote) return err(id, -32601, `method not found: ${method}`);
125
+ }
126
+ }
127
+ return new Promise((res) => rl.on('close', () => chain.then(res)));
128
+ }
package/src/raster.js ADDED
@@ -0,0 +1,136 @@
1
+ // Software turntable rasterizer + PNG encoder. Orthographic, z-buffer, flat lambert, flat studio background (or transparent), 2x2 SSAA.
2
+ import { deflateSync } from 'node:zlib';
3
+ import { crc32 } from './emitters/zip.js';
4
+
5
+ export function encodePNG(w, h, rgba) {
6
+ const raw = Buffer.alloc((w * 4 + 1) * h);
7
+ for (let y = 0; y < h; y++) { raw[y * (w * 4 + 1)] = 0; rgba.copy(raw, y * (w * 4 + 1) + 1, y * w * 4, (y + 1) * w * 4); }
8
+ const chunk = (type, data) => {
9
+ const b = Buffer.alloc(12 + data.length); b.writeUInt32BE(data.length, 0); b.write(type, 4, 'latin1'); data.copy(b, 8);
10
+ b.writeUInt32BE(crc32(b.subarray(4, 8 + data.length)), 8 + data.length); return b;
11
+ };
12
+ const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 6;
13
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
14
+ }
15
+
16
+ export function decodePNGHeader(buf) { return { w: buf.readUInt32BE(16), h: buf.readUInt32BE(20), sig: buf.subarray(0, 8).toString('hex') }; }
17
+
18
+ const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
19
+
20
+ export const STUDIO_BG = '#0C1019'; // flat studio background, measured from the reference image: rgb(12,16,25)
21
+
22
+ /** Normalize a background option: hex '#rrggbb' -> hex; null / 'transparent' -> null (alpha 0 where nothing is drawn). */
23
+ export function parseBackground(bg) {
24
+ if (bg === null || bg === 'transparent') return null;
25
+ if (typeof bg === 'string' && /^#[0-9a-fA-F]{6}$/.test(bg)) return bg;
26
+ throw new Error('background must be a #rrggbb hex string, "transparent" or null');
27
+ }
28
+
29
+ /** Render one frame. angle in radians about +z; elevation in radians. Returns RGBA Buffer (size*size*4).
30
+ * background: '#rrggbb' (default STUDIO_BG, opaque PNG) or null for a transparent background. */
31
+ export function renderFrame(mesh, { size = 256, angle = 0, elevation = 0.45, ssaa = 2, background = STUDIO_BG, zoom = 1 } = {}) {
32
+ const bg = parseBackground(background); const [br, bgc, bb] = bg ? rgb(bg) : [0, 0, 0];
33
+ const S = size * ssaa;
34
+ const color = new Uint8Array(S * S * 4); const depth = new Float32Array(S * S).fill(Infinity);
35
+ // bounds -> center + radius
36
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
37
+ for (const p of mesh.parts) for (let i = 0; i < p.positions.length; i += 3) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], p.positions[i + a]); hi[a] = Math.max(hi[a], p.positions[i + a]); }
38
+ const c = lo.map((v, i) => (v + hi[i]) / 2);
39
+ const r = Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) / 2 || 1;
40
+ const ca = Math.cos(angle), sa = Math.sin(angle), ce = Math.cos(elevation), se = Math.sin(elevation);
41
+ // world(z-up) -> view: rotate about z by -angle, then tilt about x by elevation; view x right, y up, z toward camera
42
+ const toView = (x, y, z) => {
43
+ const rx = x * ca + y * sa, ry = -x * sa + y * ca;
44
+ return [rx, z * ce + ry * se, z * se - ry * ce]; // camera above, on the -y side looking +y; view z points at the camera
45
+ };
46
+ const scale = ((S * 0.46) / r) * zoom;
47
+ const L = norm([-0.4, -0.5, 0.75]); // key light, view space
48
+ for (const p of mesh.parts) {
49
+ const [pr, pg, pb] = rgb(p.tint); const P = p.positions; const V = new Float32Array(P.length);
50
+ for (let i = 0; i < P.length; i += 3) {
51
+ const [vx, vy, vz] = toView(P[i] - c[0], P[i + 1] - c[1], P[i + 2] - c[2]);
52
+ V[i] = S / 2 + vx * scale; V[i + 1] = S / 2 - vy * scale; V[i + 2] = vz;
53
+ }
54
+ for (let t = 0; t < p.indices.length; t += 3) {
55
+ const a = p.indices[t] * 3, b = p.indices[t + 1] * 3, d = p.indices[t + 2] * 3;
56
+ const ux = V[b] - V[a], uy = V[b + 1] - V[a + 1], vx = V[d] - V[a], vy = V[d + 1] - V[a + 1];
57
+ const area = ux * vy - uy * vx; // screen space (y down): CCW front faces have negative area
58
+ if (area === 0) continue;
59
+ // view-space normal from 3D positions (y up)
60
+ const A = [V[a], -V[a + 1], V[a + 2]], B = [V[b], -V[b + 1], V[b + 2]], D = [V[d], -V[d + 1], V[d + 2]];
61
+ let n = norm(cross(sub(B, A), sub(D, A)));
62
+ if (n[2] < 0) n = [-n[0], -n[1], -n[2]]; // two-sided: light the face we see
63
+ const k = 0.28 + 0.72 * Math.max(0, dot(n, L));
64
+ const cr = Math.min(255, pr * k) | 0, cg = Math.min(255, pg * k) | 0, cb = Math.min(255, pb * k) | 0;
65
+ const minx = Math.max(0, Math.floor(Math.min(V[a], V[b], V[d]))), maxx = Math.min(S - 1, Math.ceil(Math.max(V[a], V[b], V[d])));
66
+ const miny = Math.max(0, Math.floor(Math.min(V[a + 1], V[b + 1], V[d + 1]))), maxy = Math.min(S - 1, Math.ceil(Math.max(V[a + 1], V[b + 1], V[d + 1])));
67
+ const inv = 1 / area;
68
+ for (let y = miny; y <= maxy; y++) for (let x = minx; x <= maxx; x++) {
69
+ const px = x + 0.5 - V[a], py = y + 0.5 - V[a + 1];
70
+ const w1 = (px * vy - py * vx) * inv, w2 = (ux * py - uy * px) * inv, w0 = 1 - w1 - w2;
71
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;
72
+ const z = -(w0 * V[a + 2] + w1 * V[b + 2] + w2 * V[d + 2]); // smaller = nearer
73
+ const o = y * S + x;
74
+ if (z < depth[o]) { depth[o] = z; color[o * 4] = cr; color[o * 4 + 1] = cg; color[o * 4 + 2] = cb; color[o * 4 + 3] = 255; }
75
+ }
76
+ }
77
+ }
78
+ // downsample (premultiplied average)
79
+ const out = Buffer.alloc(size * size * 4); const n2 = ssaa * ssaa;
80
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
81
+ let R = 0, G = 0, B = 0, A = 0;
82
+ for (let sy = 0; sy < ssaa; sy++) for (let sx = 0; sx < ssaa; sx++) { const o = ((y * ssaa + sy) * S + x * ssaa + sx) * 4; const al = color[o + 3]; R += color[o] * al; G += color[o + 1] * al; B += color[o + 2] * al; A += al; }
83
+ const o = (y * size + x) * 4;
84
+ if (A) {
85
+ const cov = A / (255 * n2); // geometry coverage of this pixel; the rest is background
86
+ out[o] = Math.round((R / A) * cov + br * (1 - cov)); out[o + 1] = Math.round((G / A) * cov + bgc * (1 - cov)); out[o + 2] = Math.round((B / A) * cov + bb * (1 - cov));
87
+ out[o + 3] = bg ? 255 : Math.round(A / n2);
88
+ } else if (bg) { out[o] = br; out[o + 1] = bgc; out[o + 2] = bb; out[o + 3] = 255; }
89
+ }
90
+ return out;
91
+ }
92
+
93
+ export function renderTurntable(mesh, { frames = 8, size = 256, elevation = 0.45 } = {}) {
94
+ const out = [];
95
+ for (let i = 0; i < frames; i++) {
96
+ const rgba = renderFrame(mesh, { size, elevation, angle: (i / frames) * Math.PI * 2, background: null }); // turntable stays transparent
97
+ out.push(encodePNG(size, size, rgba));
98
+ }
99
+ return out;
100
+ }
101
+
102
+ /** Standard preview: front-on (0 deg, 8 deg up) left, angled-high (30 deg, 32 deg up) right, one square PNG.
103
+ * Each panel is a square render (zoomed so the model's projected bbox fills it) sized to its half of the canvas, centred vertically. */
104
+ export const STANDARD_PANELS = { front: { angle_deg: 0, elevation_deg: 8 }, high: { angle_deg: 30, elevation_deg: 32 } };
105
+ /** zoom that makes the model's bbox (all 8 corners, projected from this camera) fill a panel; bbox is symmetric about its centre, so the view stays centred. */
106
+ function bboxZoom(mesh, angle, elevation) {
107
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
108
+ for (const p of mesh.parts) for (let i = 0; i < p.positions.length; i += 3) for (let a = 0; a < 3; a++) { lo[a] = Math.min(lo[a], p.positions[i + a]); hi[a] = Math.max(hi[a], p.positions[i + a]); }
109
+ const hx = (hi[0] - lo[0]) / 2, hy = (hi[1] - lo[1]) / 2, hz = (hi[2] - lo[2]) / 2;
110
+ const r = Math.hypot(hx, hy, hz) || 1; const ca = Math.cos(angle), sa = Math.sin(angle), ce = Math.cos(elevation), se = Math.sin(elevation);
111
+ let ex = 0, ey = 0;
112
+ for (const sx of [-1, 1]) for (const sy of [-1, 1]) for (const sz of [-1, 1]) {
113
+ const x = sx * hx, y = sy * hy, z = sz * hz; const rx = x * ca + y * sa, ry = -x * sa + y * ca;
114
+ ex = Math.max(ex, Math.abs(rx)); ey = Math.max(ey, Math.abs(z * ce + ry * se));
115
+ }
116
+ return r / (Math.max(ex, ey) || r);
117
+ }
118
+
119
+ export function renderStandard(mesh, { size = 1024, background = STUDIO_BG } = {}) {
120
+ const bg = parseBackground(background); const gap = Math.max(2, Math.round(size * 0.02));
121
+ const pw = Math.floor((size - gap) / 2); const x0 = Math.floor((size - (2 * pw + gap)) / 2); const y0 = Math.floor((size - pw) / 2);
122
+ const canvas = Buffer.alloc(size * size * 4);
123
+ if (bg) { const [r, g, b] = rgb(bg); for (let i = 0; i < size * size; i++) { canvas[i * 4] = r; canvas[i * 4 + 1] = g; canvas[i * 4 + 2] = b; canvas[i * 4 + 3] = 255; } }
124
+ [['front', x0], ['high', x0 + pw + gap]].forEach(([k, x]) => {
125
+ const { angle_deg, elevation_deg } = STANDARD_PANELS[k];
126
+ const angle = (angle_deg * Math.PI) / 180, elevation = (elevation_deg * Math.PI) / 180;
127
+ const f = renderFrame(mesh, { size: pw, angle, elevation, background: bg, zoom: bboxZoom(mesh, angle, elevation) });
128
+ for (let row = 0; row < pw; row++) f.copy(canvas, ((y0 + row) * size + x) * 4, row * pw * 4, (row + 1) * pw * 4);
129
+ });
130
+ return encodePNG(size, size, canvas);
131
+ }
132
+
133
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
134
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
135
+ 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]];
136
+ function norm(v) { const l = Math.hypot(...v) || 1; return [v[0] / l, v[1] / l, v[2] / l]; }
package/src/recipe.js ADDED
@@ -0,0 +1,186 @@
1
+ // Recipe parse / validate / normalize / csg->scad transpile. Pure, no I/O.
2
+ import { createHash } from 'node:crypto';
3
+
4
+ const KINDS = ['scad', 'csg'];
5
+ /** Recipe length unit -> metres per unit. Coordinates in a recipe are in this unit; the default is architectural (1 unit = 10 cm). */
6
+ export const UNIT = { mm: 0.001, cm: 0.01, dm: 0.1, m: 1 };
7
+ export const DEFAULT_UNITS = 'dm';
8
+ export const metersPerUnit = (recipe) => UNIT[recipe.units];
9
+ const NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
10
+ const PARAM_RE = /^\$?[A-Za-z_][A-Za-z0-9_]*$/;
11
+ const HEX_RE = /^#[0-9a-fA-F]{6}$/;
12
+ const PALETTE = ['#c8ccd0', '#d9822b', '#3f8fd2', '#5fae5f', '#c0504d', '#8e6fc1', '#d8c24a', '#4bb3a8'];
13
+ const MAX_NODES = 2000;
14
+ const MAX_DEPTH = 64;
15
+
16
+ export class RecipeError extends Error {}
17
+ const fail = (m) => { throw new RecipeError(m); };
18
+
19
+ export function slug(s) {
20
+ return String(s || 'solid').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'solid';
21
+ }
22
+
23
+ function checkParams(params) {
24
+ if (params === undefined) return {};
25
+ if (!params || typeof params !== 'object' || Array.isArray(params)) fail('params must be an object');
26
+ const out = {};
27
+ for (const k of Object.keys(params).sort()) {
28
+ if (!PARAM_RE.test(k)) fail(`bad param name: ${k}`);
29
+ const v = params[k];
30
+ const ok = (x) => typeof x === 'string' || typeof x === 'boolean' || (typeof x === 'number' && Number.isFinite(x));
31
+ if (!(ok(v) || (Array.isArray(v) && v.every((e) => ok(e) || (Array.isArray(e) && e.every(ok)))))) fail(`param ${k}: unsupported value`);
32
+ out[k] = v;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Validate + normalize into a canonical recipe (sorted keys for stable bytes). Throws RecipeError. */
38
+ export function normalize(input) {
39
+ if (!input || typeof input !== 'object' || Array.isArray(input)) fail('recipe must be an object');
40
+ const kind = input.kind ?? 'scad';
41
+ if (!KINDS.includes(kind)) fail(`kind must be one of ${KINDS.join('|')}`);
42
+ const units = input.units ?? DEFAULT_UNITS;
43
+ if (typeof units !== 'string' || !Object.hasOwn(UNIT, units)) fail(`units must be one of ${Object.keys(UNIT).join('|')}`);
44
+ const seed = input.seed ?? 0;
45
+ if (!Number.isInteger(seed)) fail('seed must be an integer');
46
+ const title = String(input.title ?? 'untitled').slice(0, 120);
47
+ const r = { kind, title, units, seed, params: checkParams(input.params) };
48
+
49
+ let parts = input.parts;
50
+ if (kind === 'scad') {
51
+ if (typeof input.program !== 'string') fail('kind "scad" needs a string "program"');
52
+ r.program = input.program;
53
+ if (parts === undefined) parts = { solid: '' }; // program's own top-level geometry
54
+ if (!parts || typeof parts !== 'object' || Array.isArray(parts)) fail('parts must be an object name -> scad statement');
55
+ r.parts = {};
56
+ for (const k of Object.keys(parts)) {
57
+ if (!NAME_RE.test(k)) fail(`bad part name: ${k}`);
58
+ if (typeof parts[k] !== 'string') fail(`part ${k}: must be a string of scad`);
59
+ r.parts[k] = terminate(parts[k]);
60
+ }
61
+ } else {
62
+ if (parts === undefined && input.tree) parts = { solid: input.tree };
63
+ if (!parts || typeof parts !== 'object' || Array.isArray(parts)) fail('kind "csg" needs "tree" or "parts" (name -> node)');
64
+ r.parts = {};
65
+ const budget = { n: 0 };
66
+ for (const k of Object.keys(parts)) {
67
+ if (!NAME_RE.test(k)) fail(`bad part name: ${k}`);
68
+ checkNode(parts[k], 0, budget);
69
+ r.parts[k] = parts[k];
70
+ }
71
+ }
72
+ if (!Object.keys(r.parts).length) fail('recipe needs at least one part');
73
+ if (input.tints !== undefined) {
74
+ if (!input.tints || typeof input.tints !== 'object') fail('tints must be an object');
75
+ r.tints = {};
76
+ for (const k of Object.keys(input.tints)) {
77
+ if (!(k in r.parts)) fail(`tint for unknown part: ${k}`);
78
+ if (!HEX_RE.test(input.tints[k])) fail(`tint ${k}: must be #rrggbb`);
79
+ r.tints[k] = input.tints[k].toLowerCase();
80
+ }
81
+ }
82
+ return sortKeys(r);
83
+ }
84
+
85
+ function sortKeys(v) {
86
+ if (Array.isArray(v)) return v.map(sortKeys);
87
+ if (v && typeof v === 'object') return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
88
+ return v;
89
+ }
90
+
91
+ export const canonical = (recipe) => JSON.stringify(sortKeys(recipe));
92
+
93
+ // A part statement may be authored without its closing `;` (e.g. `"shell()"`), which OpenSCAD
94
+ // reads as an unterminated statement -> a cryptic "Parser error: syntax error ... line N+1" at EOF.
95
+ // Normalize so every part string is a well-formed statement (ends with `;`) or block (ends with `}`).
96
+ const terminate = (s) => {
97
+ const t = s.trimEnd();
98
+ return /[;}]$/.test(t) ? t : t + ';';
99
+ };
100
+
101
+ export const recipeHash = (recipe) => createHash('sha256').update(canonical(recipe)).digest('hex');
102
+
103
+ export function partTint(recipe, name) {
104
+ if (recipe.tints?.[name]) return recipe.tints[name];
105
+ return PALETTE[Object.keys(recipe.parts).indexOf(name) % PALETTE.length];
106
+ }
107
+
108
+ // ---- csg ------------------------------------------------------------------
109
+ const PRIMS = { cube: ['size', 'center'], cylinder: ['h', 'r', 'r1', 'r2', 'd', 'center', 'fn'], sphere: ['r', 'd', 'fn'] };
110
+ const XFORMS = { translate: 'v', rotate: 'a', scale: 'v', mirror: 'v' };
111
+ const BOOLS = ['union', 'difference', 'intersection', 'hull'];
112
+
113
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
114
+ const isRef = (x) => x && typeof x === 'object' && !Array.isArray(x) && Object.keys(x).length === 1 && PARAM_RE.test(x.param ?? '');
115
+ const isScalar = (x) => isNum(x) || isRef(x);
116
+ const isVec = (x) => Array.isArray(x) && (x.length === 3 || x.length === 2) && x.every(isScalar);
117
+
118
+ function checkNode(n, depth, budget) {
119
+ if (!n || typeof n !== 'object' || Array.isArray(n)) fail('csg node must be an object');
120
+ if (++budget.n > MAX_NODES) fail('csg tree too large');
121
+ if (depth > MAX_DEPTH) fail('csg tree too deep');
122
+ const op = n.op;
123
+ if (op in PRIMS) {
124
+ for (const k of Object.keys(n)) if (k !== 'op' && !PRIMS[op].includes(k)) fail(`${op}: unknown field ${k}`);
125
+ if (op === 'cube' && !(isScalar(n.size) || isVec(n.size))) fail('cube.size must be a number or [x,y,z]');
126
+ if (op === 'cylinder' && !isScalar(n.h)) fail('cylinder.h required');
127
+ if (op === 'cylinder' && !['r', 'd', 'r1'].some((k) => n[k] !== undefined)) fail('cylinder needs r, d or r1/r2');
128
+ if (op === 'sphere' && n.r === undefined && n.d === undefined) fail('sphere needs r or d');
129
+ for (const k of ['h', 'r', 'r1', 'r2', 'd', 'fn']) if (n[k] !== undefined && !isScalar(n[k])) fail(`${op}.${k} must be a number`);
130
+ if (n.center !== undefined && typeof n.center !== 'boolean') fail(`${op}.center must be boolean`);
131
+ } else if (op in XFORMS || BOOLS.includes(op)) {
132
+ if (op in XFORMS && !isVec(n[XFORMS[op]])) fail(`${op}.${XFORMS[op]} must be [x,y,z]`);
133
+ if (!Array.isArray(n.children) || !n.children.length) fail(`${op}.children must be a non-empty array`);
134
+ for (const c of n.children) checkNode(c, depth + 1, budget);
135
+ } else fail(`unknown csg op: ${op}`);
136
+ }
137
+
138
+ const sc = (x) => (isRef(x) ? x.param : String(x));
139
+ const vec = (v) => `[${v.map(sc).join(', ')}]`;
140
+
141
+ function nodeToScad(n, ind = '') {
142
+ const op = n.op;
143
+ if (op === 'cube') {
144
+ return `${ind}cube(${isScalar(n.size) ? sc(n.size) : vec(n.size)}, center=${!!n.center});`;
145
+ }
146
+ if (op === 'cylinder') {
147
+ const a = [`h=${sc(n.h)}`];
148
+ if (n.r1 !== undefined) a.push(`r1=${sc(n.r1)}`, `r2=${sc(n.r2 ?? 0)}`);
149
+ else if (n.d !== undefined) a.push(`d=${sc(n.d)}`);
150
+ else a.push(`r=${sc(n.r)}`);
151
+ a.push(`center=${!!n.center}`, `$fn=${sc(n.fn ?? 48)}`);
152
+ return `${ind}cylinder(${a.join(', ')});`;
153
+ }
154
+ if (op === 'sphere') return `${ind}sphere(${n.d !== undefined ? `d=${sc(n.d)}` : `r=${sc(n.r)}`}, $fn=${sc(n.fn ?? 48)});`;
155
+ const kids = n.children.map((c) => nodeToScad(c, ind + ' ')).join('\n');
156
+ const head = op in XFORMS ? `${op}(${vec(n[XFORMS[op]])})` : `${op}()`;
157
+ return `${ind}${head} {\n${kids}\n${ind}}`;
158
+ }
159
+
160
+ /** Returns { program, partCode } — the same shape a kind:"scad" recipe has. */
161
+ export function toScadParts(recipe) {
162
+ if (recipe.kind === 'scad') return { program: recipe.program, partCode: { ...recipe.parts } };
163
+ const defaults = Object.entries(recipe.params).filter(([k]) => !k.startsWith('$')).map(([k, v]) => `${k} = ${scadValue(v)};`).join('\n');
164
+ const partCode = {};
165
+ for (const [k, node] of Object.entries(recipe.parts)) partCode[k] = nodeToScad(node);
166
+ return { program: defaults, partCode };
167
+ }
168
+
169
+ export function scadValue(v) {
170
+ if (typeof v === 'string') return JSON.stringify(v);
171
+ if (Array.isArray(v)) return `[${v.map(scadValue).join(', ')}]`;
172
+ return String(v);
173
+ }
174
+
175
+ /** Declarations for seed + params, placed ahead of the program: OpenSCAD's -D only overrides variables the
176
+ * file already declares ("Ignoring unknown variable"), so an undeclared `seed` would otherwise reach the program as undef. */
177
+ export function declareHeader(recipe) {
178
+ const p = { seed: recipe.seed, ...recipe.params };
179
+ return Object.keys(p).sort().map((k) => `${k} = ${scadValue(p[k])};`).join(' ');
180
+ }
181
+
182
+ /** -D arguments: params override program defaults; `seed` is injected unless the recipe sets it. */
183
+ export function defineArgs(recipe) {
184
+ const p = { seed: recipe.seed, ...recipe.params };
185
+ return Object.keys(p).sort().flatMap((k) => ['-D', `${k}=${scadValue(p[k])}`]);
186
+ }
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ // No args: stdio MCP server. `call <tool> --json '{...}'` runs one tool and prints JSON; `tools` lists them.
3
+ import { serve, makeHandlers, callTool, TOOLS } from './mcp.js';
4
+
5
+ const [cmd, name, flag, json] = process.argv.slice(2);
6
+ if (!cmd) {
7
+ await serve();
8
+ } else if (cmd === 'tools') {
9
+ console.log(TOOLS.map((t) => `${t.name}\t${t.description}`).join('\n'));
10
+ } else if (cmd === 'call' && name) {
11
+ try {
12
+ const args = flag === '--json' ? JSON.parse(json ?? '{}') : {};
13
+ console.log(JSON.stringify(await callTool(makeHandlers(), name, args), null, 2));
14
+ } catch (e) { console.error(String(e?.message ?? e)); process.exitCode = 1; }
15
+ } else {
16
+ console.error('usage: scadify # stdio MCP server\n scadify tools\n scadify call <tool> --json \'{...}\'');
17
+ process.exitCode = 2;
18
+ }
package/src/store.js ADDED
@@ -0,0 +1,64 @@
1
+ // Plain JSON filesystem store: one file per ref. No DB.
2
+ import { mkdirSync, readFileSync, writeFileSync, renameSync, readdirSync, existsSync } from 'node:fs';
3
+ import { join, dirname, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { normalize, recipeHash, slug } from './recipe.js';
6
+
7
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
8
+ const REF_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
9
+
10
+ export const defaultStoreDir = () => resolve(process.env.SCADIFY_STORE || join(ROOT, 'store'));
11
+ export const defaultOutDir = () => resolve(process.env.SCADIFY_OUT || join(ROOT, 'out'));
12
+
13
+ export function checkRef(ref) {
14
+ if (typeof ref !== 'string' || !REF_RE.test(ref)) throw new Error(`invalid ref: ${JSON.stringify(ref)}`);
15
+ return ref;
16
+ }
17
+
18
+ export class Store {
19
+ constructor(dir = defaultStoreDir()) { this.dir = dir; }
20
+ file(ref) { return join(this.dir, `${checkRef(ref)}.json`); }
21
+ has(ref) { return existsSync(this.file(ref)); }
22
+
23
+ /** Store a recipe. ref = slug(title)-<8 hex of content hash>; minting identical content is idempotent. */
24
+ mint(input) {
25
+ const recipe = normalize(input);
26
+ const ref = `${slug(recipe.title)}-${recipeHash(recipe).slice(0, 8)}`;
27
+ this.#write(ref, recipe);
28
+ return { ref, recipe };
29
+ }
30
+
31
+ get(ref) {
32
+ const f = this.file(ref);
33
+ if (!existsSync(f)) throw new Error(`no such solid: ${ref}`);
34
+ return JSON.parse(readFileSync(f, 'utf8'));
35
+ }
36
+
37
+ /** Edit in place (ref is stable): params merge, program/parts/tree/title/seed/tints replace. */
38
+ update(ref, patch) {
39
+ const cur = this.get(ref);
40
+ const next = { ...cur };
41
+ for (const k of ['title', 'program', 'parts', 'seed', 'tints']) if (patch[k] !== undefined) next[k] = patch[k];
42
+ if (patch.tree !== undefined) next.parts = { solid: patch.tree };
43
+ if (patch.params !== undefined) next.params = { ...cur.params, ...patch.params };
44
+ const recipe = normalize(next);
45
+ this.#write(ref, recipe);
46
+ return recipe;
47
+ }
48
+
49
+ list() {
50
+ if (!existsSync(this.dir)) return [];
51
+ return readdirSync(this.dir).filter((f) => f.endsWith('.json')).sort().map((f) => {
52
+ const ref = f.slice(0, -5);
53
+ try { const r = this.get(ref); return { ref, title: r.title, kind: r.kind }; } catch { return { ref, title: null, kind: null }; }
54
+ });
55
+ }
56
+
57
+ #write(ref, recipe) {
58
+ mkdirSync(this.dir, { recursive: true });
59
+ const f = this.file(ref);
60
+ const tmp = `${f}.${process.pid}.tmp`;
61
+ writeFileSync(tmp, JSON.stringify(recipe, null, 2) + '\n');
62
+ renameSync(tmp, f);
63
+ }
64
+ }