@womp/spark-agent 17.7.3 → 17.8.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/CHANGELOG.md CHANGED
@@ -4,6 +4,22 @@ Notable changes to `@womp/spark-agent`, newest first. Versions follow
4
4
  [Semantic Versioning](https://semver.org/). Add an entry with each version bump; describe what
5
5
  changed for hosts and users, and how to migrate across breaking changes.
6
6
 
7
+ ## 17.8.0 — 2026-12-01
8
+
9
+ ### Added
10
+
11
+ - `womp.scene.screenshot({ fit })` frames objects (`ids`) or a world-space `box` from a `direction`, centred
12
+ and unclipped, using renderer bounds and the capture's real aspect ratio. Agents no longer hand-place
13
+ cameras for whole-object views.
14
+ - Hosts receive `SceneScreenshotOptions.fitted` beside the 16:9 camera. SDK-backed capture refits it to
15
+ the image aspect it learns; other hosts can call `fitSceneCamera(fitted, aspect)` or use `camera` as is.
16
+
17
+ ### Changed
18
+
19
+ - The scene-editing skill frames every view of objects with `fit`, including views that match a reference
20
+ image's angle and lens, and keeps `camera` for views whose position itself matters. It states that
21
+ `orthographicWidth` and the FOV span the frame's width.
22
+
7
23
  ## 17.7.3 — 2026-11-25
8
24
 
9
25
  ### Changed
package/README.md CHANGED
@@ -315,6 +315,47 @@ It prints each case's routes and pass rate and writes `report.json`, with every
315
315
  calls, deciding call and reply, under `.spark/intent-bench/`. It exits 1 when any run took a route
316
316
  the case does not expect. Model calls are paid; the full set costs about $0.10 on gpt-6-luna.
317
317
 
318
+ ## Measure build quality
319
+
320
+ `yarn quality-bench` builds cases from `bench/quality/cases/` (split into `tune` and `holdout`),
321
+ renders standardized same-camera views (fixed 3/4, 4 sides, 5-view turntable, 2×2 grid, and case
322
+ close-ups), counts deterministic SDF structure (top-level Areas, same-material seams, Cubes, curves,
323
+ curve ribbing depth, floating clusters), and exports one full-resolution lossless PNG comparison
324
+ sheet per repeat (`sheet-run-<n>.png`) alongside `report.json`, `report.md`, and `results.csv`.
325
+ AI vision judges are opt-in via `--judge` (default `false`); blinded order-swapped pairwise
326
+ comparisons between two runs use `--ab`.
327
+
328
+ ```sh
329
+ git lfs pull # case images are stored in git LFS
330
+ yarn quality-bench # every case, 2 repeats, 32 builds at once
331
+ yarn quality-bench --only kiko,retro-car --repeat 1 --output .spark/quality/my-run
332
+ yarn quality-bench --split tune --judge # run tune split with AI vision judges
333
+ yarn quality-bench --sheet .spark/quality/my-run # regenerate sheet-run-<n>.png without rebuilding
334
+ yarn quality-bench --ab .spark/quality/cand --baseline .spark/quality/base
335
+ ```
336
+
337
+ Builds share one Kakapo through an in-process `kakapo-mux` (below). If Kakapo starts with an empty
338
+ scene, the bench seeds a minimal root scene automatically. Each build, with its `scene.json`,
339
+ renders, timings, and optional judge answers, is saved under
340
+ `.spark/quality/<timestamp>/<case>/run-<n>/`. With `--baseline <report.json>`, `report.md` adds
341
+ each metric's change and marks changes beyond two standard errors. `--score-only <run-dir>`
342
+ re-renders and scores saved `scene.json` files to recover after a Kakapo crash.
343
+
344
+ A case is a directory with `case.json` (`id`, `split`, `prompt`, `images`, `reference`, `parts`,
345
+ `checks`) and its images. Check views frame a band of the build's height (`band`) or the parts
346
+ whose names match a pattern (`match`, optionally one `half`), from the side the build faces turned
347
+ by `turn` degrees, with a `label` that tells the judge what it shows. See `src/quality-bench.ts`
348
+ for the fields.
349
+
350
+ ### Share one Kakapo between benches
351
+
352
+ `yarn kakapo-mux --port 5600` serves many bench clients from one Kakapo. Connections to
353
+ `ws://127.0.0.1:5600/s/<name>` share a scene that outlives them; other connections each get their
354
+ own. Before a call that reads or changes a scene, the proxy loads that scene into the engine, so
355
+ clients never see each other's nodes, and a screenshot keeps the engine until its frame arrives.
356
+ New scenes start from the engine's scene when the proxy started. While it runs, do not use the
357
+ engine directly. It is bench tooling with no authentication; never expose it.
358
+
318
359
  ## Run cost estimates
319
360
 
320
361
  The chat displays estimated API token cost in USD after every completed model step, from the
@@ -5,5 +5,39 @@ export type BenchBounds = {
5
5
  };
6
6
  /** Groups organize geometry; query their visible renderable children, not Group bounds. */
7
7
  export declare function benchGeometryIds(api: Pick<KakapoAPI, "listNodes">, parentId?: number): number[];
8
- /** Fixed Spark-space three-quarter view, fitted against all eight native-world bounding-box corners. */
9
- export declare function benchCamera(bounds: BenchBounds, aspect: number): CameraConfiguration;
8
+ export declare const BENCH_SHEET_CAMERAS: readonly [{
9
+ readonly file: "fixed-3q.jpg";
10
+ readonly offset: {
11
+ readonly x: 1;
12
+ readonly y: 0.65;
13
+ readonly z: 1;
14
+ };
15
+ }, {
16
+ readonly file: "fixed-front.jpg";
17
+ readonly offset: {
18
+ readonly x: 0;
19
+ readonly y: 0.12;
20
+ readonly z: 1;
21
+ };
22
+ }, {
23
+ readonly file: "fixed-back.jpg";
24
+ readonly offset: {
25
+ readonly x: 0;
26
+ readonly y: 0.12;
27
+ readonly z: -1;
28
+ };
29
+ }, {
30
+ readonly file: "fixed-top.jpg";
31
+ readonly offset: {
32
+ readonly x: 0.7;
33
+ readonly y: 1.4;
34
+ readonly z: 0.7;
35
+ };
36
+ }];
37
+ /** Fixed Spark-space view (default three-quarter), fitted against all eight native-world bounding-box corners. */
38
+ export declare function benchCamera(bounds: BenchBounds, aspect: number, sparkOffset?: Vec3): CameraConfiguration;
39
+ /**
40
+ * Orthographic camera that looks along -`back` (a direction from the build toward the camera, in engine space) and
41
+ * fits every corner of `boxes` in a frame of `aspect` (width / height), with `margin` around the tighter dimension.
42
+ */
43
+ export declare function fitOrthographicCamera(boxes: BenchBounds[], back: Vec3, aspect?: number, margin?: number): CameraConfiguration;
@@ -1,4 +1,5 @@
1
1
  import { toEnginePosition } from "./coordinates.js";
2
+ import { fitCamera } from "./camera-fit.js";
2
3
  /** Groups organize geometry; query their visible renderable children, not Group bounds. */
3
4
  export function benchGeometryIds(api, parentId = 0) {
4
5
  return api.listNodes({ parentId }).flatMap(node => {
@@ -7,13 +8,19 @@ export function benchGeometryIds(api, parentId = 0) {
7
8
  return node.kind === "group" ? benchGeometryIds(api, node.id) : [node.id];
8
9
  });
9
10
  }
10
- /** Fixed Spark-space three-quarter view, fitted against all eight native-world bounding-box corners. */
11
- export function benchCamera(bounds, aspect) {
11
+ export const BENCH_SHEET_CAMERAS = [
12
+ { file: "fixed-3q.jpg", offset: { x: 1, y: 0.65, z: 1 } },
13
+ { file: "fixed-front.jpg", offset: { x: 0, y: 0.12, z: 1 } },
14
+ { file: "fixed-back.jpg", offset: { x: 0, y: 0.12, z: -1 } },
15
+ { file: "fixed-top.jpg", offset: { x: 0.7, y: 1.4, z: 0.7 } },
16
+ ];
17
+ /** Fixed Spark-space view (default three-quarter), fitted against all eight native-world bounding-box corners. */
18
+ export function benchCamera(bounds, aspect, sparkOffset = { x: 1, y: 0.65, z: 1 }) {
12
19
  const axes = ["x", "y", "z"];
13
20
  if (!Number.isFinite(aspect) || aspect <= 0 || axes.some(a => !Number.isFinite(bounds.min[a]) || !Number.isFinite(bounds.max[a]) || bounds.min[a] > bounds.max[a]))
14
21
  throw new Error("Benchmark framing requires finite ordered bounds and a positive aspect ratio.");
15
22
  const target = { x: (bounds.min.x + bounds.max.x) / 2, y: (bounds.min.y + bounds.max.y) / 2, z: (bounds.min.z + bounds.max.z) / 2 };
16
- const offset = toEnginePosition({ x: 1, y: 0.65, z: 1 });
23
+ const offset = toEnginePosition(sparkOffset);
17
24
  const length = Math.hypot(offset.x, offset.y, offset.z);
18
25
  const back = { x: offset.x / length, y: offset.y / length, z: offset.z / length };
19
26
  const horizontal = Math.hypot(back.x, back.z);
@@ -30,3 +37,11 @@ export function benchCamera(bounds, aspect) {
30
37
  }
31
38
  return { position: { x: target.x + back.x * distance, y: target.y + back.y * distance, z: target.z + back.z * distance }, target, projection: "perspective", horizontalFovDegrees: 60 };
32
39
  }
40
+ /**
41
+ * Orthographic camera that looks along -`back` (a direction from the build toward the camera, in engine space) and
42
+ * fits every corner of `boxes` in a frame of `aspect` (width / height), with `margin` around the tighter dimension.
43
+ */
44
+ export function fitOrthographicCamera(boxes, back, aspect = 16 / 9, margin = 1.1) {
45
+ // The SDK accepts orthographic widths from about 0.24 world units (a 6 mm frame); 40 units keeps the camera clear of the build.
46
+ return fitCamera(boxes, { direction: back, projection: "orthographic", aspect, margin, minWidth: 0.25, standoff: 40 });
47
+ }
@@ -0,0 +1,47 @@
1
+ /** A Y-up axis-aligned box. The fit works in any Y-up frame and unit: Womp project space or Kakapo's engine space. */
2
+ export type FitBox = {
3
+ min: {
4
+ x: number;
5
+ y: number;
6
+ z: number;
7
+ };
8
+ max: {
9
+ x: number;
10
+ y: number;
11
+ z: number;
12
+ };
13
+ };
14
+ type V = {
15
+ x: number;
16
+ y: number;
17
+ z: number;
18
+ };
19
+ export type FitCameraOptions = {
20
+ /** From the boxes toward the camera; any length. It must not be vertical. */
21
+ direction: V;
22
+ projection?: "orthographic" | "perspective";
23
+ /** Frame width / height. */
24
+ aspect?: number;
25
+ /** Frame size over the boxes' projected size along the limiting dimension, 1 or more. */
26
+ margin?: number;
27
+ /** Perspective only. */
28
+ horizontalFovDegrees?: number;
29
+ /** Smallest orthographic width, in the boxes' units. */
30
+ minWidth?: number;
31
+ /** How far an orthographic camera sits in front of the nearest box corner, in the boxes' units. */
32
+ standoff?: number;
33
+ };
34
+ export type FittedCamera = {
35
+ position: V;
36
+ target: V;
37
+ projection: "orthographic" | "perspective";
38
+ orthographicWidth?: number;
39
+ horizontalFovDegrees?: number;
40
+ };
41
+ /**
42
+ * Camera looking along -`direction` whose frame holds every corner of `boxes`, centred, with `margin` around the
43
+ * limiting dimension. The corners are projected onto the tilted camera's own right and up axes, so elevated views fit
44
+ * too. `orthographicWidth` and `horizontalFovDegrees` are horizontal: the vertical span is the width / `aspect`.
45
+ */
46
+ export declare function fitCamera(boxes: FitBox[], options: FitCameraOptions): FittedCamera;
47
+ export {};
@@ -0,0 +1,70 @@
1
+ const dot = (p, q) => p.x * q.x + p.y * q.y + p.z * q.z;
2
+ /**
3
+ * Camera looking along -`direction` whose frame holds every corner of `boxes`, centred, with `margin` around the
4
+ * limiting dimension. The corners are projected onto the tilted camera's own right and up axes, so elevated views fit
5
+ * too. `orthographicWidth` and `horizontalFovDegrees` are horizontal: the vertical span is the width / `aspect`.
6
+ */
7
+ export function fitCamera(boxes, options) {
8
+ const { direction, projection = "orthographic", aspect = 16 / 9, margin = 1.1, horizontalFovDegrees = 60, minWidth = 0, standoff = 0 } = options;
9
+ const axes = ["x", "y", "z"];
10
+ if (!boxes.length || boxes.some(b => axes.some(a => !Number.isFinite(b.min[a]) || !Number.isFinite(b.max[a]) || b.min[a] > b.max[a])))
11
+ throw new Error("Camera fit needs at least one box with finite ordered bounds.");
12
+ if (!Number.isFinite(aspect) || aspect <= 0 || !Number.isFinite(margin) || margin < 1)
13
+ throw new Error("Camera fit needs a positive aspect ratio and a margin of at least 1.");
14
+ if (projection === "perspective" && !(horizontalFovDegrees > 0 && horizontalFovDegrees < 180))
15
+ throw new Error("Camera fit needs a horizontal field of view between 0 and 180 degrees.");
16
+ const length = Math.hypot(direction.x, direction.y, direction.z);
17
+ const back = { x: direction.x / length, y: direction.y / length, z: direction.z / length };
18
+ const horizontal = Math.hypot(back.x, back.z);
19
+ if (!(horizontal > 1e-3))
20
+ throw new Error("Camera fit needs a direction that is not vertical.");
21
+ const right = { x: back.z / horizontal, y: 0, z: -back.x / horizontal };
22
+ const up = { x: -back.x * back.y / horizontal, y: horizontal, z: -back.z * back.y / horizontal };
23
+ const corners = [];
24
+ for (const b of boxes)
25
+ for (const x of [b.min.x, b.max.x])
26
+ for (const y of [b.min.y, b.max.y])
27
+ for (const z of [b.min.z, b.max.z])
28
+ corners.push({ x, y, z });
29
+ const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
30
+ for (const p of corners)
31
+ [dot(p, right), dot(p, up), dot(p, back)].forEach((v, i) => { lo[i] = Math.min(lo[i], v); hi[i] = Math.max(hi[i], v); });
32
+ const [cu, cv, cw] = [0, 1, 2].map(i => (lo[i] + hi[i]) / 2);
33
+ const target = {
34
+ x: cu * right.x + cv * up.x + cw * back.x,
35
+ y: cu * right.y + cv * up.y + cw * back.y,
36
+ z: cu * right.z + cv * up.z + cw * back.z,
37
+ };
38
+ const at = (distance) => ({ x: target.x + back.x * distance, y: target.y + back.y * distance, z: target.z + back.z * distance });
39
+ if (projection === "orthographic") {
40
+ const width = Math.max(minWidth, Math.max(hi[0] - lo[0], (hi[1] - lo[1]) * aspect) * margin);
41
+ return { position: at((hi[2] - lo[2]) / 2 + standoff), target, projection, orthographicWidth: width };
42
+ }
43
+ // Perspective: the eye sits at (eu, ev, ew) on the camera's right/up/back axes. Corner (u, v, w) is inside the frame
44
+ // with the margin when |u - eu| <= kH (ew - w) and |v - ev| <= kV (ew - w). Per axis that needs
45
+ // ew >= (max(u + k w) - min(u - k w)) / 2k, so the nearest eye is exact; the sideways offset that centres the
46
+ // projected extent is the root of a decreasing function, found by bisection.
47
+ const kH = Math.tan(horizontalFovDegrees * Math.PI / 360) / margin, kV = kH / aspect;
48
+ const uvw = corners.map(p => [dot(p, right), dot(p, up), dot(p, back)]);
49
+ const nearest = (axis, k) => (Math.max(...uvw.map(c => c[axis] + k * c[2])) - Math.min(...uvw.map(c => c[axis] - k * c[2]))) / (2 * k);
50
+ const ew = Math.max(nearest(0, kH), nearest(1, kV), hi[2] + 1e-9 * Math.max(1, hi[2] - lo[2]));
51
+ const centre = (axis) => {
52
+ const offset = (e) => {
53
+ const r = uvw.map(c => (c[axis] - e) / (ew - c[2]));
54
+ return Math.max(...r) + Math.min(...r);
55
+ };
56
+ let [a, b] = [lo[axis], hi[axis]];
57
+ for (let i = 0; i < 100 && b - a > 1e-12 * Math.max(1, Math.abs(a)); i++) {
58
+ const m = (a + b) / 2;
59
+ if (offset(m) > 0)
60
+ a = m;
61
+ else
62
+ b = m;
63
+ }
64
+ return (a + b) / 2;
65
+ };
66
+ const [eu, ev] = [centre(0), centre(1)];
67
+ const eye = { x: eu * right.x + ev * up.x + ew * back.x, y: eu * right.y + ev * up.y + ew * back.y, z: eu * right.z + ev * up.z + ew * back.z };
68
+ const aim = { x: eye.x - back.x * (ew - cw), y: eye.y - back.y * (ew - cw), z: eye.z - back.z * (ew - cw) };
69
+ return { position: eye, target: aim, projection, horizontalFovDegrees };
70
+ }
@@ -13,14 +13,59 @@ export type SceneSnapshot = {
13
13
  parentId: number;
14
14
  }[];
15
15
  };
16
+ type SceneVector = {
17
+ x: number;
18
+ y: number;
19
+ z: number;
20
+ };
21
+ type SceneBox = {
22
+ min: SceneVector;
23
+ max: SceneVector;
24
+ };
25
+ /** A resolved fit, in Womp scene coordinates and project units. */
26
+ export type SceneScreenshotFitted = {
27
+ boxes: SceneBox[];
28
+ direction: SceneVector;
29
+ projection: "perspective" | "orthographic";
30
+ margin: number;
31
+ horizontalFovDegrees?: number;
32
+ unitMultiplier: number;
33
+ };
34
+ /** What a host captures. */
16
35
  export type SceneScreenshotOptions = {
17
36
  /** Position/target and orthographic width use Womp scene coordinates and current project units. */
18
37
  camera?: CameraConfiguration;
38
+ /**
39
+ * Present when `camera` was fitted to these boxes for a 16:9 frame. A host that knows its capture aspect may refit
40
+ * the camera with `fitSceneCamera`; one that does not captures `camera` as given.
41
+ */
42
+ fitted?: SceneScreenshotFitted;
43
+ };
44
+ /** Frame objects or a box instead of placing the camera by hand. */
45
+ export type SceneScreenshotFit = {
46
+ /** Objects to frame. A part frames its owning top-level Area and a Group its visible Areas. Omit ids and box to frame every visible object. */
47
+ ids?: number[];
48
+ /** A world-space box in project units, framed together with any ids. */
49
+ box?: SceneBox;
50
+ /** From the subject toward the camera; any length, not vertical. Defaults to a front three-quarter view, {x: 1, y: 0.65, z: 1}. */
51
+ direction?: SceneVector;
52
+ /** Defaults to orthographic. */
53
+ projection?: "perspective" | "orthographic";
54
+ /** Perspective only; defaults to 60. */
55
+ horizontalFovDegrees?: number;
56
+ /** Frame size over the subject's size along the limiting dimension, 1 to 4; defaults to 1.1. */
57
+ margin?: number;
58
+ };
59
+ export type SceneScreenshotRequest = {
60
+ /** Position/target and orthographic width use Womp scene coordinates and current project units. */
61
+ camera?: CameraConfiguration;
62
+ /** Fit the camera to objects or a box; use instead of camera. */
63
+ fit?: SceneScreenshotFit;
19
64
  };
20
65
  export type WompSceneApi = {
21
66
  health(objectIds?: number[]): Promise<SceneHealth>;
22
67
  access<T>(callback: (draft: WompSceneDraft) => T | Promise<T>): Promise<T>;
23
- screenshot(options?: SceneScreenshotOptions): Promise<ArtifactRef>;
68
+ screenshot(options?: SceneScreenshotRequest): Promise<ArtifactRef>;
24
69
  };
25
70
  export interface SceneHealthHost {
26
71
  read(objectIds: number[], context: SparkInvocationContext): Promise<SceneHealth>;
@@ -30,6 +75,27 @@ export interface SceneHost {
30
75
  access<T>(callback: (draft: WompSceneDraft) => T | Promise<T>, context: SparkInvocationContext): Promise<T>;
31
76
  screenshot(options: SceneScreenshotOptions, context: SparkInvocationContext): Promise<ArtifactRef>;
32
77
  }
78
+ /** A screenshot placed by an explicit camera only. */
79
+ export declare const cameraScreenshotOptions: z.ZodObject<{
80
+ camera: z.ZodOptional<z.ZodObject<{
81
+ position: z.ZodObject<{
82
+ x: z.ZodNumber;
83
+ y: z.ZodNumber;
84
+ z: z.ZodNumber;
85
+ }, z.core.$strict>;
86
+ target: z.ZodObject<{
87
+ x: z.ZodNumber;
88
+ y: z.ZodNumber;
89
+ z: z.ZodNumber;
90
+ }, z.core.$strict>;
91
+ projection: z.ZodOptional<z.ZodEnum<{
92
+ perspective: "perspective";
93
+ orthographic: "orthographic";
94
+ }>>;
95
+ horizontalFovDegrees: z.ZodOptional<z.ZodNumber>;
96
+ orthographicWidth: z.ZodOptional<z.ZodNumber>;
97
+ }, z.core.$strict>>;
98
+ }, z.core.$strict>;
33
99
  export declare const screenshotOptions: z.ZodObject<{
34
100
  camera: z.ZodOptional<z.ZodObject<{
35
101
  position: z.ZodObject<{
@@ -49,5 +115,37 @@ export declare const screenshotOptions: z.ZodObject<{
49
115
  horizontalFovDegrees: z.ZodOptional<z.ZodNumber>;
50
116
  orthographicWidth: z.ZodOptional<z.ZodNumber>;
51
117
  }, z.core.$strict>>;
118
+ fitted: z.ZodOptional<z.ZodObject<{
119
+ boxes: z.ZodArray<z.ZodObject<{
120
+ min: z.ZodObject<{
121
+ x: z.ZodNumber;
122
+ y: z.ZodNumber;
123
+ z: z.ZodNumber;
124
+ }, z.core.$strict>;
125
+ max: z.ZodObject<{
126
+ x: z.ZodNumber;
127
+ y: z.ZodNumber;
128
+ z: z.ZodNumber;
129
+ }, z.core.$strict>;
130
+ }, z.core.$strict>>;
131
+ direction: z.ZodObject<{
132
+ x: z.ZodNumber;
133
+ y: z.ZodNumber;
134
+ z: z.ZodNumber;
135
+ }, z.core.$strict>;
136
+ projection: z.ZodEnum<{
137
+ perspective: "perspective";
138
+ orthographic: "orthographic";
139
+ }>;
140
+ margin: z.ZodNumber;
141
+ horizontalFovDegrees: z.ZodOptional<z.ZodNumber>;
142
+ unitMultiplier: z.ZodNumber;
143
+ }, z.core.$strict>>;
52
144
  }, z.core.$strict>;
145
+ /**
146
+ * Camera fitted to `fitted` for a frame of `aspect` (width / height), in Womp scene coordinates and project units.
147
+ * Hosts that know their capture aspect call this to refit a fitted screenshot.
148
+ */
149
+ export declare function fitSceneCamera(fitted: SceneScreenshotFitted, aspect?: number): CameraConfiguration;
53
150
  export declare function createSceneCapability(host: SceneHost): SparkCapability<WompSceneApi>;
151
+ export {};
@@ -3,6 +3,7 @@ import { meshWompifySkill } from "./wompify.js";
3
3
  import { maxLightIntensity } from "@womp/kakapo-sdk";
4
4
  import { WOMP_SCENE_DECLARATIONS } from "../generated/scene-declarations.js";
5
5
  import { unverifiedSceneHealth } from "../scene-health.js";
6
+ import { fitCamera } from "../camera-fit.js";
6
7
  // A node id, as `scene.access()` publishes them: the scene root is 0, so a health
7
8
  // read has to accept it. `openscad.ts` and `geometry.ts` spell an object id the
8
9
  // same way; `positive()` here refused an id this capability had just handed out.
@@ -25,21 +26,108 @@ function readHealthObjectIds(objectIds) {
25
26
  throw new Error(`scene.health takes object ids from scene.access(): whole numbers from 0 up, in an array. ${named} ${invalid.length === 1 ? "is not one" : "are not ids"}.`);
26
27
  }
27
28
  const cameraVector = z.object({ x: z.number().finite(), y: z.number().finite(), z: z.number().finite() }).strict();
29
+ const cameraBox = z.object({ min: cameraVector, max: cameraVector }).strict();
30
+ const cameraProjection = z.enum(["perspective", "orthographic"]);
31
+ const explicitCamera = z.object({
32
+ position: cameraVector,
33
+ target: cameraVector,
34
+ projection: cameraProjection.optional(),
35
+ horizontalFovDegrees: z.number().finite().optional(),
36
+ orthographicWidth: z.number().finite().positive().optional(),
37
+ }).strict();
38
+ /** A screenshot placed by an explicit camera only. */
39
+ export const cameraScreenshotOptions = z.object({ camera: explicitCamera.optional() }).strict();
28
40
  export const screenshotOptions = z.object({
29
- camera: z.object({
30
- position: cameraVector,
31
- target: cameraVector,
32
- projection: z.enum(["perspective", "orthographic"]).optional(),
41
+ camera: explicitCamera.optional(),
42
+ fitted: z.object({
43
+ boxes: z.array(cameraBox).min(1),
44
+ direction: cameraVector,
45
+ projection: cameraProjection,
46
+ margin: z.number().finite().min(1),
33
47
  horizontalFovDegrees: z.number().finite().optional(),
34
- orthographicWidth: z.number().finite().positive().optional(),
48
+ unitMultiplier: z.number().finite().positive(),
35
49
  }).strict().optional(),
36
50
  }).strict();
51
+ const screenshotRequest = z.object({
52
+ camera: explicitCamera.optional(),
53
+ fit: z.object({
54
+ ids: z.array(objectId).optional(),
55
+ box: cameraBox.optional(),
56
+ direction: cameraVector.optional(),
57
+ projection: cameraProjection.optional(),
58
+ horizontalFovDegrees: z.number().finite().gt(0).lt(180).optional(),
59
+ margin: z.number().finite().min(1).max(4).optional(),
60
+ }).strict().optional(),
61
+ }).strict().refine(value => !(value.camera && value.fit), "Pass either camera or fit, not both.");
62
+ const DEFAULT_FIT_DIRECTION = { x: 1, y: 0.65, z: 1 };
63
+ const LIGHT = 2, GROUP = 4;
64
+ /**
65
+ * Camera fitted to `fitted` for a frame of `aspect` (width / height), in Womp scene coordinates and project units.
66
+ * Hosts that know their capture aspect call this to refit a fitted screenshot.
67
+ */
68
+ export function fitSceneCamera(fitted, aspect = 16 / 9) {
69
+ const mm = fitted.unitMultiplier;
70
+ // A 6.25 mm frame is the narrowest the SDK accepts; 1 m in front keeps an orthographic camera clear of the subject.
71
+ return fitCamera(fitted.boxes, { ...fitted, aspect, minWidth: 6.25 * mm, standoff: 1000 * mm });
72
+ }
73
+ /** Renderer bounds for a fit request, read in a read-only access. */
74
+ async function fitBoxes(draft, fit) {
75
+ const boxes = fit.box ? [fit.box] : [];
76
+ const areas = new Set();
77
+ // The root lists itself among its own children.
78
+ const children = (id) => draft.nodes({ parentId: id, limit: 1000 }).filter(child => child.id !== id);
79
+ const visit = (id, explicit) => {
80
+ const type = draft.nodeGetType(id);
81
+ if (type === LIGHT || (!explicit && draft.nodeGetHide(id)))
82
+ return;
83
+ if (type === GROUP)
84
+ for (const child of children(id))
85
+ visit(child.id, false);
86
+ else
87
+ areas.add(id);
88
+ };
89
+ const owner = (id) => {
90
+ for (let node = id;; node = draft.nodeGetParentId(node)) {
91
+ const parent = draft.nodeGetParentId(node);
92
+ if (parent === 0 || draft.nodeGetType(parent) === GROUP)
93
+ return node;
94
+ }
95
+ };
96
+ const ids = fit.ids?.length ? fit.ids : fit.box ? [] : [0];
97
+ for (const id of ids) {
98
+ if (id === 0)
99
+ for (const child of children(0))
100
+ visit(child.id, false);
101
+ else if (draft.nodeGetType(id) === LIGHT)
102
+ throw new Error(`Object ${id} is a light, which has no bounds to frame.`);
103
+ else if (draft.nodeGetType(id) === GROUP)
104
+ visit(id, true);
105
+ else
106
+ areas.add(owner(id));
107
+ }
108
+ for (const id of areas) {
109
+ let box;
110
+ try {
111
+ box = await draft.nodeGetAABB(id);
112
+ }
113
+ catch {
114
+ continue;
115
+ }
116
+ const values = [box.min.x, box.min.y, box.min.z, box.max.x, box.max.y, box.max.z];
117
+ const empty = box.min.x === box.max.x && box.min.y === box.max.y && box.min.z === box.max.z;
118
+ if (values.every(Number.isFinite) && box.min.x <= box.max.x && !empty)
119
+ boxes.push(box);
120
+ }
121
+ if (!boxes.length)
122
+ throw new Error("screenshot fit found nothing with bounds to frame. Check the ids, or pass a box.");
123
+ return boxes;
124
+ }
37
125
  export function createSceneCapability(host) {
38
126
  return {
39
127
  skills: [
40
128
  {
41
129
  name: "scene-editing",
42
- version: "77",
130
+ version: "78",
43
131
  description: "Inspect the open scene and edit its objects, materials, curves, and environment.",
44
132
  instructions: `Use womp.scene.access(callback) for both inspection and edits. Inspect targets inside each callback using scene.nodes({ name, type, parentId, ids, offset, limit }) and detailed getters; filters are optional, name is a case-insensitive substring, and results default to 100 (maximum 1000). Page with offset as needed. Inspection reflects changes made in the callback. scene.unitMultiplier gives project units. Do not reuse an earlier inspection as current state.
45
133
  Use womp.scene.health() to refresh whole-scene health or womp.scene.health(objectIds) to check specific objects (mapped to their owning Areas).
@@ -63,7 +151,7 @@ Rect/Sphere lights support nodeSetCollimation(id, value) in 0..1 (broad to colli
63
151
  cameraReadDepthOfField() inspects the current camera. cameraSetDepthOfField({enabled, mode, focusDistance, aperturePercent}) changes only supplied DoF fields and the acting user's active saved camera. mode is physical or post-process; physical DoF requires perspective projection and production rendering. Focus distance uses project units; aperturePercent is Womp's 0..100 blur strength, not an f-number. Use a converged production render to evaluate bokeh and focus.
64
152
  For text, nodeSetTextSize(id, {fontSize, depth}) sets font em size and extrusion in project units, not a bounding box. Layout width and additional letter spacing also use project units; spacing clamps to ±25 mm. Line height is a multiplier clamped to 0.5–3. The origin anchors the first baseline; alignment uses the layout width. Empty text clears its geometry.
65
153
  Decals require an existing loaded image and receiving geometry. Projection is a uniform cube: native scale.x (public size.z) controls all dimensions, not independent width/height/depth. Restriction to an Area requires that parent Area; root decals project globally. Missing image data can yield no projection even when no resource is pending.
66
- nodeCreate(SVG, parentAreaId) creates an editable SVG node. Set structured paths with nodeSetSvgPaths(id, paths) and read them with nodeGetSvgPaths(id). Each path has closed and at least two segments; point, handleIn and handleOut are 2D vectors in project units, with handles relative to their point. SVG coordinates are local to the node, with y up. Unrotated SVG geometry lies in the node's Y–Z plane facing ±X; nodeSetRot(id, {x: 0, y: -90, z: 0}) faces it toward +Z with path x to the right. Fill uses the nonzero rule: a contour wound opposite to its enclosing contour cuts a hole, and same-direction overlaps merge. nodeSetSvgDepth(id, depth) sets normal extrusion in project units, including the parent Area scale; nodeGetSvgDepth reads it back. Native local depth must be 0.01–1000 mm. Generic nodeSetSize does not set this depth. SVG nodes have no round or color property; color them with a material. Inspect the visible result before claiming holes or exact thickness.
154
+ nodeCreate(SVG, parentAreaId) creates an editable SVG node. Set structured paths with nodeSetSvgPaths(id, paths) and read them with nodeGetSvgPaths(id). Each path has closed and at least two segments; point, handleIn and handleOut are 2D vectors in project units, with handles relative to their point. SVG coordinates are local to the node, with y up. Unrotated SVG geometry lies in the node's Y–Z plane facing ±X; nodeSetRot(id, {x: 0, y: -90, z: 0}) faces it toward +Z with path x to the right, and nodeSetRot(id, {x: 0, y: 0, z: 90}) lays it flat in X–Z extruded along Y (path x along +Z, path y along −X; best for crisp unrounded hard-surface plates or flanges). Fill uses the nonzero rule: a contour wound opposite to its enclosing contour cuts a hole, and same-direction overlaps merge. nodeSetSvgDepth(id, depth) sets normal extrusion in project units, including the parent Area scale; nodeGetSvgDepth reads it back. Native local depth must be 0.01–1000 mm. Generic nodeSetSize does not set this depth. SVG nodes have no round or color property; color them with a material. Inspect the visible result before claiming holes or exact thickness.
67
155
 
68
156
  ## Curve authoring
69
157
  - Choose the construction by the geometry. Use standalone primitives for simple volumes. Replace Cube placeholders for shallow parts with full-width rounded ends, such as the toe of a sneaker sole. Fit the perimeter first. For an outline-defined part of uniform thickness, extrude its fitted closed SVG contours once, using as few Bézier spans as each contour needs. For a form defined by a path and cross-sections, try one editable V3 Curve when a single profile type can describe the sections along it. Use intersected SVG outlines where independent projected contours define the shape, and Boolean cuts or joins for cross-sections that need several shapes.
@@ -111,7 +199,7 @@ Womp shapes are signed distance fields. Build continuous main forms with fitted
111
199
  - Model one side of a symmetric object and mirror it: nodeSetMirror(id, slot, axis, planePosition) reflects a Primitive or Curve across a plane in its parent frame, so one wheel, eye, fender or wing makes the pair and later edits stay symmetric.
112
200
  - For a hollow or recess with a continuous rim, fit the shell and cutter together. Adjust the cutter's offset, cross-section and taper to shape the remaining wall before adding raised details. Inspect the rim and wall from an oblique view.
113
201
  - To intersect two independently fitted outlines, draw the top as a closed SVG path, preserving any asymmetry, and extrude it through the height. Draw the side as a second SVG facing sideways and extruded through the width, with OperationType.Intersect. Set the blend for the intended edge radius and verify the resulting contours. Intersect mating parts with the same outline when they need to follow that surface.
114
- - Keep surfaces smooth and continuous, as if cast in one mould: shape bumpers, intakes, spoilers, face plates, panels, feet and bases to follow the body's curvature, with a curve or a rounded shape, and fillet each one into the body with a blend of a few millimetres. A flat block laid on a curved surface, a hard ledge or a stair-step reads as stacked parts. Round boxes with nodeSetRound; keep sharp only what is sharp on the real thing.
202
+ - Keep surfaces smooth and continuous, as if cast in one mould: shape bumpers, intakes, spoilers, face plates, panels, cuffs, soles and bases to match the curved outline of the part they meet—use an Ellipsoid, Capsule, Cylinder, closed Curve or extruded rounded SVG outline, never a rectangular Cube for a curved ring, cuff or foot sole—so a base or sole wraps flush around the upper instead of sticking out as a boxy shelf, and fillet each join where the reference is continuous. Seat thin straps, laces and cords cleanly along the curved surface (never buried completely inside or floating with a gap) while keeping reference details such as tied bows. A flat block laid on a curved surface, a hard ledge or a stair-step reads as stacked parts. Round boxes with nodeSetRound; keep sharp only what is sharp on the real thing, and inspect small layered parts and back/side overlaps in close-ups before finishing so inner geometry never pokes through outer shells.
115
203
  - Give every visibly distinct part its own material and colour.
116
204
  Before building, settle the target in numbers: the side, front and top silhouettes with their key heights, widths and lengths, using actual references when available. Inspect the main forms from matching views and fix their largest mismatch before adding detail. Batch related changes and capture the views needed to check their effect. A rounded outline may enclose a broad flat face; preserve that distinction rather than inflating every section. Finish with fine detail at its real scale, such as meshes, treads, fasteners, seams and trim: build one, then repeat it or copy its assembly with cloneSubtree.
117
205
  Build and verify coarse geometry and unfamiliar operations before replicating details. Check one representative result, then repeat it.
@@ -133,12 +221,20 @@ unavailable. Selecting an HDR resets its intensity; apply a custom intensity aft
133
221
  For library materials, use listSuperMaterials(), then await materialImport(name) inside scene.access and assign the returned numeric ID the way that object requires: nodeSetMaterialId or curvePointSetMaterialId for scene nodes, the FlowIR SetMaterial node for a Geometry Nodes graph. A failed import rolls back the draft.
134
222
  Filter large read results with JavaScript and print only useful details.
135
223
  After a major edit, capture a screenshot outside the transaction and emitImage its reference.
136
- screenshot({ camera: { position: {x,y,z}, target: {x,y,z}, projection: 'perspective', horizontalFovDegrees: 60 } })
137
- sets a world-space camera in the same Womp coordinates and project units as scene positions (Y-up).
138
- For orthographic framing use projection: 'orthographic' and orthographicWidth in project units instead of FOV.
139
- Direction is derived from position/target; do not use coincident points or an exactly vertical viewing direction.
140
- Omitted projection/lens settings come from the active camera. Pass the camera again for repeatable captures.
141
- For object-focused screenshots, identify the requested object and frame it using world-space bounds. Convert local bounds using the object’s and applicable ancestor transforms, including translation, rotation, and scale; do not transform world-space bounds again. Reuse established framing when appropriate and avoid clipping the subject.
224
+ Frame every view of objects with screenshot({ fit: { ids, box, direction, projection, horizontalFovDegrees, margin } }).
225
+ It centres the subject and sets the distance and frame size from current renderer bounds and the capture's real aspect
226
+ ratio, so nothing is clipped. ids frame objects (a part frames its owning top-level Area, a Group its visible Areas); omit
227
+ ids and box to frame every visible object. For a close-up of a part, pass box as its world-space bounds in project units, converting local bounds through the
228
+ part’s and its ancestors’ translation, rotation and scale.
229
+ direction points from the subject toward the camera, like camera position minus target; it defaults to the front
230
+ three-quarter view {x: 1, y: 0.65, z: 1}. The front faces +Z, so {x: 0, y: 0.1, z: 1} is the front view and
231
+ {x: 1, y: 0.1, z: 0} the right side. projection defaults to orthographic; margin defaults to 1.1.
232
+ To match a reference image's viewpoint, give fit the direction it was taken from with projection: 'perspective' and a
233
+ horizontalFovDegrees matching its lens (narrower for a flatter, telephoto look).
234
+ Use screenshot({ camera: { position, target, projection, horizontalFovDegrees | orthographicWidth } }) only when the
235
+ camera's own position matters, such as a view from inside an object. It uses Womp coordinates and project units (Y-up).
236
+ orthographicWidth and horizontalFovDegrees span the frame's width, and the frame is wider than tall. Do not use coincident
237
+ points or an exactly vertical direction. Omitted lens settings come from the active camera.
142
238
  Omitting camera captures the active viewport without auto-fit. Use it when the user asks about the current viewport or clearly refers to what is visible on screen, not on the assumption that it shows the requested object.
143
239
  Respect the host's camera-lock restrictions. Verify silhouette,
144
240
  connections, openings, proportions, and materials before claiming completion. Use the owning top-level Area for scene-space bounds;
@@ -225,7 +321,21 @@ A failed script can retain earlier committed effects. Use receipts and inspect u
225
321
  throw new Error("scene.access requires a callback.");
226
322
  return host.access(callback, context);
227
323
  },
228
- screenshot: (options) => host.screenshot(screenshotOptions.parse(options ?? {}), context),
324
+ screenshot: async (options) => {
325
+ const request = screenshotRequest.parse(options ?? {});
326
+ if (!request.fit)
327
+ return host.screenshot(request.camera ? { camera: request.camera } : {}, context);
328
+ const fit = request.fit;
329
+ const resolved = await host.access(async (draft) => ({ boxes: await fitBoxes(draft, fit), unitMultiplier: draft.unitMultiplier }), context);
330
+ const fitted = {
331
+ ...resolved,
332
+ direction: fit.direction ?? DEFAULT_FIT_DIRECTION,
333
+ projection: fit.projection ?? "orthographic",
334
+ margin: fit.margin ?? 1.1,
335
+ ...(fit.projection === "perspective" ? { horizontalFovDegrees: fit.horizontalFovDegrees ?? 60 } : {}),
336
+ };
337
+ return host.screenshot({ camera: fitSceneCamera(fitted), fitted }, context);
338
+ },
229
339
  };
230
340
  },
231
341
  };
@@ -1,7 +1,7 @@
1
1
  import type { JavaScriptGlobals } from "./executor.js";
2
2
  import type { SparkArtifact } from "./ui.js";
3
- export { createSceneCapability } from "./capabilities/scene.js";
4
- export type { WompSceneApi, SceneHost, SceneSnapshot, SceneScreenshotOptions, } from "./capabilities/scene.js";
3
+ export { createSceneCapability, fitSceneCamera } from "./capabilities/scene.js";
4
+ export type { WompSceneApi, SceneHost, SceneSnapshot, SceneScreenshotOptions, SceneScreenshotFitted, SceneScreenshotFit, SceneScreenshotRequest, } from "./capabilities/scene.js";
5
5
  export type { WompSceneDraft } from "./capabilities/scene-draft.js";
6
6
  export { createKnowledgeCapability } from "./capabilities/knowledge.js";
7
7
  export { createAccountCapability } from "./capabilities/account.js";
@@ -1,4 +1,4 @@
1
- export { createSceneCapability } from "./capabilities/scene.js";
1
+ export { createSceneCapability, fitSceneCamera } from "./capabilities/scene.js";
2
2
  export { createKnowledgeCapability } from "./capabilities/knowledge.js";
3
3
  export { createAccountCapability } from "./capabilities/account.js";
4
4
  export { createOperationsCapability } from "./capabilities/operations.js";