spi3der 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.
Files changed (113) hide show
  1. package/APP.md +40 -0
  2. package/Dockerfile +4 -0
  3. package/MCP.md +149 -0
  4. package/PLAYER.md +136 -0
  5. package/README.md +35 -2
  6. package/api/mcp.mjs +31 -0
  7. package/api/store.mjs +158 -0
  8. package/bin/spi3der.mjs +20 -0
  9. package/emulator.html +17 -0
  10. package/engine/8fa668821759/bevel.js +265 -0
  11. package/engine/8fa668821759/camera.js +76 -0
  12. package/engine/8fa668821759/character.js +1019 -0
  13. package/engine/8fa668821759/check.js +83 -0
  14. package/engine/8fa668821759/csg.js +342 -0
  15. package/engine/8fa668821759/edit.js +48 -0
  16. package/engine/8fa668821759/galaxy.js +265 -0
  17. package/engine/8fa668821759/gl.js +798 -0
  18. package/engine/8fa668821759/gpu.js +1356 -0
  19. package/engine/8fa668821759/index.js +48 -0
  20. package/engine/8fa668821759/instances.js +41 -0
  21. package/engine/8fa668821759/joints.js +355 -0
  22. package/engine/8fa668821759/kernel-bytes.js +2 -0
  23. package/engine/8fa668821759/kernel.js +82 -0
  24. package/engine/8fa668821759/lathe.js +87 -0
  25. package/engine/8fa668821759/material.js +19 -0
  26. package/engine/8fa668821759/mesh.js +131 -0
  27. package/engine/8fa668821759/order.js +125 -0
  28. package/engine/8fa668821759/pick.js +85 -0
  29. package/engine/8fa668821759/place.js +17 -0
  30. package/engine/8fa668821759/planet.js +376 -0
  31. package/engine/8fa668821759/rig.js +417 -0
  32. package/engine/8fa668821759/saw.js +121 -0
  33. package/engine/8fa668821759/sky.js +428 -0
  34. package/engine/8fa668821759/svg.js +239 -0
  35. package/engine/8fa668821759/text.js +231 -0
  36. package/engine/8fa668821759/triangulate.js +72 -0
  37. package/engine/8fa668821759/types.js +2 -0
  38. package/engine/8fa668821759/vec.js +22 -0
  39. package/engine/8fa668821759/version.js +7 -0
  40. package/engine/8fa668821759/vrtsh.js +354 -0
  41. package/engine/8fa668821759/wire.js +346 -0
  42. package/favicon.svg +15 -0
  43. package/help.md +289 -0
  44. package/icons/apple-touch-icon.png +0 -0
  45. package/icons/favicon-32.png +0 -0
  46. package/icons/icon-192.png +0 -0
  47. package/icons/icon-512.png +0 -0
  48. package/icons/icon-maskable-512.png +0 -0
  49. package/icons/icon-maskable.svg +13 -0
  50. package/icons/icon.svg +15 -0
  51. package/index.html +13730 -0
  52. package/manifest.webmanifest +37 -0
  53. package/mcp/engine/bevel.js +265 -0
  54. package/mcp/engine/camera.js +76 -0
  55. package/mcp/engine/character.js +1019 -0
  56. package/mcp/engine/check.js +83 -0
  57. package/mcp/engine/csg.js +342 -0
  58. package/mcp/engine/edit.js +48 -0
  59. package/mcp/engine/galaxy.js +265 -0
  60. package/mcp/engine/gl.js +798 -0
  61. package/mcp/engine/gpu.js +1356 -0
  62. package/mcp/engine/index.js +48 -0
  63. package/mcp/engine/instances.js +41 -0
  64. package/mcp/engine/joints.js +355 -0
  65. package/mcp/engine/kernel-bytes.js +2 -0
  66. package/mcp/engine/kernel.js +82 -0
  67. package/mcp/engine/lathe.js +87 -0
  68. package/mcp/engine/material.js +19 -0
  69. package/mcp/engine/mesh.js +131 -0
  70. package/mcp/engine/order.js +125 -0
  71. package/mcp/engine/pick.js +85 -0
  72. package/mcp/engine/place.js +17 -0
  73. package/mcp/engine/planet.js +376 -0
  74. package/mcp/engine/rig.js +417 -0
  75. package/mcp/engine/saw.js +121 -0
  76. package/mcp/engine/sky.js +428 -0
  77. package/mcp/engine/svg.js +239 -0
  78. package/mcp/engine/text.js +231 -0
  79. package/mcp/engine/triangulate.js +72 -0
  80. package/mcp/engine/types.js +2 -0
  81. package/mcp/engine/vec.js +22 -0
  82. package/mcp/engine/version.js +7 -0
  83. package/mcp/engine/vrtsh.js +354 -0
  84. package/mcp/engine/wire.js +346 -0
  85. package/mcp/http.js +292 -0
  86. package/mcp/live.js +95 -0
  87. package/mcp/package.json +10 -0
  88. package/mcp/scene.js +1027 -0
  89. package/mcp/serve.js +87 -0
  90. package/mcp/server.js +97 -0
  91. package/media/face-of-spider.png +0 -0
  92. package/media/spider-paint-2015.png +0 -0
  93. package/media/spider-web.png +0 -0
  94. package/models/deepsky-lark.scene.json +1 -0
  95. package/models/deepsky.scene.json +1 -0
  96. package/models/globe.scene.json +1 -0
  97. package/models/lark-4.scene.json +1 -0
  98. package/models/lark.game.json +14 -0
  99. package/models/spider-build-v2.md +215 -0
  100. package/models/spider-build-v2.mjs +355 -0
  101. package/models/spider-build-v2.schema.json +1001 -0
  102. package/nginx.conf +12 -0
  103. package/package.json +45 -4
  104. package/player.html +274 -0
  105. package/sky.html +133 -0
  106. package/sky.md +285 -0
  107. package/src/demo.js +92 -0
  108. package/src/emulator/devices.js +22 -0
  109. package/src/emulator/xr.js +362 -0
  110. package/src/math.js +77 -0
  111. package/sw.js +37 -0
  112. package/xr-compare.html +332 -0
  113. package/xr-test.html +248 -0
