@constructorfleet/sketchforge3d 1.4.0 → 1.7.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/README.md +43 -6
- package/dist/client.d.ts +33 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +51 -0
- package/dist/client.js.map +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/resources/arrange.d.ts +75 -0
- package/dist/resources/arrange.d.ts.map +1 -0
- package/dist/resources/arrange.js +137 -0
- package/dist/resources/arrange.js.map +1 -0
- package/dist/resources/imports.d.ts +34 -0
- package/dist/resources/imports.d.ts.map +1 -0
- package/dist/resources/imports.js +60 -0
- package/dist/resources/imports.js.map +1 -0
- package/dist/resources/measurements.d.ts +26 -0
- package/dist/resources/measurements.d.ts.map +1 -0
- package/dist/resources/measurements.js +57 -0
- package/dist/resources/measurements.js.map +1 -0
- package/dist/types.d.ts +164 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +34 -0
- package/dist/types.js.map +1 -1
- package/mcp/localEngine.mjs +402 -0
- package/mcp/localMacroRunner.mjs +125 -0
- package/mcp/macroTools.mjs +8 -1
- package/mcp/server.mjs +156 -45
- package/package.json +7 -2
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
import { writeFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
const projectsDir = process.env.SKETCHFORGE_PROJECTS_DIR;
|
|
5
|
+
let backend;
|
|
6
|
+
let enginePackagePromise;
|
|
7
|
+
let selectedObjectIds = [];
|
|
8
|
+
|
|
9
|
+
async function getBackend() {
|
|
10
|
+
if (!projectsDir) throw new Error("Set SKETCHFORGE_PROJECTS_DIR to a directory containing SketchForge project files.");
|
|
11
|
+
if (!backend) {
|
|
12
|
+
enginePackagePromise ??= import("@constructorfleet/sketchforge-engine");
|
|
13
|
+
const { createEngine, directoryProjectStore } = await enginePackagePromise;
|
|
14
|
+
const store = directoryProjectStore(projectsDir);
|
|
15
|
+
backend = { store, engine: createEngine(store), package: await enginePackagePromise };
|
|
16
|
+
}
|
|
17
|
+
return backend;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function requireProjectId(args) {
|
|
21
|
+
if (typeof args.projectId !== "string" || !args.projectId.trim()) {
|
|
22
|
+
throw new Error("projectId is required in local mode. Use a project id from the configured project directory.");
|
|
23
|
+
}
|
|
24
|
+
return args.projectId;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function unwrap(result) {
|
|
28
|
+
if (result.ok) return result.value;
|
|
29
|
+
throw new Error(`Engine operation failed: ${JSON.stringify(result.failure)}`);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function objectSummary(shape) {
|
|
33
|
+
const { id, name, kind, x, z, elevation, width, depth, height, rotation, rotationX, rotationZ, color, hole, locked, group, features } = shape;
|
|
34
|
+
return { id, name, kind, x, z, elevation, width, depth, height, rotation, rotationX, rotationZ, color, hole, locked, ...(group ? { group } : {}), ...(features ? { features } : {}) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function stlBytesFromPositions(positions) {
|
|
38
|
+
if (!Array.isArray(positions) || positions.length === 0 || positions.length % 9 !== 0 || !positions.every(Number.isFinite)) {
|
|
39
|
+
throw new Error("positions must contain finite XYZ coordinates for one or more complete triangles.");
|
|
40
|
+
}
|
|
41
|
+
const facets = [];
|
|
42
|
+
for (let i = 0; i < positions.length; i += 9) {
|
|
43
|
+
const [ax, ay, az, bx, by, bz, cx, cy, cz] = positions.slice(i, i + 9);
|
|
44
|
+
const ux = bx - ax, uy = by - ay, uz = bz - az;
|
|
45
|
+
const vx = cx - ax, vy = cy - ay, vz = cz - az;
|
|
46
|
+
const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
|
|
47
|
+
const length = Math.hypot(nx, ny, nz) || 1;
|
|
48
|
+
facets.push(` facet normal ${nx / length} ${ny / length} ${nz / length}\n outer loop\n vertex ${ax} ${ay} ${az}\n vertex ${bx} ${by} ${bz}\n vertex ${cx} ${cy} ${cz}\n endloop\n endfacet`);
|
|
49
|
+
}
|
|
50
|
+
return new TextEncoder().encode(`solid SketchForge MCP\n${facets.join("\n")}\nendsolid SketchForge MCP\n`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function readScene(args) {
|
|
54
|
+
const id = requireProjectId(args);
|
|
55
|
+
const { engine } = await getBackend();
|
|
56
|
+
const project = await unwrap(await engine.project(id));
|
|
57
|
+
const allow = Array.isArray(args.shapeIds) ? new Set(args.shapeIds) : null;
|
|
58
|
+
const deny = new Set(Array.isArray(args.excludeShapeIds) ? args.excludeShapeIds : []);
|
|
59
|
+
const shapes = project.shapes.filter((shape) => (!allow || allow.has(shape.id)) && !deny.has(shape.id));
|
|
60
|
+
const rawIds = Array.isArray(args.includeRawShapeIds) ? new Set(args.includeRawShapeIds) : null;
|
|
61
|
+
return {
|
|
62
|
+
projectId: project.projectId,
|
|
63
|
+
name: project.name,
|
|
64
|
+
createdAt: project.createdAt,
|
|
65
|
+
revision: project.revision,
|
|
66
|
+
snapGrid: project.snapGrid,
|
|
67
|
+
workspace: project.workspace,
|
|
68
|
+
shapeCount: shapes.length,
|
|
69
|
+
objects: shapes.map(objectSummary),
|
|
70
|
+
...(args.includeRawShapes === true || rawIds ? {
|
|
71
|
+
rawShapes: shapes.filter((shape) => rawIds ? rawIds.has(shape.id) : args.includeRawShapes === true),
|
|
72
|
+
} : {}),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function exportScene(args) {
|
|
77
|
+
const id = requireProjectId(args);
|
|
78
|
+
const { store, package: enginePackage } = await getBackend();
|
|
79
|
+
const document = await store.read(id);
|
|
80
|
+
if (!document) throw new Error(`Project not found: ${id}`);
|
|
81
|
+
const requestedIds = Array.isArray(args.shapeIds) && args.shapeIds.length ? args.shapeIds : selectedObjectIds;
|
|
82
|
+
const shapes = requestedIds.length ? document.shapes.filter((shape) => requestedIds.includes(shape.id)) : document.shapes;
|
|
83
|
+
if (args.format === "skf") {
|
|
84
|
+
const bytes = await enginePackage.exportSkfProject({
|
|
85
|
+
projectId: id, projectName: document.projectName, createdAt: document.createdAt, modifiedAt: Date.now(),
|
|
86
|
+
shapes, history: document.history, historyIndex: document.historyIndex, assets: document.assets,
|
|
87
|
+
workspace: document.workspace, snapGrid: document.snapGrid, placementElevation: document.placementElevation,
|
|
88
|
+
placementWorkplane: document.placementWorkplane, sketchPlacementWorkplane: document.sketchPlacementWorkplane,
|
|
89
|
+
});
|
|
90
|
+
const artifact = { filename: `${args.name || document.projectName}.skf`, mimeType: "application/vnd.sketchforge.project+zip", bytes: bytes.byteLength, shapeCount: shapes.length, base64: Buffer.from(bytes).toString("base64") };
|
|
91
|
+
if (typeof args.outputPath === "string" && args.outputPath.trim()) {
|
|
92
|
+
const destination = path.resolve(args.outputPath);
|
|
93
|
+
writeFileSync(destination, bytes);
|
|
94
|
+
return { ...artifact, base64: undefined, savedTo: destination };
|
|
95
|
+
}
|
|
96
|
+
return artifact;
|
|
97
|
+
}
|
|
98
|
+
if (args.format === "step") {
|
|
99
|
+
const result = await enginePackage.exportShapesToStep(shapes.filter((shape) => shape.hidden !== true));
|
|
100
|
+
const artifact = { filename: `${args.name || document.projectName}.step`, mimeType: "model/step", bytes: result.blob.size, exportedCount: result.exportedCount, skipped: result.skipped, base64: Buffer.from(await result.blob.arrayBuffer()).toString("base64") };
|
|
101
|
+
if (typeof args.outputPath === "string" && args.outputPath.trim()) {
|
|
102
|
+
const destination = path.resolve(args.outputPath);
|
|
103
|
+
writeFileSync(destination, Buffer.from(artifact.base64, "base64"));
|
|
104
|
+
return { ...artifact, base64: undefined, savedTo: destination };
|
|
105
|
+
}
|
|
106
|
+
return artifact;
|
|
107
|
+
}
|
|
108
|
+
if (["stl", "obj", "3mf", "zip"].includes(args.format)) {
|
|
109
|
+
const visible = shapes.filter((shape) => shape.hidden !== true && shape.hole !== true);
|
|
110
|
+
if (!visible.length) throw new Error("No visible solid objects to export.");
|
|
111
|
+
const meshes = await enginePackage.meshProjectShapes(visible);
|
|
112
|
+
const bytes = await exportMeshFormat(args.format, meshes, document, enginePackage);
|
|
113
|
+
const extensions = args.format === "zip" ? "zip" : args.format;
|
|
114
|
+
const mimeType = { stl: "model/stl", obj: "text/plain", "3mf": "model/3mf", zip: "application/zip" }[args.format];
|
|
115
|
+
const filename = `${args.name || document.projectName}.${extensions}`;
|
|
116
|
+
const artifact = { filename, mimeType, bytes: bytes.byteLength, shapeCount: meshes.length, base64: Buffer.from(bytes).toString("base64") };
|
|
117
|
+
if (typeof args.outputPath === "string" && args.outputPath.trim()) {
|
|
118
|
+
const destination = path.resolve(args.outputPath);
|
|
119
|
+
writeFileSync(destination, bytes);
|
|
120
|
+
return { ...artifact, base64: undefined, savedTo: destination };
|
|
121
|
+
}
|
|
122
|
+
return artifact;
|
|
123
|
+
}
|
|
124
|
+
throw new Error(`Unsupported export format in local mode: ${args.format}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function meshBytesAsStl(meshes) {
|
|
128
|
+
const triangles = meshes.reduce((sum, mesh) => sum + mesh.faces.length, 0);
|
|
129
|
+
const bytes = new Uint8Array(84 + triangles * 50);
|
|
130
|
+
bytes.set(new TextEncoder().encode("SketchForge binary STL"));
|
|
131
|
+
const view = new DataView(bytes.buffer);
|
|
132
|
+
view.setUint32(80, triangles, true);
|
|
133
|
+
let offset = 84;
|
|
134
|
+
for (const mesh of meshes) for (const [ia, ib, ic] of mesh.faces) {
|
|
135
|
+
const points = [mesh.vertices[ia], mesh.vertices[ib], mesh.vertices[ic]].map(([x, y, z]) => [x, -z, y]);
|
|
136
|
+
const [a, b, c] = points;
|
|
137
|
+
const u = b.map((v, i) => v - a[i]);
|
|
138
|
+
const w = c.map((v, i) => v - a[i]);
|
|
139
|
+
let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
|
|
140
|
+
const length = Math.hypot(...n) || 1;
|
|
141
|
+
n = n.map((v) => v / length);
|
|
142
|
+
for (const value of [...n, ...a, ...b, ...c]) { view.setFloat32(offset, value, true); offset += 4; }
|
|
143
|
+
view.setUint16(offset, 0, true); offset += 2;
|
|
144
|
+
}
|
|
145
|
+
return bytes;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function meshBytesAsObj(meshes) {
|
|
149
|
+
const lines = ["# SketchForge OBJ export"];
|
|
150
|
+
let index = 1;
|
|
151
|
+
for (const mesh of meshes) {
|
|
152
|
+
lines.push(`o ${mesh.name.replace(/\\s+/g, "_")}`);
|
|
153
|
+
for (const [x, y, z] of mesh.vertices) lines.push(`v ${x} ${y} ${z}`);
|
|
154
|
+
for (const [a, b, c] of mesh.faces) lines.push(`f ${a + index} ${b + index} ${c + index}`);
|
|
155
|
+
index += mesh.vertices.length;
|
|
156
|
+
}
|
|
157
|
+
return new TextEncoder().encode(lines.join("\n"));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async function exportMeshFormat(format, meshes, document, enginePackage) {
|
|
161
|
+
if (format === "stl") return meshBytesAsStl(meshes);
|
|
162
|
+
if (format === "obj") return meshBytesAsObj(meshes);
|
|
163
|
+
const stl = meshBytesAsStl(meshes);
|
|
164
|
+
const { zipSync, strToU8 } = await import("fflate");
|
|
165
|
+
if (format === "zip") {
|
|
166
|
+
const skf = await enginePackage.exportSkfProject({
|
|
167
|
+
projectId: document.projectId, projectName: document.projectName, createdAt: document.createdAt,
|
|
168
|
+
modifiedAt: Date.now(), shapes: document.shapes, history: document.history, historyIndex: document.historyIndex,
|
|
169
|
+
assets: document.assets, workspace: document.workspace, snapGrid: document.snapGrid,
|
|
170
|
+
placementElevation: document.placementElevation, placementWorkplane: document.placementWorkplane,
|
|
171
|
+
sketchPlacementWorkplane: document.sketchPlacementWorkplane,
|
|
172
|
+
});
|
|
173
|
+
return zipSync({ [`${document.projectName}.stl`]: stl, [`${document.projectName}.skf`]: skf });
|
|
174
|
+
}
|
|
175
|
+
const xmlEscape = (value) => String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """);
|
|
176
|
+
const vertices = meshes.map((mesh, i) => `<object id="${i + 1}" type="model" name="${xmlEscape(mesh.name)}"><mesh><vertices>${mesh.vertices.map(([x,y,z]) => `<vertex x="${x}" y="${-z}" z="${y}"/>`).join("")}</vertices><triangles>${mesh.faces.map(([v1,v2,v3]) => `<triangle v1="${v1}" v2="${v2}" v3="${v3}"/>`).join("")}</triangles></mesh></object>`).join("");
|
|
177
|
+
const buildItems = meshes.map((_, i) => `<item objectid="${i + 1}"/>`).join("");
|
|
178
|
+
const model = `<?xml version="1.0" encoding="UTF-8"?><model unit="millimeter" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources>${vertices}</resources><build>${buildItems}</build></model>`;
|
|
179
|
+
return zipSync({
|
|
180
|
+
"[Content_Types].xml": strToU8('<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>'),
|
|
181
|
+
"_rels/.rels": strToU8('<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>'),
|
|
182
|
+
"3D/3dmodel.model": strToU8(model),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function validateScene(args) {
|
|
187
|
+
const id = requireProjectId(args);
|
|
188
|
+
const { engine, package: enginePackage } = await getBackend();
|
|
189
|
+
const project = await unwrap(await engine.project(id));
|
|
190
|
+
const requested = Array.isArray(args.shapeIds) && args.shapeIds.length ? new Set(args.shapeIds) : null;
|
|
191
|
+
const excluded = new Set(Array.isArray(args.excludeShapeIds) ? args.excludeShapeIds : []);
|
|
192
|
+
const shapes = project.shapes.filter((shape) => (!requested || requested.has(shape.id)) && !excluded.has(shape.id) && !shape.hidden && !shape.hole);
|
|
193
|
+
const records = await Promise.all(shapes.map(async (shape) => {
|
|
194
|
+
try {
|
|
195
|
+
const [mesh] = await enginePackage.meshProjectShapes([shape]);
|
|
196
|
+
if (!mesh) throw new Error("No mesh could be generated.");
|
|
197
|
+
const bounds = mesh.vertices.reduce((b, [x,y,z]) => ({ minX: Math.min(b.minX,x), maxX: Math.max(b.maxX,x), minY: Math.min(b.minY,y), maxY: Math.max(b.maxY,y), minZ: Math.min(b.minZ,z), maxZ: Math.max(b.maxZ,z) }), { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity, minZ: Infinity, maxZ: -Infinity });
|
|
198
|
+
const topology = enginePackage.analyzeMeshTopology(mesh.vertices, mesh.faces);
|
|
199
|
+
return { id: shape.id, name: shape.name, mesh, bounds, topology };
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return { id: shape.id, name: shape.name, error: error instanceof Error ? error.message : String(error) };
|
|
202
|
+
}
|
|
203
|
+
}));
|
|
204
|
+
const topology = records.map(({ id: objectId, name, topology: report, error }) => error ? { id: objectId, name, error } : { id: objectId, name, ...report });
|
|
205
|
+
const validRecords = records.filter((record) => record.mesh);
|
|
206
|
+
const clearances = [];
|
|
207
|
+
const intersectionPairs = [];
|
|
208
|
+
for (let i = 0; i < validRecords.length; i += 1) for (let j = i + 1; j < validRecords.length; j += 1) {
|
|
209
|
+
const a = validRecords[i].bounds, b = validRecords[j].bounds;
|
|
210
|
+
const gaps = [Math.max(0, b.minX-a.maxX, a.minX-b.maxX), Math.max(0, b.minY-a.maxY, a.minY-b.maxY), Math.max(0, b.minZ-a.maxZ, a.minZ-b.maxZ)];
|
|
211
|
+
clearances.push({ fromId: validRecords[i].id, toId: validRecords[j].id, lowerBound: Math.hypot(...gaps), overlappingBounds: gaps.every((gap) => gap === 0) });
|
|
212
|
+
if (gaps.every((gap) => gap === 0)) intersectionPairs.push([validRecords[i], validRecords[j]]);
|
|
213
|
+
}
|
|
214
|
+
const intersections = [];
|
|
215
|
+
if (intersectionPairs.length) {
|
|
216
|
+
const { default: manifoldModule } = await import("manifold-3d");
|
|
217
|
+
const runtime = await manifoldModule();
|
|
218
|
+
runtime.setup();
|
|
219
|
+
const asSolid = (mesh) => {
|
|
220
|
+
const meshData = new runtime.Mesh({
|
|
221
|
+
numProp: 3,
|
|
222
|
+
vertProperties: Float32Array.from(mesh.vertices.flat()),
|
|
223
|
+
triVerts: Uint32Array.from(mesh.faces.flat()),
|
|
224
|
+
tolerance: 0.0001,
|
|
225
|
+
});
|
|
226
|
+
meshData.merge();
|
|
227
|
+
return { meshData, solid: runtime.Manifold.ofMesh(meshData) };
|
|
228
|
+
};
|
|
229
|
+
for (const [left, right] of intersectionPairs) {
|
|
230
|
+
let a, b, overlap;
|
|
231
|
+
try {
|
|
232
|
+
a = asSolid(left.mesh); b = asSolid(right.mesh);
|
|
233
|
+
overlap = a.solid.intersect(b.solid);
|
|
234
|
+
const status = overlap.status();
|
|
235
|
+
if (status !== "NoError") throw new Error(`Manifold status ${status}`);
|
|
236
|
+
const volume = Math.max(0, overlap.volume());
|
|
237
|
+
intersections.push({ fromId: left.id, toId: right.id, volume, intersects: volume > 1e-6 });
|
|
238
|
+
} catch (error) {
|
|
239
|
+
intersections.push({ fromId: left.id, toId: right.id, error: error instanceof Error ? error.message : String(error) });
|
|
240
|
+
} finally {
|
|
241
|
+
overlap?.delete(); a?.solid?.delete(); b?.solid?.delete();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return { objectsChecked: shapes.length, topology, clearances, intersections, clearanceMethod: "AABB lower bound; conservative, not exact surface distance.", intersectionMethod: "Manifold intersection volume for overlapping AABB pairs; unsupported or invalid meshes report an error per pair." };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function captureScene(args) {
|
|
249
|
+
const id = requireProjectId(args);
|
|
250
|
+
const { engine, package: enginePackage } = await getBackend();
|
|
251
|
+
const project = await unwrap(await engine.project(id));
|
|
252
|
+
const shapes = project.shapes.filter((shape) => !shape.hidden && !shape.hole);
|
|
253
|
+
const meshes = await enginePackage.meshProjectShapes(shapes);
|
|
254
|
+
const face = ["home", "top", "bottom", "front", "back", "right", "left"].includes(args.face) ? args.face : "home";
|
|
255
|
+
const direction = {
|
|
256
|
+
top: [0, 1, 0], bottom: [0, -1, 0], front: [0, 0, 1], back: [0, 0, -1], right: [1, 0, 0], left: [-1, 0, 0],
|
|
257
|
+
}[face] ?? [1, 1, 1];
|
|
258
|
+
const unit = (v) => { const n = Math.hypot(...v) || 1; return v.map((x) => x / n); };
|
|
259
|
+
const camera = unit(direction);
|
|
260
|
+
const right = face === "top" ? [1, 0, 0] : face === "bottom" ? [-1, 0, 0] : unit([camera[2], 0, -camera[0]]);
|
|
261
|
+
const up = face === "top" || face === "bottom" ? [0, 0, -1] : unit([
|
|
262
|
+
camera[1] * right[2] - camera[2] * right[1],
|
|
263
|
+
camera[2] * right[0] - camera[0] * right[2],
|
|
264
|
+
camera[0] * right[1] - camera[1] * right[0],
|
|
265
|
+
]);
|
|
266
|
+
const all = meshes.flatMap((mesh, meshIndex) => mesh.faces.map((faceIndices) => ({
|
|
267
|
+
meshIndex,
|
|
268
|
+
points: faceIndices.map((index) => mesh.vertices[index]),
|
|
269
|
+
})));
|
|
270
|
+
const projectPoint = (point) => [point[0] * right[0] + point[1] * right[1] + point[2] * right[2], point[0] * up[0] + point[1] * up[1] + point[2] * up[2]];
|
|
271
|
+
const projected = all.map((triangle) => ({ ...triangle, projected: triangle.points.map(projectPoint), depth: triangle.points.reduce((sum, point) => sum + point.reduce((d, value, i) => d + value * camera[i], 0), 0) / 3 }));
|
|
272
|
+
const extent = projected.flatMap((triangle) => triangle.projected);
|
|
273
|
+
const minX = extent.length ? Math.min(...extent.map((p) => p[0])) : -1;
|
|
274
|
+
const maxX = extent.length ? Math.max(...extent.map((p) => p[0])) : 1;
|
|
275
|
+
const minY = extent.length ? Math.min(...extent.map((p) => p[1])) : -1;
|
|
276
|
+
const maxY = extent.length ? Math.max(...extent.map((p) => p[1])) : 1;
|
|
277
|
+
const width = 960, height = 720, margin = 56;
|
|
278
|
+
const scale = Math.min((width - margin * 2) / Math.max(maxX - minX, 1), (height - margin * 2) / Math.max(maxY - minY, 1));
|
|
279
|
+
const screen = ([x, y]) => [width / 2 + (x - (minX + maxX) / 2) * scale, height / 2 - (y - (minY + maxY) / 2) * scale];
|
|
280
|
+
const xml = (value) => String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """);
|
|
281
|
+
const draw = projected.sort((a, b) => a.depth - b.depth).map(({ meshIndex, points, projected: coordinates }) => {
|
|
282
|
+
const [a,b,c] = points;
|
|
283
|
+
const u = b.map((v,i) => v-a[i]), v = c.map((value,i) => value-a[i]);
|
|
284
|
+
const normal = unit([u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0]]);
|
|
285
|
+
const light = unit([0.3, 0.8, 0.6]);
|
|
286
|
+
const shade = Math.round(0.55 + 0.4 * Math.max(0, normal.reduce((sum, value, i) => sum + value*light[i], 0)));
|
|
287
|
+
const color = shapes[meshIndex]?.color ?? "#6f8fa8";
|
|
288
|
+
const hex = /^#[0-9a-f]{6}$/i.test(color) ? color : "#6f8fa8";
|
|
289
|
+
const channels = [1,3,5].map((index) => Math.min(255, Math.round(parseInt(hex.slice(index,index+2),16)*shade)).toString(16).padStart(2,"0"));
|
|
290
|
+
const pointsText = coordinates.map((point) => screen(point).join(",")).join(" ");
|
|
291
|
+
return `<polygon points="${pointsText}" fill="#${channels.join("")}" stroke="#34495a" stroke-width="0.65" stroke-linejoin="round"/>`;
|
|
292
|
+
}).join("");
|
|
293
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}"><rect width="100%" height="100%" fill="#f5f7f9"/><text x="28" y="36" font-family="sans-serif" font-size="16" fill="#40515e">${xml(project.projectName)} · ${face}</text>${draw}</svg>`;
|
|
294
|
+
const sharp = (await import("sharp")).default;
|
|
295
|
+
const png = await sharp(Buffer.from(svg)).png().toBuffer();
|
|
296
|
+
return { face, bytesApprox: png.byteLength, dataUrl: `data:image/png;base64,${png.toString("base64")}` };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export async function callLocalEngineTool(name, args = {}) {
|
|
300
|
+
if (["sketchforge_list_editors", "sketchforge_inspect_errors"].includes(name)) {
|
|
301
|
+
throw new Error(`${name} needs an open SketchForge editor and is unavailable in local mode.`);
|
|
302
|
+
}
|
|
303
|
+
const id = requireProjectId(args);
|
|
304
|
+
const { engine, package: enginePackage } = await getBackend();
|
|
305
|
+
switch (name) {
|
|
306
|
+
case "sketchforge_read_scene":
|
|
307
|
+
case "sketchforge_list_objects":
|
|
308
|
+
return readScene(args);
|
|
309
|
+
case "sketchforge_create_shape":
|
|
310
|
+
return unwrap(await engine.addShapes(id, [args]));
|
|
311
|
+
case "sketchforge_select_objects": {
|
|
312
|
+
const project = await unwrap(await engine.project(id));
|
|
313
|
+
const requested = Array.isArray(args.ids) ? args.ids : args.id ? [args.id] : [];
|
|
314
|
+
selectedObjectIds = requested.filter((shapeId) => project.shapes.some((shape) => shape.id === shapeId));
|
|
315
|
+
return { selectedIds: selectedObjectIds, objects: project.shapes.filter((shape) => selectedObjectIds.includes(shape.id)).map(objectSummary) };
|
|
316
|
+
}
|
|
317
|
+
case "sketchforge_import_mesh": {
|
|
318
|
+
const imported = await unwrap(await engine.importMesh(id, {
|
|
319
|
+
fileName: `${args.name || "Imported mesh"}.stl`,
|
|
320
|
+
bytes: stlBytesFromPositions(args.positions),
|
|
321
|
+
mediaType: "model/stl",
|
|
322
|
+
}));
|
|
323
|
+
const changes = Object.fromEntries(["name", "color", "x", "z", "elevation"].filter((key) => args[key] !== undefined).map((key) => [key, args[key]]));
|
|
324
|
+
return Object.keys(changes).length ? unwrap(await engine.changeShape(id, imported.shape.id, changes)) : imported;
|
|
325
|
+
}
|
|
326
|
+
case "sketchforge_update_object": {
|
|
327
|
+
const { id: shapeId, projectId, ...changes } = args;
|
|
328
|
+
return unwrap(await engine.changeShape(id, shapeId, changes));
|
|
329
|
+
}
|
|
330
|
+
case "sketchforge_delete_objects": {
|
|
331
|
+
const ids = args.ids ?? (args.id ? [args.id] : selectedObjectIds);
|
|
332
|
+
const removed = [];
|
|
333
|
+
for (const shapeId of ids) removed.push(await unwrap(await engine.removeShape(id, shapeId)));
|
|
334
|
+
return { removed };
|
|
335
|
+
}
|
|
336
|
+
case "sketchforge_align_objects":
|
|
337
|
+
return unwrap(await engine.align(id, { ...args, ids: args.ids?.length ? args.ids : selectedObjectIds }));
|
|
338
|
+
case "sketchforge_distribute_objects":
|
|
339
|
+
return unwrap(await engine.distribute(id, { ...args, ids: args.ids?.length ? args.ids : selectedObjectIds }));
|
|
340
|
+
case "sketchforge_pattern_objects":
|
|
341
|
+
return unwrap(await engine.pattern(id, { ...args, ids: args.ids?.length ? args.ids : selectedObjectIds, kind: args.kind ?? "linear", count: args.count ?? 4 }));
|
|
342
|
+
case "sketchforge_group_objects":
|
|
343
|
+
return unwrap(await engine.group(id, args.ids?.length ? args.ids : selectedObjectIds));
|
|
344
|
+
case "sketchforge_ungroup_objects": {
|
|
345
|
+
const results = [];
|
|
346
|
+
for (const shapeId of args.ids ?? (args.id ? [args.id] : selectedObjectIds)) results.push(await unwrap(await engine.ungroup(id, shapeId)));
|
|
347
|
+
return { results };
|
|
348
|
+
}
|
|
349
|
+
case "sketchforge_boolean_cut": {
|
|
350
|
+
if (args.solidIds && args.holeIds) return unwrap(await engine.cut(id, { solidIds: args.solidIds, holeIds: args.holeIds }));
|
|
351
|
+
const project = await unwrap(await engine.project(id));
|
|
352
|
+
const selected = project.shapes.filter((shape) => selectedObjectIds.includes(shape.id));
|
|
353
|
+
return unwrap(await engine.cut(id, {
|
|
354
|
+
solidIds: selected.filter((shape) => !shape.hole).map((shape) => shape.id),
|
|
355
|
+
holeIds: selected.filter((shape) => shape.hole).map((shape) => shape.id),
|
|
356
|
+
}));
|
|
357
|
+
}
|
|
358
|
+
case "sketchforge_separate_parts":
|
|
359
|
+
return unwrap(await engine.separate(id, args.id ?? selectedObjectIds[0]));
|
|
360
|
+
case "sketchforge_list_edges":
|
|
361
|
+
return unwrap(await engine.edges(id, args.shapeId ?? args.id));
|
|
362
|
+
case "sketchforge_list_faces":
|
|
363
|
+
return unwrap(await engine.faces(id, args.shapeId));
|
|
364
|
+
case "sketchforge_measure_shape":
|
|
365
|
+
return unwrap(await engine.measurements(id, args.shapeId));
|
|
366
|
+
case "sketchforge_measure_between":
|
|
367
|
+
return unwrap(await engine.measureBetween(id, args.from, args.to));
|
|
368
|
+
case "sketchforge_apply_edge_treatment":
|
|
369
|
+
return unwrap(await engine.treat(id, args.id, {
|
|
370
|
+
kind: args.kind,
|
|
371
|
+
amount: args.amount,
|
|
372
|
+
angle: args.chamferAngle,
|
|
373
|
+
edges: args.allEdges || args.edgeIds === "all" ? undefined : args.edgeIds,
|
|
374
|
+
}));
|
|
375
|
+
case "sketchforge_hollow_shape":
|
|
376
|
+
return unwrap(await engine.shell(id, args.shapeId, { thickness: args.thickness, openFaces: args.openFaces }));
|
|
377
|
+
case "sketchforge_export_scene":
|
|
378
|
+
return exportScene(args);
|
|
379
|
+
case "sketchforge_validate_scene":
|
|
380
|
+
return validateScene(args);
|
|
381
|
+
case "sketchforge_capture_image":
|
|
382
|
+
return captureScene(args);
|
|
383
|
+
case "sketchforge_mirror_objects": {
|
|
384
|
+
const ids = Array.isArray(args.ids) && args.ids.length ? args.ids : selectedObjectIds;
|
|
385
|
+
if (!ids.length || !["x", "y", "z"].includes(args.axis)) throw new Error("mirror_objects requires object ids or a local selection, and axis x, y, or z.");
|
|
386
|
+
const project = await unwrap(await engine.project(id));
|
|
387
|
+
const selected = project.shapes.filter((shape) => ids.includes(shape.id));
|
|
388
|
+
if (!selected.length) throw new Error("No matching objects to mirror.");
|
|
389
|
+
const { nextShapes, moved: count } = enginePackage.mirrorShapes(project.shapes, ids, args.axis);
|
|
390
|
+
const moved = [];
|
|
391
|
+
for (const shape of selected) {
|
|
392
|
+
if (shape.locked) continue;
|
|
393
|
+
const reflected = nextShapes.find((item) => item.id === shape.id);
|
|
394
|
+
const changes = Object.fromEntries(["x", "z", "elevation", "rotation", "rotationX", "rotationZ", "mirrorX", "mirrorY", "mirrorZ"].filter((key) => reflected[key] !== shape[key]).map((key) => [key, reflected[key]]));
|
|
395
|
+
moved.push(unwrap(await engine.changeShape(id, shape.id, changes)));
|
|
396
|
+
}
|
|
397
|
+
return { moved: count, axis: args.axis, objects: moved };
|
|
398
|
+
}
|
|
399
|
+
default:
|
|
400
|
+
throw new Error(`${name} needs an open SketchForge editor and is unavailable in local mode.`);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { writeFile, unlink } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { directoryProjectStore, createEngine } from "@constructorfleet/sketchforge-engine";
|
|
6
|
+
import { macroFromModule, runMacro } from "../dist/index.js";
|
|
7
|
+
|
|
8
|
+
const root = process.env.SKETCHFORGE_PROJECTS_DIR;
|
|
9
|
+
if (!root) throw new Error("SKETCHFORGE_PROJECTS_DIR is required for local macro execution.");
|
|
10
|
+
const store = directoryProjectStore(path.resolve(root));
|
|
11
|
+
const engine = createEngine(store);
|
|
12
|
+
const unwrap = (result) => {
|
|
13
|
+
if (result.ok) return result.value;
|
|
14
|
+
throw new Error(`Engine operation failed: ${JSON.stringify(result.failure)}`);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
async function projectSummary(record) {
|
|
18
|
+
const project = unwrap(await engine.project(record.projectId));
|
|
19
|
+
return {
|
|
20
|
+
id: record.projectId,
|
|
21
|
+
name: String(record.metadata.name ?? "Untitled design"),
|
|
22
|
+
shapes: project.shapes.length,
|
|
23
|
+
revision: project.revision,
|
|
24
|
+
updatedAt: record.updatedAt,
|
|
25
|
+
packageBytes: record.packageBytes,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function createProject(name) {
|
|
30
|
+
const id = randomUUID();
|
|
31
|
+
const now = Date.now();
|
|
32
|
+
await writeFile(path.join(root, `${id}.json`), JSON.stringify({ name: String(name).slice(0, 80), createdAt: now, updatedAt: now, revision: 1 }));
|
|
33
|
+
return { id, name: String(name).slice(0, 80), shapes: 0, revision: 1, updatedAt: now, packageBytes: 0 };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function projectHandle(id) {
|
|
37
|
+
const read = async () => unwrap(await engine.project(id));
|
|
38
|
+
const addMany = async (shapes) => unwrap(await engine.addShapes(id, shapes));
|
|
39
|
+
const getEdges = async (shapeId) => unwrap(await engine.edges(id, shapeId));
|
|
40
|
+
const withTriangleCount = (written) => ({ ...written, triangles: written.shape.importedMesh?.triangleCount ?? 0 });
|
|
41
|
+
const treat = async (shapeId, treatment) => withTriangleCount(unwrap(await engine.treat(id, shapeId, treatment)));
|
|
42
|
+
const shell = async (shapeId, request) => withTriangleCount(unwrap(await engine.shell(id, shapeId, request)));
|
|
43
|
+
return {
|
|
44
|
+
id,
|
|
45
|
+
get: async () => {
|
|
46
|
+
const project = await read();
|
|
47
|
+
return { id, name: project.name, createdAt: project.createdAt, snapGrid: project.snapGrid, workspace: project.workspace, shapes: project.shapes };
|
|
48
|
+
},
|
|
49
|
+
listShapes: async () => (await read()).shapes,
|
|
50
|
+
add: async (shape) => (await addMany([shape])).shapes[0],
|
|
51
|
+
addMany,
|
|
52
|
+
update: async (shapeId, changes) => unwrap(await engine.changeShape(id, shapeId, changes)),
|
|
53
|
+
remove: (shapeId) => engine.removeShape(id, shapeId).then(unwrap),
|
|
54
|
+
clear: async () => {
|
|
55
|
+
const shapes = (await read()).shapes;
|
|
56
|
+
for (const shape of shapes) await unwrap(await engine.removeShape(id, shape.id));
|
|
57
|
+
return shapes.length;
|
|
58
|
+
},
|
|
59
|
+
edges: getEdges,
|
|
60
|
+
filletableEdges: async (shapeId) => (await getEdges(shapeId)).filter((edge) => edge.filletable).map((edge) => edge.index),
|
|
61
|
+
treat,
|
|
62
|
+
fillet: (shapeId, radius, edges) => treat(shapeId, { kind: "fillet", amount: radius, ...(edges ? { edges } : {}) }),
|
|
63
|
+
chamfer: (shapeId, distance, options = {}) => treat(shapeId, { kind: "chamfer", amount: distance, ...options }),
|
|
64
|
+
faces: async (shapeId) => unwrap(await engine.faces(id, shapeId)),
|
|
65
|
+
facesFacing: async (shapeId, direction) => (await unwrap(await engine.faces(id, shapeId))).filter((face) => face.direction === direction).map((face) => face.index),
|
|
66
|
+
measurements: (shapeId) => engine.measurements(id, shapeId).then(unwrap),
|
|
67
|
+
measureBetween: (from, to) => engine.measureBetween(id, from, to).then(unwrap),
|
|
68
|
+
shell,
|
|
69
|
+
hollow: (shapeId, thickness) => shell(shapeId, { thickness }),
|
|
70
|
+
tray: (shapeId, thickness, openFaces) => shell(shapeId, { thickness, ...(openFaces ? { openFaces } : {}) }),
|
|
71
|
+
align: (request) => engine.align(id, request).then(unwrap),
|
|
72
|
+
alignTops: (ids, anchorId) => engine.align(id, { ids: [...ids], axis: "y", target: "max", ...(anchorId ? { anchorId } : {}) }).then(unwrap),
|
|
73
|
+
distribute: (request) => engine.distribute(id, request).then(unwrap),
|
|
74
|
+
pattern: (request) => engine.pattern(id, request).then(unwrap),
|
|
75
|
+
row: (ids, count, stepX, stepZ = 0) => engine.pattern(id, { ids: [...ids], kind: "linear", count, stepX, stepZ }).then(unwrap),
|
|
76
|
+
ring: (ids, count, center, options = {}) => engine.pattern(id, { ids: [...ids], kind: "circular", count, centerX: center.x, centerZ: center.z, ...options }).then(unwrap),
|
|
77
|
+
importMesh: (request) => engine.importMesh(id, request).then(unwrap),
|
|
78
|
+
cut: (request) => engine.cut(id, request).then(unwrap),
|
|
79
|
+
group: (ids) => engine.group(id, [...ids]).then(unwrap),
|
|
80
|
+
ungroup: (shapeId) => engine.ungroup(id, shapeId).then(unwrap),
|
|
81
|
+
separate: (shapeId) => engine.separate(id, shapeId).then(unwrap),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const client = {
|
|
86
|
+
project: projectHandle,
|
|
87
|
+
projects: {
|
|
88
|
+
list: async () => Promise.all((await store.list()).map(projectSummary)),
|
|
89
|
+
findByName: async (name) => (await Promise.all((await store.list()).map(projectSummary))).find((project) => project.name === name) ?? null,
|
|
90
|
+
create: createProject,
|
|
91
|
+
get: async (id) => projectHandle(id).get(),
|
|
92
|
+
delete: async (id) => {
|
|
93
|
+
const metadata = path.join(root, `${id}.json`);
|
|
94
|
+
const file = path.join(root, `${id}.skf`);
|
|
95
|
+
let deleted = false;
|
|
96
|
+
for (const target of [metadata, file]) try { await unlink(target); deleted = true; } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
97
|
+
return { deleted };
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
client.shapes = {
|
|
102
|
+
list: async (id) => projectHandle(id).listShapes(),
|
|
103
|
+
create: async (id, shape) => projectHandle(id).add(shape),
|
|
104
|
+
createMany: async (id, shapes) => projectHandle(id).addMany(shapes),
|
|
105
|
+
update: async (id, shapeId, changes) => projectHandle(id).update(shapeId, changes),
|
|
106
|
+
delete: async (id, shapeId) => projectHandle(id).remove(shapeId),
|
|
107
|
+
deleteAll: async (id) => projectHandle(id).clear(),
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const argv = process.argv.slice(2);
|
|
111
|
+
const file = argv[0];
|
|
112
|
+
if (!file) throw new Error("Expected a macro file path.");
|
|
113
|
+
const options = { params: {}, targetProjectId: undefined };
|
|
114
|
+
for (const argument of argv.slice(1)) {
|
|
115
|
+
if (argument === "--json") continue;
|
|
116
|
+
if (argument.startsWith("--project=")) options.targetProjectId = argument.slice("--project=".length);
|
|
117
|
+
else if (argument.startsWith("--")) {
|
|
118
|
+
const [key, ...value] = argument.slice(2).split("=");
|
|
119
|
+
options.params[key] = value.join("=");
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const module = await import(pathToFileURL(path.resolve(file)).href);
|
|
123
|
+
const definition = macroFromModule(module, path.basename(file).replace(/\.[cm]?[jt]s$/, ""));
|
|
124
|
+
const report = await runMacro(client, definition, options);
|
|
125
|
+
process.stdout.write(`${JSON.stringify(report)}\n`);
|
package/mcp/macroTools.mjs
CHANGED
|
@@ -97,6 +97,12 @@ function javascriptRunner(environment) {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
function runnerFor(macroName, environment) {
|
|
100
|
+
if (environment.SKETCHFORGE_PROJECTS_DIR) {
|
|
101
|
+
if (path.extname(macroName).toLowerCase() === ".py") {
|
|
102
|
+
throw new MacroToolError("Python macros need the HTTP API adapter; local project mode runs JavaScript macros directly against the engine.");
|
|
103
|
+
}
|
|
104
|
+
return { command: process.execPath, leadingArguments: [path.join(moduleDirectory, "localMacroRunner.mjs")], extraEnvironment: {} };
|
|
105
|
+
}
|
|
100
106
|
if (path.extname(macroName).toLowerCase() === ".py") {
|
|
101
107
|
const python = environment.SKETCHFORGE_MACRO_PYTHON || "python3";
|
|
102
108
|
const pythonPath = existsSync(bundledPythonSource)
|
|
@@ -221,11 +227,12 @@ export const macroTools = [
|
|
|
221
227
|
{
|
|
222
228
|
name: "sketchforge_run_macro",
|
|
223
229
|
description:
|
|
224
|
-
"Run one installed macro by name, against
|
|
230
|
+
"Run one installed macro by name, offline by default or against an optional SketchForge server URL. Parameters are the macro's own declared parameters. Only files already present in SKETCHFORGE_MACRO_DIR can be run; code cannot be passed in.",
|
|
225
231
|
inputSchema: {
|
|
226
232
|
type: "object",
|
|
227
233
|
required: ["macro"],
|
|
228
234
|
properties: {
|
|
235
|
+
url: { type: "string", description: "Optional SketchForge server URL. Omit to run against local project files." },
|
|
229
236
|
macro: { type: "string", description: "A file name from sketchforge_list_macros." },
|
|
230
237
|
params: {
|
|
231
238
|
type: "object",
|