@mulmoclaude/shapescript-plugin 1.1.1 → 1.3.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/dist/render.js ADDED
@@ -0,0 +1,291 @@
1
+ import { In as e, Pn as t, n } from "./toThreeJS-B5LiF110.js";
2
+ import { readFile as r } from "node:fs/promises";
3
+ import { createRequire as i } from "node:module";
4
+ import { pathToFileURL as a } from "node:url";
5
+ import o from "node:path";
6
+ //#region src/render/page.ts
7
+ function s(e) {
8
+ let t = Math.ceil(Math.sqrt(e));
9
+ return {
10
+ columns: t,
11
+ rows: Math.ceil(e / t)
12
+ };
13
+ }
14
+ function c(e, t, n) {
15
+ return `import { AmbientLight, Box3, DirectionalLight, GridHelper, MathUtils, ObjectLoader, OrthographicCamera, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer } from ${JSON.stringify(e)};
16
+
17
+ const config = ${t};
18
+ const { columns, rows } = ${n};
19
+ const sheet = document.getElementById("sheet");
20
+ const context = sheet.getContext("2d");
21
+ sheet.width = config.width * columns;
22
+ sheet.height = config.height * rows;
23
+ context.fillStyle = "#ffffff";
24
+ context.fillRect(0, 0, sheet.width, sheet.height);
25
+
26
+ const model = new ObjectLoader().parse(config.scene);
27
+
28
+ // Framing is derived from the model's own bounding sphere, so one zoom value
29
+ // means the same thing for a 0.1-unit bead and a 500-unit building.
30
+ const bounds = new Box3().setFromObject(model);
31
+ const sphere = bounds.getBoundingSphere(new Sphere());
32
+ const radius = sphere.radius > 0 && isFinite(sphere.radius) ? sphere.radius : 1;
33
+
34
+ const renderer = new WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
35
+ renderer.setPixelRatio(1);
36
+ renderer.setSize(config.width, config.height, false);
37
+ renderer.setClearColor(0xffffff, 1);
38
+
39
+ const scene = new Scene();
40
+ scene.add(model);
41
+ // A headlight plus fill and ambient: a single light leaves faces pointing away
42
+ // from it black, which reads as a hole rather than a surface.
43
+ const headlight = new DirectionalLight(0xffffff, 2.2);
44
+ const fill = new DirectionalLight(0xffffff, 0.8);
45
+ fill.position.set(-1, 0.5, -1);
46
+ scene.add(headlight, fill, new AmbientLight(0xffffff, 0.9));
47
+
48
+ // A ground grid gives absolute orientation — without it a symmetric model
49
+ // renders identically from several angles.
50
+ const floor = new GridHelper(radius * 4, 12, 0xc0c0c0, 0xe4e4e4);
51
+ floor.position.y = bounds.min.y;
52
+ scene.add(floor);
53
+ `;
54
+ }
55
+ function l() {
56
+ return "\nconst aspect = config.width / config.height;\nconst distance = (radius * 3.2) / Math.max(config.zoom, 0.01);\n\nfunction cameraFor(angle) {\n const phi = MathUtils.degToRad(90 - angle.elevation);\n const theta = MathUtils.degToRad(angle.azimuth);\n const eye = new Vector3().setFromSphericalCoords(distance, phi, theta).add(sphere.center);\n const far = distance + radius * 10;\n let camera;\n if (config.projection === \"orthographic\") {\n const halfHeight = (radius * 1.3) / Math.max(config.zoom, 0.01);\n camera = new OrthographicCamera(-halfHeight * aspect, halfHeight * aspect, halfHeight, -halfHeight, 0.01, far);\n } else {\n camera = new PerspectiveCamera(35, aspect, Math.max(distance / 100, 0.01), far);\n }\n camera.position.copy(eye);\n camera.lookAt(sphere.center);\n return camera;\n}\n\nconfig.views.forEach((angle, index) => {\n const camera = cameraFor(angle);\n headlight.position.copy(camera.position);\n renderer.render(scene, camera);\n const x = (index % columns) * config.width;\n const y = Math.floor(index / columns) * config.height;\n context.drawImage(renderer.domElement, x, y);\n // Caption last, so it is never painted over by the next tile.\n context.font = \"16px system-ui, sans-serif\";\n context.fillStyle = \"#111111\";\n context.fillText(angle.label, x + 12, y + config.height - 12);\n context.strokeStyle = \"#d0d0d0\";\n context.strokeRect(x + 0.5, y + 0.5, config.width - 1, config.height - 1);\n});\n\nrenderer.dispose();\nwindow.__shapeSheet = sheet.toDataURL(\"image/png\");";
57
+ }
58
+ function u(e) {
59
+ let { threeUrl: t, sceneJson: n, views: r, width: i, height: a, zoom: o, projection: u } = e;
60
+ return `<!doctype html>
61
+ <meta charset="utf-8">
62
+ <style>html,body{margin:0;background:#ffffff}</style>
63
+ <canvas id="sheet"></canvas>
64
+ <script type="module">
65
+ ${`${c(t, JSON.stringify({
66
+ views: r,
67
+ width: i,
68
+ height: a,
69
+ zoom: o,
70
+ projection: u,
71
+ scene: n
72
+ }), JSON.stringify(s(r.length)))}\n${l()}`}
73
+ <\/script>`;
74
+ }
75
+ //#endregion
76
+ //#region src/render/renderer.ts
77
+ var d = 1e3;
78
+ function f(e) {
79
+ return e instanceof Error ? e.message : String(e);
80
+ }
81
+ var p = 60 * d, m = 30 * d, h = 9e4, g = "renderShapeScript needs Puppeteer's headless Chromium, which this host does not have. Run `npx puppeteer browsers install chrome`, then retry. Everything else, including presentShapeScript, works without it.", _ = class extends Error {};
82
+ function v(e, t) {
83
+ try {
84
+ e?.(t);
85
+ } catch {}
86
+ }
87
+ function y() {
88
+ let e = import.meta.url;
89
+ if (typeof e == "string" && e.length > 0) return e;
90
+ if (typeof __filename == "string") return a(__filename).href;
91
+ throw Error("shapescript render: cannot locate this module to resolve three from");
92
+ }
93
+ var b = i(y());
94
+ function x(t) {
95
+ return e(t) && typeof t.launch == "function";
96
+ }
97
+ async function S() {
98
+ try {
99
+ let t = await import("puppeteer");
100
+ return x(t) ? t : e(t) && x(t.default) ? t.default : null;
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+ function C() {
106
+ try {
107
+ return i(b.resolve("@mulmoclaude/shapescript-plugin/package.json"));
108
+ } catch {
109
+ return b;
110
+ }
111
+ }
112
+ function w() {
113
+ let e = C().resolve("three");
114
+ return e.endsWith("three.cjs") ? e.replace(/three\.cjs$/, "three.module.js") : e;
115
+ }
116
+ var T = "https://shapescript.invalid", E = `${T}/render.html`, D = "./three.module.js";
117
+ async function O(e, t, n) {
118
+ let i;
119
+ try {
120
+ i = new URL(e);
121
+ } catch {
122
+ return null;
123
+ }
124
+ if (i.origin !== T) return null;
125
+ let a = o.posix.basename(i.pathname);
126
+ return a === "render.html" ? {
127
+ contentType: "text/html; charset=utf-8",
128
+ body: t
129
+ } : /^three[\w.-]*\.js$/.test(a) ? {
130
+ contentType: "text/javascript; charset=utf-8",
131
+ body: await r(o.join(n, a), "utf-8")
132
+ } : null;
133
+ }
134
+ async function k(e, t) {
135
+ let n = o.dirname(w());
136
+ await e.setRequestInterception(!0), e.on("request", (e) => {
137
+ (async () => {
138
+ try {
139
+ let r = await O(e.url(), t, n);
140
+ await (r ? e.respond({
141
+ status: 200,
142
+ ...r
143
+ }) : e.abort());
144
+ } catch {}
145
+ })();
146
+ });
147
+ }
148
+ async function A(e) {
149
+ let r = await S();
150
+ if (!r) throw new _(g);
151
+ let i = n(t(e.script)).toJSON(), a = u({
152
+ ...e,
153
+ threeUrl: D,
154
+ sceneJson: i
155
+ }), o;
156
+ try {
157
+ o = await r.launch({
158
+ headless: !0,
159
+ timeout: m,
160
+ args: ["--enable-unsafe-swiftshader", "--use-gl=swiftshader"]
161
+ });
162
+ } catch (e) {
163
+ throw new _(`${g} (launch failed: ${f(e)})`);
164
+ }
165
+ try {
166
+ let e = await o.newPage();
167
+ await e.setViewport({
168
+ width: 800,
169
+ height: 600
170
+ });
171
+ let t = [];
172
+ e.on("pageerror", (e) => t.push(e.message)), await k(e, a), await e.goto(E, { waitUntil: "load" });
173
+ try {
174
+ await e.waitForFunction("typeof window.__shapeSheet === 'string'", { timeout: p });
175
+ } catch (e) {
176
+ let n = t.length > 0 ? `the render page failed: ${t.join("; ")}` : f(e);
177
+ throw Error(n, { cause: e });
178
+ }
179
+ let n = await e.evaluate("window.__shapeSheet");
180
+ if (typeof n != "string" || !n.startsWith("data:image/png;base64,")) throw Error("the render page produced no image");
181
+ return n.slice(22);
182
+ } finally {
183
+ await o.close().catch((t) => v(e.onWarning, `chromium close failed: ${f(t)}`));
184
+ }
185
+ }
186
+ //#endregion
187
+ //#region src/render/tool.ts
188
+ var j = 30, M = 25, N = 1, P = 480, F = 900, I = 160, L = 85, R = h + 3e4, z = "renderShapeScript", B = "Render a ShapeScript model to a PNG image and save it, so you can LOOK at the model you wrote and check it before showing it to the user. Returns the image path — read that file to see the result. By default it renders four camera angles onto one sheet, because a single view cannot settle what is in front of what. Takes the same source as presentShapeScript: inline `script`, or `path` to a saved .shape file.", V = "Use renderShapeScript to CHECK a 3D model you wrote before presenting it — it saves a PNG and returns the path, which you then read to see what the model actually looks like. Fix what you see and re-render. Rendering needs a local headless browser; if it reports one is missing, say so and continue with presentShapeScript rather than retrying.", H = {
189
+ type: "object",
190
+ properties: {
191
+ script: {
192
+ type: "string",
193
+ description: "ShapeScript source to render. Provide either this or `path`, not both."
194
+ },
195
+ path: {
196
+ type: "string",
197
+ description: "Path to an existing .shape file to render (e.g. one presentShapeScript saved under artifacts/shapes/)."
198
+ },
199
+ azimuth: {
200
+ type: "number",
201
+ description: `Camera rotation around the model in degrees, 0 = looking from +Z. Default ${j}. In the default four-view sheet this is the FIRST view's angle; the others are offset from it.`
202
+ },
203
+ elevation: {
204
+ type: "number",
205
+ description: `Camera height in degrees above the horizon, 90 = straight down. Default ${M}. Avoid 0 and 90 for the main view — an axis-aligned shot flattens depth.`
206
+ },
207
+ zoom: {
208
+ type: "number",
209
+ description: "Multiplier on the automatic framing, which fits the whole model. 1 = fit (default), 2 = twice as close, 0.5 = further out. Prefer this over guessing a camera distance: it means the same thing at any model scale."
210
+ },
211
+ views: {
212
+ type: "string",
213
+ enum: ["quad", "single"],
214
+ description: "`quad` (default) renders four angles on one sheet — use it to judge shape and layout. `single` renders only `azimuth`/`elevation`, for a close look at one detail."
215
+ },
216
+ projection: {
217
+ type: "string",
218
+ enum: ["perspective", "orthographic"],
219
+ description: "`perspective` (default) looks natural; `orthographic` keeps parallel edges parallel, which is better for comparing proportions."
220
+ },
221
+ width: {
222
+ type: "number",
223
+ description: `Pixel width of ONE view. Default ${P}, clamped to ${I}–${F}.`
224
+ },
225
+ height: {
226
+ type: "number",
227
+ description: `Pixel height of ONE view. Default ${P}, clamped to ${I}–${F}.`
228
+ }
229
+ },
230
+ required: []
231
+ };
232
+ function U(e, t) {
233
+ return typeof e != "number" || !Number.isFinite(e) ? t : Math.min(F, Math.max(I, Math.round(e)));
234
+ }
235
+ function W(e, t) {
236
+ return typeof e == "number" && Number.isFinite(e) ? e : t;
237
+ }
238
+ var G = (e) => `${Math.round(e)}°`;
239
+ function K(e, t, n) {
240
+ let r = (e, t, n) => ({
241
+ azimuth: e,
242
+ elevation: t,
243
+ label: `${n} — az ${G(e)}, el ${G(t)}`
244
+ });
245
+ return n ? [r(e, t, "view")] : [
246
+ r(e, t, "front-right"),
247
+ r(e + 90, t, "back-right"),
248
+ r(e + 180, t, "back-left"),
249
+ r(e, L, "top")
250
+ ];
251
+ }
252
+ async function q(e, t) {
253
+ let n = typeof t.script == "string" && t.script.trim() !== "" ? t.script : void 0, r = typeof t.path == "string" && t.path.trim() !== "" ? t.path : void 0;
254
+ if (n && r) throw Error("Provide either `script` or `path`, not both");
255
+ if (n) return n;
256
+ if (r) return e.readShape(r);
257
+ throw Error("Provide either `script` (inline source) or `path` (an existing .shape file)");
258
+ }
259
+ function J(e, t, n, r) {
260
+ return {
261
+ script: t,
262
+ views: n,
263
+ width: U(e.width, P),
264
+ height: U(e.height, P),
265
+ zoom: Math.max(W(e.zoom, N), .01),
266
+ projection: e.projection === "orthographic" ? "orthographic" : "perspective",
267
+ ...r ? { onWarning: r } : {}
268
+ };
269
+ }
270
+ function Y(e, t) {
271
+ let n = t.map((e) => e.label).join("; ");
272
+ return `Saved render to ${e} (${t.length === 1 ? "1 view" : `${t.length} views`}: ${n}). Read that file to see the model.`;
273
+ }
274
+ async function X(e, t) {
275
+ let n = await q(e, t), r = K(W(t.azimuth, j), W(t.elevation, M), t.views === "single");
276
+ try {
277
+ let i = await A(J(t, n, r, e.onWarning));
278
+ return {
279
+ message: Y(await e.saveImage(i), r),
280
+ rendered: !0
281
+ };
282
+ } catch (t) {
283
+ if (t instanceof _) return v(e.onWarning, `renderShapeScript: unavailable — ${t.message}`), {
284
+ message: t.message,
285
+ rendered: !1
286
+ };
287
+ throw t;
288
+ }
289
+ }
290
+ //#endregion
291
+ export { g as CHROMIUM_HINT, m as LAUNCH_TIMEOUT_MS, h as RENDER_BUDGET_MS, B as RENDER_SHAPE_SCRIPT_DESCRIPTION, V as RENDER_SHAPE_SCRIPT_PROMPT, H as RENDER_SHAPE_SCRIPT_SCHEMA, z as RENDER_SHAPE_SCRIPT_TOOL_NAME, p as RENDER_TIMEOUT_MS, R as RENDER_TOOL_TIMEOUT_MS, _ as RenderUnavailableError, u as buildRenderPage, X as executeRenderShapeScript, s as gridFor, J as renderOptionsFrom, A as renderShapeScriptSheet, Y as savedMessage, K as viewAngles };
@@ -0,0 +1,186 @@
1
+ const e=require("./toThreeJS-BOBpx5Dc.cjs");let t=require("@mulmoclaude/core/artifacts");var n=`presentShapeScript`,r={type:`function`,name:n,description:"Display interactive 3D visualizations using ShapeScript with expressions, variables, control flow, and functions. A new `script` is saved to `artifacts/shapes/` and the returned `filePath` names it; pass `path` instead to present a source that already exists.",parameters:{type:`object`,properties:{title:{type:`string`,description:`Title for the 3D visualization`},script:{type:`string`,description:`ShapeScript code defining the 3D scene. Supported features and syntax are listed below. Syntax, evaluation, geometry and resource-limit errors are returned as diagnostics; correct the script and retry.
2
+
3
+ ## SYNTAX OVERVIEW:
4
+
5
+ ### Expressions & Operators:
6
+ - Arithmetic: +, -, *, /, % with proper precedence
7
+ - Comparison: =, <>, <, <=, >, >=
8
+ - Boolean: and, or, not
9
+ - Parentheses for grouping: (2 + 3) * 4
10
+
11
+ ### Variables:
12
+ define radius 2
13
+ define red (1 0 0)
14
+ sphere { size radius color red }
15
+
16
+ ### Control Flow:
17
+
18
+ For loops with variables:
19
+ for i in 1 to 5 {
20
+ cube { position (i * 2) 0 0 size 1 }
21
+ }
22
+
23
+ For loops with step:
24
+ for i in 0 to 10 step 2 {
25
+ sphere { position 0 i 0 }
26
+ }
27
+
28
+ If/else conditionals:
29
+ define showSphere 1
30
+ if showSphere {
31
+ sphere { size 2 }
32
+ } else {
33
+ cube { size 2 }
34
+ }
35
+
36
+ Switch statements:
37
+ define shape 2
38
+ switch shape {
39
+ case 1
40
+ cube
41
+ case 2
42
+ sphere
43
+ else
44
+ cone
45
+ }
46
+
47
+ ### Built-in Functions:
48
+
49
+ Math: round, floor, ceil, abs, sign, sqrt, pow, min, max
50
+ Trig: sin, cos, tan, asin, acos, atan, atan2 (uses radians)
51
+ Vector: dot, cross, length, normalize, sum
52
+
53
+ IMPORTANT: Function calls require NO space between name and parenthesis:
54
+ - sin(x) ✓ function call
55
+ - sin (x) ✗ NOT a function call (identifier + parenthesized expression)
56
+
57
+ Examples:
58
+ for i in 1 to 8 {
59
+ define angle (i * 0.785) // 45 degrees in radians
60
+ cube { position (cos(angle) * 3) 0 (sin(angle) * 3) }
61
+ }
62
+
63
+ ### Primitives & Properties:
64
+
65
+ Shapes: cube, sphere, cylinder, cone, torus, circle, square, polygon (sides 3–256)
66
+ Properties: position X Y Z, rotation X Y Z, size X Y Z
67
+ Materials: color R G B (0-1), opacity (0-1)
68
+
69
+ ### CSG Operations:
70
+ union, difference, intersection, xor, stencil
71
+
72
+ Example:
73
+ difference {
74
+ sphere { size 2 color (1 0.5 0) }
75
+ cube { size 1.5 }
76
+ }
77
+
78
+ ### Builders:
79
+ - extrude: extrude { polygon { sides 3 } } or extrude path { point 0 0 point 1 0 point 0 1 }
80
+ - fill: fill { square } or fill path { ... }
81
+ - lathe: lathe path { point 1 0 curve 0 2 1 -1 } (revolves about Y)
82
+ - loft: loft { square translate 0 0 2 circle } (closed planar sections joined with caps)
83
+ - hull: hull { cube { position -1 0 0 } cube { position 1 0 0 } } (convex envelope)
84
+ - stencil preserves the first shape and paints its surface with later shapes' materials.
85
+ Loft sections must each have one perimeter and enclose an area; extrude/fill primitive profiles must lie in XY.
86
+
87
+ ### Additional Expressions:
88
+ - Constants: pi, tau, true, false
89
+ - Scientific notation and unary plus: 1e-3, +2
90
+ - Tuple/vector members: vector.x, vector.y, vector.z; color.red/green/blue/alpha
91
+ - Tuple/string length: value.count; zero-based indexing: values[0]
92
+ - String literals, join(...), trim(...); min/max also accept tuples
93
+ - Custom shapes with options:
94
+ define post { option height 2 cylinder { size 0.2 height } }
95
+ post { height 3 }
96
+
97
+ ### Compatibility:
98
+ This plugin implements the documented modeling subset, not all upstream ShapeScript syntax.
99
+ Function calls use name(...); trig functions and rotation/orientation properties use radians.
100
+ Relative rotate/orientation commands and path rotate use turns (1 = 360 degrees).
101
+ Path point/curve coordinates are relative steps. Curves accept optional control-point offsets.
102
+ Imports, textures, text/fonts, arbitrary objects, and general user-defined functions are not supported.
103
+
104
+ ### Comments:
105
+ // Single-line comment
106
+ /* Multi-line
107
+ comment */
108
+
109
+ ## COMPLETE EXAMPLES:
110
+
111
+ Linear arrangement with expressions:
112
+ define spacing 1.5
113
+ for i in 1 to 4 {
114
+ cylinder { position ((i - 2.5) * spacing) 0 0 size 0.4 1 }
115
+ }
116
+
117
+ Circular pattern:
118
+ define count 12
119
+ for i in 1 to count {
120
+ define angle ((i / count) * 6.283) // 2 * PI
121
+ cube {
122
+ position (cos(angle) * 3) 0 (sin(angle) * 3)
123
+ color (i / count) 0.5 (1 - i / count)
124
+ size 0.5
125
+ }
126
+ }
127
+
128
+ Conditional geometry:
129
+ define makeHollow 1
130
+ if makeHollow {
131
+ difference {
132
+ sphere { size 2 color (1 0 0) }
133
+ sphere { size 1.7 }
134
+ }
135
+ } else {
136
+ sphere { size 2 color (1 0 0) }
137
+ }
138
+
139
+ Mathematical visualization:
140
+ for x in -5 to 5 {
141
+ for z in -5 to 5 {
142
+ define height (sin(x * 0.5) * cos(z * 0.5) * 2)
143
+ cube {
144
+ position (x * 0.3) height (z * 0.3)
145
+ size 0.25 (abs(height) + 0.1) 0.25
146
+ color (0.5 + height * 0.25) 0.3 (0.5 - height * 0.25)
147
+ }
148
+ }
149
+ }`},path:{type:`string`,description:"Path to an EXISTING ShapeScript source to present in place, instead of `script` — a `.shape` file this tool saved earlier (`artifacts/shapes/…`) or any other on disk. Provide either `script` or `path`, never both. Edits the user makes in the view write back to that same file."}},required:[`title`]}},i=`shapes`,a=`shape`,o=[`.shape`];function s(){let e=globalThis.crypto;if(e?.getRandomValues){let t=e.getRandomValues(new Uint8Array(4));return Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}return Math.random().toString(16).slice(2,10).padEnd(8,`0`)}function c(e,n=new Date,r=s()){let o=(0,t.buildArtifactRelPath)({dir:i,title:e,ext:`.shape`,fallback:a,now:n,partitioned:!1,suffix:r});return{relPath:o,filePath:(0,t.toWorkspaceArtifactPath)(o)}}function l(e){return!e.startsWith(`${t.ARTIFACTS_ROOT}/${i}/`)||!e.endsWith(`.shape`)?!1:!(0,t.hasUnsafePathSegment)(e)}function u(e){return e.startsWith(`${t.ARTIFACTS_ROOT}/`)?e.slice(t.ARTIFACTS_ROOT.length+1):e}function d(e){return(0,t.classifyFilePath)(e,o)!==null}function f(e,t){if(l(t))return{files:e.files.artifacts,rel:u(t)};let n=e.files.byPath;return n&&d(t)?{files:n,rel:t}:null}async function p(e,t){if(typeof t?.path!=`string`)throw Error(`path must be an existing .shape file`);let n=f(e,t.path);if(!n)throw Error(`path must be an existing .shape file`);switch(t.kind){case`loadShape`:return{script:await n.files.read(n.rel)};case`saveShape`:if(typeof t.script!=`string`)throw Error("saveShape requires `script` as a string");if(!await n.files.exists(n.rel))throw Error(`No ShapeScript exists at ${t.path}`);return await n.files.write(n.rel,t.script),{path:t.path};default:throw Error(`shapescript plugin: unknown dispatch kind ${JSON.stringify(t)}`)}}var m=`Acknowledge that the 3D visualization has been created and is displayed to the user. They can rotate, zoom, and pan the camera.`,h=e=>typeof e==`string`&&e.trim()!==``;function g(t){e.r(e.n(e.Pn(t)))}async function _(e,t){let n=e.files;if(!n)throw Error("This host cannot open a ShapeScript by path — pass the source as `script` instead");let r=f({files:n},t);if(!r)throw Error("`path` must be a .shape file, without `.` / `..` segments");if(!await r.files.exists(r.rel))throw Error(`No ShapeScript exists at ${t}`);return r.files.read(r.rel)}var v=5;async function y(e,t,n){let r=e.files?.artifacts;if(r){for(let e=0;e<v;e++){let{relPath:e,filePath:i}=c(n);if(!await r.exists(e))return await r.write(e,t),i}throw Error(`Could not allocate a free path under artifacts/shapes — try again with a different title`)}}async function b(e,t){if(h(t.path)&&h(t.script))throw Error("Provide either `script` or `path`, not both");if(h(t.path))return{script:await _(e,t.path),filePath:t.path};if(!h(t.script))throw Error(`ShapeScript code is required but was not provided`);return{script:t.script}}var x=async(t,n)=>{let r=`INVALID_ARGUMENT`;try{if(!e.In(n))throw Error("presentShapeScript args must be an object with `script` or `path`");if(!h(n.title))throw Error(`A nonempty visualization title is required`);let i=await b(t??{},n);r=`EVALUATION_ERROR`,g(i.script);let a=i.filePath??await y(t??{},i.script,n.title);return{message:a?`Saved ShapeScript to ${a}`:`Created 3D visualization: ${n.title}`,title:n.title,data:a?{script:i.script,filePath:a}:{script:i.script},instructions:m}}catch(t){let n={code:t instanceof e.Fn?`PARSE_ERROR`:t instanceof e.t?`LIMIT_EXCEEDED`:r,message:t instanceof Error?t.message:String(t),...t instanceof e.Fn&&t.line!==void 0?{line:t.line}:{},...t instanceof e.Fn&&t.column!==void 0?{column:t.column}:{}};return{message:`ShapeScript error: ${n.message}`,error:n,jsonData:{error:n},instructions:`The visualization was not created. Correct the ShapeScript using the returned diagnostic and call presentShapeScript again.`}}},S={toolDefinition:r,execute:x,generatingMessage:`Creating 3D visualization...`,waitingMessage:`Tell the user that the 3D visualization was created and will be presented shortly.`,isEnabled:()=>!0},C=x,w=[{name:`Basic Shapes`,args:{title:`Basic 3D Shapes`,script:`// Basic shapes demonstration
150
+ cube { position -2 0 0 size 1 color (1 0.3 0.3) }
151
+ sphere { position 0 0 0 size 1 color (0.3 1 0.3) }
152
+ cylinder { position 2 0 0 size 0.5 1 color (0.3 0.3 1) }`}},{name:`Circular Pattern`,args:{title:`Circular Pattern`,script:`// 12個の立方体を円形に配置
153
+
154
+ define count 12
155
+ define radius 3
156
+
157
+ for i in 1 to count {
158
+ // 各立方体の角度を計算(2 * PI = 6.283ラジアン)
159
+ define angle ((i / count) * 6.283)
160
+
161
+ // 円形配置のためのX座標とZ座標を計算
162
+ define x (cos(angle) * radius)
163
+ define z (sin(angle) * radius)
164
+
165
+ // グラデーションカラーを作成
166
+ define colorValue (i / count)
167
+
168
+ cube {
169
+ position x 0 z
170
+ size 0.5
171
+ color colorValue 0.5 (1 - colorValue)
172
+ }
173
+ }
174
+
175
+ // 中心に参考用の球体を配置
176
+ sphere {
177
+ position 0 0 0
178
+ size 0.3
179
+ color 1 1 0
180
+ opacity 0.5
181
+ }`}},{name:`CSG Difference`,args:{title:`Hollow Sphere`,script:`// Create a hollow sphere using CSG difference
182
+ difference {
183
+ sphere { size 2 color (1 0.5 0) }
184
+ sphere { size 1.7 color (1 1 1) }
185
+ cube { position 0 0 2 size 2 }
186
+ }`}}];Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return p}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return c}});
@@ -0,0 +1,180 @@
1
+ import { Fn as e, In as t, Pn as n, n as r, r as i, t as a } from "./toThreeJS-B5LiF110.js";
2
+ import { ARTIFACTS_ROOT as o, buildArtifactRelPath as s, classifyFilePath as c, hasUnsafePathSegment as l, toWorkspaceArtifactPath as u } from "@mulmoclaude/core/artifacts";
3
+ //#region src/core/definition.ts
4
+ var d = "presentShapeScript", f = {
5
+ type: "function",
6
+ name: d,
7
+ description: "Display interactive 3D visualizations using ShapeScript with expressions, variables, control flow, and functions. A new `script` is saved to `artifacts/shapes/` and the returned `filePath` names it; pass `path` instead to present a source that already exists.",
8
+ parameters: {
9
+ type: "object",
10
+ properties: {
11
+ title: {
12
+ type: "string",
13
+ description: "Title for the 3D visualization"
14
+ },
15
+ script: {
16
+ type: "string",
17
+ description: "ShapeScript code defining the 3D scene. Supported features and syntax are listed below. Syntax, evaluation, geometry and resource-limit errors are returned as diagnostics; correct the script and retry.\n\n## SYNTAX OVERVIEW:\n\n### Expressions & Operators:\n- Arithmetic: +, -, *, /, % with proper precedence\n- Comparison: =, <>, <, <=, >, >=\n- Boolean: and, or, not\n- Parentheses for grouping: (2 + 3) * 4\n\n### Variables:\ndefine radius 2\ndefine red (1 0 0)\nsphere { size radius color red }\n\n### Control Flow:\n\nFor loops with variables:\nfor i in 1 to 5 {\n cube { position (i * 2) 0 0 size 1 }\n}\n\nFor loops with step:\nfor i in 0 to 10 step 2 {\n sphere { position 0 i 0 }\n}\n\nIf/else conditionals:\ndefine showSphere 1\nif showSphere {\n sphere { size 2 }\n} else {\n cube { size 2 }\n}\n\nSwitch statements:\ndefine shape 2\nswitch shape {\ncase 1\n cube\ncase 2\n sphere\nelse\n cone\n}\n\n### Built-in Functions:\n\nMath: round, floor, ceil, abs, sign, sqrt, pow, min, max\nTrig: sin, cos, tan, asin, acos, atan, atan2 (uses radians)\nVector: dot, cross, length, normalize, sum\n\nIMPORTANT: Function calls require NO space between name and parenthesis:\n- sin(x) ✓ function call\n- sin (x) ✗ NOT a function call (identifier + parenthesized expression)\n\nExamples:\nfor i in 1 to 8 {\n define angle (i * 0.785) // 45 degrees in radians\n cube { position (cos(angle) * 3) 0 (sin(angle) * 3) }\n}\n\n### Primitives & Properties:\n\nShapes: cube, sphere, cylinder, cone, torus, circle, square, polygon (sides 3–256)\nProperties: position X Y Z, rotation X Y Z, size X Y Z\nMaterials: color R G B (0-1), opacity (0-1)\n\n### CSG Operations:\nunion, difference, intersection, xor, stencil\n\nExample:\ndifference {\n sphere { size 2 color (1 0.5 0) }\n cube { size 1.5 }\n}\n\n### Builders:\n- extrude: extrude { polygon { sides 3 } } or extrude path { point 0 0 point 1 0 point 0 1 }\n- fill: fill { square } or fill path { ... }\n- lathe: lathe path { point 1 0 curve 0 2 1 -1 } (revolves about Y)\n- loft: loft { square translate 0 0 2 circle } (closed planar sections joined with caps)\n- hull: hull { cube { position -1 0 0 } cube { position 1 0 0 } } (convex envelope)\n- stencil preserves the first shape and paints its surface with later shapes' materials.\nLoft sections must each have one perimeter and enclose an area; extrude/fill primitive profiles must lie in XY.\n\n### Additional Expressions:\n- Constants: pi, tau, true, false\n- Scientific notation and unary plus: 1e-3, +2\n- Tuple/vector members: vector.x, vector.y, vector.z; color.red/green/blue/alpha\n- Tuple/string length: value.count; zero-based indexing: values[0]\n- String literals, join(...), trim(...); min/max also accept tuples\n- Custom shapes with options:\ndefine post { option height 2 cylinder { size 0.2 height } }\npost { height 3 }\n\n### Compatibility:\nThis plugin implements the documented modeling subset, not all upstream ShapeScript syntax.\nFunction calls use name(...); trig functions and rotation/orientation properties use radians.\nRelative rotate/orientation commands and path rotate use turns (1 = 360 degrees).\nPath point/curve coordinates are relative steps. Curves accept optional control-point offsets.\nImports, textures, text/fonts, arbitrary objects, and general user-defined functions are not supported.\n\n### Comments:\n// Single-line comment\n/* Multi-line\n comment */\n\n## COMPLETE EXAMPLES:\n\nLinear arrangement with expressions:\ndefine spacing 1.5\nfor i in 1 to 4 {\n cylinder { position ((i - 2.5) * spacing) 0 0 size 0.4 1 }\n}\n\nCircular pattern:\ndefine count 12\nfor i in 1 to count {\n define angle ((i / count) * 6.283) // 2 * PI\n cube {\n position (cos(angle) * 3) 0 (sin(angle) * 3)\n color (i / count) 0.5 (1 - i / count)\n size 0.5\n }\n}\n\nConditional geometry:\ndefine makeHollow 1\nif makeHollow {\n difference {\n sphere { size 2 color (1 0 0) }\n sphere { size 1.7 }\n }\n} else {\n sphere { size 2 color (1 0 0) }\n}\n\nMathematical visualization:\nfor x in -5 to 5 {\n for z in -5 to 5 {\n define height (sin(x * 0.5) * cos(z * 0.5) * 2)\n cube {\n position (x * 0.3) height (z * 0.3)\n size 0.25 (abs(height) + 0.1) 0.25\n color (0.5 + height * 0.25) 0.3 (0.5 - height * 0.25)\n }\n }\n}"
18
+ },
19
+ path: {
20
+ type: "string",
21
+ description: "Path to an EXISTING ShapeScript source to present in place, instead of `script` — a `.shape` file this tool saved earlier (`artifacts/shapes/…`) or any other on disk. Provide either `script` or `path`, never both. Edits the user makes in the view write back to that same file."
22
+ }
23
+ },
24
+ required: ["title"]
25
+ }
26
+ }, p = "shapes", m = "shape", h = [".shape"];
27
+ function g() {
28
+ let e = globalThis.crypto;
29
+ if (e?.getRandomValues) {
30
+ let t = e.getRandomValues(/* @__PURE__ */ new Uint8Array(4));
31
+ return Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
32
+ }
33
+ return Math.random().toString(16).slice(2, 10).padEnd(8, "0");
34
+ }
35
+ function _(e, t = /* @__PURE__ */ new Date(), n = g()) {
36
+ let r = s({
37
+ dir: p,
38
+ title: e,
39
+ ext: ".shape",
40
+ fallback: m,
41
+ now: t,
42
+ partitioned: !1,
43
+ suffix: n
44
+ });
45
+ return {
46
+ relPath: r,
47
+ filePath: u(r)
48
+ };
49
+ }
50
+ function v(e) {
51
+ return !e.startsWith(`${o}/${p}/`) || !e.endsWith(".shape") ? !1 : !l(e);
52
+ }
53
+ function y(e) {
54
+ return e.startsWith(`${o}/`) ? e.slice(o.length + 1) : e;
55
+ }
56
+ function b(e) {
57
+ return c(e, h) !== null;
58
+ }
59
+ //#endregion
60
+ //#region src/core/dispatch.ts
61
+ function x(e, t) {
62
+ if (v(t)) return {
63
+ files: e.files.artifacts,
64
+ rel: y(t)
65
+ };
66
+ let n = e.files.byPath;
67
+ return n && b(t) ? {
68
+ files: n,
69
+ rel: t
70
+ } : null;
71
+ }
72
+ async function S(e, t) {
73
+ if (typeof t?.path != "string") throw Error("path must be an existing .shape file");
74
+ let n = x(e, t.path);
75
+ if (!n) throw Error("path must be an existing .shape file");
76
+ switch (t.kind) {
77
+ case "loadShape": return { script: await n.files.read(n.rel) };
78
+ case "saveShape":
79
+ if (typeof t.script != "string") throw Error("saveShape requires `script` as a string");
80
+ if (!await n.files.exists(n.rel)) throw Error(`No ShapeScript exists at ${t.path}`);
81
+ return await n.files.write(n.rel, t.script), { path: t.path };
82
+ default: throw Error(`shapescript plugin: unknown dispatch kind ${JSON.stringify(t)}`);
83
+ }
84
+ }
85
+ //#endregion
86
+ //#region src/core/plugin.ts
87
+ var C = "Acknowledge that the 3D visualization has been created and is displayed to the user. They can rotate, zoom, and pan the camera.", w = (e) => typeof e == "string" && e.trim() !== "";
88
+ function T(e) {
89
+ i(r(n(e)));
90
+ }
91
+ async function E(e, t) {
92
+ let n = e.files;
93
+ if (!n) throw Error("This host cannot open a ShapeScript by path — pass the source as `script` instead");
94
+ let r = x({ files: n }, t);
95
+ if (!r) throw Error("`path` must be a .shape file, without `.` / `..` segments");
96
+ if (!await r.files.exists(r.rel)) throw Error(`No ShapeScript exists at ${t}`);
97
+ return r.files.read(r.rel);
98
+ }
99
+ var D = 5;
100
+ async function O(e, t, n) {
101
+ let r = e.files?.artifacts;
102
+ if (r) {
103
+ for (let e = 0; e < D; e++) {
104
+ let { relPath: e, filePath: i } = _(n);
105
+ if (!await r.exists(e)) return await r.write(e, t), i;
106
+ }
107
+ throw Error("Could not allocate a free path under artifacts/shapes — try again with a different title");
108
+ }
109
+ }
110
+ async function k(e, t) {
111
+ if (w(t.path) && w(t.script)) throw Error("Provide either `script` or `path`, not both");
112
+ if (w(t.path)) return {
113
+ script: await E(e, t.path),
114
+ filePath: t.path
115
+ };
116
+ if (!w(t.script)) throw Error("ShapeScript code is required but was not provided");
117
+ return { script: t.script };
118
+ }
119
+ var A = async (n, r) => {
120
+ let i = "INVALID_ARGUMENT";
121
+ try {
122
+ if (!t(r)) throw Error("presentShapeScript args must be an object with `script` or `path`");
123
+ if (!w(r.title)) throw Error("A nonempty visualization title is required");
124
+ let e = await k(n ?? {}, r);
125
+ i = "EVALUATION_ERROR", T(e.script);
126
+ let a = e.filePath ?? await O(n ?? {}, e.script, r.title);
127
+ return {
128
+ message: a ? `Saved ShapeScript to ${a}` : `Created 3D visualization: ${r.title}`,
129
+ title: r.title,
130
+ data: a ? {
131
+ script: e.script,
132
+ filePath: a
133
+ } : { script: e.script },
134
+ instructions: C
135
+ };
136
+ } catch (t) {
137
+ let n = {
138
+ code: t instanceof e ? "PARSE_ERROR" : t instanceof a ? "LIMIT_EXCEEDED" : i,
139
+ message: t instanceof Error ? t.message : String(t),
140
+ ...t instanceof e && t.line !== void 0 ? { line: t.line } : {},
141
+ ...t instanceof e && t.column !== void 0 ? { column: t.column } : {}
142
+ };
143
+ return {
144
+ message: `ShapeScript error: ${n.message}`,
145
+ error: n,
146
+ jsonData: { error: n },
147
+ instructions: "The visualization was not created. Correct the ShapeScript using the returned diagnostic and call presentShapeScript again."
148
+ };
149
+ }
150
+ }, j = {
151
+ toolDefinition: f,
152
+ execute: A,
153
+ generatingMessage: "Creating 3D visualization...",
154
+ waitingMessage: "Tell the user that the 3D visualization was created and will be presented shortly.",
155
+ isEnabled: () => !0
156
+ }, M = A, N = [
157
+ {
158
+ name: "Basic Shapes",
159
+ args: {
160
+ title: "Basic 3D Shapes",
161
+ script: "// Basic shapes demonstration\ncube { position -2 0 0 size 1 color (1 0.3 0.3) }\nsphere { position 0 0 0 size 1 color (0.3 1 0.3) }\ncylinder { position 2 0 0 size 0.5 1 color (0.3 0.3 1) }"
162
+ }
163
+ },
164
+ {
165
+ name: "Circular Pattern",
166
+ args: {
167
+ title: "Circular Pattern",
168
+ script: "// 12個の立方体を円形に配置\n\ndefine count 12\ndefine radius 3\n\nfor i in 1 to count {\n // 各立方体の角度を計算(2 * PI = 6.283ラジアン)\n define angle ((i / count) * 6.283)\n\n // 円形配置のためのX座標とZ座標を計算\n define x (cos(angle) * radius)\n define z (sin(angle) * radius)\n\n // グラデーションカラーを作成\n define colorValue (i / count)\n\n cube {\n position x 0 z\n size 0.5\n color colorValue 0.5 (1 - colorValue)\n }\n}\n\n// 中心に参考用の球体を配置\nsphere {\n position 0 0 0\n size 0.3\n color 1 1 0\n opacity 0.5\n}"
169
+ }
170
+ },
171
+ {
172
+ name: "CSG Difference",
173
+ args: {
174
+ title: "Hollow Sphere",
175
+ script: "// Create a hollow sphere using CSG difference\ndifference {\n sphere { size 2 color (1 0.5 0) }\n sphere { size 1.7 color (1 1 1) }\n cube { position 0 0 2 size 2 }\n}"
176
+ }
177
+ }
178
+ ];
179
+ //#endregion
180
+ export { S as a, b as c, y as d, f, A as i, v as l, M as n, x as o, d as p, j as r, h as s, N as t, _ as u };