package/mcp/scene.js ADDED
@@ -0,0 +1,1027 @@
1
+ // (copied from 3Draft 8fa6688 by scripts/sync.mjs: change it there)
2
+ // The model and its tools. One scene of named objects (meshes), edited by tool calls
3
+ // and judged by the deterministic SVG preview. No I/O except save/load of JSON files
4
+ // under the working directory. The MCP transport is in server.js.
5
+
6
+ import { readFileSync, writeFileSync } from 'node:fs';
7
+ import { resolve, relative, isAbsolute, extname } from 'node:path';
8
+ import { skyScene, SKY_TYPES, box, extrude, extrudeFace, moveVertices, faceNormal, faceCenter, merge, rotate, bounds, makeCamera, orbit, pick, ray as camRay, renderView, renderSheet, validate, boolean, VIEW_ORDER, triangulate, buildCharacter, normalizeCharacter, variateCharacter, posed, walkPose, HUMANOID_POSES, CHARACTER_PRESETS, makeJoint, jointNow, hingeTo, pivotTo, railTo, carried, moveMesh, springMesh } from './engine/index.js';
9
+
10
+ export class ToolError extends Error {}
11
+ const fail = (message) => {
12
+ throw new ToolError(message);
13
+ };
14
+
15
+ const r6 = (n) => Math.round(n * 1e6) / 1e6;
16
+ const rv = (v) => v.map(r6);
17
+ const isNum = (n) => typeof n === 'number' && Number.isFinite(n);
18
+
19
+ const vec3 = (v, what, fallback) => {
20
+ if (v === undefined) return fallback ?? fail(`${what} is required`);
21
+ if (!Array.isArray(v) || v.length !== 3 || !v.every(isNum)) fail(`${what} must be [x, y, z], three numbers`);
22
+ return v;
23
+ };
24
+ const name = (v) => {
25
+ if (typeof v !== 'string' || !v.trim() || v.length > 64) fail('name must be a non-empty string of at most 64 characters');
26
+ return v;
27
+ };
28
+ const color = (v, fallback = '#c8c8c8') => {
29
+ if (v === undefined) return fallback;
30
+ if (typeof v !== 'string' || !/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v)) fail('color must be #rgb or #rrggbb');
31
+ return v;
32
+ };
33
+ const number = (v, what, { min = -Infinity, max = Infinity, fallback } = {}) => {
34
+ if (v === undefined) return fallback ?? fail(`${what} is required`);
35
+ if (!isNum(v) || v < min || v > max) fail(`${what} must be a number between ${min} and ${max}`);
36
+ return v;
37
+ };
38
+
39
+ /** Validates raw mesh data from a client: positions [[x,y,z]], faces [{ v: [indices], color? }]. */
40
+ const parseMesh = (positions, faces, fallbackColor) => {
41
+ if (!Array.isArray(positions) || positions.length < 3) fail('positions must be a list of at least 3 [x, y, z] points');
42
+ positions.forEach((p, i) => vec3(p, `positions[${i}]`));
43
+ if (!Array.isArray(faces) || !faces.length) fail('faces must be a non-empty list of { v: [indices], color? }');
44
+ const out = faces.map((f, i) => {
45
+ const v = f?.v;
46
+ if (!Array.isArray(v) || v.length < 3) fail(`faces[${i}].v needs at least 3 vertex indices`);
47
+ v.forEach((k) => {
48
+ if (!Number.isInteger(k) || k < 0 || k >= positions.length) fail(`faces[${i}].v has index ${k}, but there are ${positions.length} positions`);
49
+ });
50
+ return { v: [...v], color: color(f.color, fallbackColor), ...(typeof f.mat === 'string' ? { mat: f.mat } : {}) };
51
+ });
52
+ return { positions: positions.map((p) => [...p]), faces: out };
53
+ };
54
+
55
+ const extent = (mesh) => {
56
+ const min = [Infinity, Infinity, Infinity];
57
+ const max = [-Infinity, -Infinity, -Infinity];
58
+ for (const p of mesh.positions) {
59
+ for (let a = 0; a < 3; a++) {
60
+ min[a] = Math.min(min[a], p[a]);
61
+ max[a] = Math.max(max[a], p[a]);
62
+ }
63
+ }
64
+ return { min: rv(min), max: rv(max) };
65
+ };
66
+
67
+ // ---- vectors, rotations and a ray cast, for place_on (the G G of the viewer) and the rotations of transform
68
+ const vsub = (a, b) => a.map((v, i) => v - b[i]);
69
+ const vdot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
70
+ const vcross = (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]];
71
+ const vnorm = (a) => {
72
+ const l = Math.hypot(...a);
73
+ return l > 0 ? a.map((v) => v / l) : a;
74
+ };
75
+ // rotate every point by `angle` (radians) round the unit `axis` through `pivot` (Rodrigues)
76
+ const turnAbout = (mesh, axis, angle, pivot) => {
77
+ if (!angle) return mesh;
78
+ const k = vnorm(axis), c = Math.cos(angle), sn = Math.sin(angle);
79
+ return {
80
+ ...mesh,
81
+ positions: mesh.positions.map((p) => {
82
+ const v = vsub(p, pivot), kv = vcross(k, v), d = vdot(k, v);
83
+ return [0, 1, 2].map((i) => pivot[i] + v[i] * c + kv[i] * sn + k[i] * d * (1 - c));
84
+ }),
85
+ };
86
+ };
87
+ // turn the mesh round `pivot` so that its up (+y) points along `n`
88
+ const upTo = (mesh, n, pivot) => {
89
+ const u = vnorm(n), d = Math.max(-1, Math.min(1, u[1]));
90
+ if (d > 1 - 1e-9) return mesh;
91
+ if (d < -1 + 1e-9) return turnAbout(mesh, [1, 0, 0], Math.PI, pivot);
92
+ return turnAbout(mesh, vcross([0, 1, 0], u), Math.acos(d), pivot);
93
+ };
94
+ // the nearest face of `targets` ([name, mesh] pairs) along the ray; the normal faces the ray's origin. With all: every hit,
95
+ // nearest first, each with `facing`: true where the ray meets the face's outside (entering a closed object), false inside
96
+ const castRay = (targets, origin, dir, { all = false } = {}) => {
97
+ const D = vnorm(dir);
98
+ let best = null;
99
+ const hits = [];
100
+ for (const [n, mesh] of targets) {
101
+ mesh.faces.forEach((f, fi) => {
102
+ const pts = f.v.map((k) => mesh.positions[k]);
103
+ for (const [a, b, c] of triangulate(pts)) {
104
+ const A = pts[a], e1 = vsub(pts[b], A), e2 = vsub(pts[c], A), P = vcross(D, e2), det = vdot(e1, P);
105
+ if (det * det <= 1e-24 * vdot(e1, e1) * vdot(e2, e2)) continue;
106
+ const T = vsub(origin, A), u = vdot(T, P) / det;
107
+ if (u < 0 || u > 1) continue;
108
+ const Q = vcross(T, e1), v = vdot(D, Q) / det;
109
+ if (v < 0 || u + v > 1) continue;
110
+ const t = vdot(e2, Q) / det;
111
+ if (t > 1e-9 && (all || !best || t < best.t)) {
112
+ const out = vnorm(faceNormal(pts));
113
+ const facing = vdot(out, D) < 0;
114
+ const hit = { t, object: n, face: fi, point: origin.map((o, i) => o + D[i] * t), normal: facing ? out : out.map((x) => -x), facing };
115
+ if (all) hits.push(hit);
116
+ else best = hit;
117
+ break; // (one hit a face: a ray along a diagonal would meet both its triangles)
118
+ }
119
+ }
120
+ });
121
+ }
122
+ return all ? hits.sort((a, b) => a.t - b.t) : best;
123
+ };
124
+ // the foot of a mesh: the middle of the bottom of its bounding box (for a figure: the middle of where it stands)
125
+ const footOf = (mesh) => {
126
+ const { min, max } = extent(mesh);
127
+ return [(min[0] + max[0]) / 2, min[1], (min[2] + max[2]) / 2];
128
+ };
129
+
130
+ // the map that takes mesh `a` to mesh `b` (same vertices moved by a turn, a uniform size and a move), from three spread vertices
131
+ const rigidBetween = (a, b) => {
132
+ const P = a.positions, Q = b.positions;
133
+ let i1 = 0, d1 = -1;
134
+ P.forEach((p, i) => { const d = Math.hypot(...vsub(p, P[0])); if (d > d1) ((d1 = d), (i1 = i)); });
135
+ const u = vnorm(vsub(P[i1], P[0]));
136
+ let i2 = 0, d2 = -1;
137
+ P.forEach((p, i) => { const w = vsub(p, P[0]); const d = Math.hypot(...vsub(w, u.map((x) => x * vdot(w, u)))); if (d > d2) ((d2 = d), (i2 = i)); });
138
+ const frame = (X, i) => {
139
+ const x = vnorm(vsub(X[i1], X[0])), z = vnorm(vcross(x, vsub(X[i2], X[0]))), y = vcross(z, x);
140
+ return { o: X[0], R: [x, y, z], s: Math.hypot(...vsub(X[i1], X[0])) };
141
+ };
142
+ if (d1 <= 0 || d2 <= 1e-12) { const t = vsub(Q[0], P[0]); return (p) => p.map((v, k) => v + t[k]); }
143
+ const fa = frame(P), fb = frame(Q), k = fb.s / fa.s;
144
+ return (p) => {
145
+ const w = vsub(p, fa.o), l = fa.R.map((r) => vdot(r, w));
146
+ return [0, 1, 2].map((c) => fb.o[c] + k * (fb.R[0][c] * l[0] + fb.R[1][c] * l[1] + fb.R[2][c] * l[2]));
147
+ };
148
+ };
149
+
150
+ const safePath = (p) => {
151
+ if (typeof p !== 'string' || !p) fail('path must be a string');
152
+ const full = resolve(process.cwd(), p);
153
+ const rel = relative(process.cwd(), full);
154
+ if (rel.startsWith('..') || isAbsolute(rel)) fail('path must stay inside the server working directory');
155
+ if (!['.json', '.3draft'].includes(extname(full))) fail('path must end in .3draft or .json');
156
+ return full;
157
+ };
158
+
159
+ const vec3Schema = { type: 'array', items: { type: 'number' }, minItems: 3, maxItems: 3 };
160
+ const nameSchema = { type: 'string', description: 'Object name, unique in the scene.' };
161
+ const colorSchema = { type: 'string', description: 'Face color, #rgb or #rrggbb.' };
162
+ const replaceSchema = { type: 'boolean', description: 'Overwrite an existing object with this name.' };
163
+ const viewProps = {
164
+ view: {
165
+ type: 'string',
166
+ enum: [...VIEW_ORDER, 'sheet', 'orbit'],
167
+ description: "front (eye on +z), side (eye on +x), top (eye on +y, -z is up), persp, orbit (uses yaw/pitch) or sheet (all four views on one 2x2 sheet; render only). Default: sheet for render, persp for pick.",
168
+ },
169
+ yaw: { type: 'number', description: 'orbit view, degrees: 0 looks from +z, 90 from -x, -90 from +x.' },
170
+ pitch: { type: 'number', description: 'orbit view, degrees above the horizon (default 25).' },
171
+ size: { type: 'number', description: 'Panel size in pixels, default 320.' },
172
+ };
173
+
174
+ export const createScene = () => {
175
+ const objects = new Map();
176
+ const listeners = new Set();
177
+ let rev = 0; // grows with every change, so a viewer can tell it is up to date
178
+ const info = { live: null }; // set by the server: { url, clients() }
179
+
180
+ const groups = new Map(); // object name -> group name (objects of one group move as one)
181
+ let joints = []; // the joints (src/joints.ts): glue, pivot, hinge, rail, spring
182
+ const screens = new Map(); // material name -> { name, color, url | scene | image }: the screens (set_screen), the scene's palette
183
+ const data = () => ({ format: '3draft-scene', version: 1, rev, objects: [...objects].map(([n, mesh]) => ({ name: n, mesh, ...(groups.has(n) ? { group: groups.get(n) } : {}) })), ...(joints.length ? { joints } : {}), ...(screens.size ? { palette: [...screens.values()] } : {}) });
184
+ const linked = () => [...objects.keys()].map((n) => ({ name: n, group: groups.get(n) }));
185
+ // the objects that move with `n` (its group, what is glued to it, what it holds), all moved by f(mesh) -> mesh
186
+ const moveWith = (n, f) => {
187
+ const names = carried([n], linked(), joints);
188
+ for (const m of names) objects.set(m, f(objects.get(m)));
189
+ stretchSprings();
190
+ return names;
191
+ };
192
+ // the objects carried by `n` follow its move from `before` to `after` (the rigid map that takes the one mesh to the other)
193
+ const carriedMove = (n, before, after) => {
194
+ const others = carried([n], linked(), joints).filter((m) => m !== n);
195
+ if (!others.length) return [];
196
+ const map = rigidBetween(before, after);
197
+ for (const m of others) objects.set(m, { ...objects.get(m), positions: objects.get(m).positions.map(map) });
198
+ return others;
199
+ };
200
+ const stretchSprings = () => {
201
+ for (const j of joints) if (j.spring && objects.has(j.spring.object) && objects.has(j.a) && objects.has(j.b)) objects.set(j.spring.object, springMesh(j, objects.get(j.a), objects.get(j.b)));
202
+ };
203
+ const dropLinks = (n) => {
204
+ groups.delete(n);
205
+ joints = joints.filter((j) => j.a !== n && j.b !== n);
206
+ };
207
+
208
+ const need = (n) => objects.get(name(n)) ?? fail(`no object named "${n}". Use list to see the objects.`);
209
+ // the sensing set (what the cursor of the viewer would feel): every object except the ignored ones; sense, pick and place_on
210
+ // look only at these. A call can narrow it further (exclude) or widen it (include: also ignored ones).
211
+ const ignored = new Set();
212
+ const names = (v, what) => (v === undefined ? [] : [v].flat().map((n) => (typeof n === 'string' ? n : fail(`${what} must be a name or a list of names`))));
213
+ const sensed = ({ exclude, include, only } = {}) => {
214
+ const ex = new Set(names(exclude, 'exclude')), inc = new Set(names(include, 'include'));
215
+ [...ex, ...inc].forEach(need);
216
+ const base = only !== undefined ? names(only, 'only').map((n) => (need(n), n)) : [...objects.keys()].filter((n) => !ignored.has(n) || inc.has(n));
217
+ return base.filter((n) => !ex.has(n)).map((n) => [n, objects.get(n)]);
218
+ };
219
+ const groupList = () => {
220
+ const out = {};
221
+ for (const [n, g] of groups) (out[g] ??= []).push(n);
222
+ return out;
223
+ };
224
+ const nowOut = (j) => {
225
+ const n = jointNow(j, objects.get(j.a), objects.get(j.b));
226
+ const r = (x) => (Array.isArray(x) ? (Array.isArray(x[0]) ? x.map(rv) : rv(x)) : r6(x));
227
+ return Object.fromEntries(Object.entries(n).map(([k, v]) => [k, typeof v === 'string' ? v : r(v)]));
228
+ };
229
+ const senseProps = {
230
+ exclude: { description: 'leave these objects out of the sensing for this call (to see through them: to place behind or into them)', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
231
+ include: { description: 'take these in for this call even if the sensing set ignores them', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
232
+ };
233
+ const hitOut = (h, eye) => ({ object: h.object, face: h.face, point: rv(h.point), normal: rv(h.normal), distance: r6(h.t), ...(h.facing === undefined ? {} : { outside: h.facing }) });
234
+ // a ray from the camera of a render (same view and size as render) through the pixel x, y
235
+ const pixelRay = (a) => {
236
+ if (!objects.size) fail('the scene is empty');
237
+ const { mesh } = combined();
238
+ const view = viewOf(a, 'persp');
239
+ if (view === 'sheet') fail('a single view is needed, not the sheet');
240
+ const size = number(a.size, 'size', { min: 64, max: 2000, fallback: 320 });
241
+ const cam = makeCamera(view, mesh, size, bounds(mesh));
242
+ return camRay(cam, number(a.x, 'x'), number(a.y, 'y'));
243
+ };
244
+ const put = (n, mesh, replace) => {
245
+ name(n);
246
+ if (objects.has(n) && !replace) fail(`"${n}" already exists; pass replace: true to overwrite it, or pick another name.`);
247
+ objects.set(n, mesh);
248
+ return summary(n, mesh);
249
+ };
250
+ const summary = (n, mesh) => ({ name: n, vertices: mesh.positions.length, faces: mesh.faces.length, ...extent(mesh) });
251
+
252
+ const combined = () => {
253
+ const names = [...objects.keys()];
254
+ const meshes = names.map((n) => objects.get(n));
255
+ const owners = [];
256
+ let start = 0;
257
+ names.forEach((n, i) => {
258
+ owners.push({ name: n, start, end: start + meshes[i].faces.length });
259
+ start += meshes[i].faces.length;
260
+ });
261
+ return { mesh: merge(...meshes), owners };
262
+ };
263
+
264
+ const viewOf = (args, fallback) => {
265
+ const v = args.view ?? fallback;
266
+ if (v === 'orbit') {
267
+ const yaw = (number(args.yaw, 'yaw', { fallback: 35 }) * Math.PI) / 180;
268
+ const pitch = (number(args.pitch, 'pitch', { min: -90, max: 90, fallback: 25 }) * Math.PI) / 180;
269
+ return orbit({ yaw, pitch });
270
+ }
271
+ if (VIEW_ORDER.includes(v) || v === 'sheet') return v;
272
+ return fail(`unknown view "${v}"`);
273
+ };
274
+
275
+ // a viewer command: to every open viewer through the live link (`view` event)
276
+ const sendView = (cmd) => {
277
+ if (!info.live?.command) fail('the live viewer is off (3DRAFT_LIVE=0) or could not bind a port');
278
+ const sent = info.live.command(cmd);
279
+ return sent ? { sent_to: sent, ...cmd } : { sent_to: 0, note: 'no viewer is open: call viewer for the URL and ask the user to open it' };
280
+ };
281
+
282
+ const tools = [
283
+ {
284
+ name: 'add_box',
285
+ description: 'Add an axis-aligned box. `at` is the CENTER, so its bottom is at at[1] - size[1] / 2. Y is up, the ground is y = 0. Units are arbitrary but keep them consistent.',
286
+ inputSchema: {
287
+ type: 'object',
288
+ properties: { name: nameSchema, size: { ...vec3Schema, description: '[width x, height y, depth z], default [1,1,1].' }, at: { ...vec3Schema, description: 'center, default [0,0,0].' }, color: colorSchema, replace: replaceSchema },
289
+ required: ['name'],
290
+ },
291
+ run: (a) => put(name(a.name), box({ size: vec3(a.size, 'size', [1, 1, 1]), at: vec3(a.at, 'at', [0, 0, 0]), color: color(a.color) }), a.replace),
292
+ },
293
+ {
294
+ name: 'add_extrusion',
295
+ description: 'Add a prism: a CONVEX footprint polygon on the ground plane, given as [[x, z], ...] in any winding, extruded up by `height` from `y`. Use it for triangles, hexagons, wedges, roofs, columns. Concave shapes must be split into several convex extrusions.',
296
+ inputSchema: {
297
+ type: 'object',
298
+ properties: { name: nameSchema, polygon: { type: 'array', items: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2 }, minItems: 3, description: '[[x, z], ...]' }, height: { type: 'number' }, y: { type: 'number', description: 'bottom, default 0' }, color: colorSchema, replace: replaceSchema },
299
+ required: ['name', 'polygon', 'height'],
300
+ },
301
+ run: (a) => {
302
+ if (!Array.isArray(a.polygon) || a.polygon.length < 3 || !a.polygon.every((p) => Array.isArray(p) && p.length === 2 && p.every(isNum))) fail('polygon must be [[x, z], ...] with at least 3 points');
303
+ let mesh;
304
+ try {
305
+ mesh = extrude({ polygon: a.polygon, height: number(a.height, 'height', { min: 1e-9 }), y: number(a.y, 'y', { fallback: 0 }), color: color(a.color) });
306
+ } catch (e) {
307
+ fail(e.message);
308
+ }
309
+ return put(name(a.name), mesh, a.replace);
310
+ },
311
+ },
312
+ {
313
+ name: 'add_mesh',
314
+ description: 'Add a raw mesh: `positions` [[x,y,z],...] and `faces` [{ v: [indices], color }]. Each face must be planar, convex and listed COUNTER-CLOCKWISE seen from outside (right-hand rule: the normal points out). Run inspect afterwards.',
315
+ inputSchema: {
316
+ type: 'object',
317
+ properties: {
318
+ name: nameSchema,
319
+ positions: { type: 'array', items: vec3Schema },
320
+ faces: { type: 'array', items: { type: 'object', properties: { v: { type: 'array', items: { type: 'integer' }, minItems: 3 }, color: colorSchema }, required: ['v'] } },
321
+ color: { ...colorSchema, description: 'Default color for faces without one.' },
322
+ replace: replaceSchema,
323
+ },
324
+ required: ['name', 'positions', 'faces'],
325
+ },
326
+ run: (a) => put(name(a.name), parseMesh(a.positions, a.faces, color(a.color)), a.replace),
327
+ },
328
+ {
329
+ name: 'transform',
330
+ description: 'Scale, then rotate round X, then round Z, then round Y, then move an object. Scale and rotations are about the center of its bounding box (or about `pivot`). Rotations are degrees, counter-clockwise looking from the + end of the axis towards the origin (right-hand rule): rotate_y 90 turns +x into -z, rotate_x 90 turns +y into +z, rotate_z 90 turns +x into +y.',
331
+ inputSchema: {
332
+ type: 'object',
333
+ properties: {
334
+ name: nameSchema,
335
+ scale: { description: 'Positive number, or [sx, sy, sz].', oneOf: [{ type: 'number' }, vec3Schema] },
336
+ rotate_x: { type: 'number', description: 'degrees round the X axis (tilts forward / back)' },
337
+ rotate_z: { type: 'number', description: 'degrees round the Z axis (tilts left / right)' },
338
+ rotate_y: { type: 'number', description: 'degrees, counter-clockwise seen from above' },
339
+ pivot: { ...vec3Schema, description: 'the point to scale and rotate about, default the center of the bounding box (e.g. a hinge, or the foot to tip a thing over)' },
340
+ move: { ...vec3Schema, description: 'translation [dx, dy, dz]' },
341
+ },
342
+ required: ['name'],
343
+ },
344
+ run: (a) => {
345
+ let mesh = need(a.name);
346
+ const { min, max } = extent(mesh);
347
+ const c = a.pivot !== undefined ? vec3(a.pivot, 'pivot') : [0, 1, 2].map((i) => (min[i] + max[i]) / 2);
348
+ if (a.scale !== undefined) {
349
+ const s = isNum(a.scale) ? [a.scale, a.scale, a.scale] : vec3(a.scale, 'scale');
350
+ if (!s.every((v) => v > 0)) fail('scale must be positive');
351
+ mesh = { ...mesh, positions: mesh.positions.map((p) => p.map((v, i) => c[i] + (v - c[i]) * s[i])) };
352
+ }
353
+ if (a.rotate_x !== undefined) mesh = turnAbout(mesh, [1, 0, 0], (number(a.rotate_x, 'rotate_x') * Math.PI) / 180, c);
354
+ if (a.rotate_z !== undefined) mesh = turnAbout(mesh, [0, 0, 1], (number(a.rotate_z, 'rotate_z') * Math.PI) / 180, c);
355
+ if (a.rotate_y !== undefined) {
356
+ const yaw = (number(a.rotate_y, 'rotate_y') * Math.PI) / 180;
357
+ mesh = rotate(mesh, { yaw }, c);
358
+ }
359
+ if (a.move !== undefined) {
360
+ const d = vec3(a.move, 'move');
361
+ mesh = { ...mesh, positions: mesh.positions.map((p) => p.map((v, i) => v + d[i])) };
362
+ }
363
+ const along = carriedMove(a.name, objects.get(a.name), mesh);
364
+ objects.set(a.name, mesh);
365
+ stretchSprings();
366
+ return { ...summary(a.name, mesh), ...(along.length ? { moved_along: along } : {}) };
367
+ },
368
+ },
369
+ {
370
+ name: 'place_on',
371
+ description: 'Put an object down on the surface of others, like the viewer\'s G G: its foot (the middle of the bottom of its bounding box; for a character the middle of where it stands) goes onto the surface point, and with align "normal" its up turns to the surface normal (a thing on a slope, a ball, a wall). Say where with `at` [x, z] (dropped straight down there: the highest surface under that spot), or a pixel `x`, `y` of a render (the ray from the camera, like the viewer\'s cursor; view / yaw / pitch / size as render), or `point` (+ `normal`) from sense / pick, or a ray (`from` + `dir`). Default: straight down at the object\'s own x, z. It lands on the sensing set (see sensing) without itself, or on `onto`; exclude / include change the set for this call (exclude a wall to place behind it). Returns the new bounds and the surface it landed on with its distance along the ray.',
372
+ inputSchema: {
373
+ type: 'object',
374
+ properties: {
375
+ name: nameSchema,
376
+ onto: { description: 'the object(s) to land on (a name or a list); default every other object', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
377
+ at: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: '[x, z]: drop straight down onto the surface at this spot (default: the object\'s own x, z, or the middle of `onto` when it is a single object)' },
378
+ point: { ...vec3Schema, description: 'a surface point (e.g. from pick); no ray is cast' },
379
+ normal: { ...vec3Schema, description: 'the surface normal at `point` (default up)' },
380
+ from: { ...vec3Schema, description: 'cast a ray from here …' },
381
+ dir: { ...vec3Schema, description: '… in this direction (e.g. [1, 0, 0] to hang a picture on a wall to the +x)' },
382
+ x: { type: 'number', description: 'a pixel of a render: cast from the camera through it (with y, and view / yaw / pitch / size as for render)' },
383
+ y: { type: 'number' },
384
+ view: viewProps.view, yaw: viewProps.yaw, pitch: viewProps.pitch, size: viewProps.size,
385
+ ...senseProps,
386
+ align: { type: 'string', enum: ['up', 'normal'], description: 'up (default): the object stays upright; normal: its up turns to the surface normal' },
387
+ turn: { type: 'number', description: 'degrees to turn it round its up axis first (counter-clockwise seen from above)' },
388
+ gap: { type: 'number', description: 'lift it off the surface by this much along the normal (default 0)' },
389
+ },
390
+ required: ['name'],
391
+ },
392
+ run: (a) => {
393
+ let mesh = need(a.name);
394
+ const ontoNames = a.onto === undefined ? sensed(a).map(([n]) => n).filter((n) => n !== a.name) : names(a.onto, 'onto').filter((n) => !names(a.exclude, 'exclude').includes(n));
395
+ ontoNames.forEach((n) => (n === a.name ? fail('an object cannot be placed on itself') : need(n)));
396
+ const targets = ontoNames.map((n) => [n, objects.get(n)]);
397
+ if (!targets.length) fail('there is nothing to place it on: add another object, or say `onto`');
398
+ let surface;
399
+ if (a.point !== undefined) {
400
+ surface = { object: null, point: vec3(a.point, 'point'), normal: vnorm(vec3(a.normal, 'normal', [0, 1, 0])) };
401
+ } else {
402
+ let origin, dir;
403
+ if (a.x !== undefined || a.y !== undefined) {
404
+ ({ origin, dir } = pixelRay(a));
405
+ } else if (a.from !== undefined || a.dir !== undefined) {
406
+ origin = vec3(a.from, 'from');
407
+ dir = vec3(a.dir, 'dir');
408
+ } else {
409
+ let xz;
410
+ if (a.at !== undefined) {
411
+ if (!Array.isArray(a.at) || a.at.length !== 2 || !a.at.every(isNum)) fail('at must be [x, z]');
412
+ xz = a.at;
413
+ } else if (ontoNames.length === 1 && a.onto !== undefined) {
414
+ const e = extent(targets[0][1]);
415
+ xz = [(e.min[0] + e.max[0]) / 2, (e.min[2] + e.max[2]) / 2];
416
+ } else {
417
+ const f = footOf(mesh);
418
+ xz = [f[0], f[2]];
419
+ }
420
+ const top = Math.max(...targets.map(([, m]) => extent(m).max[1]));
421
+ origin = [xz[0], top + 1, xz[1]];
422
+ dir = [0, -1, 0];
423
+ }
424
+ surface = castRay(targets, origin, dir, { all: true }).find((h) => h.facing) ?? null; // (front faces, as the cursor)
425
+ if (!surface) fail(`the ray from [${rv(origin)}] along [${rv(dir)}] hits nothing of ${ontoNames.join(', ')}`);
426
+ }
427
+ let foot = footOf(mesh);
428
+ if (a.turn !== undefined) mesh = rotate(mesh, { yaw: (number(a.turn, 'turn') * Math.PI) / 180 }, foot);
429
+ const align = a.align ?? 'up';
430
+ if (align !== 'up' && align !== 'normal') fail('align must be "up" or "normal"');
431
+ if (align === 'normal') mesh = upTo(mesh, surface.normal, foot);
432
+ const up = align === 'normal' ? surface.normal : [0, 1, 0];
433
+ const gap = number(a.gap, 'gap', { fallback: 0 });
434
+ const goal = surface.point.map((v, i) => v + up[i] * gap);
435
+ const d = vsub(goal, foot);
436
+ mesh = { ...mesh, positions: mesh.positions.map((p) => p.map((v, i) => v + d[i])) };
437
+ const along = carriedMove(a.name, objects.get(a.name), mesh);
438
+ objects.set(a.name, mesh);
439
+ stretchSprings();
440
+ return { ...summary(a.name, mesh), ...(along.length ? { moved_along: along } : {}), surface: { object: surface.object, point: rv(surface.point), normal: rv(surface.normal), ...(surface.t !== undefined ? { distance: r6(surface.t) } : {}) } };
441
+ },
442
+ },
443
+ {
444
+ name: 'add_character',
445
+ description: 'Add a character from the viewer\'s character builder: a stylized figure (about 1.6-1.9 tall, the units are metres) in a few meshes merged into one object, its feet on y = 0 at `at`, facing `yaw`. Presets: scientist, mechanic, crew (Space 1999 style uniform), astronaut. `seed` makes a random variation of the preset, `spec` overrides any field of the builder\'s spec (base: "male" | "female", body: { height, build, shoulders, head }, face: { shape, skin }, hair: { style, mat }, outfit: { kind, main, second, helmet }, prop). Pose: stand, sit (the seat under the hips at about 0.44) or walk (one stride). Give `onto` (and `at`) to stand it on a surface, as place_on.',
446
+ inputSchema: {
447
+ type: 'object',
448
+ properties: {
449
+ name: nameSchema,
450
+ preset: { type: 'string', enum: Object.keys(CHARACTER_PRESETS), description: 'default crew' },
451
+ seed: { type: 'integer', description: 'a random variation of the preset (face, hair, colours)' },
452
+ spec: { type: 'object', description: 'fields that override the preset (see the description)' },
453
+ pose: { type: 'string', enum: ['stand', 'sit', 'walk'], description: 'default stand' },
454
+ at: { ...vec3Schema, description: 'where it stands (the middle of its feet), default [0, 0, 0]; with onto only x and z count' },
455
+ yaw: { type: 'number', description: 'degrees: 0 faces +z, 90 faces +x, 180 faces -z' },
456
+ onto: { description: 'stand it on the surface of this object (or these), straight down at `at`', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
457
+ replace: replaceSchema,
458
+ },
459
+ required: ['name'],
460
+ },
461
+ run: (a) => {
462
+ name(a.name);
463
+ if (objects.has(a.name) && !a.replace) fail(`"${a.name}" already exists; pass replace: true to overwrite it, or pick another name.`);
464
+ const preset = a.preset ?? 'crew';
465
+ if (!CHARACTER_PRESETS[preset]) fail(`unknown preset "${preset}"; one of ${Object.keys(CHARACTER_PRESETS).join(', ')}`);
466
+ if (a.spec !== undefined && (typeof a.spec !== 'object' || Array.isArray(a.spec) || a.spec === null)) fail('spec must be an object');
467
+ const P = CHARACTER_PRESETS[preset], o = a.spec ?? {};
468
+ const merged = { ...P, ...o, body: { ...P.body, ...o.body }, face: { ...P.face, ...o.face }, hair: { ...P.hair, ...o.hair }, outfit: { ...P.outfit, ...o.outfit } };
469
+ let spec = normalizeCharacter(merged);
470
+ if (a.seed !== undefined) spec = variateCharacter(spec, Math.trunc(number(a.seed, 'seed')));
471
+ const pose = a.pose ?? 'stand';
472
+ if (!['stand', 'sit', 'walk'].includes(pose)) fail('pose must be stand, sit or walk');
473
+ const c = buildCharacter(spec);
474
+ const local = merge(...posed(c.parts.map((p) => p.mesh), c.rig, pose === 'sit' ? HUMANOID_POSES.sit : pose === 'walk' ? walkPose(0.12) : (HUMANOID_POSES.bind ?? {}), { ground: true }));
475
+ const at = vec3(a.at, 'at', [0, 0, 0]);
476
+ const yaw = (number(a.yaw, 'yaw', { fallback: 0 }) * Math.PI) / 180;
477
+ const cy = Math.cos(yaw), sy = Math.sin(yaw);
478
+ let mesh = { positions: local.positions.map((p) => [at[0] + p[0] * cy + p[2] * sy, at[1] + p[1], at[2] - p[0] * sy + p[2] * cy]), faces: local.faces.map((f) => ({ ...f, v: [...f.v] })) };
479
+ let surface;
480
+ if (a.onto !== undefined) {
481
+ const names = [a.onto].flat();
482
+ const targets = names.map((n) => [n, need(n)]);
483
+ const top = Math.max(...targets.map(([, m]) => extent(m).max[1]));
484
+ surface = castRay(targets, [at[0], top + 1, at[2]], [0, -1, 0]);
485
+ if (!surface) fail(`nothing of ${names.join(', ')} under x ${at[0]}, z ${at[2]}`);
486
+ const d = [0, surface.point[1] - at[1], 0];
487
+ mesh = { ...mesh, positions: mesh.positions.map((p) => p.map((v, i) => v + d[i])) };
488
+ }
489
+ objects.set(a.name, mesh);
490
+ return { ...summary(a.name, mesh), preset, pose, base: spec.base, height: r6(spec.body.height), ...(surface ? { surface: { object: surface.object, point: rv(surface.point) } } : {}) };
491
+ },
492
+ },
493
+ {
494
+ name: 'sense',
495
+ description: 'Feel the scene along a ray, as the viewer\'s cursor does from the camera: through pixel (x, y) of a render (same view and size as render), or from `from` along `dir`. Returns the first surface (object, face, point, normal, distance from the eye or `from`) and `hits`: everything along the ray, nearest first, with `outside` true where the ray enters an object and false where it leaves it, so you can see what is behind and how thick it is. Only the sensing set counts (see sensing); exclude / include change it for this call. Use the point and normal with place_on (point + normal), or give place_on the same pixel.',
496
+ inputSchema: { type: 'object', properties: { ...viewProps, x: { type: 'number' }, y: { type: 'number' }, from: vec3Schema, dir: vec3Schema, ...senseProps, limit: { type: 'integer', description: 'at most this many hits (default 12)' } } },
497
+ annotations: { readOnlyHint: true },
498
+ run: (a) => {
499
+ const r = a.from !== undefined || a.dir !== undefined ? { origin: vec3(a.from, 'from'), dir: vec3(a.dir, 'dir') } : pixelRay(a);
500
+ const targets = sensed(a);
501
+ const hits = castRay(targets, r.origin, r.dir, { all: true });
502
+ const limit = Math.trunc(number(a.limit, 'limit', { min: 1, max: 200, fallback: 12 }));
503
+ const first = hits.find((h) => h.facing) ?? null;
504
+ return { ray: { from: rv(r.origin), dir: rv(vnorm(r.dir)) }, sensed: targets.map(([n]) => n), first: first && hitOut(first), hits: hits.slice(0, limit).map((h) => hitOut(h)) };
505
+ },
506
+ },
507
+ {
508
+ name: 'sensing',
509
+ description: 'The sensing set: which objects sense, pick and place_on feel (the viewer\'s cursor feels everything; here you choose). New objects are sensed. ignore takes objects out (e.g. a wall to place things behind it, a box to place into it), sense puts them back, only senses just these, reset senses everything again. Returns the sensed and the ignored objects.',
510
+ inputSchema: {
511
+ type: 'object',
512
+ properties: {
513
+ ignore: { description: 'take these out of the sensing', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
514
+ sense: { description: 'put these back into the sensing', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
515
+ only: { description: 'sense only these (all others ignored)', oneOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }] },
516
+ reset: { type: 'boolean', description: 'sense every object again' },
517
+ },
518
+ },
519
+ run: (a) => {
520
+ if (a.reset) ignored.clear();
521
+ if (a.only !== undefined) {
522
+ const keep = new Set(names(a.only, 'only').map((n) => (need(n), n)));
523
+ for (const n of objects.keys()) if (!keep.has(n)) ignored.add(n);
524
+ for (const n of keep) ignored.delete(n);
525
+ }
526
+ for (const n of names(a.ignore, 'ignore')) (need(n), ignored.add(n));
527
+ for (const n of names(a.sense, 'sense')) (need(n), ignored.delete(n));
528
+ for (const n of [...ignored]) if (!objects.has(n)) ignored.delete(n);
529
+ return { sensed: [...objects.keys()].filter((n) => !ignored.has(n)), ignored: [...ignored] };
530
+ },
531
+ },
532
+ {
533
+ name: 'group',
534
+ description: 'Make a group: the objects move as one (in the viewer a G on any of them takes the whole group; the user groups a B selection with Ctrl+G). `objects` join the group `name` (leaving any group they were in); `rename` gives the group a new name. Returns every group.',
535
+ inputSchema: {
536
+ type: 'object',
537
+ properties: { name: { type: 'string', description: 'the group\'s name' }, objects: { type: 'array', items: { type: 'string' }, description: 'the objects to put in it' }, rename: { type: 'string', description: 'a new name for the group' } },
538
+ required: ['name'],
539
+ },
540
+ run: (a) => {
541
+ const g = name(a.name);
542
+ if (a.objects !== undefined) {
543
+ if (!Array.isArray(a.objects) || !a.objects.length) fail('objects must be a non-empty list of names');
544
+ a.objects.forEach((n) => (need(n), groups.set(n, g)));
545
+ } else if (![...groups.values()].includes(g)) fail(`no group named "${g}"; give objects to make it`);
546
+ if (a.rename !== undefined) {
547
+ const to = name(a.rename);
548
+ for (const [n, x] of groups) if (x === g) groups.set(n, to);
549
+ }
550
+ return { groups: groupList() };
551
+ },
552
+ },
553
+ {
554
+ name: 'ungroup',
555
+ description: 'Break a group up: its objects move on their own again (joints stay).',
556
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
557
+ run: (a) => {
558
+ const members = [...groups].filter(([, g]) => g === a.name).map(([n]) => n);
559
+ if (!members.length) fail(`no group named "${a.name}"`);
560
+ members.forEach((n) => groups.delete(n));
561
+ return { ungrouped: members, groups: groupList() };
562
+ },
563
+ },
564
+ {
565
+ name: 'connect',
566
+ description: 'Join two objects with a joint (the basic mechanics). `a` holds, `b` is held: moving a carries b along; b itself moves only as the joint allows (move_joint here, a drag in the viewer). Kinds: glue (a and b move together; `contact`: the touching point, line or face as points), pivot (b turns about the point `at`, a ball joint; `limits` { x: [min, max], y, z } degrees round the world axes from the pose now), hinge (b turns about a line: `edge` [i, j], two vertex indices of b, e.g. a door\'s vertical side, or `axis` [[x,y,z], [x,y,z]]; `limit` [min, max] degrees, positive counter-clockwise looking from the second point towards the first), rail (b slides along the polyline `path` of a, its point `slider` (default its vertex nearest the rail) on the rail; `limit` [min, max] distance along the rail from its start), spring (b hangs on a spring from `at` on a to `at_b` on b; `rest_length` (default the distance now), `stiffness` (default 40), `damping` (default 3), `ends` [glue | pivot, glue | pivot]; `spring_object`: an object to stretch between the ends, its line `spring_line` [i, j] (default its longest side); the viewer animates it). Every geometry is in world coordinates now and then sticks to the objects. Returns the joint and its state.',
567
+ inputSchema: {
568
+ type: 'object',
569
+ properties: {
570
+ type: { type: 'string', enum: ['glue', 'pivot', 'hinge', 'rail', 'spring'] },
571
+ a: { type: 'string', description: 'the holder' },
572
+ b: { type: 'string', description: 'the held part' },
573
+ name: { type: 'string', description: 'the joint\'s name (default type-a-b)' },
574
+ at: { ...vec3Schema, description: 'pivot: the point; glue: the contact point; spring: the end on a' },
575
+ at_b: { ...vec3Schema, description: 'spring: the end on b' },
576
+ contact: { type: 'array', items: vec3Schema, description: 'glue: the contact as points (a point, a line of 2, a face of 3+)' },
577
+ edge: { type: 'array', items: { type: 'integer' }, minItems: 2, maxItems: 2, description: 'hinge: the line as two vertex indices of b (see get_mesh)' },
578
+ axis: { type: 'array', items: vec3Schema, minItems: 2, maxItems: 2, description: 'hinge: the line as two points' },
579
+ path: { type: 'array', items: vec3Schema, minItems: 2, description: 'rail: the polyline (it belongs to a)' },
580
+ slider: { ...vec3Schema, description: 'rail: the point of b on the rail' },
581
+ limit: { type: 'array', items: { type: 'number' }, minItems: 2, maxItems: 2, description: 'hinge: [min, max] degrees; rail: [min, max] distance along the rail' },
582
+ limits: { type: 'object', description: 'pivot: { x: [min, max], y: [min, max], z: [min, max] } degrees', properties: { x: { type: 'array', items: { type: 'number' } }, y: { type: 'array', items: { type: 'number' } }, z: { type: 'array', items: { type: 'number' } } } },
583
+ rest_length: { type: 'number' },
584
+ stiffness: { type: 'number' },
585
+ damping: { type: 'number' },
586
+ ends: { type: 'array', items: { type: 'string', enum: ['glue', 'pivot'] }, minItems: 2, maxItems: 2 },
587
+ spring_object: { type: 'string' },
588
+ spring_line: { type: 'array', items: { type: 'integer' }, minItems: 2, maxItems: 2 },
589
+ },
590
+ required: ['type', 'a', 'b'],
591
+ },
592
+ run: (a) => {
593
+ const A = need(a.a), B = need(a.b);
594
+ if (a.a === a.b) fail('a joint needs two different objects');
595
+ const jname = a.name !== undefined ? name(a.name) : `${a.type}-${a.a}-${a.b}`;
596
+ if (joints.some((j) => j.name === jname)) fail(`a joint named "${jname}" exists; disconnect it or give another name`);
597
+ const pair = (v, what) => (Array.isArray(v) && v.length === 2 && v.every(isNum) ? v : fail(`${what} must be [min, max]`));
598
+ const spec = { name: jname, type: a.type, a: a.a, b: a.b };
599
+ if (a.at !== undefined) spec.at = vec3(a.at, 'at');
600
+ if (a.at_b !== undefined) spec.bAt = vec3(a.at_b, 'at_b');
601
+ if (a.contact !== undefined) spec.contact = a.contact.map((p, i) => vec3(p, `contact[${i}]`));
602
+ if (a.edge !== undefined) {
603
+ const [i, k] = a.edge;
604
+ if (![i, k].every((x) => Number.isInteger(x) && x >= 0 && x < B.positions.length) || i === k) fail(`edge must be two different vertex indices of ${a.b} (0..${B.positions.length - 1})`);
605
+ spec.axis = [B.positions[i], B.positions[k]];
606
+ } else if (a.axis !== undefined) spec.axis = a.axis.map((p, i) => vec3(p, `axis[${i}]`));
607
+ if (a.path !== undefined) spec.path = a.path.map((p, i) => vec3(p, `path[${i}]`));
608
+ if (a.slider !== undefined) spec.slider = vec3(a.slider, 'slider');
609
+ if (a.limit !== undefined) spec.limit = pair(a.limit, 'limit');
610
+ if (a.limits !== undefined) {
611
+ spec.limits = {};
612
+ for (const k of ['x', 'y', 'z']) if (a.limits[k] !== undefined) spec.limits[k] = pair(a.limits[k], `limits.${k}`);
613
+ }
614
+ if (a.rest_length !== undefined) spec.restLength = number(a.rest_length, 'rest_length', { min: 0 });
615
+ if (a.stiffness !== undefined) spec.stiffness = number(a.stiffness, 'stiffness', { min: 0 });
616
+ if (a.damping !== undefined) spec.damping = number(a.damping, 'damping', { min: 0 });
617
+ if (a.ends !== undefined) spec.ends = a.ends;
618
+ if (a.spring_object !== undefined) spec.spring = { object: a.spring_object, mesh: need(a.spring_object), ...(a.spring_line ? { line: a.spring_line } : {}) };
619
+ let j;
620
+ try {
621
+ j = makeJoint(spec, A, B);
622
+ } catch (e) {
623
+ fail(e.message);
624
+ }
625
+ joints.push(j);
626
+ return { joint: { name: j.name, type: j.type, a: j.a, b: j.b }, now: nowOut(j) };
627
+ },
628
+ },
629
+ {
630
+ name: 'disconnect',
631
+ description: 'Take a joint away (by its name; see joints).',
632
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
633
+ run: (a) => {
634
+ const n = joints.length;
635
+ joints = joints.filter((j) => j.name !== a.name);
636
+ if (joints.length === n) fail(`no joint named "${a.name}"`);
637
+ return { removed: a.name, joints: joints.length };
638
+ },
639
+ },
640
+ {
641
+ name: 'joints',
642
+ description: 'The joints and groups now: each joint\'s kind, holder (a), held part (b), its limits and its state (a hinge\'s angle, a pivot\'s angles, a rail\'s position, a spring\'s length) with its geometry in world coordinates.',
643
+ inputSchema: { type: 'object', properties: {} },
644
+ annotations: { readOnlyHint: true },
645
+ run: () => ({ joints: joints.map((j) => ({ name: j.name, type: j.type, a: j.a, b: j.b, ...(j.limit ? { limit: j.limit } : {}), ...(j.limits ? { limits: j.limits } : {}), ...(j.type === 'spring' ? { rest_length: j.restLength, stiffness: j.stiffness, damping: j.damping, ends: j.ends, ...(j.spring ? { spring_object: j.spring.object } : {}) } : {}), now: nowOut(j) })), groups: groupList() }),
646
+ },
647
+ {
648
+ name: 'move_joint',
649
+ description: 'Move a held part as its joint allows, kept inside the limits: a hinge to `angle` (degrees from the pose it was connected in), a pivot to `angles` [x, y, z] (degrees round the world axes), a rail to `position` (distance along the rail). What b holds moves along. Returns the state reached (clamped).',
650
+ inputSchema: { type: 'object', properties: { name: { type: 'string' }, angle: { type: 'number' }, angles: vec3Schema, position: { type: 'number' } }, required: ['name'] },
651
+ run: (a) => {
652
+ const j = joints.find((x) => x.name === a.name) ?? fail(`no joint named "${a.name}"`);
653
+ const A = objects.get(j.a), B = objects.get(j.b);
654
+ let r;
655
+ if (j.type === 'hinge') r = hingeTo(j, A, B, number(a.angle, 'angle'));
656
+ else if (j.type === 'pivot') r = pivotTo(j, A, B, vec3(a.angles, 'angles'));
657
+ else if (j.type === 'rail') r = railTo(j, A, B, number(a.position, 'position'));
658
+ else fail(`a ${j.type} cannot be moved like this (glue holds still; a spring moves by itself in the viewer)`);
659
+ const moved = moveWith(j.b, (m) => moveMesh(m, r.move));
660
+ return { name: j.name, now: nowOut(j), moved };
661
+ },
662
+ },
663
+ {
664
+ name: 'get_mesh',
665
+ description: 'Read an object\'s geometry so you can shape it: the vertices (index = position in the list) and the faces with their vertex indices, color, center and outward normal. Use it to find the face or vertex indices for extrude_face and move_vertices.',
666
+ inputSchema: { type: 'object', properties: { name: nameSchema }, required: ['name'] },
667
+ annotations: { readOnlyHint: true },
668
+ run: (a) => {
669
+ const mesh = need(a.name);
670
+ return {
671
+ name: a.name,
672
+ vertices: mesh.positions.map(rv),
673
+ faces: mesh.faces.map((f, i) => {
674
+ const pts = f.v.map((k) => mesh.positions[k]);
675
+ const n = faceNormal(pts);
676
+ const l = Math.hypot(...n) || 1;
677
+ return { i, v: f.v, color: f.color, center: rv(faceCenter(pts)), normal: rv(n.map((c) => c / l)) };
678
+ }),
679
+ };
680
+ },
681
+ },
682
+ {
683
+ name: 'extrude_face',
684
+ description: 'Shape an object by pushing one of its faces out, like a modeller. The face is replaced (same index) by a copy moved `distance` along its outward normal and scaled by `scale` about its center, joined to the old edges by new side faces. distance > 0 and scale 1: a prism grows out (a wing, a chimney, a step). distance > 0 and scale < 1: a taper (roof, tower top, frustum). distance 0 and scale < 1: an inset (a panel or window frame; extrude it again, negative, for a recess). distance < 0: a dent into the solid (a niche, a door recess). The result is a closed solid again; chain calls on the returned `cap` face.',
685
+ inputSchema: {
686
+ type: 'object',
687
+ properties: { name: nameSchema, face: { type: 'integer', description: 'face index inside the object (see get_mesh)' }, distance: { type: 'number', description: 'along the outward normal, default 0' }, scale: { type: 'number', description: 'about the face center, > 0, default 1' }, color: { ...colorSchema, description: 'color for the new faces (default: the face color)' } },
688
+ required: ['name', 'face'],
689
+ },
690
+ run: (a) => {
691
+ const mesh = need(a.name);
692
+ if (!Number.isInteger(a.face)) fail('face must be an integer');
693
+ let out;
694
+ try {
695
+ out = extrudeFace(mesh, a.face, { distance: number(a.distance, 'distance', { fallback: 0 }), scale: number(a.scale, 'scale', { min: 1e-9, fallback: 1 }), color: a.color === undefined ? undefined : color(a.color) });
696
+ } catch (e) {
697
+ fail(e.message);
698
+ }
699
+ objects.set(a.name, out.mesh);
700
+ const c = validate(out.mesh);
701
+ return { ...summary(a.name, out.mesh), cap_face: out.cap, side_faces: out.sides, ok: c.ok, notes: c.notes };
702
+ },
703
+ },
704
+ {
705
+ name: 'move_vertices',
706
+ description: 'Move the vertices with the given indices by [dx, dy, dz] (see get_mesh for the indices): shear, lean, pinch a roof ridge, raise a corner. Faces keep their vertices, so moving only some corners of a face can make it non-planar; the result reports that. Move all the corners of a face together to keep it flat.',
707
+ inputSchema: { type: 'object', properties: { name: nameSchema, indices: { type: 'array', items: { type: 'integer' }, minItems: 1 }, by: { ...vec3Schema, description: '[dx, dy, dz]' } }, required: ['name', 'indices', 'by'] },
708
+ run: (a) => {
709
+ const mesh = need(a.name);
710
+ if (!Array.isArray(a.indices) || !a.indices.length) fail('indices must be a non-empty list of vertex indices');
711
+ let moved;
712
+ try {
713
+ moved = moveVertices(mesh, a.indices, vec3(a.by, 'by'));
714
+ } catch (e) {
715
+ fail(e.message);
716
+ }
717
+ objects.set(a.name, moved);
718
+ const c = validate(moved);
719
+ return { ...summary(a.name, moved), ok: c.ok, notes: c.notes };
720
+ },
721
+ },
722
+ {
723
+ name: 'boolean',
724
+ description: 'Boolean of two closed solids: union, subtract (a minus b: a door, a window, a hole) or intersect. Both objects must be closed solids with outward faces (inspect says so). The result is a new closed solid; faces keep their colors and a face cut into a solid takes the color of the cutting face. By default a and b are replaced by the result; `keep: true` keeps them.',
725
+ inputSchema: {
726
+ type: 'object',
727
+ properties: { a: nameSchema, b: nameSchema, op: { type: 'string', enum: ['union', 'subtract', 'intersect'] }, name: { ...nameSchema, description: 'name of the result (default a-op-b)' }, keep: { type: 'boolean', description: 'keep a and b (default false)' } },
728
+ required: ['a', 'b', 'op'],
729
+ },
730
+ run: (x) => {
731
+ const ma = need(x.a);
732
+ const mb = need(x.b);
733
+ if (!['union', 'subtract', 'intersect'].includes(x.op)) fail("op must be 'union', 'subtract' or 'intersect'");
734
+ let out;
735
+ try {
736
+ out = boolean(ma, mb, x.op);
737
+ } catch (e) {
738
+ fail(e.message);
739
+ }
740
+ if (!out.faces.length) fail(`the ${x.op} of ${x.a} and ${x.b} is empty`);
741
+ const result = x.name === undefined ? `${x.a}-${x.op}-${x.b}` : name(x.name);
742
+ if (!x.keep) {
743
+ objects.delete(x.a);
744
+ objects.delete(x.b);
745
+ }
746
+ objects.set(result, out);
747
+ const c = validate(out);
748
+ return { ...summary(result, out), closed: c.closed, ok: c.ok, notes: c.notes };
749
+ },
750
+ },
751
+ {
752
+ name: 'recolor',
753
+ description: 'Change the color of a whole object, or of one face when `face` is given.',
754
+ inputSchema: { type: 'object', properties: { name: nameSchema, color: colorSchema, face: { type: 'integer', description: 'face index inside the object' } }, required: ['name', 'color'] },
755
+ run: (a) => {
756
+ const mesh = need(a.name);
757
+ const c = color(a.color);
758
+ if (a.face !== undefined && (!Number.isInteger(a.face) || a.face < 0 || a.face >= mesh.faces.length)) fail(`face must be 0..${mesh.faces.length - 1}`);
759
+ objects.set(a.name, { ...mesh, faces: mesh.faces.map((f, i) => (a.face === undefined || a.face === i ? { ...f, color: c } : f)) });
760
+ return summary(a.name, objects.get(a.name));
761
+ },
762
+ },
763
+ {
764
+ name: 'set_screen',
765
+ description: 'Make faces of an object a screen in the viewer: give exactly one of `image` (a picture, .png .jpg .jpeg .webp .gif .avif .svg: laid on the face as a texture, cut to the face\'s shape, depth tested and seen in VR too; its server must allow cross-origin reading (CORS), else the desktop shows it as a page), `scene` (a 3Draft scene file .3draft / .json, played on the face turning round its middle) or `url` (a web page, shown in an iframe over the face on the desktop; not in VR, sites that forbid framing stay blank). Only four-cornered faces show it; seen from the front (the side the face\'s CCW winding faces). Without `face` every four-cornered face of the object becomes the screen (a box: all six sides), so for one side give its face index (get_mesh). The screen is a material (`material`, default "screen-<object>") kept in the scene\'s palette (export / import keep it); give none of image / scene / url to make the faces plain again.',
766
+ inputSchema: {
767
+ type: 'object',
768
+ properties: {
769
+ name: nameSchema,
770
+ face: { type: 'integer', description: 'face index inside the object (get_mesh); omitted: every four-cornered face' },
771
+ image: { type: 'string', description: 'a picture address (https://… or relative to the viewer page): .png .jpg .jpeg .webp .gif .avif .svg' },
772
+ scene: { type: 'string', description: 'a 3Draft scene file address (.3draft or .json)' },
773
+ url: { type: 'string', description: 'a web page address (https://…)' },
774
+ material: { type: 'string', description: 'the screen material\'s name (default "screen-<object>"); faces that share it share the screen' },
775
+ color: colorSchema,
776
+ },
777
+ required: ['name'],
778
+ },
779
+ run: (a) => {
780
+ const mesh = need(a.name);
781
+ const given = ['image', 'scene', 'url'].filter((k) => typeof a[k] === 'string' && a[k].trim());
782
+ if (given.length > 1) fail('give one of image, scene, url');
783
+ const kind = given[0], addr = kind ? a[kind].trim() : '';
784
+ if (kind && /^[a-z][a-z0-9+.-]*:/i.test(addr) && !/^https?:\/\//i.test(addr)) fail(`${kind} must be an http(s) address or a relative path`);
785
+ if (kind === 'image' && !/\.(?:png|jpe?g|webp|gif|avif|svg)(?:[?#].*)?$/i.test(addr)) fail('image must end in .png .jpg .jpeg .webp .gif .avif or .svg');
786
+ if (kind === 'scene' && !/\.(?:3draft|json)(?:[?#].*)?$/i.test(addr)) fail('scene must be a .3draft (or .json) scene file');
787
+ if (kind === 'url' && /\.(?:png|jpe?g|webp|gif|avif|svg|json|3draft)(?:[?#].*)?$/i.test(addr)) fail('that address is an image or a scene: give it as image or scene');
788
+ if (a.face !== undefined && (!Number.isInteger(a.face) || a.face < 0 || a.face >= mesh.faces.length)) fail(`face must be 0..${mesh.faces.length - 1}`);
789
+ const mat = typeof a.material === 'string' && a.material.trim() ? a.material.trim().slice(0, 60) : `screen-${a.name}`;
790
+ const picked = mesh.faces.map((f, i) => (a.face === undefined ? f.v.length === 4 : a.face === i));
791
+ const four = mesh.faces.filter((f, i) => picked[i] && f.v.length === 4).length;
792
+ if (!kind) {
793
+ objects.set(a.name, { ...mesh, faces: mesh.faces.map((f, i) => (picked[i] && f.mat === mat ? (({ mat: _m, ...rest }) => rest)(f) : f)) });
794
+ if (![...objects.values()].some((m) => m.faces.some((f) => f.mat === mat))) screens.delete(mat);
795
+ return { name: a.name, material: mat, screen: null };
796
+ }
797
+ const first = mesh.faces.find((f, i) => picked[i]);
798
+ const c = a.color !== undefined ? color(a.color) : first?.color ?? '#202020';
799
+ screens.set(mat, { name: mat, color: c, [kind]: addr });
800
+ objects.set(a.name, { ...mesh, faces: mesh.faces.map((f, i) => (picked[i] ? { ...f, mat } : f)) });
801
+ return { name: a.name, material: mat, [kind]: addr, faces: picked.filter(Boolean).length, fourCornered: four, ...(four ? {} : { note: 'no four-cornered face among them: nothing will show (screens need quads)' }) };
802
+ },
803
+ },
804
+ {
805
+ name: 'remove',
806
+ description: 'Remove one object.',
807
+ inputSchema: { type: 'object', properties: { name: nameSchema }, required: ['name'] },
808
+ run: (a) => {
809
+ need(a.name);
810
+ objects.delete(a.name);
811
+ dropLinks(a.name);
812
+ return { removed: a.name, objects: objects.size };
813
+ },
814
+ },
815
+ { name: 'clear', description: 'Remove every object.', inputSchema: { type: 'object', properties: {} }, run: () => {
816
+ const n = objects.size;
817
+ objects.clear();
818
+ groups.clear();
819
+ screens.clear();
820
+ joints = [];
821
+ return { removed: n };
822
+ } },
823
+ {
824
+ name: 'list',
825
+ description: 'List the objects with their face counts and axis-aligned bounds (min / max corners).',
826
+ inputSchema: { type: 'object', properties: {} },
827
+ annotations: { readOnlyHint: true },
828
+ run: () => ({ objects: [...objects].map(([n, m]) => summary(n, m)), scene: objects.size ? extent(combined().mesh) : null }),
829
+ },
830
+ {
831
+ name: 'inspect',
832
+ description: 'Check an object (or all when name is omitted): closed shell, faces CCW from outside, planar, convex. Returns plain-text notes about what to fix. Run it after add_mesh.',
833
+ inputSchema: { type: 'object', properties: { name: nameSchema } },
834
+ annotations: { readOnlyHint: true },
835
+ run: (a) => {
836
+ const names = a.name === undefined ? [...objects.keys()] : [name(a.name)];
837
+ return { checked: names.map((n) => ({ name: n, ...validate(need(n)) })) };
838
+ },
839
+ },
840
+ {
841
+ name: 'render',
842
+ description: 'Render the scene as a flat-colored SVG with edges and points (text, deterministic). Default is a 2x2 sheet of front, side, top and perspective. Each <polygon data-face=".."> is one face, <circle data-v=".."> a vertex. Look at it to judge the model, then fix and render again.',
843
+ inputSchema: { type: 'object', properties: { ...viewProps, points: { type: 'boolean', description: 'draw vertices, default true' } } },
844
+ annotations: { readOnlyHint: true },
845
+ run: (a) => {
846
+ const { mesh } = combined();
847
+ const view = viewOf(a, 'sheet');
848
+ const opts = { size: number(a.size, 'size', { min: 64, max: 2000, fallback: 320 }), points: a.points ?? true };
849
+ return { text: view === 'sheet' ? renderSheet(mesh, opts) : renderView(mesh, view, opts) };
850
+ },
851
+ },
852
+ {
853
+ name: 'pick',
854
+ description: 'What is at pixel (x, y) of a render? Uses the same camera and size as render. Returns the object, its face index, the 3D point, the surface normal and the distance. Use it to find coordinates to place or stack things. Only the sensing set counts (see sensing; exclude / include for this call); sense also lists what lies behind.',
855
+ inputSchema: { type: 'object', properties: { ...viewProps, x: { type: 'number' }, y: { type: 'number' }, ...senseProps }, required: ['x', 'y'] },
856
+ annotations: { readOnlyHint: true },
857
+ run: (a) => {
858
+ if (viewOf(a, 'persp') === 'sheet') fail('pick needs a single view, not the sheet');
859
+ if (!objects.size) return { hit: null };
860
+ const { origin, dir } = pixelRay(a);
861
+ const hits = castRay(sensed(a), origin, dir, { all: true }).filter((h) => h.facing); // (like the viewer: front faces)
862
+ if (!hits.length) return { hit: null };
863
+ const h = hits[0];
864
+ return { hit: { ...hitOut(h), color: objects.get(h.object).faces[h.face].color } };
865
+ },
866
+ },
867
+ {
868
+ name: 'export',
869
+ description: 'Return the scene as JSON, or write it to `path` (relative, inside the server working directory, ending in .3draft (the 3Draft scene file) or .json).',
870
+ inputSchema: { type: 'object', properties: { path: { type: 'string' } } },
871
+ annotations: { readOnlyHint: true },
872
+ run: (a) => {
873
+ if (a.path === undefined) return { text: JSON.stringify(data()) };
874
+ writeFileSync(safePath(a.path), JSON.stringify(data()));
875
+ return { written: a.path, objects: objects.size };
876
+ },
877
+ },
878
+ {
879
+ name: 'import',
880
+ description: 'Replace the scene with a JSON scene, given as `json` text or read from `path` (same rules as export).',
881
+ inputSchema: { type: 'object', properties: { json: { type: 'string' }, path: { type: 'string' } } },
882
+ run: (a) => {
883
+ if ((a.json === undefined) === (a.path === undefined)) fail('give exactly one of json or path');
884
+ let parsed;
885
+ try {
886
+ parsed = JSON.parse(a.json ?? readFileSync(safePath(a.path), 'utf8'));
887
+ } catch (e) {
888
+ fail(`could not read the scene: ${e.message}`);
889
+ }
890
+ if (parsed?.format !== '3draft-scene' || !Array.isArray(parsed.objects)) fail('not a 3draft scene (format, objects)');
891
+ const next = new Map();
892
+ for (const o of parsed.objects) {
893
+ name(o?.name);
894
+ next.set(o.name, parseMesh(o.mesh?.positions, o.mesh?.faces));
895
+ }
896
+ objects.clear();
897
+ groups.clear();
898
+ for (const [k, v] of next) objects.set(k, v);
899
+ for (const o of parsed.objects) if (typeof o.group === 'string' && o.group) groups.set(o.name, o.group);
900
+ joints = Array.isArray(parsed.joints) ? parsed.joints.filter((j) => j && objects.has(j.a) && objects.has(j.b)) : [];
901
+ // (the screens of its palette: the materials with an image, a scene or a url)
902
+ screens.clear();
903
+ for (const m of Array.isArray(parsed.palette) ? parsed.palette : []) {
904
+ const k = ['image', 'scene', 'url'].find((x) => typeof m?.[x] === 'string');
905
+ if (k && typeof m.name === 'string') screens.set(m.name, { name: m.name, color: color(m.color, '#202020'), [k]: m[k] });
906
+ }
907
+ return { objects: objects.size, groups: new Set(groups.values()).size, joints: joints.length, screens: screens.size };
908
+ },
909
+ },
910
+ // ---- The open viewer (the live link): these do not change the scene, they steer what the browser shows
911
+ {
912
+ name: 'view_target',
913
+ description: 'Make the open viewer target an object by name (as the viewer\'s Enter search: case and accents do not matter; the whole name, then the start, a word start, any part). In a star map the starship turns to it and the braking program stops it at the surface when you fly there. Works on everything the viewer shows, also the loaded example scenes (stars, galaxies), not only the MCP objects.',
914
+ inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'the name or a part of it, e.g. "andromeda", "Sirius", "seat"' } }, required: ['name'] },
915
+ live: true,
916
+ run: (a) => sendView({ cmd: 'target', name: String(a.name ?? fail('name is required')) }),
917
+ },
918
+ {
919
+ name: 'view_camera',
920
+ description: 'Put the open viewer\'s eye at a point, looking along yaw / pitch (degrees; yaw 0 looks towards -z, positive yaw turns towards +x, positive pitch looks down, as in the Spider Build format). In a star map the units are light years (the Sun at the origin). `roll` (degrees) banks the starship.',
921
+ inputSchema: { type: 'object', properties: { eye: vec3Schema, yaw: { type: 'number' }, pitch: { type: 'number' }, roll: { type: 'number' } }, required: ['eye'] },
922
+ live: true,
923
+ run: (a) => sendView({ cmd: 'camera', eye: vec3(a.eye, 'eye'), yaw: number(a.yaw, 'yaw', { fallback: 0 }), pitch: number(a.pitch, 'pitch', { min: -90, max: 90, fallback: 0 }), roll: number(a.roll, 'roll', { fallback: 0 }) }),
924
+ },
925
+ {
926
+ name: 'view_vehicle',
927
+ description: 'Switch the open viewer\'s vehicle: "starship" (space flight, light years), "car" (drives on the ground), or "none" (the ordinary model camera).',
928
+ inputSchema: { type: 'object', properties: { vehicle: { type: 'string', enum: ['none', 'starship', 'car'] } }, required: ['vehicle'] },
929
+ live: true,
930
+ run: (a) => {
931
+ if (!['none', 'starship', 'car'].includes(a.vehicle)) fail('vehicle must be none, starship or car');
932
+ return sendView({ cmd: 'vehicle', vehicle: a.vehicle });
933
+ },
934
+ },
935
+ {
936
+ name: 'view_example',
937
+ description: 'Load one of the viewer\'s bundled scenes into the open viewer (beside the MCP objects, or instead of everything with replace: true). The names are the viewer\'s scene list, e.g. deepsky (1000 galaxies, 400 black holes, 3000 stars), stars, milkyway, stars-plain, sky:trappist-1 (a sky catalogue), globe, bridge, ex27, betterman (Spider Paint also: human, tr74, station-screen). It is shown in the browser only: render and inspect do not see it.',
938
+ inputSchema: { type: 'object', properties: { name: { type: 'string' }, replace: { type: 'boolean', description: 'clear the viewer first (default false)' } }, required: ['name'] },
939
+ live: true,
940
+ run: (a) => sendView({ cmd: 'example', name: String(a.name ?? fail('name is required')), replace: Boolean(a.replace) }),
941
+ },
942
+ {
943
+ name: 'view_sky',
944
+ description: 'Make a space scene from a sky catalogue and show it in the open viewer (the format is app/sky.md, "3draft-sky"): stars, planets, moons, dwarf planets, exoplanets, black holes and galaxies in astronomers\' units. A place is ra / dec (degrees, or "hh mm ss" / "±dd mm ss" strings, or ra_h hours) with dist + unit (ly, pc, kpc, Mpc, AU, kly, Mly, Gly) or parallax (mas), or at [x, y, z] in scene light years (the Sun at the origin, y = equatorial north). A star: spect (e.g. "G2V", "M5.5Ve", "DA"), temp (K), lum (L☉) or absmag or vmag, radius (R☉). A planet / moon goes round another object with around (its name), a (AU) or a_km, optional incl / node / angle (degrees), radius_earth / radius_km / radius_jup, teq (K, else from the star), surface (a planet shader recipe), ring, orbit: true (draw the orbit). A black hole: mass (M☉), radius_ly (drawn size). A galaxy: kind (spiral, elliptical, irregular, dwarf, interacting, early), diameter_kly or radius_ly, incl / pa, arms, bar. Any object: name, info (shown under the name when targeted), category (the find box\'s kind), color. start: { near: name, distance: ly } or { eye, yaw, pitch }. Returns the counts and notes about anything left out; save writes the made scene as a .3draft file the viewer opens (f↑).',
945
+ inputSchema: {
946
+ type: 'object',
947
+ properties: {
948
+ sky: { type: 'object', description: 'the catalogue: { format: "3draft-sky", name, start, objects: [ { type, name, … } ] }', properties: { name: { type: 'string' }, objects: { type: 'array', items: { type: 'object', properties: { type: { type: 'string', enum: [...SKY_TYPES] }, name: { type: 'string' } } } } } },
949
+ path: { type: 'string', description: 'or read the catalogue from a .json (or .3draft) file (relative, inside the server working directory)' },
950
+ replace: { type: 'boolean', description: 'clear the viewer first (default true)' },
951
+ save: { type: 'string', description: 'also write the made scene to this path (.3draft, or .json)' },
952
+ },
953
+ },
954
+ live: true,
955
+ run: (a) => {
956
+ if ((a.sky === undefined) === (a.path === undefined)) fail('give exactly one of sky or path');
957
+ let sky = a.sky;
958
+ if (a.path !== undefined) {
959
+ try {
960
+ sky = JSON.parse(readFileSync(safePath(a.path), 'utf8'));
961
+ } catch (e) {
962
+ fail(`could not read the catalogue: ${e.message}`);
963
+ }
964
+ }
965
+ let made;
966
+ try {
967
+ made = skyScene(sky);
968
+ } catch (e) {
969
+ fail(e.message);
970
+ }
971
+ const { scene, warnings, counts } = made;
972
+ if (!scene.objects.length) fail(`nothing to show: ${warnings.slice(0, 5).join('; ') || 'no objects'}`);
973
+ if (a.save !== undefined) writeFileSync(safePath(a.save), JSON.stringify(scene));
974
+ const sent = info.live?.command ? info.live.command({ cmd: 'scene', scene, replace: a.replace !== false }) : 0;
975
+ return {
976
+ sent_to: sent,
977
+ ...(sent ? {} : { note: info.live?.command ? 'no viewer is open: call viewer for the URL and ask the user to open it' : 'the live viewer is off' }),
978
+ counts,
979
+ ...(warnings.length ? { notes: warnings } : {}),
980
+ start: scene.start,
981
+ ...(a.save !== undefined ? { written: a.save } : {}),
982
+ };
983
+ },
984
+ },
985
+ {
986
+ name: 'view_state',
987
+ description: 'What the open viewer shows now (it reports every 2 seconds): vehicle, eye, yaw / pitch / roll (degrees), the target, the speed, the object count, the loaded scene. null when no viewer is open.',
988
+ inputSchema: { type: 'object', properties: {} },
989
+ annotations: { readOnlyHint: true },
990
+ run: () => ({ viewer: info.live?.viewer?.() ?? null, open_tabs: info.live?.clients() ?? 0 }),
991
+ },
992
+ {
993
+ name: 'viewer',
994
+ description: 'The URL of the live viewer: a browser page that shows this scene and updates after every change you make. Tell the user to open it. Returns null when the live viewer is off.',
995
+ inputSchema: { type: 'object', properties: {} },
996
+ annotations: { readOnlyHint: true },
997
+ run: () => (info.live ? { url: info.live.url, ...(Object.keys(info.live.viewers ?? {}).length > 1 ? { viewers: info.live.viewers } : {}), open_tabs: info.live.clients() } : { url: null, note: 'the live viewer is off (3DRAFT_LIVE=0) or could not bind a port' }),
998
+ },
999
+ ];
1000
+
1001
+ /** Runs a tool: { text, isError }. Plain objects come back as JSON text. */
1002
+ const call = (toolName, args = {}) => {
1003
+ const tool = tools.find((t) => t.name === toolName);
1004
+ if (!tool) return { isError: true, text: `unknown tool "${toolName}"` };
1005
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) return { isError: true, text: 'arguments must be an object' };
1006
+ try {
1007
+ const out = tool.run(args);
1008
+ if (!tool.annotations?.readOnlyHint && !tool.live) {
1009
+ rev += 1;
1010
+ for (const fn of listeners) fn(rev);
1011
+ }
1012
+ return { isError: false, text: out?.text ?? JSON.stringify(out, null, 1) };
1013
+ } catch (e) {
1014
+ return { isError: true, text: e instanceof ToolError ? e.message : `internal error: ${e.message}` };
1015
+ }
1016
+ };
1017
+
1018
+ const list = () => tools.map(({ name: n, description, inputSchema, annotations }) => ({ name: n, description, inputSchema, ...(annotations ? { annotations } : {}) }));
1019
+
1020
+ /** fn(rev) runs after every successful change. Returns an unsubscribe function. */
1021
+ const subscribe = (fn) => {
1022
+ listeners.add(fn);
1023
+ return () => listeners.delete(fn);
1024
+ };
1025
+
1026
+ return { call, list, objects, data, subscribe, info };
1027
+ };