depthview-mcp 0.1.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -19
- package/dist/cli.js +1009 -1194
- package/dist/probe.js +782 -0
- package/package.json +5 -1
- package/skill/SKILL.md +583 -54
- package/skill/references/award-sites.md +175 -0
- package/skill/references/extension-ui.md +190 -0
- package/skill/references/modeling.md +198 -0
- package/skill/references/particles.md +137 -0
- package/skill/references/performance.md +114 -0
- package/skill/references/r3f.md +151 -0
- package/skill/references/rendering.md +150 -0
- package/skill/references/shaders.md +200 -0
- package/skill/references/site-build.md +288 -0
- package/skill/references/threejs.md +387 -0
- package/skill/references/visual-qa.md +152 -0
- package/skill/references/volumetrics.md +165 -0
package/dist/cli.js
CHANGED
|
@@ -1,1148 +1,1035 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import{StdioServerTransport as pn}from"@modelcontextprotocol/sdk/server/stdio.js";import{cpSync as mn,existsSync as fn,mkdirSync as gn,readFileSync as vn,writeFileSync as wn}from"node:fs";import{dirname as bn,join as ze,resolve as yn,sep as xn}from"node:path";import{fileURLToPath as kn}from"node:url";import{McpServer as Wr}from"@modelcontextprotocol/sdk/server/mcp.js";import{z as s}from"zod";var X=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e.texture=="string",Ve={uTime:"float: seconds, following the site clock (set_time holds it)",uResolution:"vec2: the drawing buffer in pixels",uCameraLocal:"vec3: the camera position in the effect object's own space",uNoise:"sampler2D: a 256 x 256 tiling noise texture (r and b: white noise, g: r moved by 37, 17 so one read gives 3D value noise; see dvNoise in the clouds shader)",uDepth:"sampler2D: the depth of the solid scene behind this pixel, read at gl_FragCoord.xy / uResolution (0 near, 1 far). Only valid while uHasDepth is 1",uHasDepth:"float: 1 when uDepth holds the scene depth, 0 when the page cannot provide it",uDepthToLocal:"mat4: takes vec4(screen * 2 - 1, depth * 2 - 1, 1) to the effect object's own space (divide by w)"};var Eo=1e5,kt=6e4,se=`
|
|
3
|
+
float dvHash(vec3 p) {
|
|
4
|
+
p = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3));
|
|
5
|
+
p *= 17.0;
|
|
6
|
+
return fract(p.x * p.y * p.z * (p.x + p.y + p.z));
|
|
7
|
+
}
|
|
8
|
+
float dvNoise(vec3 x) {
|
|
9
|
+
vec3 i = floor(x);
|
|
10
|
+
vec3 f = fract(x);
|
|
11
|
+
f = f * f * (3.0 - 2.0 * f);
|
|
12
|
+
return mix(
|
|
13
|
+
mix(mix(dvHash(i), dvHash(i + vec3(1.0, 0.0, 0.0)), f.x),
|
|
14
|
+
mix(dvHash(i + vec3(0.0, 1.0, 0.0)), dvHash(i + vec3(1.0, 1.0, 0.0)), f.x), f.y),
|
|
15
|
+
mix(mix(dvHash(i + vec3(0.0, 0.0, 1.0)), dvHash(i + vec3(1.0, 0.0, 1.0)), f.x),
|
|
16
|
+
mix(dvHash(i + vec3(0.0, 1.0, 1.0)), dvHash(i + vec3(1.0, 1.0, 1.0)), f.x), f.y),
|
|
17
|
+
f.z);
|
|
18
|
+
}
|
|
19
|
+
float dvFbm(vec3 p) {
|
|
20
|
+
float amplitude = 0.5;
|
|
21
|
+
float sum = 0.0;
|
|
22
|
+
for (int i = 0; i < 4; i++) {
|
|
23
|
+
sum += amplitude * dvNoise(p);
|
|
24
|
+
p = p * 2.02 + vec3(13.1, 7.7, 3.3);
|
|
25
|
+
amplitude *= 0.5;
|
|
26
|
+
}
|
|
27
|
+
return sum / 0.9375;
|
|
28
|
+
}
|
|
29
|
+
float dvFbmLow(vec3 p) {
|
|
30
|
+
return (0.5 * dvNoise(p) + 0.25 * dvNoise(p * 2.02 + vec3(13.1, 7.7, 3.3))) / 0.75;
|
|
31
|
+
}
|
|
32
|
+
`,$o=`
|
|
33
|
+
uniform sampler2D uNoise;
|
|
34
|
+
float dvNoise(vec3 x) {
|
|
35
|
+
vec3 i = floor(x);
|
|
36
|
+
vec3 f = fract(x);
|
|
37
|
+
f = f * f * (3.0 - 2.0 * f);
|
|
38
|
+
vec2 uv = (i.xy + vec2(37.0, 17.0) * i.z) + f.xy;
|
|
39
|
+
vec2 rg = texture2D(uNoise, (uv + 0.5) / 256.0).yx;
|
|
40
|
+
return mix(rg.x, rg.y, f.z);
|
|
41
|
+
}
|
|
42
|
+
float dvFbm(vec3 p) {
|
|
43
|
+
float amplitude = 0.5;
|
|
44
|
+
float sum = 0.0;
|
|
45
|
+
for (int i = 0; i < 4; i++) {
|
|
46
|
+
sum += amplitude * dvNoise(p);
|
|
47
|
+
p = p * 2.02 + vec3(13.1, 7.7, 3.3);
|
|
48
|
+
amplitude *= 0.5;
|
|
49
|
+
}
|
|
50
|
+
return sum / 0.9375;
|
|
51
|
+
}
|
|
52
|
+
float dvFbmLow(vec3 p) {
|
|
53
|
+
return (0.5 * dvNoise(p) + 0.25 * dvNoise(p * 2.02 + vec3(13.1, 7.7, 3.3))) / 0.75;
|
|
54
|
+
}
|
|
55
|
+
`,B=`#include <tonemapping_fragment>
|
|
56
|
+
#include <colorspace_fragment>`,jo=`
|
|
57
|
+
attribute vec2 dvCorner;
|
|
58
|
+
attribute vec4 dvSeed;
|
|
59
|
+
uniform float uTime;
|
|
60
|
+
uniform float uSize;
|
|
61
|
+
uniform float uSizeRandom;
|
|
62
|
+
uniform float uSpeed;
|
|
63
|
+
uniform float uTurbulence;
|
|
64
|
+
uniform float uTwinkle;
|
|
65
|
+
uniform float uStretch;
|
|
66
|
+
uniform vec3 uDirection;
|
|
67
|
+
varying vec2 vUv;
|
|
68
|
+
varying float vFade;
|
|
69
|
+
varying float vSeed;
|
|
2
70
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
71
|
+
void main() {
|
|
72
|
+
// Each sprite drifts through a unit box and wraps round, so the field never empties.
|
|
73
|
+
vec3 p = position + uDirection * uSpeed * uTime * (0.5 + dvSeed.x);
|
|
74
|
+
float t = uTime * 0.25;
|
|
75
|
+
p += uTurbulence * 0.08 * vec3(
|
|
76
|
+
sin(t * 1.3 + dvSeed.y * 6.2832 + position.y * 4.0),
|
|
77
|
+
sin(t * 1.7 + dvSeed.z * 6.2832 + position.z * 4.0),
|
|
78
|
+
sin(t * 1.1 + dvSeed.w * 6.2832 + position.x * 4.0));
|
|
79
|
+
p = fract(p + 0.5) - 0.5;
|
|
80
|
+
// Fade out towards the faces of the box: the wrap is never seen.
|
|
81
|
+
vec3 edge = smoothstep(0.5, 0.4, abs(p));
|
|
82
|
+
vFade = edge.x * edge.y * edge.z;
|
|
83
|
+
vFade *= 1.0 - uTwinkle * (0.5 + 0.5 * sin(uTime * (1.0 + dvSeed.y * 3.0) + dvSeed.z * 6.2832));
|
|
8
84
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
85
|
+
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
|
86
|
+
// Size is in scene units whatever the scale of the box. Stretch pulls the sprite out along
|
|
87
|
+
// its direction of travel (rain, sparks).
|
|
88
|
+
float size = uSize * mix(1.0, 0.25 + 0.75 * dvSeed.w, uSizeRandom);
|
|
89
|
+
vec2 axis = (modelViewMatrix * vec4(uDirection, 0.0)).xy;
|
|
90
|
+
axis = length(axis) > 0.0001 ? normalize(axis) : vec2(0.0, 1.0);
|
|
91
|
+
vec2 across = vec2(-axis.y, axis.x);
|
|
92
|
+
mv.xy += (across * dvCorner.x + axis * dvCorner.y * (1.0 + uStretch)) * size * 0.5;
|
|
93
|
+
gl_Position = projectionMatrix * mv;
|
|
94
|
+
vUv = dvCorner;
|
|
95
|
+
vSeed = dvSeed.x;
|
|
96
|
+
}
|
|
97
|
+
`,Ue=`
|
|
98
|
+
uniform vec3 uColor;
|
|
99
|
+
uniform vec3 uColor2;
|
|
100
|
+
uniform float uOpacity;
|
|
101
|
+
uniform float uSoftness;
|
|
102
|
+
varying vec2 vUv;
|
|
103
|
+
varying float vFade;
|
|
104
|
+
varying float vSeed;
|
|
12
105
|
|
|
13
|
-
|
|
14
|
-
|
|
106
|
+
void main() {
|
|
107
|
+
float d = length(vUv);
|
|
108
|
+
if (d > 1.0) discard;
|
|
109
|
+
float alpha = 1.0 - smoothstep(1.0 - max(uSoftness, 0.001), 1.0, d);
|
|
110
|
+
gl_FragColor = vec4(mix(uColor, uColor2, vSeed), alpha * uOpacity * vFade);
|
|
111
|
+
${B}
|
|
112
|
+
}
|
|
113
|
+
`,be=`
|
|
114
|
+
attribute vec2 dvCorner;
|
|
115
|
+
attribute vec4 dvSeed;
|
|
116
|
+
uniform float uTime;
|
|
117
|
+
uniform float uSize;
|
|
118
|
+
uniform float uSpeed;
|
|
119
|
+
uniform float uSpread;
|
|
120
|
+
uniform float uTurbulence;
|
|
121
|
+
uniform vec3 uWind;
|
|
122
|
+
varying vec2 vUv;
|
|
123
|
+
varying float vLife;
|
|
124
|
+
varying float vSeed;
|
|
15
125
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
126
|
+
void main() {
|
|
127
|
+
// One puff rises from the object's origin to one unit above it, then starts again: the
|
|
128
|
+
// position of the effect is where the smoke comes from.
|
|
129
|
+
float life = fract(dvSeed.x + uTime * uSpeed * (0.6 + 0.8 * dvSeed.y));
|
|
130
|
+
vec3 p = vec3(position.x, 0.0, position.z) * uSpread * (0.25 + life);
|
|
131
|
+
p.y = life;
|
|
132
|
+
p.xz += uTurbulence * 0.15 * life * vec2(
|
|
133
|
+
sin(life * 6.0 + dvSeed.z * 6.2832 + uTime * 0.3),
|
|
134
|
+
cos(life * 5.0 + dvSeed.w * 6.2832 + uTime * 0.25));
|
|
135
|
+
p += uWind * life * life;
|
|
22
136
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
argument: {
|
|
36
|
-
name: "goal",
|
|
37
|
-
description: 'What should change, e.g. "warmer, moodier lighting" or "camera closer".'
|
|
38
|
-
},
|
|
39
|
-
text: (goal) => `Tune my live three.js scene with the Depthview tools. Goal: ${goal?.trim() || "ask me what I want changed"}.
|
|
40
|
-
|
|
41
|
-
Steps: get_status, describe_scene, then find the objects that matter (find_objects, get_object). Take a take_screenshot view:"site" first. Make the change in small steps with set_values, starting from the current values, and check each step with take_screenshot view:"site" compare:true. At most three rounds. Do not write anything into the source yet: tell me what you changed (object, path, old to new) and ask whether to keep it.`
|
|
42
|
-
},
|
|
43
|
-
{
|
|
44
|
-
name: "apply",
|
|
45
|
-
title: "Write Depthview changes into the code",
|
|
46
|
-
description: "Write every change made in the inspector (by you or by hand) into the source.",
|
|
47
|
-
text: () => 'Write my Depthview changes into the code: get_changes, then apply_changes_to_code. For every edit that comes back "queued", call get_edit_context and finish it with apply_edit or your own edit plus mark_edit_done. Write changes without a source location yourself from get_changes. Then list_pending_edits to confirm nothing is left, and list per change: file, prop, old value to new value. Change nothing else.'
|
|
48
|
-
},
|
|
49
|
-
{
|
|
50
|
-
name: "performance",
|
|
51
|
-
title: "Check scene performance",
|
|
52
|
-
description: "Measure the scene and find what costs the most.",
|
|
53
|
-
text: () => "Check the performance of my live three.js scene: get_performance, get_resources and get_lighting. Name the three biggest costs with numbers, and for each one the change you would make. Try a fix live only if it is a value change, measure again with get_performance, and put it back with undo_change unless I say keep it."
|
|
54
|
-
}
|
|
55
|
-
];
|
|
56
|
-
|
|
57
|
-
// src/mcp.ts
|
|
58
|
-
var text = (value2) => ({
|
|
59
|
-
content: [
|
|
60
|
-
{
|
|
61
|
-
type: "text",
|
|
62
|
-
text: typeof value2 === "string" ? value2 : JSON.stringify(value2, null, 2)
|
|
63
|
-
}
|
|
64
|
-
]
|
|
65
|
-
});
|
|
66
|
-
var withNext = (data, next) => next && data && typeof data === "object" && !Array.isArray(data) ? { ...data, next } : data;
|
|
67
|
-
var asRec = (v) => v && typeof v === "object" ? v : {};
|
|
68
|
-
var CHECK_NEXT = 'Check it: take_screenshot view:"site" compare:true. Adjust, or when it is right: get_changes, then apply_changes_to_code.';
|
|
69
|
-
var animatedNext = (paths) => `The site's own code moved ${paths.join(", ")} back right after the change: it is animated, scrolled or driven by state. Call get_animated_values. Do not write a constant for it into the source without asking the developer.`;
|
|
70
|
-
var ANGLE_PATHS = /* @__PURE__ */ new Set(["rotation", "angle"]);
|
|
71
|
-
function toRadians(path, value2) {
|
|
72
|
-
if (!ANGLE_PATHS.has(path))
|
|
73
|
-
throw new Error(
|
|
74
|
-
`degrees:true only applies to rotation and angle, not "${path}" (fov is in degrees already).`
|
|
75
|
-
);
|
|
76
|
-
const rad = (n) => Math.round(n * Math.PI / 180 * 1e6) / 1e6;
|
|
77
|
-
if (typeof value2 === "number") return rad(value2);
|
|
78
|
-
if (Array.isArray(value2) && value2.every((n) => typeof n === "number"))
|
|
79
|
-
return value2.map((n) => rad(n));
|
|
80
|
-
throw new Error(`"${path}" with degrees:true needs a number or [x, y, z].`);
|
|
137
|
+
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
|
138
|
+
float size = uSize * (0.4 + 1.6 * life) * (0.7 + 0.6 * dvSeed.w);
|
|
139
|
+
// Each puff has its own slow turn, so the sprites do not read as copies.
|
|
140
|
+
float turn = dvSeed.z * 6.2832 + life * (dvSeed.w - 0.5) * 2.0;
|
|
141
|
+
vec2 corner = vec2(
|
|
142
|
+
cos(turn) * dvCorner.x - sin(turn) * dvCorner.y,
|
|
143
|
+
sin(turn) * dvCorner.x + cos(turn) * dvCorner.y);
|
|
144
|
+
mv.xy += corner * size * 0.5;
|
|
145
|
+
gl_Position = projectionMatrix * mv;
|
|
146
|
+
vUv = dvCorner;
|
|
147
|
+
vLife = life;
|
|
148
|
+
vSeed = dvSeed.x * 31.0 + dvSeed.y * 17.0;
|
|
81
149
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
inputSchema: {
|
|
100
|
-
status: z.enum(["queued", "applied", "failed", "done"]).optional().describe("Only edits with this status. Default: queued.")
|
|
101
|
-
}
|
|
102
|
-
},
|
|
103
|
-
async ({ status }) => text(core.list(status ?? "queued"))
|
|
104
|
-
);
|
|
105
|
-
mcp.registerTool(
|
|
106
|
-
"get_edit_context",
|
|
107
|
-
{
|
|
108
|
-
description: "Source code around the JSX element an edit targets, with line numbers, plus why it was queued. Always call this before editing.",
|
|
109
|
-
inputSchema: {
|
|
110
|
-
id: z.string(),
|
|
111
|
-
radius: z.number().int().min(1).max(80).optional().describe("Lines before and after. Default 12.")
|
|
112
|
-
}
|
|
113
|
-
},
|
|
114
|
-
async ({ id, radius }) => {
|
|
115
|
-
try {
|
|
116
|
-
return text(core.context(id, radius));
|
|
117
|
-
} catch (err) {
|
|
118
|
-
return failure(err);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
);
|
|
122
|
-
mcp.registerTool(
|
|
123
|
-
"apply_edit",
|
|
124
|
-
{
|
|
125
|
-
description: 'Apply one edit with exact AST replacement of the JSX prop (formatting and comments are kept). Pass `expression` to write a specific expression instead of the literal value, e.g. "[x, 2.5, 0]".',
|
|
126
|
-
inputSchema: { id: z.string(), expression: z.string().max(500).optional() }
|
|
127
|
-
},
|
|
128
|
-
async ({ id, expression }) => {
|
|
129
|
-
try {
|
|
130
|
-
return text(core.apply(id, expression));
|
|
131
|
-
} catch (err) {
|
|
132
|
-
return failure(err);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
);
|
|
136
|
-
mcp.registerTool(
|
|
137
|
-
"mark_edit_done",
|
|
138
|
-
{
|
|
139
|
-
description: "Report the outcome of an edit you made yourself with your own file tools. The browser inspector shows it.",
|
|
140
|
-
inputSchema: {
|
|
141
|
-
id: z.string(),
|
|
142
|
-
status: z.enum(["done", "failed"]).optional(),
|
|
143
|
-
note: z.string().max(300).optional()
|
|
144
|
-
}
|
|
145
|
-
},
|
|
146
|
-
async ({ id, status, note }) => {
|
|
147
|
-
try {
|
|
148
|
-
return text(core.markDone(id, status ?? "done", note));
|
|
149
|
-
} catch (err) {
|
|
150
|
-
return failure(err);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
);
|
|
154
|
-
mcp.registerTool(
|
|
155
|
-
"get_scene_snapshot",
|
|
156
|
-
{
|
|
157
|
-
description: "The live three.js scene from the inspected page as JSON: scene tree, site camera, renderer info and the values the developer changed.",
|
|
158
|
-
inputSchema: {}
|
|
159
|
-
},
|
|
160
|
-
async () => {
|
|
161
|
-
const snapshot = await server.requestSnapshot();
|
|
162
|
-
return snapshot ? text(snapshot) : failure(
|
|
163
|
-
"No scene snapshot yet. Open the Depthview inspector on the page and pair it with this server."
|
|
164
|
-
);
|
|
165
|
-
}
|
|
166
|
-
);
|
|
167
|
-
const live = async (method, params = {}, timeoutMs, next) => {
|
|
168
|
-
try {
|
|
169
|
-
const data = await server.rpc(method, params, timeoutMs);
|
|
170
|
-
return text(next ? withNext(data, next(asRec(data))) : data);
|
|
171
|
-
} catch (err) {
|
|
172
|
-
return failure(err);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
const target = {
|
|
176
|
-
uuid: z.string().max(64).optional().describe("Object id from find_objects."),
|
|
177
|
-
name: z.string().max(128).optional().describe("Object name, when it is unique in the scene. Use uuid otherwise.")
|
|
178
|
-
};
|
|
179
|
-
const editValue = z.union([
|
|
180
|
-
z.number().finite(),
|
|
181
|
-
z.boolean(),
|
|
182
|
-
z.string().max(128),
|
|
183
|
-
z.array(z.number().finite()).length(3)
|
|
184
|
-
]);
|
|
185
|
-
mcp.registerTool(
|
|
186
|
-
"get_status",
|
|
187
|
-
{
|
|
188
|
-
description: "Whether the browser inspector is connected, which page it is on, the three.js version, the object the developer has selected and how many values are changed. Call this first.",
|
|
189
|
-
inputSchema: {}
|
|
190
|
-
},
|
|
191
|
-
async () => {
|
|
192
|
-
if (!server.extensionConnected)
|
|
193
|
-
return text({
|
|
194
|
-
paired: false,
|
|
195
|
-
pairingCode: server.code,
|
|
196
|
-
next: `Tell the developer: open your site in Chrome, click the Depthview icon, and type ${server.code} under "AI agent & code sync" in the side panel. Then wait for them and call get_status again.`
|
|
197
|
-
});
|
|
198
|
-
try {
|
|
199
|
-
const status = asRec(await server.rpc("status"));
|
|
200
|
-
const next = status.sceneAvailable === false ? "This page has no readable three.js scene (not loaded yet, or the WebGPU renderer). Say so; do not guess values." : status.sourceLocations === false ? "Live tuning works, but objects have no source locations: you will find the code yourself when writing changes. Call describe_scene next." : "Call describe_scene to learn the scale, camera and lights, then find_objects.";
|
|
201
|
-
return text({ paired: true, ...status, next });
|
|
202
|
-
} catch (err) {
|
|
203
|
-
return text({
|
|
204
|
-
paired: true,
|
|
205
|
-
inspectorOpen: false,
|
|
206
|
-
error: err.message,
|
|
207
|
-
next: "Ask the developer to click the Depthview icon on their page and keep that tab in front, then call get_status again."
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
);
|
|
212
|
-
mcp.registerTool(
|
|
213
|
-
"describe_scene",
|
|
214
|
-
{
|
|
215
|
-
description: "A short summary of the live scene: how big it is in scene units (center and radius), what the site camera looks at, the camera (position, fov, distance to the scene), every light (type, colour, intensity, position), object counts by kind and renderer numbers. Call it once before moving, sizing or adding anything, so values fit the scene's scale.",
|
|
216
|
-
inputSchema: {}
|
|
217
|
-
},
|
|
218
|
-
async () => live(
|
|
219
|
-
"describe",
|
|
220
|
-
{},
|
|
221
|
-
void 0,
|
|
222
|
-
() => "find_objects to locate what you want to change, then get_object for its editable paths."
|
|
223
|
-
)
|
|
224
|
-
);
|
|
225
|
-
mcp.registerTool(
|
|
226
|
-
"find_objects",
|
|
227
|
-
{
|
|
228
|
-
description: "Search the live scene. Returns id, name, type, kind and the path from the scene root for each match. Use it instead of get_scene_snapshot when the scene is large.",
|
|
229
|
-
inputSchema: {
|
|
230
|
-
query: z.string().max(128).optional().describe("Part of a name or a three.js type, case ignored. Empty: everything."),
|
|
231
|
-
kind: z.enum(["mesh", "points", "light", "camera", "object"]).optional(),
|
|
232
|
-
limit: z.number().int().min(1).max(500).optional().describe("Default 50.")
|
|
233
|
-
}
|
|
234
|
-
},
|
|
235
|
-
async (params) => live(
|
|
236
|
-
"find",
|
|
237
|
-
params,
|
|
238
|
-
void 0,
|
|
239
|
-
(d) => d.total === 0 ? 'Nothing matched. Try a three.js type ("light", "Mesh", "PerspectiveCamera"), a kind filter, or an empty query.' : "get_object with a uuid to read its values and editable paths."
|
|
240
|
-
)
|
|
241
|
-
);
|
|
242
|
-
mcp.registerTool(
|
|
243
|
-
"get_object",
|
|
244
|
-
{
|
|
245
|
-
description: "Everything the inspector knows about one object: transform, light / camera / material values, shader uniforms, textures, its world-space bounding box in scene units (`worldBounds`: min, max, size, center; null for lights and cameras), and where its JSX element is in the source (`source`, `materialSource`) when the project uses @depthview/r3f-bridge. `editable` lists every path set_value accepts for it, with the current value. With no uuid or name: the object the developer has selected.",
|
|
246
|
-
inputSchema: target
|
|
247
|
-
},
|
|
248
|
-
async (params) => live(
|
|
249
|
-
"object",
|
|
250
|
-
params,
|
|
251
|
-
void 0,
|
|
252
|
-
() => "Change it with set_value (one value) or set_values (several, one undo step), using a path from editable. select_object shows the developer which object you mean."
|
|
253
|
-
)
|
|
254
|
-
);
|
|
255
|
-
mcp.registerTool(
|
|
256
|
-
"set_value",
|
|
257
|
-
{
|
|
258
|
-
description: 'Change one value on the live page, at once, without touching source code. The developer sees it happen, it appears under Changes in the inspector and can be undone. Paths: position, rotation (radians), scale, visible, castShadow, receiveShadow; lights: color, intensity, distance, decay, angle, penumbra; cameras: fov, near, far, zoom; materials: material.color, material.roughness, material.metalness, material.opacity, material.transparent, material.emissive, material.emissiveIntensity, material.side, material.wireframe, material.flatShading, material.depthTest, material.depthWrite, material.size; shaders: uniform.<name>. Vectors are [x, y, z], colours are "#rrggbb". The result has `before`, the new `value`, and `overwritten: true` when the site\'s own code moved the value back straight away (it is animated).',
|
|
259
|
-
inputSchema: {
|
|
260
|
-
...target,
|
|
261
|
-
path: z.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),
|
|
262
|
-
value: editValue,
|
|
263
|
-
degrees: z.boolean().optional().describe("The value of rotation or angle is in degrees; it is converted to radians.")
|
|
264
|
-
}
|
|
265
|
-
},
|
|
266
|
-
async ({ degrees, ...params }) => {
|
|
267
|
-
try {
|
|
268
|
-
if (degrees) params.value = toRadians(params.path, params.value);
|
|
269
|
-
} catch (err) {
|
|
270
|
-
return failure(err);
|
|
271
|
-
}
|
|
272
|
-
return live(
|
|
273
|
-
"set",
|
|
274
|
-
params,
|
|
275
|
-
void 0,
|
|
276
|
-
(d) => d.overwritten ? animatedNext([String(d.path)]) : CHECK_NEXT
|
|
277
|
-
);
|
|
278
|
-
}
|
|
279
|
-
);
|
|
280
|
-
mcp.registerTool(
|
|
281
|
-
"set_values",
|
|
282
|
-
{
|
|
283
|
-
description: "Change several values on the live page in one go, on one or more objects: a lighting set-up, a camera move, a material look. Every change is checked first and nothing is changed if one is wrong. They appear under Changes and one undo_change takes all of them back. Same paths and values as set_value.",
|
|
284
|
-
inputSchema: {
|
|
285
|
-
changes: z.array(
|
|
286
|
-
z.object({
|
|
287
|
-
...target,
|
|
288
|
-
path: z.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),
|
|
289
|
-
value: editValue,
|
|
290
|
-
degrees: z.boolean().optional()
|
|
291
|
-
})
|
|
292
|
-
).min(1).max(40)
|
|
293
|
-
}
|
|
294
|
-
},
|
|
295
|
-
async ({ changes }) => {
|
|
296
|
-
let converted;
|
|
297
|
-
try {
|
|
298
|
-
converted = changes.map(
|
|
299
|
-
({ degrees, ...c }) => degrees ? { ...c, value: toRadians(c.path, c.value) } : c
|
|
300
|
-
);
|
|
301
|
-
} catch (err) {
|
|
302
|
-
return failure(err);
|
|
303
|
-
}
|
|
304
|
-
return live("setMany", { changes: converted }, 15e3, (d) => {
|
|
305
|
-
const moved = (Array.isArray(d.results) ? d.results : []).filter((r) => r.overwritten).map((r) => `${String(r.object || r.uuid)}.${String(r.path)}`);
|
|
306
|
-
return moved.length ? animatedNext(moved) : CHECK_NEXT;
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
);
|
|
310
|
-
mcp.registerTool(
|
|
311
|
-
"get_changes",
|
|
312
|
-
{
|
|
313
|
-
description: "Everything that differs from what the page loaded with, whether the developer changed it in the inspector or you did: changed values (object, path, original and current value, source location when known, and the same as React Three Fiber JSX), objects added (with their JSX), objects removed, and shaders replaced.",
|
|
314
|
-
inputSchema: {}
|
|
315
|
-
},
|
|
316
|
-
async () => live("changes", {}, void 0, (d) => {
|
|
317
|
-
const n = (Array.isArray(d.changes) ? d.changes.length : 0) + (Array.isArray(d.added) ? d.added.length : 0) + (Array.isArray(d.removed) ? d.removed.length : 0) + (Array.isArray(d.shaders) ? d.shaders.length : 0);
|
|
318
|
-
return n === 0 ? "Nothing is changed. Say so and stop." : "apply_changes_to_code writes the value changes. Added objects, removed objects and shaders are written by you with your own file tools.";
|
|
319
|
-
})
|
|
320
|
-
);
|
|
321
|
-
mcp.registerTool(
|
|
322
|
-
"apply_changes_to_code",
|
|
323
|
-
{
|
|
324
|
-
description: 'Write all current changes into the source files (same as the "Apply to code" button). Literal props are rewritten directly; the rest come back with status "queued" for you to finish with get_edit_context and apply_edit. Changes on objects without a source location are counted in `unmapped`: write those yourself from get_changes.',
|
|
325
|
-
inputSchema: {}
|
|
326
|
-
},
|
|
327
|
-
async () => live("apply", {}, void 0, (d) => {
|
|
328
|
-
const edits = Array.isArray(d.edits) ? d.edits : [];
|
|
329
|
-
const queued = edits.filter((e) => e.status === "queued").length;
|
|
330
|
-
const failed = edits.filter((e) => e.status === "failed").length;
|
|
331
|
-
const unmapped = typeof d.unmapped === "number" ? d.unmapped : 0;
|
|
332
|
-
const todo = [
|
|
333
|
-
queued && `${queued} queued: get_edit_context, then apply_edit or mark_edit_done for each`,
|
|
334
|
-
failed && `${failed} failed: report their message`,
|
|
335
|
-
unmapped && `${unmapped} without a source location: write them yourself from get_changes`
|
|
336
|
-
].filter(Boolean);
|
|
337
|
-
if (todo.length)
|
|
338
|
-
return `${todo.join("; ")}. Then list_pending_edits to confirm nothing is left.`;
|
|
339
|
-
return edits.length ? "All written. Tell the developer per change: file, prop, old value to new value." : void 0;
|
|
340
|
-
})
|
|
341
|
-
);
|
|
342
|
-
mcp.registerTool(
|
|
343
|
-
"select_object",
|
|
344
|
-
{
|
|
345
|
-
description: "Select an object in the inspector so the developer sees which one you mean (it is outlined and its values are shown).",
|
|
346
|
-
inputSchema: target
|
|
347
|
-
},
|
|
348
|
-
async (params) => live("select", params)
|
|
349
|
-
);
|
|
350
|
-
mcp.registerTool(
|
|
351
|
-
"undo_change",
|
|
352
|
-
{ description: "Undo the latest live change (one step).", inputSchema: {} },
|
|
353
|
-
async () => live(
|
|
354
|
-
"undo",
|
|
355
|
-
{},
|
|
356
|
-
void 0,
|
|
357
|
-
() => "One undo step taken (a whole set_values call is one step)."
|
|
358
|
-
)
|
|
359
|
-
);
|
|
360
|
-
mcp.registerTool(
|
|
361
|
-
"reset_changes",
|
|
362
|
-
{
|
|
363
|
-
description: "Put everything back to what the page loaded with: changed values, added and removed objects, replaced shaders. Ask the developer first if they made changes themselves.",
|
|
364
|
-
inputSchema: {}
|
|
365
|
-
},
|
|
366
|
-
async () => live("reset")
|
|
367
|
-
);
|
|
368
|
-
mcp.registerTool(
|
|
369
|
-
"take_screenshot",
|
|
370
|
-
{
|
|
371
|
-
description: 'A picture of what is on screen now. view "inspector" (default): the whole tab with the inspector\'s panels. "scene": only the inspector\'s 3D view, from its free camera, with helpers. "site": the real page exactly as a visitor sees it, HTML included, with the inspector out of the way: use this to judge the result. `angle` turns the inspector camera first (not for "site"). `compare: true` also returns the previous picture of the same view, labelled before and after, to judge a change. The tab must be in front.',
|
|
372
|
-
inputSchema: {
|
|
373
|
-
view: z.enum(["inspector", "scene", "site"]).optional(),
|
|
374
|
-
angle: z.enum(["front", "side", "back", "reset"]).optional(),
|
|
375
|
-
compare: z.boolean().optional().describe('Also return the previous picture of this view, as "before".')
|
|
376
|
-
}
|
|
377
|
-
},
|
|
378
|
-
async ({ compare, ...params }) => {
|
|
379
|
-
try {
|
|
380
|
-
const view = params.view ?? "inspector";
|
|
381
|
-
const shot = await server.rpc("screenshot", params, 2e4);
|
|
382
|
-
const image = { type: "image", data: shot.data, mimeType: shot.mimeType };
|
|
383
|
-
const previous = server.lastShots.get(view);
|
|
384
|
-
server.lastShots.set(view, { data: shot.data, mimeType: shot.mimeType });
|
|
385
|
-
if (!compare) return { content: [image] };
|
|
386
|
-
if (!previous)
|
|
387
|
-
return {
|
|
388
|
-
content: [
|
|
389
|
-
{
|
|
390
|
-
type: "text",
|
|
391
|
-
text: `No earlier "${view}" picture to compare with: this one is the baseline. Take another after the change.`
|
|
392
|
-
},
|
|
393
|
-
image
|
|
394
|
-
]
|
|
395
|
-
};
|
|
396
|
-
return {
|
|
397
|
-
content: [
|
|
398
|
-
{ type: "text", text: `Before (previous "${view}" picture):` },
|
|
399
|
-
{ type: "image", data: previous.data, mimeType: previous.mimeType },
|
|
400
|
-
{ type: "text", text: "After (now):" },
|
|
401
|
-
image
|
|
402
|
-
]
|
|
403
|
-
};
|
|
404
|
-
} catch (err) {
|
|
405
|
-
return failure(err);
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
);
|
|
409
|
-
mcp.registerTool(
|
|
410
|
-
"get_performance",
|
|
411
|
-
{
|
|
412
|
-
description: "Measures the running scene for a moment: frames per second, frame time (average, 95th percentile, worst), draw calls, triangles and render passes per frame, canvas size and pixel ratio, JS heap, and every renderer.render() call of one frame (scene, shadow and post-processing passes with their cost). Use it before and after a change to prove the change helped.",
|
|
413
|
-
inputSchema: {
|
|
414
|
-
seconds: z.number().min(0.5).max(5).optional().describe("How long to measure. Default 1.5.")
|
|
415
|
-
}
|
|
416
|
-
},
|
|
417
|
-
async (params) => live("performance", params, 15e3)
|
|
418
|
-
);
|
|
419
|
-
mcp.registerTool(
|
|
420
|
-
"get_resources",
|
|
421
|
-
{
|
|
422
|
-
description: "What the scene holds in GPU memory: textures, geometries and materials, biggest first, with size, memory and how many objects use each. Finds the oversized texture, the duplicated material and the heavy geometry.",
|
|
423
|
-
inputSchema: {
|
|
424
|
-
limit: z.number().int().min(1).max(100).optional().describe("Rows per list. Default 15.")
|
|
425
|
-
}
|
|
426
|
-
},
|
|
427
|
-
async (params) => live("resources", params)
|
|
428
|
-
);
|
|
429
|
-
mcp.registerTool(
|
|
430
|
-
"get_errors",
|
|
431
|
-
{
|
|
432
|
-
description: "What the page logged: uncaught errors and rejected promises since it loaded, console.error and console.warn since the inspector was opened, and shader programs that failed to compile. Call it when something does not show or after a source edit.",
|
|
433
|
-
inputSchema: {
|
|
434
|
-
clear: z.boolean().optional().describe("Empty the list after reading it.")
|
|
435
|
-
}
|
|
436
|
-
},
|
|
437
|
-
async (params) => live("errors", params)
|
|
438
|
-
);
|
|
439
|
-
mcp.registerTool(
|
|
440
|
-
"get_lighting",
|
|
441
|
-
{
|
|
442
|
-
description: "Every light with its cost and shadow set-up, and a list of problems found: castShadow with shadows switched off on the renderer, nothing casting or receiving, oversized shadow maps, point-light shadows (6 passes), a directional shadow camera that is far larger than the casters (blurry shadows) or too small (cut-off shadows), too many lights.",
|
|
443
|
-
inputSchema: {}
|
|
444
|
-
},
|
|
445
|
-
async () => live("lighting")
|
|
446
|
-
);
|
|
447
|
-
mcp.registerTool(
|
|
448
|
-
"get_shader",
|
|
449
|
-
{
|
|
450
|
-
description: "The GLSL of an object's material as it runs on the page, with line numbers, plus its uniforms. `kind` says whether this is the full program three.js compiled or the source as written. Long shaders: read them in parts with fromLine and lines.",
|
|
451
|
-
inputSchema: {
|
|
452
|
-
...target,
|
|
453
|
-
stage: z.enum(["vertex", "fragment"]).optional().describe("Default: both."),
|
|
454
|
-
fromLine: z.number().int().min(1).optional(),
|
|
455
|
-
lines: z.number().int().min(1).max(2e3).optional().describe("Default 400.")
|
|
456
|
-
}
|
|
457
|
-
},
|
|
458
|
-
async (params) => live("shader", params)
|
|
459
|
-
);
|
|
460
|
-
mcp.registerTool(
|
|
461
|
-
"set_shader",
|
|
462
|
-
{
|
|
463
|
-
description: "Replace the vertex and/or fragment shader of a ShaderMaterial or RawShaderMaterial on the live page and compile it. Returns the compiler's errors with line numbers; a shader that does not compile is put back at once. Send the material's own source (as in the project file), complete, not the expanded program from get_shader. Live only: write the same source into the file when it is right.",
|
|
464
|
-
inputSchema: {
|
|
465
|
-
...target,
|
|
466
|
-
vertex: z.string().max(2e5).optional(),
|
|
467
|
-
fragment: z.string().max(2e5).optional()
|
|
468
|
-
}
|
|
469
|
-
},
|
|
470
|
-
async (params) => live("setShader", params, 12e3)
|
|
471
|
-
);
|
|
472
|
-
mcp.registerTool(
|
|
473
|
-
"set_scroll",
|
|
474
|
-
{
|
|
475
|
-
description: "Scroll the site to a position, 0 (top) to 100 (bottom), and return where the site camera is there. Use it to check a scroll-driven scene at several points.",
|
|
476
|
-
inputSchema: { percent: z.number().min(0).max(100) }
|
|
477
|
-
},
|
|
478
|
-
async (params) => live("scroll", params, 12e3)
|
|
479
|
-
);
|
|
480
|
-
mcp.registerTool(
|
|
481
|
-
"set_time",
|
|
482
|
-
{
|
|
483
|
-
description: 'Hold, step or release the site\'s animation. "pause" freezes the page\'s clock and its animation frames; "step" moves it on by `frames` frames of `stepMs` each (default 1 frame of 16.67 ms) so you can look at one exact moment; "resume" lets it run again without a jump. Always resume when done.',
|
|
484
|
-
inputSchema: {
|
|
485
|
-
action: z.enum(["pause", "step", "resume"]),
|
|
486
|
-
frames: z.number().int().min(1).max(600).optional(),
|
|
487
|
-
stepMs: z.number().min(0.1).max(1e3).optional()
|
|
488
|
-
}
|
|
489
|
-
},
|
|
490
|
-
async (params) => live("time", params)
|
|
491
|
-
);
|
|
492
|
-
mcp.registerTool(
|
|
493
|
-
"get_animated_values",
|
|
494
|
-
{
|
|
495
|
-
description: "Which values the site's own code is moving: `overTime` lists what changes by itself while you watch, `onScroll` what changes when the page scrolls. Also reports animation clips on objects, React Three Fiber useFrame callbacks and GSAP tweens. Call it before writing any position, rotation, scale, opacity or uniform into the source: a value listed here is driven by code, and a constant in JSX would be overwritten.",
|
|
496
|
-
inputSchema: {
|
|
497
|
-
seconds: z.number().min(0.3).max(4).optional().describe("How long to watch. Default 1."),
|
|
498
|
-
checkScroll: z.boolean().optional().describe("Also scroll the page to see what follows it, then scroll back. Default true.")
|
|
499
|
-
}
|
|
500
|
-
},
|
|
501
|
-
async (params) => live("animated", params, 2e4)
|
|
502
|
-
);
|
|
503
|
-
mcp.registerTool(
|
|
504
|
-
"get_camera_path",
|
|
505
|
-
{
|
|
506
|
-
description: "How the site camera moves as the page scrolls: position, rotation (quaternion) and field of view at up to 40 scroll positions. Records the path by scrolling the page if it has not been recorded yet.",
|
|
507
|
-
inputSchema: {
|
|
508
|
-
record: z.boolean().optional().describe("Record again even if a path exists.")
|
|
509
|
-
}
|
|
510
|
-
},
|
|
511
|
-
async (params) => live("cameraPath", params, 6e4)
|
|
512
|
-
);
|
|
513
|
-
mcp.registerTool(
|
|
514
|
-
"add_object",
|
|
515
|
-
{
|
|
516
|
-
description: 'Add an object to the live scene and get its React Three Fiber JSX back. `copyOf` duplicates an existing object (always works). `kind` makes a new one: "box", "sphere", "plane" (unit-sized meshes), "Group", or a light type the page already uses, such as "PointLight" (the classes are taken from the site\'s own three.js, so a light type the site never created cannot be made: the error lists what can). Live only: it is gone after a reload until the JSX is in the source.',
|
|
517
|
-
inputSchema: {
|
|
518
|
-
kind: z.string().max(40).optional(),
|
|
519
|
-
copyOf: z.string().max(64).optional().describe("uuid of the object to duplicate."),
|
|
520
|
-
parent: z.string().max(64).optional().describe("uuid of the parent. Default: the scene."),
|
|
521
|
-
objectName: z.string().max(80).optional().describe("Name for the new object."),
|
|
522
|
-
position: z.array(z.number().finite()).length(3).optional(),
|
|
523
|
-
color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),
|
|
524
|
-
intensity: z.number().finite().optional()
|
|
525
|
-
}
|
|
526
|
-
},
|
|
527
|
-
async (params) => live("add", params)
|
|
528
|
-
);
|
|
529
|
-
mcp.registerTool(
|
|
530
|
-
"remove_object",
|
|
531
|
-
{
|
|
532
|
-
description: "Take an object (and its children) out of the live scene, to see the scene without it or measure what it costs. Returns its source location when known. Live only: reset_changes puts it back.",
|
|
533
|
-
inputSchema: target
|
|
534
|
-
},
|
|
535
|
-
async (params) => live("remove", params)
|
|
536
|
-
);
|
|
537
|
-
mcp.registerTool(
|
|
538
|
-
"set_viewport",
|
|
539
|
-
{
|
|
540
|
-
description: "Responsive check. `width` and `height` resize the browser window so the page gets that size, and the site's own resize code runs; the result says the size really reached (a window cannot go below about 500 px wide). `pixelRatio` sets the renderer's pixel ratio live, to measure what a 2x or 3x phone screen costs with get_performance. `reset: true` puts the window and the pixel ratio back: always do that when done.",
|
|
541
|
-
inputSchema: {
|
|
542
|
-
width: z.number().int().min(200).max(7680).optional(),
|
|
543
|
-
height: z.number().int().min(200).max(4320).optional(),
|
|
544
|
-
pixelRatio: z.number().min(0.25).max(4).optional(),
|
|
545
|
-
reset: z.boolean().optional()
|
|
546
|
-
}
|
|
547
|
-
},
|
|
548
|
-
async (params) => live("viewport", params, 12e3)
|
|
549
|
-
);
|
|
550
|
-
for (const prompt of PROMPTS) {
|
|
551
|
-
const arg = prompt.argument;
|
|
552
|
-
if (arg)
|
|
553
|
-
mcp.registerPrompt(
|
|
554
|
-
prompt.name,
|
|
555
|
-
{
|
|
556
|
-
title: prompt.title,
|
|
557
|
-
description: prompt.description,
|
|
558
|
-
argsSchema: { [arg.name]: z.string().optional().describe(arg.description) }
|
|
559
|
-
},
|
|
560
|
-
(args) => promptMessage(prompt.text(args[arg.name]))
|
|
561
|
-
);
|
|
562
|
-
else
|
|
563
|
-
mcp.registerPrompt(
|
|
564
|
-
prompt.name,
|
|
565
|
-
{ title: prompt.title, description: prompt.description },
|
|
566
|
-
() => promptMessage(prompt.text(void 0))
|
|
567
|
-
);
|
|
568
|
-
}
|
|
569
|
-
const resource = (name, uri, description, read) => {
|
|
570
|
-
mcp.registerResource(
|
|
571
|
-
name,
|
|
572
|
-
uri,
|
|
573
|
-
{ title: name, description, mimeType: "application/json" },
|
|
574
|
-
async () => {
|
|
575
|
-
let value2;
|
|
576
|
-
try {
|
|
577
|
-
value2 = await read();
|
|
578
|
-
} catch (err) {
|
|
579
|
-
value2 = { error: err instanceof Error ? err.message : String(err) };
|
|
580
|
-
}
|
|
581
|
-
return {
|
|
582
|
-
contents: [{ uri, mimeType: "application/json", text: JSON.stringify(value2, null, 2) }]
|
|
583
|
-
};
|
|
584
|
-
}
|
|
585
|
-
);
|
|
586
|
-
};
|
|
587
|
-
resource(
|
|
588
|
-
"status",
|
|
589
|
-
"depthview://status",
|
|
590
|
-
"Paired? Which page, what is selected, how many values are changed.",
|
|
591
|
-
async () => server.extensionConnected ? { paired: true, ...asRec(await server.rpc("status")) } : { paired: false, pairingCode: server.code }
|
|
592
|
-
);
|
|
593
|
-
resource(
|
|
594
|
-
"scene",
|
|
595
|
-
"depthview://scene",
|
|
596
|
-
"Summary of the live scene: scale, camera, lights, object counts.",
|
|
597
|
-
() => server.rpc("describe")
|
|
598
|
-
);
|
|
599
|
-
resource(
|
|
600
|
-
"selection",
|
|
601
|
-
"depthview://selection",
|
|
602
|
-
"The object selected in the inspector, with its editable values and bounds.",
|
|
603
|
-
() => server.rpc("object")
|
|
604
|
-
);
|
|
605
|
-
resource(
|
|
606
|
-
"changes",
|
|
607
|
-
"depthview://changes",
|
|
608
|
-
"Everything changed on the live page, with source locations.",
|
|
609
|
-
() => server.rpc("changes")
|
|
610
|
-
);
|
|
611
|
-
if (options.includePairingCode) {
|
|
612
|
-
mcp.registerTool(
|
|
613
|
-
"get_pairing_code",
|
|
614
|
-
{
|
|
615
|
-
description: "One-time code the developer types into the Depthview extension to pair it with this server.",
|
|
616
|
-
inputSchema: {}
|
|
617
|
-
},
|
|
618
|
-
async () => text({ code: server.code, paired: server.extensionConnected })
|
|
619
|
-
);
|
|
620
|
-
}
|
|
621
|
-
return mcp;
|
|
150
|
+
`,ye=`
|
|
151
|
+
uniform vec3 uColor;
|
|
152
|
+
uniform vec3 uColor2;
|
|
153
|
+
uniform float uOpacity;
|
|
154
|
+
uniform float uDetail;
|
|
155
|
+
uniform float uSoftEdge;
|
|
156
|
+
uniform sampler2D uDepth;
|
|
157
|
+
uniform float uHasDepth;
|
|
158
|
+
uniform vec2 uResolution;
|
|
159
|
+
uniform mat4 projectionMatrix;
|
|
160
|
+
varying vec2 vUv;
|
|
161
|
+
varying float vLife;
|
|
162
|
+
varying float vSeed;
|
|
163
|
+
${se}
|
|
164
|
+
// Distance in front of the camera, from a depth-buffer value.
|
|
165
|
+
float dvViewDepth(float depth) {
|
|
166
|
+
return projectionMatrix[3][2] / (depth * 2.0 - 1.0 + projectionMatrix[2][2]);
|
|
622
167
|
}
|
|
623
168
|
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
//
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
// src/edits.ts
|
|
639
|
-
import { parse as babelParse, parseExpression } from "@babel/parser";
|
|
640
|
-
import recast from "recast";
|
|
641
|
-
var b = recast.types.builders;
|
|
642
|
-
var parser = {
|
|
643
|
-
parse: (source) => babelParse(source, {
|
|
644
|
-
sourceType: "module",
|
|
645
|
-
tokens: true,
|
|
646
|
-
allowReturnOutsideFunction: true,
|
|
647
|
-
plugins: ["jsx", "typescript"]
|
|
648
|
-
})
|
|
649
|
-
};
|
|
650
|
-
var round = (n) => {
|
|
651
|
-
const r = Math.round(n * 1e3) / 1e3;
|
|
652
|
-
return Object.is(r, -0) ? 0 : r;
|
|
653
|
-
};
|
|
654
|
-
var numberNode = (n) => {
|
|
655
|
-
const v = round(n);
|
|
656
|
-
return v < 0 ? b.unaryExpression("-", b.numericLiteral(-v)) : b.numericLiteral(v);
|
|
657
|
-
};
|
|
658
|
-
function evalConstant(node) {
|
|
659
|
-
if (!node) return void 0;
|
|
660
|
-
switch (node.type) {
|
|
661
|
-
case "NumericLiteral":
|
|
662
|
-
return node.value;
|
|
663
|
-
case "Literal":
|
|
664
|
-
return typeof node.value === "number" ? node.value : void 0;
|
|
665
|
-
case "UnaryExpression": {
|
|
666
|
-
const v = evalConstant(node.argument);
|
|
667
|
-
if (v === void 0) return void 0;
|
|
668
|
-
return node.operator === "-" ? -v : node.operator === "+" ? v : void 0;
|
|
669
|
-
}
|
|
670
|
-
case "BinaryExpression": {
|
|
671
|
-
const l = evalConstant(node.left);
|
|
672
|
-
const r = evalConstant(node.right);
|
|
673
|
-
if (l === void 0 || r === void 0) return void 0;
|
|
674
|
-
if (node.operator === "+") return l + r;
|
|
675
|
-
if (node.operator === "-") return l - r;
|
|
676
|
-
if (node.operator === "*") return l * r;
|
|
677
|
-
if (node.operator === "/") return l / r;
|
|
678
|
-
return void 0;
|
|
679
|
-
}
|
|
680
|
-
case "MemberExpression":
|
|
681
|
-
return !node.computed && node.object?.type === "Identifier" && node.object.name === "Math" && node.property?.name === "PI" ? Math.PI : void 0;
|
|
682
|
-
case "ParenthesizedExpression":
|
|
683
|
-
case "TSAsExpression":
|
|
684
|
-
case "TSNonNullExpression":
|
|
685
|
-
return evalConstant(node.expression);
|
|
686
|
-
default:
|
|
687
|
-
return void 0;
|
|
169
|
+
void main() {
|
|
170
|
+
float d = length(vUv);
|
|
171
|
+
if (d > 1.0) discard;
|
|
172
|
+
// A soft disc, eaten into by noise so the edge is ragged like real smoke.
|
|
173
|
+
float body = 1.0 - smoothstep(0.2, 1.0, d);
|
|
174
|
+
float wisps = dvFbm(vec3(vUv * 1.6, vSeed));
|
|
175
|
+
float alpha = body * mix(1.0, smoothstep(0.25, 0.75, wisps), uDetail);
|
|
176
|
+
// In fast, out slowly.
|
|
177
|
+
alpha *= smoothstep(0.0, 0.08, vLife) * pow(1.0 - vLife, 1.5);
|
|
178
|
+
// Fade out where a puff comes close to a surface: no hard line where it cuts the floor.
|
|
179
|
+
if (uHasDepth > 0.5) {
|
|
180
|
+
float solid = dvViewDepth(texture2D(uDepth, gl_FragCoord.xy / uResolution).r);
|
|
181
|
+
alpha *= smoothstep(0.0, max(uSoftEdge, 0.0001), solid - dvViewDepth(gl_FragCoord.z));
|
|
688
182
|
}
|
|
183
|
+
// Lit from above: the underside of a puff is darker.
|
|
184
|
+
float lit = mix(0.72, 1.0, vUv.y * 0.5 + 0.5);
|
|
185
|
+
gl_FragColor = vec4(mix(uColor, uColor2, vLife) * lit, alpha * uOpacity);
|
|
186
|
+
${B}
|
|
187
|
+
}
|
|
188
|
+
`,Ro=`
|
|
189
|
+
uniform vec3 uCameraLocal;
|
|
190
|
+
varying vec3 vOrigin;
|
|
191
|
+
varying vec3 vDirection;
|
|
192
|
+
|
|
193
|
+
void main() {
|
|
194
|
+
vOrigin = uCameraLocal;
|
|
195
|
+
vDirection = position - uCameraLocal;
|
|
196
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
197
|
+
}
|
|
198
|
+
`,Mo=`
|
|
199
|
+
uniform float uTime;
|
|
200
|
+
uniform float uSteps;
|
|
201
|
+
uniform float uDensity;
|
|
202
|
+
uniform float uCoverage;
|
|
203
|
+
uniform float uScale;
|
|
204
|
+
uniform float uDetail;
|
|
205
|
+
uniform float uEdge;
|
|
206
|
+
uniform float uBottom;
|
|
207
|
+
uniform float uTop;
|
|
208
|
+
uniform float uAbsorption;
|
|
209
|
+
uniform float uPowder;
|
|
210
|
+
uniform float uSilver;
|
|
211
|
+
uniform float uOpacity;
|
|
212
|
+
uniform vec3 uWind;
|
|
213
|
+
uniform vec3 uLightDir;
|
|
214
|
+
uniform vec3 uLightColor;
|
|
215
|
+
uniform vec3 uShadowColor;
|
|
216
|
+
uniform sampler2D uDepth;
|
|
217
|
+
uniform mat4 uDepthToLocal;
|
|
218
|
+
uniform float uHasDepth;
|
|
219
|
+
uniform vec2 uResolution;
|
|
220
|
+
varying vec3 vOrigin;
|
|
221
|
+
varying vec3 vDirection;
|
|
222
|
+
${$o}
|
|
223
|
+
// Where the ray enters and leaves the unit box.
|
|
224
|
+
vec2 dvHitBox(vec3 origin, vec3 direction) {
|
|
225
|
+
vec3 inv = 1.0 / direction;
|
|
226
|
+
vec3 t0 = (vec3(-0.5) - origin) * inv;
|
|
227
|
+
vec3 t1 = (vec3(0.5) - origin) * inv;
|
|
228
|
+
vec3 near = min(t0, t1);
|
|
229
|
+
vec3 far = max(t0, t1);
|
|
230
|
+
return vec2(max(near.x, max(near.y, near.z)), min(far.x, min(far.y, far.z)));
|
|
231
|
+
}
|
|
232
|
+
// Fades the volume out before the faces of the box, so the box itself is never seen.
|
|
233
|
+
float dvShape(vec3 p) {
|
|
234
|
+
vec3 edge = smoothstep(vec3(0.5), vec3(0.5 - uEdge), abs(p));
|
|
235
|
+
float h = p.y + 0.5;
|
|
236
|
+
float height = smoothstep(0.0, max(uBottom, 0.001), h) * (1.0 - smoothstep(1.0 - max(uTop, 0.001), 1.0, h));
|
|
237
|
+
return edge.x * edge.z * height;
|
|
238
|
+
}
|
|
239
|
+
float dvRemap(float n) {
|
|
240
|
+
return clamp((n - (1.0 - uCoverage)) / max(uCoverage, 0.001), 0.0, 1.0);
|
|
689
241
|
}
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
if (
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
242
|
+
float dvDensity(vec3 p) {
|
|
243
|
+
float shape = dvShape(p);
|
|
244
|
+
if (shape <= 0.0) return 0.0;
|
|
245
|
+
vec3 q = p * uScale + uWind * uTime;
|
|
246
|
+
float n = dvFbm(q);
|
|
247
|
+
// Fine noise carves the edges: that is what makes the billows.
|
|
248
|
+
n -= uDetail * 0.25 * (1.0 - dvNoise(q * 4.1 + vec3(5.0)));
|
|
249
|
+
return dvRemap(n) * shape * uDensity;
|
|
696
250
|
}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
return
|
|
251
|
+
// A cheaper density for the steps towards the light.
|
|
252
|
+
float dvDensityLow(vec3 p) {
|
|
253
|
+
float shape = dvShape(p);
|
|
254
|
+
if (shape <= 0.0) return 0.0;
|
|
255
|
+
return dvRemap(dvFbmLow(p * uScale + uWind * uTime)) * shape * uDensity;
|
|
701
256
|
}
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
257
|
+
|
|
258
|
+
void main() {
|
|
259
|
+
vec3 direction = normalize(vDirection);
|
|
260
|
+
vec2 hit = dvHitBox(vOrigin, direction);
|
|
261
|
+
if (hit.x > hit.y) discard;
|
|
262
|
+
hit.x = max(hit.x, 0.0);
|
|
263
|
+
// Stop at whatever solid thing is behind this pixel: the cloud goes round objects, not over.
|
|
264
|
+
if (uHasDepth > 0.5) {
|
|
265
|
+
vec2 screen = gl_FragCoord.xy / uResolution;
|
|
266
|
+
float depth = texture2D(uDepth, screen).r;
|
|
267
|
+
if (depth < 1.0) {
|
|
268
|
+
vec4 solid = uDepthToLocal * vec4(screen * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
|
|
269
|
+
hit.y = min(hit.y, dot(solid.xyz / solid.w - vOrigin, direction));
|
|
270
|
+
}
|
|
271
|
+
if (hit.x >= hit.y) discard;
|
|
711
272
|
}
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
273
|
+
float stepLength = (hit.y - hit.x) / uSteps;
|
|
274
|
+
// Start each ray at a different depth: the slices of the march turn into fine grain.
|
|
275
|
+
float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
|
|
276
|
+
float t = hit.x + stepLength * jitter;
|
|
277
|
+
vec3 toLight = normalize(uLightDir);
|
|
278
|
+
// Looking towards the light, thin edges glow (forward scattering).
|
|
279
|
+
float towards = max(dot(direction, toLight), 0.0);
|
|
280
|
+
float silver = 1.0 + uSilver * pow(towards, 8.0) * 2.0;
|
|
281
|
+
|
|
282
|
+
float transmittance = 1.0;
|
|
283
|
+
vec3 light = vec3(0.0);
|
|
284
|
+
for (int i = 0; i < 96; i++) {
|
|
285
|
+
if (float(i) >= uSteps || transmittance < 0.02) break;
|
|
286
|
+
vec3 p = vOrigin + direction * t;
|
|
287
|
+
float density = dvDensity(p);
|
|
288
|
+
if (density > 0.001) {
|
|
289
|
+
float towardsLight = 0.0;
|
|
290
|
+
for (int j = 1; j <= 3; j++) towardsLight += dvDensityLow(p + toLight * 0.07 * float(j));
|
|
291
|
+
float sun = exp(-towardsLight * 0.07 * uAbsorption);
|
|
292
|
+
// Dense cores scatter light back out: the "powdered sugar" look of cumulus.
|
|
293
|
+
float powder = mix(1.0, 1.0 - exp(-density * 2.0), uPowder);
|
|
294
|
+
vec3 colour = uShadowColor + uLightColor * sun * powder * silver;
|
|
295
|
+
float absorbed = 1.0 - exp(-density * stepLength * uAbsorption);
|
|
296
|
+
light += transmittance * absorbed * colour;
|
|
297
|
+
transmittance *= 1.0 - absorbed;
|
|
718
298
|
}
|
|
719
|
-
|
|
720
|
-
const element = onLine.find((n) => n.loc.start.column === edit.column) ?? (onLine.length === 1 ? onLine[0] : void 0);
|
|
721
|
-
if (!element) {
|
|
722
|
-
return needsAgent(
|
|
723
|
-
`No JSX element starts at line ${edit.line}, column ${edit.column}. The file may have changed since the page loaded.`
|
|
724
|
-
);
|
|
299
|
+
t += stepLength;
|
|
725
300
|
}
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
301
|
+
float alpha = 1.0 - transmittance;
|
|
302
|
+
if (alpha < 0.003) discard;
|
|
303
|
+
gl_FragColor = vec4(light / alpha, alpha * uOpacity);
|
|
304
|
+
${B}
|
|
305
|
+
}
|
|
306
|
+
`,Co=`
|
|
307
|
+
attribute vec2 dvCorner;
|
|
308
|
+
attribute vec4 dvSeed;
|
|
309
|
+
uniform float uTime;
|
|
310
|
+
uniform float uSize;
|
|
311
|
+
uniform float uArms;
|
|
312
|
+
uniform float uTwist;
|
|
313
|
+
uniform float uSpin;
|
|
314
|
+
uniform float uThickness;
|
|
315
|
+
varying vec2 vUv;
|
|
316
|
+
varying float vFade;
|
|
317
|
+
varying float vSeed;
|
|
318
|
+
|
|
319
|
+
void main() {
|
|
320
|
+
// Each sprite sits on one of the spiral arms, further out the larger its first seed.
|
|
321
|
+
float radius = pow(dvSeed.x, 0.7) * 0.5;
|
|
322
|
+
float arm = floor(dvSeed.y * uArms) / uArms * 6.2832;
|
|
323
|
+
float scatter = (dvSeed.z - 0.5) * (0.25 + radius * 1.2);
|
|
324
|
+
float angle = arm + radius * uTwist + scatter + uTime * uSpin * (1.0 - radius);
|
|
325
|
+
vec3 p = vec3(cos(angle) * radius, (dvSeed.w - 0.5) * uThickness * (1.0 - radius * 1.6), sin(angle) * radius);
|
|
326
|
+
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
|
327
|
+
mv.xy += dvCorner * uSize * (0.4 + 0.6 * dvSeed.w) * 0.5;
|
|
328
|
+
gl_Position = projectionMatrix * mv;
|
|
329
|
+
vUv = dvCorner;
|
|
330
|
+
vFade = 1.0 - smoothstep(0.35, 0.5, radius);
|
|
331
|
+
vSeed = radius * 2.0;
|
|
332
|
+
}
|
|
333
|
+
`,Ao=`
|
|
334
|
+
attribute vec2 dvCorner;
|
|
335
|
+
attribute vec4 dvSeed;
|
|
336
|
+
uniform float uTime;
|
|
337
|
+
uniform float uSize;
|
|
338
|
+
uniform float uShape;
|
|
339
|
+
uniform float uFlow;
|
|
340
|
+
uniform float uSpin;
|
|
341
|
+
varying vec2 vUv;
|
|
342
|
+
varying float vFade;
|
|
343
|
+
varying float vSeed;
|
|
344
|
+
|
|
345
|
+
// Three shapes built from the same seeds: a sphere, a ring and a box.
|
|
346
|
+
vec3 dvSphere(vec4 s) {
|
|
347
|
+
float z = s.x * 2.0 - 1.0;
|
|
348
|
+
float a = s.y * 6.2832;
|
|
349
|
+
float r = sqrt(max(1.0 - z * z, 0.0));
|
|
350
|
+
return vec3(r * cos(a), z, r * sin(a)) * 0.42;
|
|
351
|
+
}
|
|
352
|
+
vec3 dvRing(vec4 s) {
|
|
353
|
+
float a = s.x * 6.2832;
|
|
354
|
+
float b = s.y * 6.2832;
|
|
355
|
+
float tube = 0.09 * sqrt(s.z);
|
|
356
|
+
return vec3((0.36 + tube * cos(b)) * cos(a), tube * sin(b), (0.36 + tube * cos(b)) * sin(a));
|
|
357
|
+
}
|
|
358
|
+
vec3 dvBox(vec4 s) {
|
|
359
|
+
vec3 p = vec3(s.x, s.y, s.z) - 0.5;
|
|
360
|
+
// Push every point out to the nearest face, so the box is a shell, not a cloud.
|
|
361
|
+
vec3 a = abs(p);
|
|
362
|
+
float m = max(a.x, max(a.y, a.z));
|
|
363
|
+
return p / max(m, 0.001) * 0.36;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
void main() {
|
|
367
|
+
float shape = mod(uShape, 3.0);
|
|
368
|
+
vec3 a = dvSphere(dvSeed);
|
|
369
|
+
vec3 b = dvRing(dvSeed);
|
|
370
|
+
vec3 c = dvBox(dvSeed);
|
|
371
|
+
// Each sprite leaves a little earlier or later: the shape flows over instead of snapping.
|
|
372
|
+
float lag = (dvSeed.w - 0.5) * 0.35;
|
|
373
|
+
vec3 p = mix(a, b, smoothstep(0.0, 1.0, clamp(shape + lag, 0.0, 1.0)));
|
|
374
|
+
p = mix(p, c, smoothstep(0.0, 1.0, clamp(shape - 1.0 + lag, 0.0, 1.0)));
|
|
375
|
+
p = mix(p, a, smoothstep(0.0, 1.0, clamp(shape - 2.0 + lag, 0.0, 1.0)));
|
|
376
|
+
float t = uTime * 0.6;
|
|
377
|
+
p += uFlow * 0.03 * vec3(
|
|
378
|
+
sin(t * 1.3 + dvSeed.y * 40.0 + p.y * 9.0),
|
|
379
|
+
sin(t * 1.7 + dvSeed.z * 40.0 + p.z * 9.0),
|
|
380
|
+
sin(t * 1.1 + dvSeed.x * 40.0 + p.x * 9.0));
|
|
381
|
+
float turn = uTime * uSpin;
|
|
382
|
+
p.xz = mat2(cos(turn), -sin(turn), sin(turn), cos(turn)) * p.xz;
|
|
383
|
+
vec4 mv = modelViewMatrix * vec4(p, 1.0);
|
|
384
|
+
mv.xy += dvCorner * uSize * (0.5 + 0.5 * dvSeed.w) * 0.5;
|
|
385
|
+
gl_Position = projectionMatrix * mv;
|
|
386
|
+
vUv = dvCorner;
|
|
387
|
+
vFade = 1.0;
|
|
388
|
+
vSeed = dvSeed.x;
|
|
389
|
+
}
|
|
390
|
+
`,Lo=`
|
|
391
|
+
varying vec3 vWorld;
|
|
392
|
+
|
|
393
|
+
void main() {
|
|
394
|
+
vec4 world = modelMatrix * vec4(position.x, 0.0, -position.y, 1.0);
|
|
395
|
+
vWorld = world.xyz;
|
|
396
|
+
gl_Position = projectionMatrix * viewMatrix * world;
|
|
397
|
+
}
|
|
398
|
+
`,Po=`
|
|
399
|
+
uniform float uTime;
|
|
400
|
+
uniform float uWaveScale;
|
|
401
|
+
uniform float uWaveHeight;
|
|
402
|
+
uniform float uSpeed;
|
|
403
|
+
uniform float uGloss;
|
|
404
|
+
uniform float uOpacity;
|
|
405
|
+
uniform vec3 uDeep;
|
|
406
|
+
uniform vec3 uShallow;
|
|
407
|
+
uniform vec3 uSky;
|
|
408
|
+
uniform vec3 uLightDir;
|
|
409
|
+
uniform vec3 uLightColor;
|
|
410
|
+
varying vec3 vWorld;
|
|
411
|
+
${se}
|
|
412
|
+
// Height of the surface: a few crossing swells plus fine chop.
|
|
413
|
+
float dvWave(vec2 p) {
|
|
414
|
+
float t = uTime * uSpeed;
|
|
415
|
+
float h = sin(dot(p, vec2(1.0, 0.3)) * 1.1 + t * 1.1) * 0.5;
|
|
416
|
+
h += sin(dot(p, vec2(-0.4, 1.0)) * 1.7 + t * 1.4) * 0.3;
|
|
417
|
+
h += sin(dot(p, vec2(0.7, -0.8)) * 2.9 + t * 1.9) * 0.15;
|
|
418
|
+
h += (dvNoise(vec3(p * 3.0, t * 0.6)) - 0.5) * 0.35;
|
|
419
|
+
return h;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
void main() {
|
|
423
|
+
vec2 p = vWorld.xz * uWaveScale;
|
|
424
|
+
float e = 0.05;
|
|
425
|
+
float h = dvWave(p);
|
|
426
|
+
vec3 normal = normalize(vec3(
|
|
427
|
+
(h - dvWave(p + vec2(e, 0.0))) * uWaveHeight,
|
|
428
|
+
e,
|
|
429
|
+
(h - dvWave(p + vec2(0.0, e))) * uWaveHeight));
|
|
430
|
+
vec3 view = normalize(cameraPosition - vWorld);
|
|
431
|
+
// Water is a mirror at a glancing angle and see-through from above.
|
|
432
|
+
float fresnel = 0.02 + 0.98 * pow(1.0 - max(dot(normal, view), 0.0), 5.0);
|
|
433
|
+
vec3 body = mix(uDeep, uShallow, 0.5 + 0.5 * h * 0.6);
|
|
434
|
+
vec3 colour = mix(body, uSky, fresnel);
|
|
435
|
+
vec3 halfway = normalize(normalize(uLightDir) + view);
|
|
436
|
+
colour += uLightColor * pow(max(dot(normal, halfway), 0.0), uGloss) * 2.0;
|
|
437
|
+
gl_FragColor = vec4(colour, mix(uOpacity, 1.0, fresnel));
|
|
438
|
+
${B}
|
|
439
|
+
}
|
|
440
|
+
`,Do=`
|
|
441
|
+
varying vec2 vUv;
|
|
442
|
+
|
|
443
|
+
void main() {
|
|
444
|
+
vUv = uv;
|
|
445
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
446
|
+
}
|
|
447
|
+
`,Fo=`
|
|
448
|
+
uniform float uTime;
|
|
449
|
+
uniform float uSpeed;
|
|
450
|
+
uniform float uBands;
|
|
451
|
+
uniform float uRays;
|
|
452
|
+
uniform float uOpacity;
|
|
453
|
+
uniform vec3 uColor;
|
|
454
|
+
uniform vec3 uColor2;
|
|
455
|
+
varying vec2 vUv;
|
|
456
|
+
${se}
|
|
457
|
+
void main() {
|
|
458
|
+
float t = uTime * uSpeed;
|
|
459
|
+
// Slow folds along the curtain, fine vertical rays inside them.
|
|
460
|
+
float fold = dvFbm(vec3(vUv.x * uBands + t * 0.3, vUv.y * 0.4, t * 0.2));
|
|
461
|
+
float rays = dvNoise(vec3(vUv.x * 60.0 + fold * 6.0, t * 0.8, 3.0));
|
|
462
|
+
float curtain = smoothstep(0.35, 0.75, fold) * mix(1.0, 0.4 + 0.6 * rays, uRays);
|
|
463
|
+
// Bright along the lower edge, fading upwards; nothing at the very bottom and sides.
|
|
464
|
+
float height = smoothstep(0.0, 0.12, vUv.y) * pow(1.0 - vUv.y, 1.6);
|
|
465
|
+
float sides = smoothstep(0.0, 0.15, vUv.x) * smoothstep(1.0, 0.85, vUv.x);
|
|
466
|
+
float alpha = curtain * height * sides * uOpacity;
|
|
467
|
+
gl_FragColor = vec4(mix(uColor, uColor2, smoothstep(0.1, 0.9, vUv.y)) * 1.6, alpha);
|
|
468
|
+
${B}
|
|
469
|
+
}
|
|
470
|
+
`,Be=`
|
|
471
|
+
varying vec3 vNormal;
|
|
472
|
+
varying vec3 vView;
|
|
473
|
+
varying vec3 vLocal;
|
|
474
|
+
varying vec2 vUv;
|
|
475
|
+
|
|
476
|
+
void main() {
|
|
477
|
+
vec4 mv = modelViewMatrix * vec4(position, 1.0);
|
|
478
|
+
vNormal = normalize(normalMatrix * normal);
|
|
479
|
+
vView = normalize(-mv.xyz);
|
|
480
|
+
vLocal = position;
|
|
481
|
+
vUv = uv;
|
|
482
|
+
gl_Position = projectionMatrix * mv;
|
|
483
|
+
}
|
|
484
|
+
`,Oo=`
|
|
485
|
+
uniform float uTime;
|
|
486
|
+
uniform float uLines;
|
|
487
|
+
uniform float uSpeed;
|
|
488
|
+
uniform float uRim;
|
|
489
|
+
uniform float uFlicker;
|
|
490
|
+
uniform float uOpacity;
|
|
491
|
+
uniform vec3 uColor;
|
|
492
|
+
varying vec3 vNormal;
|
|
493
|
+
varying vec3 vView;
|
|
494
|
+
varying vec3 vLocal;
|
|
495
|
+
${se}
|
|
496
|
+
void main() {
|
|
497
|
+
float facing = abs(dot(normalize(vNormal), normalize(vView)));
|
|
498
|
+
float rim = pow(1.0 - facing, uRim);
|
|
499
|
+
float lines = 0.5 + 0.5 * sin((vLocal.y * uLines - uTime * uSpeed) * 6.2832);
|
|
500
|
+
lines = smoothstep(0.35, 0.65, lines);
|
|
501
|
+
// A bright band sweeps up now and then, and the whole thing flickers a little.
|
|
502
|
+
float sweep = smoothstep(0.06, 0.0, abs(fract(vLocal.y - uTime * 0.25) - 0.5));
|
|
503
|
+
float flicker = 1.0 - uFlicker * dvHash(vec3(floor(uTime * 24.0), 1.0, 2.0)) * 0.5;
|
|
504
|
+
float alpha = (rim + lines * 0.25 + sweep * 0.5) * flicker * uOpacity;
|
|
505
|
+
gl_FragColor = vec4(uColor * (1.0 + rim * 1.5), alpha);
|
|
506
|
+
${B}
|
|
507
|
+
}
|
|
508
|
+
`,zo=`
|
|
509
|
+
uniform float uTime;
|
|
510
|
+
uniform float uCells;
|
|
511
|
+
uniform float uPulse;
|
|
512
|
+
uniform float uRim;
|
|
513
|
+
uniform float uOpacity;
|
|
514
|
+
uniform vec3 uColor;
|
|
515
|
+
uniform vec3 uColor2;
|
|
516
|
+
varying vec3 vNormal;
|
|
517
|
+
varying vec3 vView;
|
|
518
|
+
varying vec3 vLocal;
|
|
519
|
+
|
|
520
|
+
// Distance to the nearest edge of a hexagonal cell.
|
|
521
|
+
float dvHex(vec2 p) {
|
|
522
|
+
p = abs(mod(p, vec2(1.7320508, 1.0) * 2.0) - vec2(1.7320508, 1.0));
|
|
523
|
+
vec2 q = abs(p - vec2(0.8660254, 0.5));
|
|
524
|
+
p = (dot(q, q) < dot(p, p)) ? q : p;
|
|
525
|
+
return max(p.y, p.x * 0.8660254 + p.y * 0.5);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
void main() {
|
|
529
|
+
vec3 n = normalize(vLocal);
|
|
530
|
+
float rim = pow(1.0 - abs(dot(normalize(vNormal), normalize(vView))), uRim);
|
|
531
|
+
vec2 surface = vec2(atan(n.z, n.x) * 1.9099, asin(clamp(n.y, -1.0, 1.0)) * 1.9099);
|
|
532
|
+
float edge = smoothstep(0.42, 0.5, dvHex(surface * uCells));
|
|
533
|
+
// A ring of light travels from the top of the shield to the bottom.
|
|
534
|
+
float wave = smoothstep(0.12, 0.0, abs(fract(n.y * 0.5 + 0.5 + uTime * uPulse) - 0.5));
|
|
535
|
+
float alpha = (rim + edge * (0.25 + wave) + wave * 0.15) * uOpacity;
|
|
536
|
+
gl_FragColor = vec4(mix(uColor, uColor2, wave) * (1.0 + rim), alpha);
|
|
537
|
+
${B}
|
|
538
|
+
}
|
|
539
|
+
`,Io=`
|
|
540
|
+
uniform float uTime;
|
|
541
|
+
uniform float uStreaks;
|
|
542
|
+
uniform float uFalloff;
|
|
543
|
+
uniform float uEdge;
|
|
544
|
+
uniform float uOpacity;
|
|
545
|
+
uniform vec3 uColor;
|
|
546
|
+
varying vec3 vNormal;
|
|
547
|
+
varying vec3 vView;
|
|
548
|
+
varying vec2 vUv;
|
|
549
|
+
${se}
|
|
550
|
+
void main() {
|
|
551
|
+
// vUv.y is 1 at the lamp and 0 where the beam ends.
|
|
552
|
+
float along = pow(vUv.y, uFalloff);
|
|
553
|
+
// The sides of the cone fade out, so there is no hard silhouette.
|
|
554
|
+
float soft = pow(abs(dot(normalize(vNormal), normalize(vView))), uEdge);
|
|
555
|
+
float streaks = mix(1.0, 0.55 + 0.9 * dvNoise(vec3(vUv.x * 24.0, uTime * 0.15, 1.0)), uStreaks);
|
|
556
|
+
float alpha = along * soft * streaks * smoothstep(0.0, 0.08, vUv.y) * uOpacity;
|
|
557
|
+
gl_FragColor = vec4(uColor, alpha);
|
|
558
|
+
${B}
|
|
559
|
+
}
|
|
560
|
+
`,No=`
|
|
561
|
+
void main() {
|
|
562
|
+
gl_Position = vec4(position.xy, 1.0, 1.0);
|
|
563
|
+
}
|
|
564
|
+
`,Wo=`
|
|
565
|
+
uniform float uTime;
|
|
566
|
+
uniform vec2 uResolution;
|
|
567
|
+
uniform float uSpeed;
|
|
568
|
+
uniform float uBlobs;
|
|
569
|
+
uniform float uVignette;
|
|
570
|
+
uniform float uGrain;
|
|
571
|
+
uniform vec3 uColor;
|
|
572
|
+
uniform vec3 uColor2;
|
|
573
|
+
uniform vec3 uColor3;
|
|
574
|
+
${se}
|
|
575
|
+
void main() {
|
|
576
|
+
vec2 uv = gl_FragCoord.xy / uResolution;
|
|
577
|
+
vec2 p = (uv - 0.5) * vec2(uResolution.x / uResolution.y, 1.0);
|
|
578
|
+
float t = uTime * uSpeed;
|
|
579
|
+
// Two soft fields that drift past each other: a gradient that is never still.
|
|
580
|
+
float a = dvFbmLow(vec3(p * uBlobs + vec2(t * 0.3, -t * 0.2), t * 0.15));
|
|
581
|
+
float b = dvFbmLow(vec3(p * uBlobs * 0.7 - vec2(t * 0.2, t * 0.25), t * 0.1 + 5.0));
|
|
582
|
+
vec3 colour = mix(uColor2, uColor, smoothstep(0.0, 1.0, uv.y + (a - 0.5) * 0.6));
|
|
583
|
+
colour = mix(colour, uColor3, smoothstep(0.45, 0.85, b) * 0.7);
|
|
584
|
+
colour *= 1.0 - uVignette * dot(p, p);
|
|
585
|
+
// A grain of noise: without it a dark gradient shows bands.
|
|
586
|
+
colour += (dvHash(vec3(gl_FragCoord.xy, fract(uTime) * 60.0)) - 0.5) * uGrain;
|
|
587
|
+
gl_FragColor = vec4(colour, 1.0);
|
|
588
|
+
${B}
|
|
589
|
+
}
|
|
590
|
+
`,Bo=`
|
|
591
|
+
varying vec2 vUv;
|
|
592
|
+
|
|
593
|
+
void main() {
|
|
594
|
+
vUv = uv;
|
|
595
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
596
|
+
}
|
|
597
|
+
`,Uo=`
|
|
598
|
+
uniform float uTime;
|
|
599
|
+
uniform vec3 uColor;
|
|
600
|
+
varying vec2 vUv;
|
|
601
|
+
|
|
602
|
+
void main() {
|
|
603
|
+
float wave = 0.5 + 0.5 * sin(vUv.x * 12.0 + uTime * 2.0);
|
|
604
|
+
gl_FragColor = vec4(uColor * wave, 1.0);
|
|
605
|
+
${B}
|
|
606
|
+
}
|
|
607
|
+
`,J=(e,t,o,r,n,i)=>({geometry:"sprites",count:o,vertex:e,fragment:t,uniforms:i,blending:r,transparent:!0,depthTest:!0,depthWrite:!1,side:"double",volume:!1,scale:n}),oe=(e,t,o,r)=>J(jo,Ue,e,t,o,{uSize:.03,uSizeRandom:.6,uSpeed:.03,uTurbulence:1,uTwinkle:0,uStretch:0,uDirection:[0,1,0],uColor:"#ffffff",uColor2:"#ffffff",uOpacity:.6,uSoftness:.8,...r}),re=(e,t)=>({geometry:"box",count:0,vertex:Ro,fragment:Mo,uniforms:{uSteps:32,uDensity:1,uCoverage:.5,uScale:3,uDetail:.6,uEdge:.2,uBottom:.15,uTop:.35,uAbsorption:9,uPowder:.6,uSilver:.5,uOpacity:1,uWind:[.03,0,.01],uLightDir:[.4,.8,.3],uLightColor:"#ffffff",uShadowColor:"#6f7f97",...t},blending:"normal",transparent:!0,depthTest:!0,depthWrite:!1,side:"front",volume:!0,scale:e}),ne=(e,t,o,r,n,i,a={})=>({geometry:e,count:0,vertex:t,fragment:o,uniforms:n,blending:"additive",transparent:!0,depthTest:!0,depthWrite:!1,side:"double",volume:!1,scale:r,controls:i,...a}),k=(e,t,o,r)=>({uniform:e,min:t,max:o,about:r}),Ge={particles:{dust:oe(600,"additive",[1.6,1.2,1.6],{uSize:.008,uSpeed:.012,uOpacity:.45,uTwinkle:.5,uColor:"#fff4dc",uColor2:"#ffffff"}),snow:oe(1500,"normal",[2.2,1.6,2.2],{uSize:.012,uSpeed:.09,uDirection:[.15,-1,0],uTurbulence:1.6,uOpacity:.85,uSoftness:.6}),embers:oe(300,"additive",[.8,1.2,.8],{uSize:.01,uSpeed:.12,uTurbulence:2.2,uTwinkle:.7,uOpacity:.9,uColor:"#ff7a1a",uColor2:"#ffd27a",uSoftness:1}),fireflies:oe(80,"additive",[1.6,.8,1.6],{uSize:.016,uSpeed:.01,uTurbulence:3,uTwinkle:1,uOpacity:.9,uColor:"#d8ff7a",uColor2:"#fff2a8",uSoftness:1}),rain:oe(2500,"normal",[2.2,1.6,2.2],{uSize:.004,uSizeRandom:.2,uSpeed:1.4,uDirection:[.08,-1,0],uTurbulence:0,uStretch:14,uOpacity:.35,uColor:"#b9c7d6",uColor2:"#e4ecf5",uSoftness:.5}),stars:oe(3e3,"additive",[12,12,12],{uSize:.04,uSpeed:0,uTurbulence:0,uTwinkle:.6,uOpacity:.9,uColor:"#cfdcff",uColor2:"#fff1d6",uSoftness:1}),galaxy:{...J(Co,Ue,6e3,"additive",[1.6,1.6,1.6],{uSize:.008,uArms:3,uTwist:9,uSpin:.08,uThickness:.12,uColor:"#ffd9a8",uColor2:"#5f8bff",uOpacity:.8,uSoftness:1}),controls:[k("uSize",.002,.2,"sprite size in scene units"),k("uArms",1,8,"spiral arms"),k("uTwist",0,30,"how tightly the arms wind"),k("uSpin",-1,1,"turns per second at the centre"),k("uThickness",0,.6,"height of the disc"),k("uOpacity",0,1,"additive: the dense core adds up fast")]},swarm:{...J(Ao,Ue,8e3,"additive",[.9,.9,.9],{uSize:.006,uShape:0,uFlow:1,uSpin:.15,uColor:"#7fd4ff",uColor2:"#ffffff",uOpacity:.7,uSoftness:1}),controls:[k("uSize",.002,.2,"sprite size in scene units"),k("uShape",0,3,"0 sphere, 1 ring, 2 box, 3 sphere again; in between it flows from one to the next"),k("uFlow",0,4,"how much the sprites wander on the shape"),k("uSpin",-2,2,"turns of the whole swarm"),k("uOpacity",0,1,"overall")]}},shader:{water:ne("plane",Lo,Po,[3,1,3],{uWaveScale:2.2,uWaveHeight:.35,uSpeed:.8,uGloss:180,uOpacity:.82,uDeep:"#0a2f44",uShallow:"#1f6f7f",uSky:"#a9c4d8",uLightDir:[.4,.6,.5],uLightColor:"#fff2d6"},[k("uWaveScale",.2,12,"waves per scene unit: higher means smaller waves"),k("uWaveHeight",0,1.5,"0 a mirror, 1 a choppy sea"),k("uSpeed",0,3,"how fast the swell travels"),k("uGloss",20,600,"tightness of the sun glint"),k("uOpacity",0,1,"looking straight down; the surface is always solid at a glancing angle")],{blending:"normal"}),aurora:ne("plane",Do,Fo,[4,1.6,1],{uSpeed:.25,uBands:3,uRays:.7,uOpacity:.7,uColor:"#3dffa2",uColor2:"#b04dff"},[k("uSpeed",0,2,"how fast the curtain moves"),k("uBands",.5,10,"folds along the curtain"),k("uRays",0,1,"how strongly it breaks into vertical rays"),k("uOpacity",0,1,"additive: over 0.8 burns white")]),hologram:ne("sphere",Be,Oo,[.7,.7,.7],{uLines:40,uSpeed:.6,uRim:2.2,uFlicker:.5,uOpacity:.8,uColor:"#4fd8ff"},[k("uLines",4,200,"scan lines across the object"),k("uSpeed",-4,4,"how fast the lines travel"),k("uRim",.5,6,"higher keeps the glow to the very edge"),k("uFlicker",0,1,"unsteadiness"),k("uOpacity",0,1,"overall")]),shield:ne("sphere",Be,zo,[1,1,1],{uCells:6,uPulse:.2,uRim:3,uOpacity:.7,uColor:"#38b6ff",uColor2:"#e8fbff"},[k("uCells",1,30,"hexagons around the sphere"),k("uPulse",0,2,"speed of the travelling ring"),k("uRim",.5,6,"higher keeps the glow to the very edge"),k("uOpacity",0,1,"overall")]),"light-shaft":ne("cone",Be,Io,[.7,1.6,.7],{uStreaks:.6,uFalloff:1.6,uEdge:1.5,uOpacity:.28,uColor:"#fff1cf"},[k("uStreaks",0,1,"dusty streaks inside the beam"),k("uFalloff",.3,5,"how quickly the beam dies away from the lamp"),k("uEdge",.3,5,"softness of the sides"),k("uOpacity",0,1,"a beam is faint: 0.1 to 0.4")]),backdrop:ne("screen",No,Wo,[1,1,1],{uSpeed:.15,uBlobs:1.4,uVignette:.5,uGrain:.006,uColor:"#1c2a5e",uColor2:"#05060b",uColor3:"#5a2f8a"},[k("uSpeed",0,2,"how fast the colours drift"),k("uBlobs",.3,6,"higher means smaller patches of colour"),k("uVignette",0,1.5,"darkening towards the corners"),k("uGrain",0,.05,"film grain; also hides banding. Keep it under 0.015")],{blending:"normal",transparent:!1,side:"front"})},smoke:{smoke:J(be,ye,90,"normal",[.35,.9,.35],{uSize:.2,uSoftEdge:.12,uSpeed:.12,uSpread:.5,uTurbulence:1,uWind:[.15,0,0],uColor:"#5a5a5e",uColor2:"#b9bcc2",uOpacity:.35,uDetail:.8}),steam:J(be,ye,50,"normal",[.2,.5,.2],{uSize:.1,uSoftEdge:.06,uSpeed:.22,uSpread:.35,uTurbulence:1.4,uWind:[0,0,0],uColor:"#f2f4f7",uColor2:"#ffffff",uOpacity:.22,uDetail:.6}),"ground-mist":J(be,ye,70,"normal",[2,.2,2],{uSize:.6,uSoftEdge:.15,uSpeed:.04,uSpread:1.6,uTurbulence:.6,uWind:[.3,0,.1],uColor:"#c9d2dc",uColor2:"#e7ecf2",uOpacity:.16,uDetail:.5}),fire:J(be,ye,80,"additive",[.2,.45,.2],{uSize:.12,uSoftEdge:.06,uSpeed:.55,uSpread:.3,uTurbulence:1.2,uWind:[0,0,0],uColor:"#ffb347",uColor2:"#c2260a",uOpacity:.5,uDetail:.9})},clouds:{cumulus:re([1.6,.7,1.6],{}),overcast:re([2.6,.5,2.6],{uCoverage:.75,uDensity:1.3,uPowder:.3,uSilver:.2,uLightColor:"#dfe5ee",uShadowColor:"#59626f"}),wisps:re([2,.45,2],{uCoverage:.38,uDensity:.6,uScale:4.5,uDetail:.9,uAbsorption:6}),sunset:re([1.8,.7,1.8],{uLightDir:[.9,.25,.2],uLightColor:"#ffb27a",uShadowColor:"#5b4a78",uSilver:1})},fog:{"ground-fog":re([3,.35,3],{uSteps:20,uCoverage:.9,uDensity:.35,uScale:2,uDetail:.2,uBottom:.02,uTop:.9,uAbsorption:5,uPowder:0,uSilver:.1,uLightColor:"#dfe6ee",uShadowColor:"#aab4c0",uWind:[.05,0,.02]}),haze:re([3,1.5,3],{uSteps:16,uCoverage:1,uDensity:.12,uScale:1.2,uDetail:0,uBottom:.05,uTop:.6,uAbsorption:4,uPowder:0,uSilver:.6,uLightColor:"#fff3df",uShadowColor:"#c8cfd8"})}},He={particles:[{uniform:"uSize",min:.002,max:.2,about:"sprite size in scene units"},{uniform:"uSizeRandom",min:0,max:1,about:"0 all the same size, 1 mixed"},{uniform:"uSpeed",min:0,max:3,about:"boxes travelled per second along uDirection"},{uniform:"uTurbulence",min:0,max:4,about:"sideways wander"},{uniform:"uTwinkle",min:0,max:1,about:"how much each sprite blinks"},{uniform:"uStretch",min:0,max:30,about:"length along the direction (rain, sparks)"},{uniform:"uOpacity",min:0,max:1,about:"over 0.6 with additive blending burns white"},{uniform:"uSoftness",min:0,max:1,about:"0 a hard disc, 1 a soft glow"}],smoke:[{uniform:"uSize",min:.02,max:3,about:"puff size in scene units; it grows as it rises"},{uniform:"uSpeed",min:.01,max:1,about:"lifetimes per second"},{uniform:"uSpread",min:0,max:2,about:"how wide the column opens"},{uniform:"uTurbulence",min:0,max:3,about:"sideways curl"},{uniform:"uOpacity",min:0,max:1,about:"puffs overlap: 0.15 to 0.4 is plenty"},{uniform:"uDetail",min:0,max:1,about:"how ragged the edge of a puff is"},{uniform:"uSoftEdge",min:0,max:2,about:"distance in scene units over which a puff fades into a surface it touches"}],clouds:[{uniform:"uSteps",min:8,max:96,about:"samples per ray: the main cost. 24 to 40"},{uniform:"uDensity",min:0,max:3,about:"how thick"},{uniform:"uCoverage",min:0,max:1,about:"0 clear sky, 1 solid"},{uniform:"uScale",min:.5,max:10,about:"noise frequency: higher means smaller puffs"},{uniform:"uDetail",min:0,max:1,about:"fine erosion of the edges"},{uniform:"uEdge",min:.02,max:.5,about:"fade towards the sides of the box"},{uniform:"uBottom",min:0,max:1,about:"fade at the bottom (0 a flat base)"},{uniform:"uTop",min:0,max:1,about:"fade at the top"},{uniform:"uAbsorption",min:1,max:30,about:"how fast light dies inside"},{uniform:"uPowder",min:0,max:1,about:"dark creases between the billows"},{uniform:"uSilver",min:0,max:2,about:"glow on thin edges towards the light"},{uniform:"uOpacity",min:0,max:1,about:"overall"}],fog:[],shader:[]};He.fog=He.clouds;var Ho=["particles","smoke","clouds","fog","shader","custom"];function Vo(e){return e==="custom"?[]:Object.keys(Ge[e])}function qe(e,t){if(e==="custom")return[];let o=Ge[e];return o[t??Object.keys(o)[0]]?.controls??He[e]}function Rt(){return Ho.map(e=>({kind:e,presets:Vo(e).map(t=>({preset:t,uniforms:qe(e,t)}))}))}var Go=/^#[0-9a-fA-F]{6}$/,qo=/^[A-Za-z_][A-Za-z0-9_]{0,47}$/;function Jo(e){return X(e)?/^(scene:[\w-]{1,64}|file:[^\0]{1,400})$/.test(e.texture):typeof e=="number"?Number.isFinite(e):typeof e=="string"?Go.test(e):Array.isArray(e)&&e.length>=2&&e.length<=4&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}var xe=e=>X(e)?"a texture":typeof e=="number"?"a number":typeof e=="string"?'a colour "#rrggbb"':`${e.length} numbers`;function St(e,t,o){let r={};for(let[n,i]of Object.entries(t)){if(!qo.test(n))throw new Error(`"${n}" is not a uniform name.`);if(n in Ve)throw new Error(`${n} is filled in by the page every frame and cannot be set.`);if(!Jo(i))throw new Error(`${n}: a uniform is a number, 2 to 4 numbers, a colour as "#rrggbb", or a texture as { "texture": "scene:<uuid>" } or { "texture": "file:<path in the project>" }.`);let a=e.uniforms[n];if(a===void 0){if(!o)throw new Error(`This effect has no uniform ${n}. It has: ${Object.keys(e.uniforms).join(", ")}.`)}else if(X(a)||X(i)){if(!(X(a)&&X(i)))throw new Error(`${n} is ${xe(a)}, not ${xe(i)}.`)}else if(typeof a!=typeof i||Array.isArray(a)&&Array.isArray(i)&&a.length!==i.length){let l=h=>typeof h=="string"||Array.isArray(h)&&h.length===3;if(!(l(a)&&l(i)))throw new Error(`${n} is ${xe(a)}, not ${xe(i)}.`)}r[n]=i}return r}var _t=e=>Math.min(Eo,Math.max(1,Math.round(e)));function Mt(e,t){let o=Number.isFinite(t)&&t>0?t:1,r=e.position??[0,0,0];if(e.kind==="custom"){let f=e.geometry??"plane",v={kind:"custom",preset:null,name:e.name??"Custom effect",geometry:f,count:f==="sprites"?_t(e.count??500):0,vertex:e.vertex??Bo,fragment:e.fragment??Uo,uniforms:e.vertex||e.fragment?{}:{uColor:"#4f8cff"},blending:e.blending??"normal",transparent:e.transparent??!1,depthTest:e.depthTest??f!=="screen",depthWrite:e.depthWrite??!(e.transparent??!1),side:e.side??"double",volume:!1,position:r,scale:e.scale??[o,o,o]};return Tt(v.vertex,"vertex"),Tt(v.fragment,"fragment"),Object.assign(v.uniforms,St(v,e.uniforms??{},!0)),v}let n=Ge[e.kind];if(!n)throw new Error(`Unknown effect kind "${String(e.kind)}".`);let i=e.preset??Object.keys(n)[0],a=n[i];if(!a)throw new Error(`${e.kind} has no preset "${i}". It has: ${Object.keys(n).join(", ")}.`);let l={...a.uniforms};for(let f of["uSize","uSoftEdge"])typeof l[f]=="number"&&(l[f]=K(l[f]*o));let{controls:h,...u}=a,p={...u,uniforms:l,kind:e.kind,preset:i,name:e.name??`${i[0].toUpperCase()}${i.slice(1)}`,count:a.geometry==="sprites"?_t(e.count??a.count):0,position:r,scale:e.scale??a.scale.map(f=>K(f*o))};return Object.assign(p.uniforms,St(p,e.uniforms??{},!1)),p}function Tt(e,t){if(e.length>kt)throw new Error(`The ${t} shader is over ${kt} characters.`);if(!/void\s+main\s*\(/.test(e))throw new Error(`The ${t} shader has no main().`);if(/^\s*#version/m.test(e))throw new Error(`Leave #version out of the ${t} shader: three.js adds it, with the declarations of position, uv, the matrices and cameraPosition.`)}function K(e,t=4){let o=10**t;return Math.round(e*o)/o}var Xo=e=>{let o=e.replace(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).map(r=>r[0].toUpperCase()+r.slice(1)).join("");return/^[A-Za-z]/.test(o)?o:`Effect${o}`};function Ko(e){if(X(e)){let[o,...r]=e.texture.split(":"),n=r.join(":");return o==="file"?`new THREE.TextureLoader().load('/${n.replace(/^(\.\/)?(public\/)?/,"")}')`:`null /* the texture with id ${n} on the page: load the same image here */`}if(typeof e=="number")return String(K(e,5));if(typeof e=="string")return`new THREE.Color('${e}')`;let t=e.map(o=>K(o,5)).join(", ");return`new THREE.Vector${e.length}(${t})`}function A(e,t){let o=new RegExp(`\\buniform\\s+\\w+\\s+${t}\\b`);return o.test(e.vertex)||o.test(e.fragment)}function Yo(e,t){let o=[];A(e,"uTime")&&o.push("uTime: { value: 0 },"),A(e,"uResolution")&&o.push("uResolution: { value: new THREE.Vector2(1, 1) },"),(A(e,"uCameraLocal")||e.volume)&&o.push("uCameraLocal: { value: new THREE.Vector3() },"),A(e,"uNoise")&&o.push("uNoise: { value: noiseTexture() },"),A(e,"uDepth")&&o.push("uDepth: { value: null as THREE.Texture | null },","uHasDepth: { value: 0 },",...A(e,"uDepthToLocal")?["uDepthToLocal: { value: new THREE.Matrix4() },"]:[]);for(let[r,n]of Object.entries(e.uniforms))o.push(`${r}: { value: ${Ko(n)} },`);return o.map(r=>t+r).join(`
|
|
608
|
+
`)}var Zo={box:"new THREE.BoxGeometry(1, 1, 1)",plane:"new THREE.PlaneGeometry(1, 1)",sphere:"new THREE.SphereGeometry(0.5, 36, 24)",cone:"new THREE.ConeGeometry(0.5, 1, 40, 1, true)",screen:`new THREE.BufferGeometry()
|
|
609
|
+
.setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3))
|
|
610
|
+
.setAttribute('uv', new THREE.Float32BufferAttribute([0, 0, 2, 0, 0, 2], 2))`},Qo=`/** Two triangles per sprite, each with its corner and four random numbers. */
|
|
611
|
+
function spriteGeometry(count: number): THREE.BufferGeometry {
|
|
612
|
+
let a = (count * 7919 + 1) >>> 0;
|
|
613
|
+
const random = (): number => {
|
|
614
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
615
|
+
let t = a;
|
|
616
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
617
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
618
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
735
619
|
};
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
620
|
+
const corners = [-1, -1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1];
|
|
621
|
+
const position = new Float32Array(count * 18);
|
|
622
|
+
const corner = new Float32Array(count * 12);
|
|
623
|
+
const seed = new Float32Array(count * 24);
|
|
624
|
+
for (let i = 0; i < count; i++) {
|
|
625
|
+
const p = [random() - 0.5, random() - 0.5, random() - 0.5];
|
|
626
|
+
const s = [random(), random(), random(), random()];
|
|
627
|
+
for (let v = 0; v < 6; v++) {
|
|
628
|
+
position.set(p, i * 18 + v * 3);
|
|
629
|
+
corner.set([corners[v * 2]!, corners[v * 2 + 1]!], i * 12 + v * 2);
|
|
630
|
+
seed.set(s, i * 24 + v * 4);
|
|
746
631
|
}
|
|
747
|
-
const container = b.jsxExpressionContainer(expression);
|
|
748
|
-
if (attr) attr.value = container;
|
|
749
|
-
else attributes.push(b.jsxAttribute(b.jsxIdentifier(edit.prop), container));
|
|
750
|
-
return print();
|
|
751
|
-
}
|
|
752
|
-
const value2 = edit.newValue;
|
|
753
|
-
if (!attr) {
|
|
754
|
-
if (hasSpread)
|
|
755
|
-
return needsAgent(
|
|
756
|
-
`\`${edit.prop}\` is not written on this element and the element spreads props from a variable.`
|
|
757
|
-
);
|
|
758
|
-
attributes.push(b.jsxAttribute(b.jsxIdentifier(edit.prop), attributeValue(value2)));
|
|
759
|
-
return print(`Added the \`${edit.prop}\` prop (it was not set in source).`);
|
|
760
632
|
}
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
633
|
+
const geometry = new THREE.BufferGeometry();
|
|
634
|
+
geometry.setAttribute('position', new THREE.BufferAttribute(position, 3));
|
|
635
|
+
geometry.setAttribute('dvCorner', new THREE.BufferAttribute(corner, 2));
|
|
636
|
+
geometry.setAttribute('dvSeed', new THREE.BufferAttribute(seed, 4));
|
|
637
|
+
return geometry;
|
|
638
|
+
}
|
|
639
|
+
`,er={front:"THREE.FrontSide",back:"THREE.BackSide",double:"THREE.DoubleSide"},Et=e=>`[${e.map(t=>K(t,4)).join(", ")}]`;function $t(e,t,o,r){let n=[];if(A(e,"uTime")&&n.push("material.uniforms.uTime.value = elapsed;"),A(e,"uResolution")&&n.push(`material.uniforms.uResolution.value.copy(${r});`),A(e,"uCameraLocal")||e.volume){let i=`${t}.worldToLocal(material.uniforms.uCameraLocal.value.copy(${o}.position))`;n.push(e.volume?`const local = ${i};`:`${i};`),e.volume&&n.push("// Inside the box the front faces are behind the camera: draw the back faces instead,","// without a depth test, or a floor in front of the far side would cut the volume away.","const inside = Math.max(Math.abs(local.x), Math.abs(local.y), Math.abs(local.z)) < 0.5;","const side = inside ? THREE.BackSide : THREE.FrontSide;","if (material.side !== side) {"," material.side = side;",` material.depthTest = inside ? false : ${e.depthTest};`," material.needsUpdate = true;","}")}return A(e,"uDepth")&&(n.push("// With the depth of the solid scene the effect meets objects softly instead of cutting","// through them. Without it (no depth given) it draws as before.","material.uniforms.uDepth.value = depth ?? null;","material.uniforms.uHasDepth.value = depth ? 1 : 0;"),A(e,"uDepthToLocal")&&n.push("if (depth) {"," const toLocal = material.uniforms.uDepthToLocal.value as THREE.Matrix4;",` toLocal.multiplyMatrices(${o}.projectionMatrix, ${o}.matrixWorldInverse).invert();`,` toLocal.premultiply(inverseWorld.copy(${t}.matrixWorld).invert());`,...e.volume?[" // The march now stops at solid objects by itself: draw the far faces, untested."," if (material.side !== THREE.BackSide || material.depthTest) {"," material.side = THREE.BackSide;"," material.depthTest = false;"," material.needsUpdate = true;"," }"]:[],"}")),n}var tr=`/** 256 x 256 tiling noise; green is red moved by (37, 17), so one read gives 3D noise. */
|
|
640
|
+
function noiseTexture(): THREE.DataTexture {
|
|
641
|
+
const size = 256;
|
|
642
|
+
let a = 20240229 >>> 0;
|
|
643
|
+
const random = (): number => {
|
|
644
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
645
|
+
let t = a;
|
|
646
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
647
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
648
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
649
|
+
};
|
|
650
|
+
const data = new Uint8Array(size * size * 4);
|
|
651
|
+
for (let i = 0; i < size * size; i++) {
|
|
652
|
+
data[i * 4] = Math.floor(random() * 256);
|
|
653
|
+
data[i * 4 + 2] = Math.floor(random() * 256);
|
|
654
|
+
data[i * 4 + 3] = 255;
|
|
769
655
|
}
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
const computed = () => needsAgent(`\`${edit.prop}\` is computed in code (\`${text2}\`), not a literal.`);
|
|
775
|
-
if (Array.isArray(value2)) {
|
|
776
|
-
if (expr.type === "ArrayExpression") {
|
|
777
|
-
const current = expr.elements.map(evalConstant);
|
|
778
|
-
if (current.some((v) => v === void 0)) return computed();
|
|
779
|
-
if (current.length !== value2.length) attr.value.expression = literalNode(value2);
|
|
780
|
-
else {
|
|
781
|
-
value2.forEach((v, i) => {
|
|
782
|
-
if (Math.abs(current[i] - v) > 5e-4) expr.elements[i] = numberNode(v);
|
|
783
|
-
});
|
|
784
|
-
}
|
|
785
|
-
return print();
|
|
656
|
+
for (let y = 0; y < size; y++)
|
|
657
|
+
for (let x = 0; x < size; x++) {
|
|
658
|
+
const from = ((y - 17 + size) % size) * size + ((x - 37 + size) % size);
|
|
659
|
+
data[(y * size + x) * 4 + 1] = data[from * 4]!;
|
|
786
660
|
}
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
if (!isSimpleLiteral(expr)) return computed();
|
|
793
|
-
if (typeof value2 === "number") {
|
|
794
|
-
const current = evalConstant(expr);
|
|
795
|
-
if (current !== void 0 && Math.abs(current - value2) <= 5e-4) return print();
|
|
796
|
-
}
|
|
797
|
-
attr.value.expression = literalNode(value2);
|
|
798
|
-
return print();
|
|
661
|
+
const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
|
|
662
|
+
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
|
|
663
|
+
texture.minFilter = texture.magFilter = THREE.LinearFilter;
|
|
664
|
+
texture.needsUpdate = true;
|
|
665
|
+
return texture;
|
|
799
666
|
}
|
|
800
|
-
function
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
667
|
+
`;function jt(e){return`new THREE.ShaderMaterial({
|
|
668
|
+
vertexShader,
|
|
669
|
+
fragmentShader,
|
|
670
|
+
uniforms: {
|
|
671
|
+
${Yo(e," ")}
|
|
672
|
+
},
|
|
673
|
+
transparent: ${e.transparent},
|
|
674
|
+
depthTest: ${e.depthTest},
|
|
675
|
+
depthWrite: ${e.depthWrite},
|
|
676
|
+
blending: ${e.blending==="additive"?"THREE.AdditiveBlending":"THREE.NormalBlending"},
|
|
677
|
+
side: ${er[e.side]},
|
|
678
|
+
})`}function Ct(e,t){let o=Xo(e.name),r=e.geometry==="sprites"?`spriteGeometry(${e.count})`:Zo[e.geometry],n=`const vertexShader = /* glsl */ \`${e.vertex}\`;
|
|
679
|
+
|
|
680
|
+
const fragmentShader = /* glsl */ \`${e.fragment}\`;
|
|
681
|
+
`,i=A(e,"uDepth"),a=(e.geometry==="sprites"?`
|
|
682
|
+
${Qo}`:"")+(A(e,"uNoise")?`
|
|
683
|
+
${tr}`:"")+(i&&A(e,"uDepthToLocal")?`
|
|
684
|
+
const inverseWorld = new THREE.Matrix4();
|
|
685
|
+
`:"");if(t==="r3f"){let u=$t(e,"mesh","state.camera","state.gl.getDrawingBufferSize(size)"),p=A(e,"uResolution");return`import { useMemo, useRef } from 'react';
|
|
686
|
+
import { useFrame } from '@react-three/fiber';
|
|
687
|
+
import * as THREE from 'three';
|
|
688
|
+
|
|
689
|
+
${n}${a}
|
|
690
|
+
${p?`const size = new THREE.Vector2();
|
|
691
|
+
|
|
692
|
+
`:""}${i?"/**\n * `depth`: the depth texture of the solid scene, e.g. `useDepthBuffer()` from\n * @react-three/drei, at the size of the canvas. Without it the effect ignores what it touches.\n */\n":""}export function ${o}({${i?" depth,":""} ...props }: JSX.IntrinsicElements['mesh']${i?" & { depth?: THREE.Texture }":""}) {
|
|
693
|
+
const ref = useRef<THREE.Mesh>(null);
|
|
694
|
+
const geometry = useMemo(() => ${r}, []);
|
|
695
|
+
const material = useMemo(
|
|
696
|
+
() =>
|
|
697
|
+
${jt(e).replace(/\n/g,`
|
|
698
|
+
`)},
|
|
699
|
+
[],
|
|
700
|
+
);
|
|
701
|
+
${u.length?` useFrame((state) => {
|
|
702
|
+
const mesh = ref.current;
|
|
703
|
+
if (!mesh) return;
|
|
704
|
+
const elapsed = state.clock.elapsedTime;
|
|
705
|
+
${u.join(`
|
|
706
|
+
`)}
|
|
707
|
+
});
|
|
708
|
+
`:""} return (
|
|
709
|
+
<mesh
|
|
710
|
+
ref={ref}
|
|
711
|
+
name="${e.name}"
|
|
712
|
+
geometry={geometry}
|
|
713
|
+
material={material}
|
|
714
|
+
position={${Et(e.position)}}
|
|
715
|
+
scale={${Et(e.scale)}}
|
|
716
|
+
frustumCulled={false}
|
|
717
|
+
{...props}
|
|
718
|
+
/>
|
|
719
|
+
);
|
|
808
720
|
}
|
|
721
|
+
`}let l=$t(e,"mesh","camera","renderer.getDrawingBufferSize(size)"),h=A(e,"uResolution");return`import * as THREE from 'three';
|
|
809
722
|
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
})
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
}
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
const result = applyJsxPropEdit(source, {
|
|
855
|
-
line: edit.line,
|
|
856
|
-
column: edit.column,
|
|
857
|
-
prop: edit.prop,
|
|
858
|
-
newValue: edit.newValue,
|
|
859
|
-
expression
|
|
860
|
-
});
|
|
861
|
-
if (result.ok) {
|
|
862
|
-
if (result.changed) writeFileSync(path, result.code);
|
|
863
|
-
edit.status = "applied";
|
|
864
|
-
edit.message = result.note;
|
|
865
|
-
} else {
|
|
866
|
-
edit.status = result.needsAgent ? "queued" : "failed";
|
|
867
|
-
edit.message = result.reason;
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
/** Takes a batch from the extension. Returns one result per intent, in the same order. */
|
|
871
|
-
submit(intents) {
|
|
872
|
-
const edits = intents.map((intent) => ({
|
|
873
|
-
...intent,
|
|
874
|
-
id: randomUUID().slice(0, 8),
|
|
875
|
-
status: "queued"
|
|
876
|
-
}));
|
|
877
|
-
for (const edit of [...edits].sort(
|
|
878
|
-
(a, b2) => a.file === b2.file ? b2.line - a.line || b2.column - a.column : 0
|
|
879
|
-
)) {
|
|
880
|
-
this.tryApply(edit);
|
|
881
|
-
this.edits.set(edit.id, edit);
|
|
882
|
-
}
|
|
883
|
-
return edits;
|
|
884
|
-
}
|
|
885
|
-
list(status) {
|
|
886
|
-
const all = [...this.edits.values()];
|
|
887
|
-
return status ? all.filter((e) => e.status === status) : all;
|
|
888
|
-
}
|
|
889
|
-
get(id) {
|
|
890
|
-
const edit = this.edits.get(id);
|
|
891
|
-
if (!edit) throw new Error(`Unknown edit id: ${id}`);
|
|
892
|
-
return edit;
|
|
893
|
-
}
|
|
894
|
-
context(id, radius = 12) {
|
|
895
|
-
const edit = this.get(id);
|
|
896
|
-
const file = this.resolveFile(edit.file);
|
|
897
|
-
return { edit, file, source: sourceContext(readFileSync(file, "utf8"), edit.line, radius) };
|
|
898
|
-
}
|
|
899
|
-
/** Applies a queued edit, optionally with an expression chosen by the agent. */
|
|
900
|
-
apply(id, expression) {
|
|
901
|
-
const edit = this.get(id);
|
|
902
|
-
this.tryApply(edit, expression);
|
|
903
|
-
this.emit("change", edit);
|
|
904
|
-
return edit;
|
|
905
|
-
}
|
|
906
|
-
markDone(id, status, note) {
|
|
907
|
-
const edit = this.get(id);
|
|
908
|
-
edit.status = status;
|
|
909
|
-
if (note) edit.message = note;
|
|
910
|
-
this.emit("change", edit);
|
|
911
|
-
return edit;
|
|
912
|
-
}
|
|
913
|
-
};
|
|
914
|
-
|
|
915
|
-
// src/server.ts
|
|
916
|
-
var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
|
917
|
-
var MAX_ATTEMPTS = 5;
|
|
918
|
-
var editsMessage = z3.object({
|
|
919
|
-
type: z3.literal("edits"),
|
|
920
|
-
requestId: z3.string().max(64),
|
|
921
|
-
edits: z3.array(editIntentSchema).max(200)
|
|
723
|
+
${n}${a}
|
|
724
|
+
/**
|
|
725
|
+
* Add the returned mesh to the scene, and call update(elapsedSeconds) every frame.${i?`
|
|
726
|
+
* Pass the depth texture of the solid scene (a render target's depthTexture, at the size of
|
|
727
|
+
* the canvas) as the second argument: without it the effect ignores what it touches.`:""}
|
|
728
|
+
*/
|
|
729
|
+
export function create${o}(camera: THREE.Camera${h?", renderer: THREE.WebGLRenderer":""}) {
|
|
730
|
+
const material = ${jt(e).replace(/\n/g,`
|
|
731
|
+
`)};
|
|
732
|
+
const mesh = new THREE.Mesh(${r}, material);
|
|
733
|
+
mesh.name = '${e.name}';
|
|
734
|
+
mesh.position.set(${e.position.map(u=>K(u,4)).join(", ")});
|
|
735
|
+
mesh.scale.set(${e.scale.map(u=>K(u,4)).join(", ")});
|
|
736
|
+
mesh.frustumCulled = false;
|
|
737
|
+
${h?` const size = new THREE.Vector2();
|
|
738
|
+
`:""} const update = (elapsed: number${i?", depth?: THREE.Texture":""}): void => {
|
|
739
|
+
${l.length?l.join(`
|
|
740
|
+
`):"void elapsed;"}
|
|
741
|
+
};
|
|
742
|
+
return { mesh, update };
|
|
743
|
+
}
|
|
744
|
+
`}import{existsSync as or,mkdirSync as rr,realpathSync as Je,writeFileSync as nr}from"node:fs";import{dirname as sr,relative as Xe,resolve as Ke,sep as ie}from"node:path";var At="https://api.polyhaven.com",Lt={"user-agent":"depthview-mcp"},ir={model:"models",texture:"textures",hdri:"hdris"},Ye=12*1024*1024,G=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Pt=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Dt=e=>{let t=e.split("/").filter(Boolean);if(!t.length||t.some(o=>o===".."||o==="."||!/^[\w.\- ]+$/.test(o)))throw new Error(`The library returned a file name that is not safe to write: ${e}`);return t.join("/")};function Ft(e){let t=G(e);if(typeof t.url!="string"||typeof t.size!="number")return null;let o=new URL(t.url).hostname;if(t.url.startsWith("https://")&&(o==="polyhaven.org"||o.endsWith(".polyhaven.org")))return{url:t.url,size:t.size,include:G(t.include)};throw new Error(`Refusing a download from ${o}: not the asset library.`)}var ke=class{constructor(t,o=fetch){this.root=t;this.fetcher=o}lists=new Map;async get(t){let o=await this.fetcher(t,{headers:Lt,signal:AbortSignal.timeout(25e3)});if(!o.ok)throw new Error(`The asset library answered ${o.status} for ${t}`);return o.json()}async list(t){let o=this.lists.get(t);if(o&&Date.now()-o.at<10*6e4)return o.items;let r=G(await this.get(`${At}/assets?t=${ir[t]}`)),n=new Map(Object.entries(r).map(([i,a])=>[i,G(a)]));return this.lists.set(t,{at:Date.now(),items:n}),n}async search(t,o,r=8){let n=t.toLowerCase().split(/[^a-z0-9]+/).filter(a=>a.length>1),i=[];for(let[a,l]of await this.list(o)){let h=String(l.name??a),u=Pt(l.tags),p=Pt(l.categories),f={name:`${a} ${h}`.toLowerCase(),tags:u.join(" ").toLowerCase(),categories:p.join(" ").toLowerCase()},v=0;for(let x of n)v+=(f.name.includes(x)?3:0)+(f.categories.includes(x)?2:0)+(f.tags.includes(x)?1:0);n.length&&v===0||i.push({score:v,downloads:Number(l.download_count)||0,hit:{id:a,name:h,type:o,categories:p,tags:u.slice(0,8),...typeof l.polycount=="number"?{polycount:l.polycount}:{},page:`https://polyhaven.com/a/${a}`,license:"CC0"}})}return i.sort((a,l)=>l.score-a.score||l.downloads-a.downloads).slice(0,Math.min(25,Math.max(1,r))).map(a=>a.hit)}async plan(t,o,r){if(!/^[\w-]{1,80}$/.test(t))throw new Error("That is not an asset id.");let n=G(await this.get(`${At}/files/${t}`)),i=(h,u)=>{let p=G(n[h]),f=G(p[r]??p["2k"]??p["1k"]);return f[u]===void 0?null:Ft(f[u])},a=h=>Dt(decodeURIComponent(h.split("/").pop())),l=[];if(o==="texture"){let h=[["Diffuse","colour (sRGB)"],["nor_gl","normal map (OpenGL)"],["arm","ambient occlusion, roughness, metalness packed in R, G, B"]];for(let[u,p]of h){let f=i(u,"jpg");f&&l.push({url:f.url,path:a(f.url),bytes:f.size,role:p})}if(!l.some(u=>u.role.startsWith("ambient"))){let u=i("Rough","jpg");u&&l.push({url:u.url,path:a(u.url),bytes:u.size,role:"roughness"})}}else if(o==="model"){let h=i("gltf","gltf");if(!h)throw new Error(`"${t}" has no glTF version in the library.`);let u=h.url.slice(0,h.url.lastIndexOf("/")+1);l.push({url:h.url,path:a(h.url),bytes:h.size,role:"model (glTF)"});for(let[p,f]of Object.entries(h.include)){let v=G(f),x=typeof v.url=="string"?Ft(v).url:u+p;l.push({url:x,path:Dt(p),bytes:Number(v.size)||0,role:p.endsWith(".bin")?"geometry":"texture"})}}else{let h=i("hdri","hdr");if(!h)throw new Error(`"${t}" has no .hdr version in the library.`);l.push({url:h.url,path:a(h.url),bytes:h.size,role:"lighting panorama (HDR)"})}if(!l.length)throw new Error(`Nothing to download for "${t}" as a ${o}.`);return l}folderFor(t,o){let r=Je(this.root),n=o?.trim()||(or(Ke(r,"public"))?"public/assets":"assets"),i=Ke(r,n,t);if(!i.startsWith(r+ie))throw new Error("Folder is outside the project root");if(i.split(ie).includes("node_modules"))throw new Error("Assets are not written into node_modules");let a=Xe(r,i).split(ie).join("/");return{dir:i,served:a.startsWith("public/")?`/${a.slice(7)}`:null}}async import(t){let o=t.resolution??"1k",r=t.maxBytes??Ye,n=await this.plan(t.id,t.type,o),i=n.reduce((x,b)=>x+b.bytes,0),a=x=>`${(x/1048576).toFixed(1)} MB`;if(i>r)throw new Error(`"${t.id}" at ${o} is ${a(i)}, over the ${a(r)} budget for one asset. ${o==="1k"?"Choose a lighter asset, or raise maxBytes if the page can afford it.":"Use a lower resolution (1k is enough for most web scenes)."}`);let{dir:l,served:h}=this.folderFor(t.id,t.folder),u=[];for(let x of n){let b=await this.fetcher(x.url,{headers:Lt,signal:AbortSignal.timeout(12e4)});if(!b.ok)throw new Error(`Download failed (${b.status}): ${x.url}`);let S=Buffer.from(await b.arrayBuffer());if(S.length>r)throw new Error(`${x.path} is larger than the budget.`);let w=Ke(l,x.path);if(!w.startsWith(l+ie))throw new Error("Unsafe file path");rr(sr(w),{recursive:!0}),nr(w,S),u.push({path:Xe(Je(this.root),w).split(ie).join("/"),bytes:S.length,role:x.role})}let p=Xe(Je(this.root),l).split(ie).join("/"),f=x=>h?`${h}/${x.path}`:`./${p}/${x.path}`,v=[];return h||v.push(`The project has no public/ folder, so the files are in ${p}/: import them from your code or move them to where your site serves static files.`),{id:t.id,type:t.type,resolution:o,folder:p,files:u,totalBytes:u.reduce((x,b)=>x+b.bytes,0),license:"CC0",source:`https://polyhaven.com/a/${t.id}`,usage:lr(t.type,n,f),notes:[...v,...ar(t.type,u)]}}};function ar(e,t){let o=t.reduce((r,n)=>r+n.bytes,0);return e==="model"?["Name the meshes you want to tune, then use set_surface and the look on them like any other object.",...o>4*1048576?["This model is over 4 MB. To shrink it (meshopt geometry, WebP textures), run with the developer's approval: npx @gltf-transform/cli optimize <in>.gltf <out>.glb --compress meshopt --texture-compress webp"]:[]]:e==="texture"?['Set texture.anisotropy (or turn on "Sharp textures" in the look) so the surface stays crisp at glancing angles.',"The object needs UV coordinates. Scale the pattern with texture.repeat."]:[`A real panorama replaces the generated studio world: set the look's world to "site" so the two do not fight.`]}function lr(e,t,o){if(e==="model"){let f=o(t[0]);return{r3f:`import { useGLTF } from '@react-three/drei';
|
|
745
|
+
|
|
746
|
+
function Model(props) {
|
|
747
|
+
const { scene } = useGLTF('${f}');
|
|
748
|
+
return <primitive object={scene} {...props} />;
|
|
749
|
+
}
|
|
750
|
+
useGLTF.preload('${f}');`,three:`import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
|
|
751
|
+
|
|
752
|
+
const { scene: model } = await new GLTFLoader().loadAsync('${f}');
|
|
753
|
+
scene.add(model);`}}if(e==="hdri"){let f=o(t[0]);return{r3f:`import { Environment } from '@react-three/drei';
|
|
754
|
+
|
|
755
|
+
<Environment files="${f}" />`,three:`import * as THREE from 'three';
|
|
756
|
+
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
|
|
757
|
+
|
|
758
|
+
const panorama = await new RGBELoader().loadAsync('${f}');
|
|
759
|
+
panorama.mapping = THREE.EquirectangularReflectionMapping;
|
|
760
|
+
scene.environment = panorama;`}}let r=f=>t.find(v=>v.role.startsWith(f)),n=r("colour"),i=r("normal"),a=r("ambient"),l=r("roughness"),h=[n&&`map: '${o(n)}'`,i&&`normalMap: '${o(i)}'`,a&&`aoMap: '${o(a)}'`,a&&`roughnessMap: '${o(a)}'`,a&&`metalnessMap: '${o(a)}'`,!a&&l&&`roughnessMap: '${o(l)}'`].filter(Boolean),u=[n&&`const map = loader.load('${o(n)}');
|
|
761
|
+
map.colorSpace = THREE.SRGBColorSpace;`,i&&`const normalMap = loader.load('${o(i)}');`,a&&`const arm = loader.load('${o(a)}'); // ambient occlusion, roughness, metalness in R, G, B`,!a&&l&&`const roughnessMap = loader.load('${o(l)}');`].filter(Boolean),p=[n&&"map",i&&"normalMap",a&&"aoMap: arm, roughnessMap: arm, metalnessMap: arm",!a&&l&&"roughnessMap"].filter(Boolean);return{r3f:`import { useTexture } from '@react-three/drei';
|
|
762
|
+
|
|
763
|
+
// The colour map is sRGB (drei sets that); the others are data.
|
|
764
|
+
const textures = useTexture({
|
|
765
|
+
${h.join(`,
|
|
766
|
+
`)},
|
|
922
767
|
});
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
if (waiter) waiter(this.core.snapshot);
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
async onRequest(req, res) {
|
|
1096
|
-
const json = (status, body) => {
|
|
1097
|
-
res.writeHead(status, { "content-type": "application/json" });
|
|
1098
|
-
res.end(JSON.stringify(body));
|
|
1099
|
-
};
|
|
1100
|
-
try {
|
|
1101
|
-
const host = (req.headers.host ?? "").replace(/:\d+$/, "");
|
|
1102
|
-
const origin = req.headers.origin;
|
|
1103
|
-
if (!LOOPBACK.has(req.socket.remoteAddress ?? "") || !["127.0.0.1", "localhost", "[::1]"].includes(host))
|
|
1104
|
-
return json(403, { error: "Local connections only" });
|
|
1105
|
-
if (origin !== void 0 && !/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(origin))
|
|
1106
|
-
return json(403, { error: "Origin not allowed" });
|
|
1107
|
-
const path = (req.url ?? "/").split("?")[0];
|
|
1108
|
-
if (path === "/health")
|
|
1109
|
-
return json(200, { name: "depthview-mcp", extensionConnected: this.extensionConnected });
|
|
1110
|
-
if (path !== "/mcp" || !this.options.mcpHttp) return json(404, { error: "Not found" });
|
|
1111
|
-
if (req.method !== "POST")
|
|
1112
|
-
return json(405, {
|
|
1113
|
-
jsonrpc: "2.0",
|
|
1114
|
-
error: { code: -32e3, message: "Method not allowed" },
|
|
1115
|
-
id: null
|
|
1116
|
-
});
|
|
1117
|
-
const chunks = [];
|
|
1118
|
-
let size = 0;
|
|
1119
|
-
for await (const chunk of req) {
|
|
1120
|
-
size += chunk.length;
|
|
1121
|
-
if (size > 4 * 1024 * 1024) return json(413, { error: "Request too large" });
|
|
1122
|
-
chunks.push(chunk);
|
|
768
|
+
<meshStandardMaterial {...textures}${a?" metalness={1} roughness={1}":""} />`,three:`import * as THREE from 'three';
|
|
769
|
+
|
|
770
|
+
const loader = new THREE.TextureLoader();
|
|
771
|
+
${u.join(`
|
|
772
|
+
`)}
|
|
773
|
+
const material = new THREE.MeshStandardMaterial({ ${p.join(", ")}${a?", metalness: 1, roughness: 1":""} });`}}import{readFileSync as cr}from"node:fs";import{dirname as hr,join as Ot}from"node:path";import{fileURLToPath as ur}from"node:url";var ce={"site-build":"building a 3D site from an empty folder, step by step: page and type, studio environment, set without a horizon, framing with view offset, scroll camera, last pass, phone, reveal, and the faults every first draft has",modeling:"making the subject in code: lathe profiles, bevelled extrusions, cut detail, displaced natural shapes, canvas-drawn labels and surfaces, what makes it read as real",threejs:"three.js as it is now (r187): renamed and removed names, renderer set-up, colour, light units, shadows, materials and their defaults, geometry classes, post-processing order, WebGPU status","award-sites":"how igloo.inc-level sites are built: pipeline, asset baking, scroll, loading, what makes them feel expensive",rendering:"colour management, tone mapping, PBR materials, environment lighting, shadows, post-processing order",shaders:"GLSL in three.js: ShaderMaterial, onBeforeCompile, noise, fresnel, dissolve, displacement, TSL",particles:"sprites, instancing, GPGPU / FBO simulation, curl noise, soft particles, trails",volumetrics:"clouds, smoke, fog, god rays: sprite stacks, ray marching, 3D noise, jitter, half resolution",performance:"budgets, draw calls, instancing, texture and geometry compression, pixel ratio, adaptive quality, loading",r3f:"React Three Fiber and drei patterns, what must never happen in a component, scroll rigs, postprocessing","visual-qa":"every visual bug audit_visuals reports and more: symptom, cause, how to confirm, fix","extension-ui":"the Depthview extension itself: every panel, tab, switch and shortcut, where it is and what it changes, so you can tell the developer what to click"};function dr(){return Ot(hr(ur(import.meta.url)),"..","skill","references")}function zt(e){if(!(e in ce))throw new Error(`No guide "${e}". Topics: ${Object.keys(ce).join(", ")}.`);return cr(Ot(dr(),`${e}.md`),"utf8")}var It=`Depthview connects you to a three.js / React Three Fiber scene running in the developer's Chrome. You can read the live scene, change values on the page at once (undoable), look at the result, and write the final values into the source.
|
|
774
|
+
|
|
775
|
+
1. Call get_status first. mode "none": connect one of two ways. Without the extension: open_preview { url } opens the dev page in a headless browser on this machine and the live tools work on it (start the dev server first; call open_preview again after each source edit to reload; take_screenshot is how you see). With the extension: give the developer the pairingCode to type into the Depthview side panel, then wait. Never write 3D code blind when you can open a preview and look.
|
|
776
|
+
2. Call describe_scene once to learn the scene's scale, camera and lights before you move or size anything.
|
|
777
|
+
3. Find objects with find_objects, then get_object. Only paths listed in "editable" can be set. Use uuids; they change after a page reload.
|
|
778
|
+
4. Change values with set_value, or set_values for several at once (one undo step). Start from the current value and work in small steps. Rotations and angles are radians unless you pass degrees:true.
|
|
779
|
+
5. Check every visible change with take_screenshot view:"site" (compare:true shows before and after). If a result says overwritten:true, the site's code animates that value: tell the developer instead of retrying.
|
|
780
|
+
6. When it looks right: get_changes, then apply_changes_to_code, then finish every "queued" edit (get_edit_context, then apply_edit or mark_edit_done). Report file, prop and old to new value.
|
|
781
|
+
|
|
782
|
+
Camera views ("change what shows when the page loads", "show the product from the left in the features section", "the camera should stop on each section"): get_camera_views lists one view for the page on load and one per section; set_camera_view sets a view by framing an object, by position/target, or from the view the developer framed by hand (fromView), with hold to keep the camera still on a section. The path between views is built for you. Check each with take_screenshot view:"site", then save_camera_path. Prefer this over editing single keys.
|
|
783
|
+
|
|
784
|
+
Scroll camera path: get_camera_path shows it; edit_camera_path edits it (the developer can also drag its handles); get_camera_path_edit returns the edited keys; save_camera_path writes camera-path.json, or rewrite the developer's own camera code with the keys.
|
|
785
|
+
|
|
786
|
+
Realism ("make it look real / premium / like a product shot"): get_realism scores the scene and lists what is missing; fix_realism applies the one-click fixes; set_look tunes colour, world lighting (studio light boxes), shadows, bevels and lens effects; set_surface sets what an object is made of. Check each step with take_screenshot view:"site" compare:true. save_look writes the look into the project. Do not hand-write lighting or post-processing code for this: tune it live first, then save.
|
|
787
|
+
|
|
788
|
+
Building a page or a scene from nothing ("make me a site like\u2026", "a landing page with a 3D \u2026"): read get_guide topic:"site-build" first and follow it: decide subject, three materials, palette and journey; build the page and its typography around a fixed canvas; a studio environment; a set with no horizon; the subject modelled in code (topic "modeling") or a real model; one camera key per section with the subject placed by camera.setViewOffset; a restrained last pass; the phone layout; a reveal. After every round: open_preview to reload, get_errors, then review_site, which returns a picture of every scroll stop and the design faults it measured (glare, flat frame, horizon line, fringe, unreadable copy, a stock primitive as subject, no copy, a scroll that changes nothing). Fix and repeat until no high or medium issue is left, then judge the pictures by its lookFor questions. A realism score of 95 only says the render settings are in order.
|
|
789
|
+
|
|
790
|
+
three.js changes between versions. Before writing a class, add-on or option you are not sure of, three_docs { name } returns its documentation from the three.js this project has installed (import path, constructor, defaults, deprecations); three_docs { manual } a page of the three.js manual; get_guide topic:"threejs" what was renamed or removed. A name three_docs cannot find does not exist here.
|
|
791
|
+
|
|
792
|
+
create_scene writes a starter scaffold (placeholder objects, look, scroll camera path, controls): a start for tuning, not a finished page. Detail that primitives cannot give: find_assets and import_asset bring in real CC0 models and textures (ask first: it writes files), and set_surface detail draws fine relief (brushed, rings, knurl, engraved text) as a normal map. A reference picture of the look wanted: compare_to_reference measures the differences and gives the change for each.
|
|
793
|
+
|
|
794
|
+
A model was added (import_asset, a new glTF, a new mesh): after the reload, adapt_model fits the look to it from measurements (shadows, texture colour, focus, occlusion, reflections, frame rate) and reports how it sits: its size against the scene and its gap above the floor. Scale and grounding are advice: tell the developer the numbers and ask.
|
|
795
|
+
|
|
796
|
+
Frame rate is part of the result: get_realism reports fps with and without the look; measure_look_cost says which part costs what; lighten_look steps it down. Never leave a look that costs more than a fifth of the site's frame rate.
|
|
797
|
+
|
|
798
|
+
The site's own controls (depthviewControls in its code): get_site_controls, set_site_control, save_site_controls.
|
|
799
|
+
|
|
800
|
+
Effects (particles, snow, dust, embers, rain, a galaxy, a shape-forming swarm, smoke, steam, fire, clouds, fog, water, aurora, hologram, shield, light shaft, an animated gradient backdrop, or any custom GLSL): list_effects, add_effect, tune with set_effect and a screenshot after each step, measure with get_performance, then get_effect_code and write the file into the project. patch_shader injects GLSL into a built-in material (displacement, fresnel, dissolve) and returns the onBeforeCompile source.
|
|
801
|
+
|
|
802
|
+
Testing a 3D page ("why is it pixelated / blurry / flickering", "check my site"): audit_visuals first. It measures the real frame and the set-up and returns each bug with evidence, cause and fix. Run it at several scroll positions (scroll: [0, 25, 50, 75, 100]) and after set_viewport for phone sizes. Then get_errors and get_performance. On a page whose camera follows the scroll, audit_camera_motion judges the move itself: jumps, moves with no ease, doubling back, side-to-side swings, whip turns, a tilted horizon, dead scroll. Its checkAt lists the scroll stops to screenshot for framing.
|
|
803
|
+
|
|
804
|
+
Before writing three.js code in an area you have not read about in this session, call get_guide with the topic (site-build, modeling, threejs, award-sites, rendering, shaders, particles, volumetrics, performance, r3f, visual-qa). When the developer asks where something is in the extension, or a result looks wrong for no reason in the scene: get_inspector_state (its affectsYourTools lists switches that change your results) and get_guide topic "extension-ui".
|
|
805
|
+
|
|
806
|
+
Never change unrelated code. Never write a value into the source that is not in get_changes or given by the developer. Tool results often end with "next": follow it.`,Nt=[{name:"pair",title:"Pair with Depthview",description:"Connect this agent to the Depthview inspector open in Chrome.",text:()=>"Pair with Depthview: call get_status. If it is not paired, give me the pairing code and tell me where to type it, then wait for me. Once paired, call describe_scene and tell me in two lines what the scene contains."},{name:"tune",title:"Tune the 3D scene",description:"Change the live scene towards a goal, checking each step with a screenshot.",argument:{name:"goal",description:'What should change, e.g. "warmer, moodier lighting" or "camera closer".'},text:e=>`Tune my live three.js scene with the Depthview tools. Goal: ${e?.trim()||"ask me what I want changed"}.
|
|
807
|
+
|
|
808
|
+
Steps: get_status, describe_scene, then find the objects that matter (find_objects, get_object). Take a take_screenshot view:"site" first. Make the change in small steps with set_values, starting from the current values, and check each step with take_screenshot view:"site" compare:true. At most three rounds. Do not write anything into the source yet: tell me what you changed (object, path, old to new) and ask whether to keep it.`},{name:"apply",title:"Write Depthview changes into the code",description:"Write every change made in the inspector (by you or by hand) into the source.",text:()=>'Write my Depthview changes into the code: get_changes, then apply_changes_to_code. For every edit that comes back "queued", call get_edit_context and finish it with apply_edit or your own edit plus mark_edit_done. Write changes without a source location yourself from get_changes. Then list_pending_edits to confirm nothing is left, and list per change: file, prop, old value to new value. Change nothing else.'},{name:"camera-views",title:"Set the camera view on load and for each section",description:"Choose what the camera shows when the page loads and at each section, check it live, then put it into the project.",argument:{name:"goal",description:'What each view should show, e.g. "open on the bottle from the front-left".'},text:e=>`Set my camera views. ${e?.trim()?`Goal: ${e.trim()}.`:"Ask me what each view should show, or use what I framed by hand if I say so."}
|
|
809
|
+
|
|
810
|
+
1. get_status, then get_camera_views. It lists view 1 (the page on load) and one view per section.
|
|
811
|
+
2. describe_scene and find_objects, so you know what there is to show and how big it is.
|
|
812
|
+
3. For each view I asked about, set_camera_view: frame { object, from, fill } to show an object, or position/target for an exact pose. If I said I framed it myself, use fromView: true for that view. Use hold: true where the camera should rest on a section. Leave views I did not mention alone.
|
|
813
|
+
4. After each one, take_screenshot view:"site" and judge it: is the subject in frame, clear of the page's text, not cut off? Adjust fill, from or the target and look again.
|
|
814
|
+
5. When I am happy, put it into the project. If it already uses useCameraPath with a JSON file: save_camera_path to that file. If it has its own scroll camera code: follow the "camera-path" prompt. If the camera does not move at all yet: save_camera_path, then add useCameraPath(path) from depthview-r3f-bridge/camera-path inside <Canvas> (plain three.js: evaluatePath from the same package in the render loop), and ask before removing any camera code of mine.
|
|
815
|
+
6. A page with one screen only has one view: write its position, look-at and fov into my camera in the source instead of a path file.
|
|
816
|
+
7. Tell me what each view shows now and which file holds it.`},{name:"camera-path",title:"Write the edited camera path into the code",description:"Put the scroll camera path edited in Depthview into the project: as camera-path.json, or in your own camera code.",text:()=>`Write my edited Depthview camera path into the code.
|
|
817
|
+
|
|
818
|
+
1. get_camera_path_edit. If it is not editing, tell me to set the views first (Camera views > Set camera views in the inspector) and stop.
|
|
819
|
+
2. Find how my project moves the camera on scroll: search for useScroll / ScrollControls, ScrollTrigger or gsap timelines on camera.position, CatmullRomCurve3 or other curves, and useFrame code that sets camera.position or calls camera.lookAt. Also check for useCameraPath and camera-path.json.
|
|
820
|
+
3. If the project already uses useCameraPath with a JSON file, call save_camera_path with that file and stop.
|
|
821
|
+
4. Otherwise, change my camera code so it follows the keys: each key is a scroll percent with a camera position, a look-at target and a fov. Keep my code's structure (same library, same scroll source, same easing where possible): replace keyframe values, curve points or look-at targets with the new ones, adding or removing keyframes to match. If my code cannot express the path well, ask me whether to switch to useCameraPath(path) from depthview-r3f-bridge/camera-path with save_camera_path.
|
|
822
|
+
5. Tell me per key what changed in which file, and ask me to check it by scrolling the site.`},{name:"realism",title:"Make the scene look real",description:"Take the live three.js scene from first draft to a realistic, premium render: check, fix, tune, compare, save.",argument:{name:"goal",description:'The look you are after, e.g. "silver product shot on a dark blue background" or "warm sunset". Optional.'},text:e=>`Make my live three.js scene look realistic with the Depthview tools. Target look: ${e?.trim()||"a clean, premium product render (ask me if you need a direction)"}.
|
|
823
|
+
|
|
824
|
+
Work live first, write code last:
|
|
825
|
+
|
|
826
|
+
1. get_status, describe_scene, then take_screenshot view:"site" so you know what it looks like now.
|
|
827
|
+
2. get_realism. Tell me the score and the issues in one line each.
|
|
828
|
+
3. fix_realism for the one-click fixes. Then take_screenshot view:"site" compare:true and look at the result yourself.
|
|
829
|
+
4. Tune towards the target, one kind of change per step, a screenshot after each:
|
|
830
|
+
- World: set_look world. Pick the preset closest to the target (studio for metal and glass, softbox for bright product, sunset / overcast / night for mood), then move the light boxes: send the whole boxes list back with your change. A highlight sits where a box is mirrored in the surface, so turn the world (rotation) or move a box (azimuth, elevation) until the highlight falls where it flatters the shape. Big soft boxes make broad gradients; small bright ones make sharp glints.
|
|
831
|
+
- Surfaces: set_surface per object (find_objects for the names). Metal: metalness 1, roughness 0.1 to 0.4. Never roughness 0. Glass and clear coat need MeshPhysicalMaterial: if "notes" says so, change the material in the source.
|
|
832
|
+
- Edges: bevel amount 0.03 to 0.08 for hard-surface objects. More looks like a toy.
|
|
833
|
+
- Colour: AgX for natural highlights, ACES for contrast, Neutral when brand colours must stay exact. Then exposure, in steps of 0.1.
|
|
834
|
+
- Shadows: on, softness 3 to 5.
|
|
835
|
+
- Lens (needs the dev bridge): antialias and ambient occlusion on; bloom only if something is brighter than white, strength under 0.3; vignette under 0.35; grain under 0.2.
|
|
836
|
+
5. Read "notes" in every result: it says what the page could not do and what must change in the source. Issues that are not fixable live (materials that are Basic/Lambert, low segment counts, antialias:false, the output colour space) you fix in the code.
|
|
837
|
+
6. If lens effects are locked, offer to add the dev bridge: depthview-r3f-bridge as a dev dependency and depthviewVite() from "depthview-r3f-bridge/vite" in the Vite plugins. Ask before installing.
|
|
838
|
+
7. Frame rate: get_realism reports fps with the look and siteFps without it. If the look costs more than a fifth, measure_look_cost to see which part, then lighten_look (or switch that part off). Before saving, set_look performance { adaptive: true } so phones and slow laptops step the look down by themselves.
|
|
839
|
+
8. If I gave you a picture of the look I want (or dropped one into the inspector): compare_to_reference, apply the patch of the biggest difference with set_look, compare again. One change per round; stop when match stops rising.
|
|
840
|
+
9. If the scene needs detail that boxes and spheres cannot give: set_surface detail for a finish or an engraving; find_assets and import_asset for a real model or scanned texture (show me the candidates and ask before importing). After a model is in the scene: adapt_model with its name, tell me what it measured, and ask before scaling it or setting it on the ground.
|
|
841
|
+
10. When I say it looks right: save_look, then add the code from its "usage" to the project (ask before replacing my own lighting or effect code). Objects whose surface or bevel you set must have a name in the source.
|
|
842
|
+
11. For values I will keep tuning (a material's roughness, a light's strength, a speed), offer site controls: declare them with depthviewControls / useDepthviewControls from "depthview-r3f-bridge/controls", read the returned values where the scene uses them, and tell me they now show in the inspector under Realism > Your site's controls.
|
|
843
|
+
|
|
844
|
+
Stop after three rounds of tuning and show me before and after. Do not write lighting, environment or post-processing code by hand while the look can do it.`},{name:"build-site",title:"Build a 3D site",description:"Build a finished 3D page from nothing: subject, page, light, camera journey, reviewed until it is clean.",argument:{name:"brief",description:'What the site is for, e.g. "a landing page for a perfume called Noctua" or "a hero for a mechanical watch".'},text:e=>`Build a 3D site in this project with the Depthview tools. The brief: ${e?.trim()||"ask me what the site is for"}.
|
|
845
|
+
|
|
846
|
+
1. get_guide topic:"site-build" and follow it. Also "modeling" if there is no model file, and "threejs" before the first line of three.js. Check any import you are not sure of with three_docs.
|
|
847
|
+
2. Tell me in a few lines: the subject, the three materials, the palette, the journey (three to five stops, one line of copy each). Then build; do not wait for me unless I said I want to choose.
|
|
848
|
+
3. Build in this order: page and typography with a fixed canvas behind it, renderer and studio environment, the set (fog in the background colour, a glow behind the subject, a contact shadow), the subject, one camera key per section with the subject placed by camera.setViewOffset, the last pass, the phone layout, the reveal.
|
|
849
|
+
4. Start the dev server yourself, open_preview, get_errors, then review_site. Fix every high and medium issue in the source, reload, review again. Repeat until it is clean. Then answer its lookFor questions from the pictures and improve the weakest stop. Then review_site with phone: true.
|
|
850
|
+
5. audit_visuals with scroll: [0, 25, 50, 75, 100], audit_camera_motion, get_performance.
|
|
851
|
+
6. Show me the pictures of every stop. Tell me that I can now place the view of each section by hand in the Depthview extension (Camera views) and that you will read my views back with get_camera_views and write them into the camera keys.
|
|
852
|
+
|
|
853
|
+
Do not stop at a first draft: a first draft always has a glare, a horizon line or copy over the subject. The review finds them; fix them before you show me anything.`},{name:"new-scene",title:"Start a 3D page",description:"Start a 3D page from a working starter instead of an empty file, then make it yours.",argument:{name:"idea",description:'What the page is for, e.g. "hero for a silver watch" or "scroll story in three scenes".'},text:e=>`Start a 3D page in this project with the Depthview tools. What I want: ${e?.trim()||"ask me what the page is for"}.
|
|
854
|
+
|
|
855
|
+
1. Look at the project: is it React Three Fiber or plain three.js, where do pages live, which bundler? Check package.json for three (>= 0.160) and depthview-r3f-bridge; tell me what needs installing and ask before you install.
|
|
856
|
+
2. create_scene with the template that fits ("product-hero" for one object shown off, "scroll-journey" for several stops along a scroll) and the project's framework. Mount it with the code in "mount". With Vite, add depthviewVite() from "depthview-r3f-bridge/vite" to the plugins.
|
|
857
|
+
3. Ask me to start the dev server, open the page and click the Depthview icon. Then get_status and take_screenshot view:"site".
|
|
858
|
+
4. Make it mine, live first: replace the placeholder with a real model if I want one (find_assets, show me the candidates, import_asset after I pick), set_surface for materials and fine detail, set_look for the lighting and mood, edit_camera_path for the camera move. A screenshot after each step.
|
|
859
|
+
5. get_realism: the score, and the frame rate with and without the look. lighten_look if the look costs more than a fifth.
|
|
860
|
+
6. Write what I approved into the files the starter made: save_look into its look.json, save_camera_path into its camera-path.json, save_site_controls for the controls.
|
|
861
|
+
|
|
862
|
+
Keep the starter's structure: named objects, the look in look.json, the camera in camera-path.json, tunable values as controls.`},{name:"test",title:"Test the 3D page for visual bugs",description:"Audit the live scene for pixelation, blur, jagged edges, z-fighting, texture, colour and shadow bugs across the scroll and at phone size.",text:()=>`Test my live three.js page for visual bugs with the Depthview tools.
|
|
863
|
+
|
|
864
|
+
1. get_status, describe_scene, get_errors (anything that failed to compile or threw).
|
|
865
|
+
2. audit_visuals with scroll: [0, 25, 50, 75, 100]. For every high and medium issue tell me in one line: what is wrong, the measured evidence, and where on the scroll it shows.
|
|
866
|
+
3. Confirm before you fix: where an issue has tryLive, run it, then take_screenshot view:"site" compare:true. Say whether the picture really changed.
|
|
867
|
+
4. Phone check: set_viewport { width: 500, height: 900, pixelRatio: 3 }, audit_visuals again, get_performance, then set_viewport { reset: true }.
|
|
868
|
+
5. get_performance at the heaviest scroll position. An issue that costs frames goes on the list.
|
|
869
|
+
6. If the camera follows the scroll: audit_camera_motion. Report the score, each issue with its scroll range, and take_screenshot at its checkAt stops to judge framing.
|
|
870
|
+
7. Give me the list, worst first: issue, cause, the exact source change. Fix nothing in the source until I say which ones. Leave the page as you found it (scroll, viewport, time).`},{name:"effect",title:"Add an effect",description:"Add particles, smoke, clouds, fog or a custom shader effect to the live scene, tune it, and write it into the project.",argument:{name:"what",description:'The effect, e.g. "slow dust in the light beam", "low fog over the ground", "embers rising from the fire".'},text:e=>`Add an effect to my live three.js scene with the Depthview tools: ${e?.trim()||"ask me what effect I want"}.
|
|
871
|
+
|
|
872
|
+
1. get_status, describe_scene (the scale decides every size), take_screenshot view:"site". get_guide topic "particles" or "volumetrics" if you have not read it in this session.
|
|
873
|
+
2. list_effects, then add_effect with the closest kind and preset. Place it with position and scale so it sits where the effect belongs: around the subject for dust, on the ground for fog, behind the subject for clouds.
|
|
874
|
+
3. Tune with set_effect, one kind of change per step, and take_screenshot view:"site" compare:true after each. Keep it subtle: an effect should be noticed second, after the subject. If no preset can do it, write the GLSL yourself (kind "custom", or set_effect with vertex / fragment).
|
|
875
|
+
4. get_performance before and after. If it costs more than a fifth of the frame rate: fewer sprites, fewer steps (uSteps), a smaller box.
|
|
876
|
+
5. Show me before and after. When I say it is right: get_effect_code in my project's framework, write the file, mount it, and remove the live one with reset_changes.`},{name:"performance",title:"Check scene performance",description:"Measure the scene and find what costs the most.",text:()=>"Check the performance of my live three.js scene: get_performance, get_resources and get_lighting. Name the three biggest costs with numbers, and for each one the change you would make. Try a fix live only if it is a value change, measure again with get_performance, and put it back with undo_change unless I say keep it."}];import{existsSync as Wt,mkdirSync as Er,realpathSync as $r,writeFileSync as jr}from"node:fs";import{relative as Bt,resolve as Ee,sep as Ze}from"node:path";var pr={top:"#2b2f38",horizon:"#3c4048",ground:"#15161a",intensity:1};function mr(){return{version:1,color:{toneMapping:"site",exposure:null},quality:{pixelRatio:null,anisotropy:!1,supersample:!1},world:{preset:"site",strength:1,rotation:0,background:!1,sky:{...pr},boxes:[]},shadows:{mode:"site",softness:3,resolution:2048},materials:[],bevel:{mode:"off",amount:.06,segments:4,targets:[]},effects:{antialias:!1,ao:{on:!1,intensity:1,radius:.5},bloom:{on:!1,strength:.15,threshold:1.1,radius:.4},dof:{on:!1,focus:8,aperture:8e-4,maxBlur:.008},vignette:0,grain:0},performance:{adaptive:!1,targetFps:60},adapt:{follow:!0,textures:!1},models:[]}}var L=(e,t,o,r,n,i,a,l="#ffffff",h=.35)=>({id:e,name:t,azimuth:o,elevation:r,width:n,height:i,intensity:a,color:l,softness:h}),fr={studio:{label:"Studio",hint:"Dark room, three softboxes: the product-shot look for metal and glass.",sky:{top:"#1b1d22",horizon:"#2a2d34",ground:"#0c0d10",intensity:1},boxes:[L("key","Key",-42,34,62,44,7,"#fff4e6"),L("fill","Fill",62,12,58,70,2.2,"#dfeaff",.6),L("rim","Rim",158,26,34,80,6,"#ffffff",.25),L("top","Top",0,86,80,80,3,"#ffffff",.5),L("front","Front card",0,4,150,80,1.1,"#eef1f6",1)]},softbox:{label:"Softbox",hint:"Bright, even light from all sides: clean e-commerce product.",sky:{top:"#a9adb5",horizon:"#c3c6cc",ground:"#55575c",intensity:1},boxes:[L("top","Top",0,88,120,120,3.2,"#ffffff",.7),L("left","Left",-75,10,70,90,2.4,"#ffffff",.6),L("right","Right",75,10,70,90,2.4,"#ffffff",.6)]},sunset:{label:"Sunset",hint:"Low warm sun, deep blue sky.",sky:{top:"#16264d",horizon:"#e2854a",ground:"#1c1410",intensity:1.1},boxes:[L("sun","Sun",-58,7,10,10,40,"#ffb469",.5),L("glow","Glow",-58,6,70,30,2.5,"#ff9a5c",1),L("sky","Sky fill",120,40,90,70,.9,"#7fa2ff",1)]},overcast:{label:"Overcast",hint:"Soft daylight with no direct sun: matte, honest materials.",sky:{top:"#c9d2dc",horizon:"#aab3bd",ground:"#3a3b3d",intensity:1.15},boxes:[L("zenith","Sky",0,80,150,150,1.4,"#eef3ff",1)]},night:{label:"Night",hint:"Dark blue world, a cool moon and one warm accent.",sky:{top:"#050a18",horizon:"#101b33",ground:"#04050a",intensity:1},boxes:[L("moon","Moon",-35,48,26,26,6,"#bcd4ff",.4),L("accent","Accent",110,6,26,40,3.5,"#ff9a4a",.6),L("rim","Rim",170,22,28,70,2.2,"#8fb4ff",.4)]}};var $=(e,t,o,r)=>typeof e=="number"&&Number.isFinite(e)?Math.min(r,Math.max(o,e)):t,Se=(e,t)=>typeof e=="string"&&/^#[0-9a-fA-F]{6}$/.test(e)?e.toLowerCase():t,he=(e,t,o)=>typeof e=="string"&&t.includes(e)?e:o,M=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},_e=(e,t,o)=>typeof e=="number"&&Number.isFinite(e)?Math.min(o,Math.max(t,e)):void 0,gr=["site","none","linear","reinhard","cineon","aces","agx","neutral"],vr=["site","studio","softbox","sunset","overcast","night"],wr=["custom","polished-metal","brushed-metal","gold","car-paint","glass","plastic","ceramic","rubber"],br=["brushed","rings","hammered","knurl","text"],yr={brushed:60,rings:14,hammered:18,knurl:40,text:1},xr={brushed:.3,rings:.8,hammered:.55,knurl:.7,text:1};function kr(e,t){let o=M(e);return{id:typeof o.id=="string"&&o.id?o.id.slice(0,40):`box${t+1}`,name:typeof o.name=="string"&&o.name?o.name.slice(0,40):`Light ${t+1}`,azimuth:$(o.azimuth,0,-360,360),elevation:$(o.elevation,30,-90,90),width:$(o.width,40,1,180),height:$(o.height,40,1,180),intensity:$(o.intensity,4,0,100),color:Se(o.color,"#ffffff"),softness:$(o.softness,.35,0,1)}}function Sr(e){let t=M(e),o=typeof t.name=="string"?t.name.slice(0,128):"",r=typeof t.uuid=="string"?t.uuid.slice(0,64):void 0;if(!o&&!r)return null;let n={name:o,preset:he(t.preset,wr,"custom")};r&&(n.uuid=r),typeof t.color=="string"&&/^#[0-9a-fA-F]{6}$/.test(t.color)&&(n.color=t.color.toLowerCase());let i=[["metalness",0,1],["roughness",0,1],["clearcoat",0,1],["clearcoatRoughness",0,1],["transmission",0,1],["ior",1,2.333],["thickness",0,100],["envMapIntensity",0,10]];for(let[l,h,u]of i){let p=_e(t[l],h,u);p!==void 0&&(n[l]=p)}let a=M(t.detail);return typeof a.pattern=="string"&&br.includes(a.pattern)&&(n.detail={pattern:a.pattern,strength:$(a.strength,xr[a.pattern],0,2),scale:$(a.scale,yr[a.pattern],1,200)},typeof a.text=="string"&&a.text.trim()&&(n.detail.text=a.text.slice(0,120))),n}function _r(e){let t=M(e),o=typeof t.name=="string"?t.name.slice(0,128):"",r=typeof t.uuid=="string"?t.uuid.slice(0,64):void 0;if(!o&&!r)return null;let n=_e(t.scale,1e-4,1e4),i=_e(t.lift,-1e5,1e5),a=_e(t.reflection,0,10),l={...r?{uuid:r}:{},name:o};return n!==void 0&&Math.abs(n-1)>1e-9&&(l.scale=n),i!==void 0&&Math.abs(i)>1e-9&&(l.lift=i),a!==void 0&&Math.abs(a-1)>1e-9&&(l.reflection=a),l.scale===void 0&&l.lift===void 0&&l.reflection===void 0?null:l}function ue(e){let t=mr(),o=M(e),r=M(o.color),n=M(o.quality),i=M(o.world),a=M(i.sky),l=M(o.shadows),h=M(o.bevel),u=M(o.effects),p=M(u.ao),f=M(u.bloom),v=M(u.dof),x=M(o.performance),b=M(o.adapt),S=he(i.preset,vr,"site"),w=S==="site"?null:fr[S],j=(Array.isArray(h.targets)?h.targets:[]).map(c=>M(c)).filter(c=>typeof c.name=="string"||typeof c.uuid=="string").slice(0,200).map(c=>({...typeof c.uuid=="string"?{uuid:c.uuid.slice(0,64)}:{},name:typeof c.name=="string"?c.name.slice(0,128):""}));return{version:1,color:{toneMapping:he(r.toneMapping,gr,"site"),exposure:r.exposure===null||r.exposure===void 0?null:$(r.exposure,1,0,10)},quality:{pixelRatio:n.pixelRatio===null||n.pixelRatio===void 0?null:$(n.pixelRatio,2,.5,3),anisotropy:n.anisotropy===!0,supersample:n.supersample===!0},world:{preset:S,strength:$(i.strength,1,0,10),rotation:$(i.rotation,0,-360,360),background:i.background===!0,sky:{top:Se(a.top,w?.sky.top??t.world.sky.top),horizon:Se(a.horizon,w?.sky.horizon??t.world.sky.horizon),ground:Se(a.ground,w?.sky.ground??t.world.sky.ground),intensity:$(a.intensity,w?.sky.intensity??1,0,10)},boxes:Array.isArray(i.boxes)?i.boxes.slice(0,12).map(kr):w?.boxes.map(c=>({...c}))??[]},shadows:{mode:he(l.mode,["site","on","off"],"site"),softness:$(l.softness,t.shadows.softness,0,10),resolution:[1024,2048,4096].includes(l.resolution)?l.resolution:t.shadows.resolution},materials:(Array.isArray(o.materials)?o.materials:[]).map(Sr).filter(c=>c!==null).slice(0,200),bevel:{mode:he(h.mode,["off","all","selected"],"off"),amount:$(h.amount,t.bevel.amount,0,.5),segments:Math.round($(h.segments,t.bevel.segments,1,8)),targets:j},effects:{antialias:u.antialias===!0,ao:{on:p.on===!0,intensity:$(p.intensity,t.effects.ao.intensity,0,3),radius:$(p.radius,t.effects.ao.radius,.01,5)},bloom:{on:f.on===!0,strength:$(f.strength,t.effects.bloom.strength,0,3),threshold:$(f.threshold,t.effects.bloom.threshold,0,5),radius:$(f.radius,t.effects.bloom.radius,0,1)},dof:{on:v.on===!0,focus:$(v.focus,t.effects.dof.focus,.01,1e4),aperture:$(v.aperture,t.effects.dof.aperture,0,.01),maxBlur:$(v.maxBlur,t.effects.dof.maxBlur,0,.05)},vignette:$(u.vignette,0,0,1),grain:$(u.grain,0,0,1)},performance:{adaptive:x.adaptive===!0,targetFps:[30,45,60].includes(x.targetFps)?x.targetFps:60},adapt:{follow:b.follow!==!1,textures:b.textures===!0},models:(Array.isArray(o.models)?o.models:[]).map(_r).filter(c=>c!==null).slice(0,200)}}var Pn=Math.PI/180;var Tr=new Float32Array(1),Dn=new Uint32Array(Tr.buffer);var Fn=4*2048*2048;function Te(e){let t=ue(e);return{...t,materials:t.materials.filter(o=>o.name).map(({uuid:o,...r})=>r),bevel:{...t.bevel,targets:t.bevel.targets.filter(o=>o.name).map(o=>({name:o.name}))},models:t.models.filter(o=>o.name).map(({uuid:o,...r})=>r)}}var Qe={color:"#b9bec6",metalness:1,roughness:.32},Y={color:"#0d0f14",metalness:0,roughness:.92},Ut=e=>ue({version:1,color:{toneMapping:"agx",exposure:1.05},quality:{pixelRatio:2,anisotropy:!0,supersample:!0},world:{preset:"studio",strength:1.1,rotation:15},shadows:{mode:"on",softness:4,resolution:2048},bevel:{mode:"all",amount:.06,segments:4},materials:e,performance:{adaptive:!0,targetFps:60}}),de={"product-hero":{title:"Product hero",description:'One product on a pedestal under studio light, with a camera that moves around it as the page scrolls. Swap the "Product" box for your model.',pieces:[{name:"Floor",geometry:"Circle",args:[9,96],position:[0,0,0],rotation:[-Math.PI/2,0,0],material:Y,receive:!0},{name:"Pedestal",geometry:"Cylinder",args:[1.6,1.6,.5,96],position:[0,.25,0],material:{physical:!0,color:"#2a2e37",metalness:.1,roughness:.35,clearcoat:.6},cast:!0,receive:!0},{name:"Product",geometry:"Box",args:[1.15,1.7,1.15],position:[0,1.4,0],rotation:[0,.6,0],material:Qe,cast:!0,receive:!0,hero:!0},{name:"Block left",geometry:"Box",args:[.7,.7,.7],position:[-2.4,.35,.6],rotation:[0,.4,0],material:Y,cast:!0,receive:!0},{name:"Block right",geometry:"Box",args:[.5,1.1,.5],position:[2.5,.55,-.4],rotation:[0,-.3,0],material:Y,cast:!0,receive:!0}],light:{position:[3.5,6,4],intensity:2.2},camera:{fov:35},path:[{percent:0,position:[0,2.2,8],target:[0,1.3,0],fov:35},{percent:50,position:[5.5,2.6,4],target:[0,1.4,0],fov:35},{percent:100,position:[2.2,4.4,-4.2],target:[0,1.2,0],fov:35}],look:Ut([{name:"Product",preset:"custom",detail:{pattern:"brushed",strength:.16,scale:60}}]),controls:{group:"Product",roughness:.32,spin:.15}},"scroll-journey":{title:"Scroll journey",description:"Three stations in a row and a camera that travels from one to the next as the page scrolls: one station per section of the page.",pieces:[{name:"Floor",geometry:"Box",args:[26,.2,9],position:[0,-.1,0],material:Y,receive:!0},{name:"Station 1",geometry:"Cylinder",args:[1.3,1.3,.4,64],position:[-7,.2,0],material:Y,cast:!0,receive:!0},{name:"Piece 1",geometry:"Box",args:[1.2,1.2,1.2],position:[-7,1.2,0],rotation:[0,.7,0],material:Qe,cast:!0,receive:!0,hero:!0},{name:"Station 2",geometry:"Cylinder",args:[1.3,1.3,.4,64],position:[0,.2,0],material:Y,cast:!0,receive:!0},{name:"Piece 2",geometry:"Cylinder",args:[.7,.7,1.6,64],position:[0,1.2,0],material:{...Qe,color:"#d8b47a"},cast:!0,receive:!0},{name:"Station 3",geometry:"Cylinder",args:[1.3,1.3,.4,64],position:[7,.2,0],material:Y,cast:!0,receive:!0},{name:"Piece 3",geometry:"Icosahedron",args:[.85,6],position:[7,1.3,0],material:{physical:!0,color:"#9fb8ff",metalness:.2,roughness:.15,clearcoat:1},cast:!0,receive:!0}],light:{position:[2,7,5],intensity:2.2},camera:{fov:38},path:[{percent:0,position:[-7,2.2,6.5],target:[-7,1.1,0],fov:38},{percent:25,position:[-3.5,3.4,6],target:[-3.5,1,0],fov:38},{percent:50,position:[0,2,5.5],target:[0,1.1,0],fov:38},{percent:75,position:[3.5,3.4,6],target:[3.5,1,0],fov:38},{percent:100,position:[7,2.2,6.5],target:[7,1.2,0],fov:38}],look:Ut([{name:"Piece 1",preset:"custom",detail:{pattern:"brushed",strength:.16,scale:60}},{name:"Piece 2",preset:"custom",detail:{pattern:"knurl",strength:.6,scale:30}}]),controls:{group:"Piece 1",roughness:.32,spin:.2}}},P=e=>String(Math.round(e*1e3)/1e3),U=e=>e.map(P).join(", "),ae=e=>e.split(/[^A-Za-z0-9]+/).filter(Boolean).map((o,r)=>r===0?o.toLowerCase():o[0].toUpperCase()+o.slice(1)).join("");function Rr(e){let t=e.pieces.find(n=>n.hero),o=[];for(let n of e.pieces){let i=ae(n.name),a=n.material,l=[`color: '${a.color}'`,`metalness: ${P(a.metalness)}`,`roughness: ${n.hero?"controls.roughness":P(a.roughness)}`,...a.clearcoat!==void 0?[`clearcoat: ${P(a.clearcoat)}`]:[]].join(", ");o.push(` const ${i} = new THREE.Mesh(`,` new THREE.${n.geometry}Geometry(${U(n.args)}),`,` new THREE.Mesh${a.physical?"Physical":"Standard"}Material({ ${l} }),`," );",` ${i}.name = '${n.name}';`,` ${i}.position.set(${U(n.position)});`,...n.rotation?[` ${i}.rotation.set(${U(n.rotation)});`]:[],...n.cast?[` ${i}.castShadow = true;`]:[],...n.receive?[` ${i}.receiveShadow = true;`]:[],` scene.add(${i});`)}let r=ae(t.name);return`import * as THREE from 'three';
|
|
877
|
+
import { depthviewControls } from 'depthview-r3f-bridge/controls';
|
|
878
|
+
import { applyLook } from 'depthview-r3f-bridge/look';
|
|
879
|
+
import { evaluatePath, pathKeys } from 'depthview-r3f-bridge/path';
|
|
880
|
+
import cameraPath from './camera-path.json';
|
|
881
|
+
import look from './look.json';
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* ${e.title}. ${e.description}
|
|
885
|
+
*
|
|
886
|
+
* Started with Depthview. Open the page, click the Depthview icon, and tune everything live:
|
|
887
|
+
* the Realism tab edits look.json, "Edit camera path" edits camera-path.json, and the controls
|
|
888
|
+
* declared below show up under "Your site's controls".
|
|
889
|
+
*/
|
|
890
|
+
export function createScene(canvas: HTMLCanvasElement): () => void {
|
|
891
|
+
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
|
|
892
|
+
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
|
893
|
+
const scene = new THREE.Scene();
|
|
894
|
+
const camera = new THREE.PerspectiveCamera(${P(e.camera.fov)}, 1, 0.1, 100);
|
|
895
|
+
|
|
896
|
+
// Values worth tuning by eye. Change them in the inspector, then "Save to code".
|
|
897
|
+
const controls = depthviewControls('${e.controls.group}', {
|
|
898
|
+
roughness: { value: ${P(e.controls.roughness)}, min: 0.05, max: 1 },
|
|
899
|
+
spin: { value: ${P(e.controls.spin)}, min: 0, max: 2, label: 'Spin speed' },
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
${o.join(`
|
|
903
|
+
`)}
|
|
904
|
+
|
|
905
|
+
const keyLight = new THREE.DirectionalLight('#ffffff', ${P(e.light.intensity)});
|
|
906
|
+
keyLight.name = 'Key light';
|
|
907
|
+
keyLight.position.set(${U(e.light.position)});
|
|
908
|
+
scene.add(keyLight);
|
|
909
|
+
|
|
910
|
+
// Colour, studio lighting, soft shadows, bevels and surface detail: all from look.json.
|
|
911
|
+
const applied = applyLook({ renderer, scene, camera }, look);
|
|
912
|
+
|
|
913
|
+
const resize = (): void => {
|
|
914
|
+
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
|
|
915
|
+
camera.aspect = canvas.clientWidth / Math.max(1, canvas.clientHeight);
|
|
916
|
+
camera.updateProjectionMatrix();
|
|
917
|
+
};
|
|
918
|
+
window.addEventListener('resize', resize);
|
|
919
|
+
resize();
|
|
920
|
+
|
|
921
|
+
// The camera follows camera-path.json as the page scrolls.
|
|
922
|
+
const keys = pathKeys(cameraPath);
|
|
923
|
+
const scrolled = (): number => {
|
|
924
|
+
const el = document.scrollingElement ?? document.documentElement;
|
|
925
|
+
const max = el.scrollHeight - el.clientHeight;
|
|
926
|
+
return max > 0 ? Math.min(1, Math.max(0, el.scrollTop / max)) : 0;
|
|
927
|
+
};
|
|
928
|
+
// (THREE.Clock is deprecated since r183; THREE.Timer is not in every version this supports.)
|
|
929
|
+
let last = performance.now();
|
|
930
|
+
renderer.setAnimationLoop((now: number) => {
|
|
931
|
+
const dt = Math.min((now - last) / 1000, 0.05);
|
|
932
|
+
last = now;
|
|
933
|
+
const pose = evaluatePath(keys, scrolled() * 100);
|
|
934
|
+
if (pose) {
|
|
935
|
+
camera.position.set(...pose.position);
|
|
936
|
+
camera.lookAt(...pose.target);
|
|
937
|
+
if (camera.fov !== pose.fov) {
|
|
938
|
+
camera.fov = pose.fov;
|
|
939
|
+
camera.updateProjectionMatrix();
|
|
1123
940
|
}
|
|
1124
|
-
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1125
|
-
const mcp = buildMcpServer(this, { includePairingCode: false });
|
|
1126
|
-
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
|
|
1127
|
-
res.on("close", () => {
|
|
1128
|
-
void transport.close();
|
|
1129
|
-
void mcp.close();
|
|
1130
|
-
});
|
|
1131
|
-
await mcp.connect(transport);
|
|
1132
|
-
await transport.handleRequest(req, res, body);
|
|
1133
|
-
} catch (err) {
|
|
1134
|
-
if (!res.headersSent)
|
|
1135
|
-
json(400, {
|
|
1136
|
-
jsonrpc: "2.0",
|
|
1137
|
-
error: { code: -32700, message: err instanceof Error ? err.message : "Bad request" },
|
|
1138
|
-
id: null
|
|
1139
|
-
});
|
|
1140
941
|
}
|
|
1141
|
-
|
|
1142
|
-
};
|
|
942
|
+
${r}.rotation.y += dt * controls.spin;
|
|
943
|
+
${r}.material.roughness = controls.roughness;
|
|
944
|
+
applied.render();
|
|
945
|
+
});
|
|
1143
946
|
|
|
1144
|
-
|
|
1145
|
-
|
|
947
|
+
return () => {
|
|
948
|
+
renderer.setAnimationLoop(null);
|
|
949
|
+
window.removeEventListener('resize', resize);
|
|
950
|
+
applied.dispose();
|
|
951
|
+
renderer.dispose();
|
|
952
|
+
};
|
|
953
|
+
}
|
|
954
|
+
`}function Mr(e){let t=e.pieces.find(i=>i.hero),o=(i,a)=>{let l=i.material,h=`mesh${l.physical?"Physical":"Standard"}Material`,u=`${i.geometry[0].toLowerCase()}${i.geometry.slice(1)}Geometry`;return[" <mesh",...a?[" ref={ref}"]:[],` name="${i.name}"`,` position={[${U(i.position)}]}`,...i.rotation?[` rotation={[${U(i.rotation)}]}`]:[],...i.cast?[" castShadow"]:[],...i.receive?[" receiveShadow"]:[]," >",` <${u} args={[${U(i.args)}]} />`,` <${h} color="${l.color}" metalness={${P(l.metalness)}} roughness={${a?"roughness":P(l.roughness)}}${l.clearcoat!==void 0?` clearcoat={${P(l.clearcoat)}}`:""} />`," </mesh>"].join(`
|
|
955
|
+
`)},r=e.pieces.filter(i=>!i.hero).map(i=>o(i,!1).replace(/^ {2}/gm,"")),n=e.path[0];return`import { Canvas, useFrame } from '@react-three/fiber';
|
|
956
|
+
import { useRef } from 'react';
|
|
957
|
+
import type { Mesh } from 'three';
|
|
958
|
+
import { CameraPath } from 'depthview-r3f-bridge/camera-path';
|
|
959
|
+
import { useDepthviewControls } from 'depthview-r3f-bridge/controls/react';
|
|
960
|
+
import { DepthviewLook } from 'depthview-r3f-bridge/look/react';
|
|
961
|
+
import cameraPath from './camera-path.json';
|
|
962
|
+
import look from './look.json';
|
|
963
|
+
|
|
964
|
+
/**
|
|
965
|
+
* ${e.title}. ${e.description}
|
|
966
|
+
*
|
|
967
|
+
* Started with Depthview. Open the page, click the Depthview icon, and tune everything live:
|
|
968
|
+
* the Realism tab edits look.json, "Edit camera path" edits camera-path.json, and the controls
|
|
969
|
+
* declared below show up under "Your site's controls".
|
|
970
|
+
*/
|
|
971
|
+
function ${ae(t.name)[0].toUpperCase()+ae(t.name).slice(1)}() {
|
|
972
|
+
// Values worth tuning by eye. Change them in the inspector, then "Save to code".
|
|
973
|
+
const { roughness, spin } = useDepthviewControls('${e.controls.group}', {
|
|
974
|
+
roughness: { value: ${P(e.controls.roughness)}, min: 0.05, max: 1 },
|
|
975
|
+
spin: { value: ${P(e.controls.spin)}, min: 0, max: 2, label: 'Spin speed' },
|
|
976
|
+
});
|
|
977
|
+
const ref = useRef<Mesh>(null);
|
|
978
|
+
useFrame((_, dt) => {
|
|
979
|
+
if (ref.current) ref.current.rotation.y += Math.min(dt, 0.05) * spin;
|
|
980
|
+
});
|
|
981
|
+
return (
|
|
982
|
+
${o(t,!0).replace(/^ {2}/gm,"")}
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
export function Scene() {
|
|
987
|
+
return (
|
|
988
|
+
<Canvas
|
|
989
|
+
shadows
|
|
990
|
+
dpr={[1, 2]}
|
|
991
|
+
gl={{ antialias: true, alpha: true }}
|
|
992
|
+
camera={{ fov: ${P(e.camera.fov)}, near: 0.1, far: 100, position: [${U(n.position)}] }}
|
|
993
|
+
style={{ position: 'fixed', inset: 0 }}
|
|
994
|
+
>
|
|
995
|
+
<${ae(t.name)[0].toUpperCase()+ae(t.name).slice(1)} />
|
|
996
|
+
${r.join(`
|
|
997
|
+
`)}
|
|
998
|
+
<directionalLight name="Key light" position={[${U(e.light.position)}]} intensity={${P(e.light.intensity)}} />
|
|
999
|
+
{/* The camera follows camera-path.json as the page scrolls. */}
|
|
1000
|
+
<CameraPath path={cameraPath} />
|
|
1001
|
+
{/* Colour, studio lighting, soft shadows, bevels and surface detail: all from look.json. */}
|
|
1002
|
+
<DepthviewLook look={look} />
|
|
1003
|
+
</Canvas>
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
`}function Cr(e,t){let o=de[e],r=o.path.length,n={"look.json":`${JSON.stringify(Te(o.look),null,2)}
|
|
1007
|
+
`,"camera-path.json":`${JSON.stringify({version:1,keys:o.path},null,2)}
|
|
1008
|
+
`};return t==="three"?(n["scene.ts"]=Rr(o),{files:n,mount:`<!-- A fixed canvas behind the page, and enough page to scroll through (${r} screens). -->
|
|
1009
|
+
<canvas id="scene" style="position: fixed; inset: 0; width: 100%; height: 100%"></canvas>
|
|
1010
|
+
<main style="position: relative; height: ${r*100}vh"><!-- your sections --></main>
|
|
1011
|
+
<script type="module">
|
|
1012
|
+
import { createScene } from './scene.ts';
|
|
1013
|
+
createScene(document.getElementById('scene'));
|
|
1014
|
+
</script>`}):(n["Scene.tsx"]=Mr(o),{files:n,mount:`// The canvas is fixed behind the page; give the page ${r} screens to scroll through.
|
|
1015
|
+
import { Scene } from './Scene';
|
|
1016
|
+
|
|
1017
|
+
<>
|
|
1018
|
+
<Scene />
|
|
1019
|
+
<main style={{ position: 'relative', height: '${r*100}vh' }}>{/* your sections */}</main>
|
|
1020
|
+
</>`})}function Ht(e,t,o,r){let n=$r(e),i=r?.trim()||(Wt(Ee(n,"src"))?`src/${t}`:t),a=Ee(n,i);if(!a.startsWith(n+Ze))throw new Error("Folder is outside the project root");if(a.split(Ze).includes("node_modules"))throw new Error("Scenes are not written into node_modules");let{files:l,mount:h}=Cr(t,o),u=Object.keys(l).filter(f=>Wt(Ee(a,f)));if(u.length)throw new Error(`${Bt(n,a)} already has ${u.join(", ")}. Nothing was written: choose another folder.`);Er(a,{recursive:!0});for(let[f,v]of Object.entries(l))jr(Ee(a,f),v);let p=Bt(n,a).split(Ze).join("/");return{folder:p,files:Object.keys(l).map(f=>`${p}/${f}`),mount:h,title:de[t].title,description:de[t].description}}import{existsSync as Jt,mkdirSync as Ar,readFileSync as $e,readdirSync as Lr,statSync as Pr,writeFileSync as Dr}from"node:fs";import{tmpdir as Fr}from"node:os";import{dirname as Or,join as H,relative as tt,sep as ot}from"node:path";function Xt(e){let t=e;for(let o=0;o<8;o++){let r=H(t,"node_modules","three"),n=H(r,"package.json");if(Jt(n))try{let a=String(JSON.parse($e(n,"utf8")).version);return{dir:r,version:a,revision:a.split(".")[1]??""}}catch{return null}let i=Or(t);if(i===t)break;t=i}return null}var Vt=new Map;function rt(e,t,o=0){if(o>6)return;let r;try{r=Lr(e)}catch{return}for(let n of r){let i=H(e,n),a;try{a=Pr(i)}catch{continue}if(a.isDirectory()){if(n==="libs"||n==="node_modules")continue;rt(i,t,o+1)}else n.endsWith(".js")&&!n.endsWith(".min.js")&&t.push(i)}}function Kt(e){let t=Vt.get(e.dir);if(t)return t;let o=[],r=[];rt(H(e.dir,"src"),r);for(let i of r){let a=tt(H(e.dir,"src"),i).split(ot).join("/"),l=a.split("/").pop().replace(/\.js$/,""),h=a.startsWith("nodes/")||a.startsWith("renderers/common/")||a.startsWith("renderers/webgpu/")||a.startsWith("materials/nodes/");o.push({name:l,file:i,from:h?"three/webgpu":"three"})}let n=[];rt(H(e.dir,"examples","jsm"),n);for(let i of n){let a=tt(H(e.dir,"examples","jsm"),i).split(ot).join("/");o.push({name:a.split("/").pop().replace(/\.js$/,""),file:i,from:`three/addons/${a}`})}return Vt.set(e.dir,o),o}var zr=e=>e.replace(/^\s*\/\*\*?/,"").replace(/\*\/\s*$/,"").split(`
|
|
1021
|
+
`).map(t=>t.replace(/^\s*\* ?/,"")).join(`
|
|
1022
|
+
`).trim();function Gt(e){let t=[],o=/\/\*\*[\s\S]*?\*\//g,r;for(;r=o.exec(e);){let i=e.slice(r.index+r[0].length,r.index+r[0].length+400).split(`
|
|
1023
|
+
`).find(h=>h.trim().length>0)?.trim()??"",a=zr(r[0]);if(!a||/^@(private|ignore)\b/m.test(a))continue;let l;(l=/^(?:export\s+(?:default\s+)?)?class\s+(\w+)/.exec(i))?t.push({name:l[1],kind:"class",signature:i.replace(/\s*\{\s*$/,""),doc:a}):(l=/^constructor\s*\(([^)]*)\)/.exec(i))?t.push({name:"constructor",kind:"constructor",signature:`constructor(${l[1].trim()})`,doc:a}):(l=/^this\.(\w+)\s*=\s*([^;]*)/.exec(i))?!l[1].startsWith("_")&&!/^is[A-Z]/.test(l[1])&&t.push({name:l[1],kind:"property",signature:`${l[1]} = ${l[2].trim().slice(0,60)}`,doc:a}):(l=/^(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)/.exec(i))?t.push({name:l[1],kind:"function",signature:`${l[1]}(${l[2].trim()})`,doc:a}):(l=/^export\s+const\s+(\w+)\s*=\s*([^;]*)/.exec(i))?t.push({name:l[1],kind:"constant",signature:`${l[1]} = ${l[2].trim().slice(0,40)}`,doc:a}):(l=/^(?:static\s+)?(?:async\s+)?(?:get\s+|set\s+)?(\w+)\s*\(([^)]*)\)\s*\{/.exec(i))&&!l[1].startsWith("_")&&!["if","for","while","switch"].includes(l[1])&&t.push({name:l[1],kind:"method",signature:`${l[1]}(${l[2].trim()})`,doc:a})}return t}var Ir=e=>{let t=e.split(/\n\s*@/)[0].replace(/\s+/g," ").trim(),o=t.search(/\.(\s|$)/);return(o>0?t.slice(0,o+1):t).slice(0,220)},qt=(e,t)=>new RegExp(`@${t}\\s+([^\\n]*)`).exec(e)?.[1]?.trim();function et(e){let t={name:e.name,kind:e.kind};e.signature&&(t.signature=e.signature);let o=Ir(e.doc);o&&(t.summary=o);let r=qt(e.doc,"type");r&&(t.type=r);let n=qt(e.doc,"default");n&&(t.default=n);let i=/@deprecated\s*([^\n]*)/.exec(e.doc);return i&&(t.deprecated=i[1].trim()||!0),t}function Yt(e,t,o={}){let r=Kt(e),n=t.trim(),i=r.filter(w=>w.name===n),a=i.length?i:r.filter(w=>w.name.toLowerCase()===n.toLowerCase());if(!a.length){let w=[],j=new RegExp(`export\\s+(?:const|function|class)\\s+${n.replace(/[^\w]/g,"")}\\b`);for(let d of r){if(w.length>=3)break;let m;try{m=$e(d.file,"utf8")}catch{continue}if(!j.test(m))continue;let g=Gt(m).find(y=>y.name===n);w.push({from:d.from,module:d.name,...g?{...et(g),doc:g.doc}:{}})}if(w.length)return{three:e.version,name:n,exports:w};let c=r.filter(d=>d.name.toLowerCase().includes(n.toLowerCase())).slice(0,20).map(d=>({name:d.name,from:d.from}));return{three:e.version,name:n,found:!1,message:`three ${e.version} has no "${n}". It may have been renamed or removed: do not use it.`,...c.length?{similar:c}:{}}}a.sort((w,j)=>(w.from==="three"?0:1)-(j.from==="three"?0:1));let l=a[0],h=$e(l.file,"utf8"),u=Gt(h),p=u.find(w=>w.kind==="class"&&w.name===l.name)??u.find(w=>w.kind==="class"),f=/export\s+default\s/.test(h),v={three:e.version,name:l.name,import:l.from==="three"||l.from==="three/webgpu"?`import { ${l.name} } from '${l.from}';`:`import { ${l.name} } from '${l.from}';${f?" // check: this module has a default export":""}`,file:tt(e.dir,l.file).split(ot).join("/")};a.length>1&&(v.alsoIn=a.slice(1).map(w=>w.from));let x=/class\s+\w+\s+extends\s+(\w+)/.exec(h);x&&(v.extends=`${x[1]} (its members apply too: look it up for them)`);let b=[...h.matchAll(/@deprecated[^\n]*|has been (?:deprecated|removed|renamed)[^\n'"`]*/g)].map(w=>w[0].trim()).slice(0,8);if(b.length&&(v.deprecations=[...new Set(b)]),o.full)return v.source=h.length>4e4?`${h.slice(0,4e4)}
|
|
1024
|
+
\u2026 (cut at 40 000 characters)`:h,v;if(o.member){let w=u.filter(j=>j.name===o.member);return w.length?(v.members=w.map(j=>({...et(j),doc:j.doc})),v):{...v,message:`No documented member "${o.member}". Members: ${u.map(j=>j.name).join(", ")}`}}p&&(v.description=p.doc.slice(0,1800));let S=u.find(w=>w.kind==="constructor");return S&&(v.constructor_={signature:S.signature,doc:S.doc.slice(0,2400)}),v.members=u.filter(w=>w.kind!=="class"&&w.kind!=="constructor").slice(0,90).map(et),v.next="For the whole text of one member: three_docs { name, member }. For the source itself: three_docs { name, full: true }.",v}function Zt(e,t){let o=t.toLowerCase().split(/\s+/).filter(Boolean),r=Kt(e).filter(n=>o.every(i=>`${n.name} ${n.from}`.toLowerCase().includes(i))).slice(0,60).map(n=>({name:n.name,from:n.from}));return{three:e.version,query:t,results:r,total:r.length}}var pe={"color-management":"colour spaces: what to mark sRGB, the working space, output, common mistakes",lights:"every light type, its units and what it costs",shadows:"shadow maps, the shadow camera, map size, fake shadows",materials:"which material for what, cost order, needsUpdate",textures:"loading, memory, mipmaps and filtering, repeat and wrap",cameras:"frustum, near and far, z-fighting, orthographic",fog:"Fog and FogExp2, matching the background",backgrounds:"CSS backgrounds, scene.background, skyboxes, equirectangular maps",primitives:"the built-in geometry classes and their segments","custom-buffergeometry":"attributes, indices, normals at seams, dynamic updates",scenegraph:"parents, children, local and world space",rendertargets:"rendering into a texture",responsive:"canvas size, drawing-buffer size, HD-DPI, capping the pixel count","rendering-on-demand":"drawing only when something changed","post-processing":"EffectComposer, passes, a custom ShaderPass","how-to-use-post-processing":"the short form: composer, RenderPass, OutputPass","how-to-update-things":"what needs needsUpdate, what cannot change after first use","how-to-dispose-of-objects":"freeing geometries, materials, textures, render targets",cleanup:"tracking and freeing everything a loaded model created",transparency:"sorting, depthWrite, alphaTest, the two-pass trick","optimize-lots-of-objects":"merging geometry, vertex colours","optimize-lots-of-objects-animated":"morph targets for many moving objects","canvas-textures":"drawing text and pictures into a texture",billboards:"sprites and facades","align-html-elements-to-3d":"HTML labels that follow 3D points","multiple-scenes":"many views on one canvas with the scissor",shadertoy:"a full-screen fragment shader, iTime and iResolution","debugging-glsl":"finding out why a shader shows nothing","debugging-javascript":"devtools, logging, common mistakes","loading-3d-models":"which format, and what to check when a model looks wrong","load-gltf":"a glTF scene: its graph, origins and scale","animation-system":"clips, mixers, actions","matrix-transformations":"matrixAutoUpdate, world matrices, quaternions","uniform-types":"which JavaScript value each GLSL uniform takes","creating-text":"seven ways to put text in a scene",tips:"screenshots, a transparent canvas, three.js as a page background",webgpurenderer:"the WebGPU renderer: imports, async init, what is not supported","webgpu-postprocessing":"RenderPipeline, pass(), MRT, renderOutput",picking:"ray casting and GPU picking",offscreencanvas:"rendering in a worker",faq:"short answers: formats, resize, invisible faces","libraries-and-plugins":"physics, post-processing, text and other libraries"},Nr=e=>e.replace(/<(script|style|head)[^>]*>[\s\S]*?<\/\1>/g,"").replace(/<pre[^>]*>/g,"\n```\n").replace(/<\/pre>/g,"\n```\n").replace(/<\/(p|h\d|li|div|tr)>/g,`
|
|
1025
|
+
`).replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n\s*\n+/g,`
|
|
1026
|
+
`).trim();async function Qt(e,t,o=fetch){if(!(e in pe))throw new Error(`No manual page "${e}". Pages: ${Object.keys(pe).join(", ")}.`);let r=/^\d+$/.test(t)?`r${t}`:"dev",n=H(Fr(),"depthview-three-manual",r),i=H(n,`${e}.txt`);if(Jt(i))return{page:e,three:r,text:$e(i,"utf8")};let a="";for(let h of[r,"dev"]){for(let u of["pages","en"]){let p=await o(`https://raw.githubusercontent.com/mrdoob/three.js/${h}/manual/${u}/${e}.html`).catch(()=>null);if(p?.ok){a=await p.text();break}}if(a)break}if(!a)throw new Error(`Could not fetch the manual page "${e}" (offline, or the page moved). The API documentation does not need the network: three_docs { name }.`);let l=Nr(a).slice(0,6e4);try{Ar(n,{recursive:!0}),Dr(i,l)}catch{}return{page:e,three:r,text:l}}var E=e=>({content:[{type:"text",text:typeof e=="string"?e:JSON.stringify(e,null,2)}]}),eo=(e,t)=>t&&e&&typeof e=="object"&&!Array.isArray(e)?{...e,next:t}:e,F=e=>e&&typeof e=="object"?e:{},to='Check it: take_screenshot view:"site" compare:true. Adjust, or when it is right: get_changes, then apply_changes_to_code.',Br='Check it: take_screenshot view:"site". Place and size it with set_value (position, scale), tune it with set_effect, then get_performance: an effect must not cost more than a fifth of the frame rate. When it is right: get_effect_code and write the file into the project.',oo=e=>`The site's own code moved ${e.join(", ")} back right after the change: it is animated, scrolled or driven by state. Call get_animated_values. Do not write a constant for it into the source without asking the developer.`,Ur=new Set(["rotation","angle"]);function ro(e,t){if(!Ur.has(e))throw new Error(`degrees:true only applies to rotation and angle, not "${e}" (fov is in degrees already).`);let o=r=>Math.round(r*Math.PI/180*1e6)/1e6;if(typeof t=="number")return o(t);if(Array.isArray(t)&&t.every(r=>typeof r=="number"))return t.map(r=>o(r));throw new Error(`"${e}" with degrees:true needs a number or [x, y, z].`)}var R=e=>({...E(e instanceof Error?e.message:String(e)),isError:!0}),no=e=>({messages:[{role:"user",content:{type:"text",text:e}}]});function je(e,t){let{core:o}=e,r=new Wr({name:"depthview",version:"0.5.0"},{instructions:It});r.registerTool("list_pending_edits",{description:'List edits sent from the Depthview browser inspector. Status "queued" means the edit could not be applied automatically and needs you; "applied" was written to source already.',inputSchema:{status:s.enum(["queued","applied","failed","done"]).optional().describe("Only edits with this status. Default: queued.")}},async({status:c})=>E(o.list(c??"queued"))),r.registerTool("get_edit_context",{description:"Source code around the JSX element an edit targets, with line numbers, plus why it was queued. Always call this before editing.",inputSchema:{id:s.string(),radius:s.number().int().min(1).max(80).optional().describe("Lines before and after. Default 12.")}},async({id:c,radius:d})=>{try{return E(o.context(c,d))}catch(m){return R(m)}}),r.registerTool("apply_edit",{description:'Apply one edit with exact AST replacement of the JSX prop (formatting and comments are kept). Pass `expression` to write a specific expression instead of the literal value, e.g. "[x, 2.5, 0]".',inputSchema:{id:s.string(),expression:s.string().max(500).optional()}},async({id:c,expression:d})=>{try{return E(o.apply(c,d))}catch(m){return R(m)}}),r.registerTool("mark_edit_done",{description:"Report the outcome of an edit you made yourself with your own file tools. The browser inspector shows it.",inputSchema:{id:s.string(),status:s.enum(["done","failed"]).optional(),note:s.string().max(300).optional()}},async({id:c,status:d,note:m})=>{try{return E(o.markDone(c,d??"done",m))}catch(g){return R(g)}}),r.registerTool("get_scene_snapshot",{description:"The live three.js scene from the inspected page as JSON: scene tree, site camera, renderer info and the values the developer changed.",inputSchema:{}},async()=>{let c=await e.requestSnapshot();return c?E(c):R("No scene snapshot yet. Open the Depthview inspector on the page and pair it with this server.")}),r.registerTool("open_preview",{description:"Open a page in a headless Chrome that this server starts, so that you can see and work on a three.js scene WITHOUT the browser extension. After it, the live tools work on that page: take_screenshot, describe_scene, find_objects, get_object, set_value, audit_visuals, get_errors, get_performance, get_resources, get_lighting, get_shader, set_shader, patch_shader, add_effect, set_effect, get_realism, fix_realism, set_look, set_surface, save_look, set_scroll, set_time, set_viewport, get_camera_path, edit_camera_path, get_camera_views, set_camera_view, apply_changes_to_code. Use it whenever no extension is paired: build, look, fix, look again. `url` is the dev server's address (start the dev server first). Call it again after you edit source files, to reload. `width`, `height` and `pixelRatio` emulate a screen: 390 x 844 at 3 is a phone, 1440 x 900 at 2 a laptop. The scroll camera path works here too (get_camera_path, edit_camera_path by keys, preview, save_camera_path). The browser has a clean profile: no cookies, no login. The developer does not see this page and has no selection in it. When the extension is paired it is used instead.",inputSchema:{url:s.string().max(2048).describe("http://localhost:5173/ or any http(s) address."),width:s.number().int().min(320).max(3840).optional().describe("CSS pixels. Default 1280."),height:s.number().int().min(320).max(2160).optional().describe("Default 800."),pixelRatio:s.number().min(1).max(4).optional().describe("Device pixel ratio. Default 1."),wait:s.number().int().min(0).max(15e3).optional().describe("Milliseconds to wait after load for the scene to come up. Default 1500.")}},async c=>{try{let d=await e.openPreview(c),m=F(await e.rpc("status").catch(()=>({})));return E({...d,three:m.three??!1,revision:m.revision??null,sceneAvailable:m.sceneAvailable??!1,sourceLocations:m.sourceLocations??!1,next:m.sceneAvailable===!0?"take_screenshot to see the page, then describe_scene. After editing source files, call open_preview again to reload.":"No three.js scene was found yet. take_screenshot and get_errors to see why; if the scene loads slowly, open_preview again with wait: 6000."})}catch(d){return R(d)}}),r.registerTool("close_preview",{description:"Close the headless preview browser opened with open_preview.",inputSchema:{}},async()=>E({closed:await e.closePreview()}));let n=async(c,d={},m,g)=>{try{let y=await e.rpc(c,d,m);return E(g?eo(y,g(F(y))):y)}catch(y){return R(y)}},i={uuid:s.string().max(64).optional().describe("Object id from find_objects."),name:s.string().max(128).optional().describe("Object name, when it is unique in the scene. Use uuid otherwise.")},a=s.union([s.number().finite(),s.boolean(),s.string().max(128),s.array(s.number().finite()).length(3)]),l=s.union([s.number().finite(),s.array(s.number().finite()).min(2).max(4),s.string().regex(/^#[0-9a-fA-F]{6}$/),s.object({texture:s.string().regex(/^(scene:[\w-]{1,64}|file:[^\0]{1,400})$/)}).describe('A texture for a sampler2D uniform: "scene:<uuid>" is one the page already has (ids from get_resources), "file:<path>" an image in the project (png, jpg, webp).')]),h=c=>{let d=F(c.uniforms),m={},g=!1;for(let[y,T]of Object.entries(d)){let z=F(T).texture;typeof z=="string"&&z.startsWith("file:")?(m[y]={texture:z,data:o.readImage(z.slice(5)).dataUrl},g=!0):m[y]=T}return g?{...c,uniforms:m}:c};r.registerTool("get_status",{description:"Whether the browser inspector is connected, which page it is on, the three.js version, the object the developer has selected and how many values are changed. Call this first.",inputSchema:{}},async()=>{if(!e.liveConnected)return E({paired:!1,mode:"none",pairingCode:e.code,next:`Two ways to connect. (1) Without the extension: call open_preview { url } with the address of the dev server (start it first if it is not running); the page opens in a headless browser and the live tools work on it. (2) With the extension, when the developer wants to watch and tune by hand: tell them to open the site in Chrome, click the Depthview icon and type ${e.code} under "AI agent & code sync"; then wait and call get_status again.`});if(!e.extensionConnected)try{let c=F(await e.rpc("status"));return E({paired:!1,mode:"preview",...c,next:c.sceneAvailable===!1?"The page is open in the headless preview but has no readable three.js scene yet (still loading, an error, or the WebGPU renderer). Call get_errors, then take_screenshot. open_preview again with a longer wait reloads it.":"Headless preview: you are working without the extension, and the developer does not see this page. take_screenshot is how you see. After a source edit call open_preview again to reload. Call describe_scene next."})}catch(c){return E({paired:!1,mode:"preview",error:c.message})}try{let c=F(await e.rpc("status")),d=c.sceneAvailable===!1?"This page has no readable three.js scene (not loaded yet, or the WebGPU renderer). Say so; do not guess values.":c.sourceLocations===!1?"Live tuning works, but objects have no source locations: you will find the code yourself when writing changes. Call describe_scene next.":"Call describe_scene to learn the scale, camera and lights, then find_objects.";return E({paired:!0,mode:"extension",...c,next:d})}catch(c){return E({paired:!0,inspectorOpen:!1,error:c.message,next:"Ask the developer to click the Depthview icon on their page and keep that tab in front, then call get_status again."})}}),r.registerTool("get_inspector_state",{description:'What the developer sees and has switched in the Depthview inspector: mode, the open side tab, the view switches (Site pipeline, Follow camera, Helpers, HTML plane, Grid, Wireframe, Site hover, Live preview), the selection, an isolated object, scroll position, camera-path recording and editing, whether a realism look is active, and "Keep changes on the page after exit". `affectsYourTools` lists the switches that change what your other tools return right now (Site pipeline off makes get_performance count nothing; an isolated object hides the rest from screenshots). Call it when a result looks wrong for no reason in the scene, and before telling the developer what to click. In the headless preview there is no inspector: it says so.',inputSchema:{}},async()=>e.extensionConnected?n("inspector"):E({inspector:!1,mode:e.previewOpen?"preview":"none",note:e.previewOpen?"This is the headless preview: there is no inspector window, no panels and no switches. The site draws through its own pipeline, nothing is isolated, and nobody has a selection. Everything the tools return is the page as it runs.":"No page is connected. get_status says how to connect."})),r.registerTool("describe_scene",{description:"A short summary of the live scene: how big it is in scene units (center and radius), what the site camera looks at, the camera (position, fov, distance to the scene), every light (type, colour, intensity, position), object counts by kind and renderer numbers. Call it once before moving, sizing or adding anything, so values fit the scene's scale.",inputSchema:{}},async()=>n("describe",{},void 0,()=>"find_objects to locate what you want to change, then get_object for its editable paths.")),r.registerTool("find_objects",{description:"Search the live scene. Returns id, name, type, kind and the path from the scene root for each match. Use it instead of get_scene_snapshot when the scene is large.",inputSchema:{query:s.string().max(128).optional().describe("Part of a name or a three.js type, case ignored. Empty: everything."),kind:s.enum(["mesh","points","light","camera","object"]).optional(),limit:s.number().int().min(1).max(500).optional().describe("Default 50.")}},async c=>n("find",c,void 0,d=>d.total===0?'Nothing matched. Try a three.js type ("light", "Mesh", "PerspectiveCamera"), a kind filter, or an empty query.':"get_object with a uuid to read its values and editable paths.")),r.registerTool("get_object",{description:"Everything the inspector knows about one object: transform, light / camera / material values, shader uniforms, textures, its world-space bounding box in scene units (`worldBounds`: min, max, size, center; null for lights and cameras), and where its JSX element is in the source (`source`, `materialSource`) when the project uses depthview-r3f-bridge. `editable` lists every path set_value accepts for it, with the current value. With no uuid or name: the object the developer has selected.",inputSchema:i},async c=>n("object",c,void 0,()=>"Change it with set_value (one value) or set_values (several, one undo step), using a path from editable. select_object shows the developer which object you mean.")),r.registerTool("set_value",{description:'Change one value on the live page, at once, without touching source code. The developer sees it happen, it appears under Changes in the inspector and can be undone. Paths: position, rotation (radians), scale, visible, castShadow, receiveShadow; lights: color, intensity, distance, decay, angle, penumbra; cameras: fov, near, far, zoom; materials: material.color, material.roughness, material.metalness, material.opacity, material.transparent, material.emissive, material.emissiveIntensity, material.side, material.wireframe, material.flatShading, material.depthTest, material.depthWrite, material.size; shaders: uniform.<name>. Vectors are [x, y, z], colours are "#rrggbb". The result has `before`, the new `value`, and `overwritten: true` when the site\'s own code moved the value back straight away (it is animated).',inputSchema:{...i,path:s.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),value:a,degrees:s.boolean().optional().describe("The value of rotation or angle is in degrees; it is converted to radians.")}},async({degrees:c,...d})=>{try{c&&(d.value=ro(d.path,d.value))}catch(m){return R(m)}return n("set",d,void 0,m=>m.overwritten?oo([String(m.path)]):to)}),r.registerTool("set_values",{description:"Change several values on the live page in one go, on one or more objects: a lighting set-up, a camera move, a material look. Every change is checked first and nothing is changed if one is wrong. They appear under Changes and one undo_change takes all of them back. Same paths and values as set_value.",inputSchema:{changes:s.array(s.object({...i,path:s.string().regex(/^[A-Za-z_$][\w$.]{0,80}$/),value:a,degrees:s.boolean().optional()})).min(1).max(40)}},async({changes:c})=>{let d;try{d=c.map(({degrees:m,...g})=>m?{...g,value:ro(g.path,g.value)}:g)}catch(m){return R(m)}return n("setMany",{changes:d},15e3,m=>{let g=(Array.isArray(m.results)?m.results:[]).filter(y=>y.overwritten).map(y=>`${String(y.object||y.uuid)}.${String(y.path)}`);return g.length?oo(g):to})}),r.registerTool("get_changes",{description:"Everything that differs from what the page loaded with, whether the developer changed it in the inspector or you did: changed values (object, path, original and current value, source location when known, and the same as React Three Fiber JSX), objects added (with their JSX), objects removed, and shaders replaced.",inputSchema:{}},async()=>n("changes",{},void 0,c=>(Array.isArray(c.changes)?c.changes.length:0)+(Array.isArray(c.added)?c.added.length:0)+(Array.isArray(c.removed)?c.removed.length:0)+(Array.isArray(c.shaders)?c.shaders.length:0)===0?"Nothing is changed. Say so and stop.":"apply_changes_to_code writes the value changes. Added objects, removed objects and shaders are written by you with your own file tools.")),r.registerTool("apply_changes_to_code",{description:'Write all current changes into the source files (same as the "Apply to code" button). Literal props are rewritten directly; the rest come back with status "queued" for you to finish with get_edit_context and apply_edit. Changes on objects without a source location are counted in `unmapped`: write those yourself from get_changes.',inputSchema:{}},async()=>n("apply",{},void 0,c=>{let d=Array.isArray(c.edits)?c.edits:[],m=d.filter(z=>z.status==="queued").length,g=d.filter(z=>z.status==="failed").length,y=typeof c.unmapped=="number"?c.unmapped:0,T=[m&&`${m} queued: get_edit_context, then apply_edit or mark_edit_done for each`,g&&`${g} failed: report their message`,y&&`${y} without a source location: write them yourself from get_changes`].filter(Boolean);return T.length?`${T.join("; ")}. Then list_pending_edits to confirm nothing is left.`:d.length?"All written. Tell the developer per change: file, prop, old value to new value.":void 0})),r.registerTool("select_object",{description:"Select an object in the inspector so the developer sees which one you mean (it is outlined and its values are shown).",inputSchema:i},async c=>n("select",c)),r.registerTool("undo_change",{description:"Undo the latest live change (one step).",inputSchema:{}},async()=>n("undo",{},void 0,()=>"One undo step taken (a whole set_values call is one step).")),r.registerTool("reset_changes",{description:"Put everything back to what the page loaded with: changed values, added and removed objects, replaced shaders. The realism look is separate (set_look reset:true). Ask the developer first if they made changes themselves.",inputSchema:{}},async()=>n("reset")),r.registerTool("take_screenshot",{description:'A picture of what is on screen now. view "inspector" (default): the whole tab with the inspector\'s panels. "scene": only the inspector\'s 3D view, from its free camera, with helpers. "site": the real page exactly as a visitor sees it, HTML included, with the inspector out of the way: use this to judge the result. `angle` turns the inspector camera first (not for "site"). `compare: true` also returns the previous picture of the same view, labelled before and after, to judge a change. The tab must be in front.',inputSchema:{view:s.enum(["inspector","scene","site"]).optional(),angle:s.enum(["front","side","back","reset"]).optional(),compare:s.boolean().optional().describe('Also return the previous picture of this view, as "before".')}},async({compare:c,...d})=>{try{let m=d.view??"inspector",g=await e.rpc("screenshot",d,2e4),y={type:"image",data:g.data,mimeType:g.mimeType},T=e.lastShots.get(m);return e.lastShots.set(m,{data:g.data,mimeType:g.mimeType}),c?T?{content:[{type:"text",text:`Before (previous "${m}" picture):`},{type:"image",data:T.data,mimeType:T.mimeType},{type:"text",text:"After (now):"},y]}:{content:[{type:"text",text:`No earlier "${m}" picture to compare with: this one is the baseline. Take another after the change.`},y]}:{content:[y]}}catch(m){return R(m)}}),r.registerTool("get_performance",{description:"Measures the running scene for a moment: frames per second, frame time (average, 95th percentile, worst), draw calls, triangles and render passes per frame, canvas size and pixel ratio, JS heap, and every renderer.render() call of one frame (scene, shadow and post-processing passes with their cost). Use it before and after a change to prove the change helped.",inputSchema:{seconds:s.number().min(.5).max(5).optional().describe("How long to measure. Default 1.5.")}},async c=>n("performance",c,15e3)),r.registerTool("get_resources",{description:"What the scene holds in GPU memory: textures, geometries and materials, biggest first, with size, memory and how many objects use each. Finds the oversized texture, the duplicated material and the heavy geometry.",inputSchema:{limit:s.number().int().min(1).max(100).optional().describe("Rows per list. Default 15.")}},async c=>n("resources",c)),r.registerTool("get_errors",{description:"What the page logged: uncaught errors and rejected promises since it loaded, console.error and console.warn since the inspector was opened, and shader programs that failed to compile. Call it when something does not show or after a source edit.",inputSchema:{clear:s.boolean().optional().describe("Empty the list after reading it.")}},async c=>n("errors",c)),r.registerTool("get_lighting",{description:"Every light with its cost and shadow set-up, and a list of problems found: castShadow with shadows switched off on the renderer, nothing casting or receiving, oversized shadow maps, point-light shadows (6 passes), a directional shadow camera that is far larger than the casters (blurry shadows) or too small (cut-off shadows), too many lights.",inputSchema:{}},async()=>n("lighting")),r.registerTool("get_shader",{description:"The GLSL of an object's material as it runs on the page, with line numbers, plus its uniforms. `kind` says whether this is the full program three.js compiled or the source as written. Long shaders: read them in parts with fromLine and lines.",inputSchema:{...i,stage:s.enum(["vertex","fragment"]).optional().describe("Default: both."),fromLine:s.number().int().min(1).optional(),lines:s.number().int().min(1).max(2e3).optional().describe("Default 400.")}},async c=>n("shader",c)),r.registerTool("set_shader",{description:"Replace the vertex and/or fragment shader of a ShaderMaterial or RawShaderMaterial on the live page and compile it. Returns the compiler's errors with line numbers; a shader that does not compile is put back at once. Send the material's own source (as in the project file), complete, not the expanded program from get_shader. Live only: write the same source into the file when it is right.",inputSchema:{...i,vertex:s.string().max(2e5).optional(),fragment:s.string().max(2e5).optional()}},async c=>n("setShader",c,12e3)),r.registerTool("patch_shader",{description:'Inject GLSL into the shader three.js generates for a built-in material (MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial...) on the live page: what onBeforeCompile does in source. Each patch replaces one piece of that shader, usually an #include line, e.g. { stage: "vertex", find: "#include <begin_vertex>", replace: "#include <begin_vertex>\n transformed.y += sin(position.x * 4.0 + uTime) * 0.1;" }. Declare new uniforms by patching "#include <common>". The material keeps its lighting, shadows and environment reflections: use this for vertex displacement, fresnel rims, dissolve, colour grading by height, wind. `uniforms` gives values (number, 2 to 4 numbers, or "#rrggbb"); uTime (seconds) is filled in every frame. A patch that does not compile, or whose `find` is not in the shader, is taken out again and reported. Returns the onBeforeCompile source to put in the project. `patches: []` removes it. Read the shader first with get_shader.',inputSchema:{...i,patches:s.array(s.object({stage:s.enum(["vertex","fragment"]),find:s.string().min(1).max(2e3),replace:s.string().max(2e4)})).max(12),uniforms:s.record(s.string(),l).optional()}},async c=>n("patchShader",c,12e3)),r.registerTool("list_effects",{description:"What add_effect and get_effect_code can make: each kind (particles, smoke, clouds, fog, shader, custom) with its presets, and for each preset its tunable uniforms with ranges and meaning; and the uniforms the page fills in every frame. Needs no page.",inputSchema:{}},async()=>E({kinds:Rt(),filledInEveryFrame:Ve})),r.registerTool("add_effect",{description:'Add an effect to the live scene, built from the site\'s own three.js and sized to the scene. kind "particles": drifting sprites (presets dust, snow, embers, fireflies, rain, stars, galaxy: a spiral of stars, swarm: thousands of sprites that flow between a sphere, a ring and a box with uShape). "smoke": rising noise-shaped puffs (smoke, steam, ground-mist, fire). "clouds": a ray-marched volume in a box (cumulus, overcast, wisps, sunset). "fog": the same volume as low fog (ground-fog, haze). "shader": ready-made shader objects: water (a reflective, rippling surface), aurora (a curtain of light), hologram and shield (glowing spheres to scale around an object), light-shaft (a cone of light: put its point at the lamp), backdrop (a slowly drifting gradient with grain behind the whole scene). "custom": your own vertex and fragment GLSL on `geometry` "plane", "box", "sphere", "cone", "sprites" (`count` quads with attributes dvCorner vec2 and dvSeed vec4) or "screen" (one full-screen triangle: gl_Position = vec4(position.xy, 0.0, 1.0)). Write custom shaders as for a three.js ShaderMaterial: position, normal, uv, the matrices and cameraPosition are declared for you, no #version line, and end the fragment shader with #include <tonemapping_fragment> and #include <colorspace_fragment>. Declare uTime (float, seconds), uResolution (vec2), uCameraLocal (vec3), uNoise (sampler2D: tiling noise) or uDepth with uHasDepth (the depth of the solid scene, for soft edges and volumes that stop at objects) to have them filled in. Textures: a uniform value { texture: "file:public/smoke.png" } tries an image of the project, { texture: "scene:<uuid>" } one the page already has. Placed where the camera looks unless `position` is given; `scale` is the size of its box. A shader that does not compile adds nothing and returns the errors. Live only: get_effect_code writes the file for the project. Call list_effects for presets and ranges.',inputSchema:{kind:s.enum(["particles","smoke","clouds","fog","shader","custom"]),preset:s.string().max(40).optional(),objectName:s.string().max(80).optional().describe("Name for the new object."),position:s.array(s.number().finite()).length(3).optional(),scale:s.array(s.number().finite()).length(3).optional().describe("Size of its box."),count:s.number().int().min(1).max(1e5).optional().describe("Sprites only."),uniforms:s.record(s.string(),l).optional(),parent:s.string().max(64).optional().describe("uuid of the parent. Default: the scene."),geometry:s.enum(["plane","box","sphere","cone","sprites","screen"]).optional(),vertex:s.string().max(6e4).optional(),fragment:s.string().max(6e4).optional(),blending:s.enum(["normal","additive"]).optional(),transparent:s.boolean().optional(),depthTest:s.boolean().optional(),depthWrite:s.boolean().optional(),side:s.enum(["front","back","double"]).optional()}},async c=>{try{return await n("addEffect",h(c),15e3,d=>d.applied?Br:void 0)}catch(d){return R(d)}}),r.registerTool("set_effect",{description:"Tune an effect made with add_effect: `uniforms` (only the ones to change), `count` (sprites), `blending`, or new `vertex` / `fragment` GLSL (complete source; it becomes a custom effect and may then take new uniforms). A shader that does not compile is put back and the errors returned. Its place and size are ordinary values: set_value with position or scale.",inputSchema:{...i,uniforms:s.record(s.string(),l).optional(),count:s.number().int().min(1).max(1e5).optional(),blending:s.enum(["normal","additive"]).optional(),vertex:s.string().max(6e4).optional(),fragment:s.string().max(6e4).optional(),objectName:s.string().max(80).optional()}},async c=>{try{return await n("setEffect",h(c),15e3)}catch(d){return R(d)}}),r.registerTool("get_effect_code",{description:'The source file for an effect: its shaders, geometry, material and per-frame update, as a React Three Fiber component (format "r3f", default) or a plain three.js function ("three"). With uuid or name: the live effect as it is tuned and placed now. With `kind` (and `preset`, `uniforms`) instead: a built-in effect without a page open. Write the returned code into the project yourself.',inputSchema:{...i,format:s.enum(["r3f","three"]).optional(),kind:s.enum(["particles","smoke","clouds","fog","shader","custom"]).optional(),preset:s.string().max(40).optional(),uniforms:s.record(s.string(),l).optional(),count:s.number().int().min(1).max(1e5).optional()}},async c=>{if(c.kind&&!c.uuid&&!c.name)try{let d=c.format==="three"?"three":"r3f",m=Mt({kind:c.kind,preset:c.preset,count:c.count,uniforms:c.uniforms},1);return E({format:d,preset:m.preset,code:Ct(m,d),uniforms:m.uniforms,ranges:qe(m.kind,m.preset),note:"Sized for a scene of radius 1: set position and scale to fit yours (scale is the size of its box). With a page connected (open_preview or the extension), add_effect sizes it to the scene and you can tune it before writing the file."})}catch(d){return R(d)}return n("effectCode",c)}),r.registerTool("audit_visuals",{description:"Find visual bugs in the running scene, from the set-up and from the pixels of a real frame. Resolution: a canvas or render target smaller than the screen (the pixelated or soft picture), a squashed canvas, a wrong camera aspect, blocky nearest-neighbour upscaling. Edges: stair-stepped silhouettes, anti-aliasing that does not reach the scene. Textures: too small for their size on screen, NearestFilter, no mipmaps (shimmer), no anisotropy, colour textures not marked sRGB, data textures marked sRGB. Depth: a near/far range that causes z-fighting, flat surfaces in the same plane. Transparency that writes depth, NaN or zero transforms, shadow set-up, banded gradients, clipped highlights, a blank frame, a lost context. Each issue has severity, the measured evidence, the cause, the fix for the source, and often `tryLive`: a tool call that confirms it on the page. `scroll: [0, 25, 50, 75, 100]` repeats the audit at those scroll positions and says where each issue shows. Read-only.",inputSchema:{scroll:s.array(s.number().min(0).max(100)).max(8).optional().describe("Scroll positions (percent) to audit. Default: where the page is now."),pixels:s.boolean().optional().describe("false skips measuring the drawn frame. Default true.")}},async c=>n("audit",c,2e4+(c.scroll?.length??0)*12e3,d=>Array.isArray(d.issues)&&d.issues.length?'Fix the high ones first. Where an issue has tryLive, run it and take_screenshot view:"site" compare:true to confirm the cause before editing the source. get_guide topic:"visual-qa" explains each issue.':void 0)),r.registerTool("audit_camera_motion",{description:"Is the scroll-driven camera move a good one? Scrolls the page top to bottom in even steps, reads the site camera at each, and judges the move the way an editor reads a shot. Finds: jumps (one step several times its neighbours), moves that start or stop at full speed (no ease), the camera doubling back, the view swinging side to side, turns too fast to follow, a tilted horizon, long stretches where scrolling moves nothing, travelling + turning + zooming all at once, a field of view that pumps in and out, and a camera that moves with no scroll. Returns a score (0\u2013100) and verdict, each issue with the scroll ranges where it shows, the cause and the fix for the source, `shots` (what the camera does in each stretch: push in, orbit, pan, hold, cut) and `checkAt` (scroll stops to take_screenshot at, to judge framing, which numbers cannot). `confidence` and `settledShare` say how far to trust it: a camera also driven by time never settles at a stop, and the report says so. Takes 20 s to several minutes (a heavily damped camera on a slow machine needs seconds per step: use fewer steps there). A page locked behind an intro must be opened past it first. Read-only.",inputSchema:{steps:s.number().int().min(24).max(200).optional().describe("Scroll steps to sample. Default 96. More finds shorter faults and takes longer.")}},async c=>n("cameraMotion",c,6e4+(c.steps??96)*6e3,d=>d.moves===!1?void 0:Array.isArray(d.issues)&&d.issues.length?'Fix the high ones first, in the code that drives the camera (get_animated_values and get_camera_path show what that is). Then set_scroll to each of checkAt and take_screenshot view:"site" to judge framing. Run this again after the change: the score should rise and no new issue appear. get_guide topic:"award-sites" covers scroll-driven camera work.':'No fault in the motion. set_scroll to each of checkAt and take_screenshot view:"site" to judge framing.')),r.registerTool("get_guide",{description:`In-depth three.js / React Three Fiber guidance, written for building award-level 3D sites. Read the topic before you write code in that area. Topics: ${Object.entries(ce).map(([c,d])=>`"${c}" (${d})`).join(", ")}.`,inputSchema:{topic:s.enum(Object.keys(ce))}},async({topic:c})=>{try{return E(zt(c))}catch(d){return R(d)}}),r.registerTool("three_docs",{description:`The three.js documentation for the version THIS project has installed, read from the package itself (the API reference on threejs.org is generated from these comments). Use it before you write a class, an add-on or an option you are not certain of: three.js renames and removes things between versions, and what you remember may be from another one. \`name\`: a class, add-on or function ("MeshPhysicalMaterial", "GTAOPass", "RoomEnvironment", "mergeGeometries"): returns the import line that works, the constructor with its parameters and defaults, every documented member with type and default, and deprecations. \`member\` with \`name\`: the whole text of one member. \`full: true\`: the source file. \`search\`: words to find what exists ("bloom", "loader hdr", "tsl display"). \`manual\`: a page of the three.js manual as text (needs the network once, then cached): ${Object.keys(pe).join(", ")}. A name that is not found does not exist in this version: do not use it.`,inputSchema:{name:s.string().max(80).optional(),member:s.string().max(80).optional(),full:s.boolean().optional(),search:s.string().max(80).optional(),manual:s.string().max(60).optional()}},async({name:c,member:d,full:m,search:g,manual:y})=>{try{let T=Xt(o.root);return y?E(await Qt(y,T?.revision??"")):T?E(g?Zt(T,g):c?Yt(T,c,{member:d,full:m}):{three:T.version,usage:"three_docs { name } for a class or add-on, { search } to find one, { manual } for a manual page.",manual:pe}):R("three is not installed in this project (no node_modules/three at or above the project root). Install it first; the documentation is read from the installed package.")}catch(T){return R(T)}}),r.registerTool("review_site",{description:"The design review: does the page look finished? Scrolls to each stop, measures the frame and the page there, and returns a picture of every stop together with what is wrong. It finds what the realism check and the visual audit cannot: a white glare over the frame, a frame that is mostly flat colour, a hard horizon line where the floor ends, colour fringes, grain seen as noise, copy that cannot be read over the picture or sits on a busy part of it, a subject that is a stock box or sphere, no copy or a default typeface, a page with nothing to scroll, scroll stops that all look the same. Each issue has the measured evidence, why it reads as unfinished, the fix, and the scroll stops it shows at. Call it after every round of building, and again until no high or medium issue is left. Then look at every picture yourself and answer `lookFor`: the measurements cannot judge composition or taste, and a page with no issue here can still be dull. `phone: true` (preview only) repeats the first and middle stop at 390 x 844. Read-only; the page is put back where it was.",inputSchema:{scroll:s.array(s.number().min(0).max(100)).min(1).max(8).optional().describe("Scroll stops in percent. Default [0, 25, 50, 75, 100]."),phone:s.boolean().optional().describe("Also review at a phone size. Only in the preview (open_preview)."),pictures:s.boolean().optional().describe("false leaves the pictures out. Default true.")}},async({scroll:c,phone:d,pictures:m})=>{try{let g=c?.length?c:[0,25,50,75,100],y=O=>new Promise(I=>setTimeout(I,O)),T=[],z=new Map,Ie=[],ee=[],Ne=[],vt=F(await e.rpc("scrollNow",{},8e3).catch(()=>({}))),_o=typeof vt.percent=="number"?vt.percent:0,wt=async(O,I)=>{for(let q of I){await e.rpc("scroll",{percent:q},15e3),await y(1100);let W=F(await e.rpc("design",{},2e4)),te=`${O}${q}%`;for(let N of W.issues??[]){let xt=z.get(String(N.id));xt?xt.atScroll.push(te):z.set(String(N.id),{...N,atScroll:[te]})}if(Array.isArray(W.thumb)&&!O&&ee.push(W.thumb),O||Ne.push(JSON.stringify(F(W.siteCamera).position??null)),Ie.push({at:te,measured:W.measured,subject:F(W.scene).subject??null,page:W.page,text:W.text}),m!==!1){let N=await e.rpc("screenshot",{view:"site"},2e4);T.push({type:"text",text:`${O||"Desktop, "}scroll ${q}%:`}),T.push({type:"image",data:N.data,mimeType:N.mimeType})}}};await wt("",g);let We;if(d)if(e.liveMode!=="preview")We="The phone pass runs in the preview only (it would resize the developer's own window): open_preview with width 390, height 844, pixelRatio 3, and call review_site again.";else{await e.rpc("viewport",{width:390,height:844,devicePixelRatio:3},15e3),await y(900);try{await wt("phone, ",[g[0],g[Math.floor(g.length/2)]])}finally{await e.rpc("viewport",{reset:!0},15e3).catch(()=>{})}}await e.rpc("scroll",{percent:_o},15e3).catch(()=>{});let le=[...z.values()],bt=Number(F(Ie[0]?.page).screens)||1;if(bt<1.3)le.push({id:"one-screen",severity:"low",title:"The page is one screen: there is nothing to scroll through",evidence:`the page is ${bt} screens tall`,why:"The sites this is measured against tell a story in three to five scroll stations, each with its own framing of the subject.",fix:"Give the page sections (about 100 to 120vh each) and a camera key per section. If one screen is the brief, ignore this.",atScroll:[]});else if(g.length>=3&&ee.length>=3){let O=0;for(let I=1;I<ee.length;I++){let q=ee[I-1],W=ee[I],te=0;for(let N=0;N<q.length;N++)te+=Math.abs(q[N]-(W[N]??0));(te/q.length>4||Ne[I]!==Ne[I-1])&&O++}O===0&&le.push({id:"scroll-changes-nothing",severity:"high",title:"The scene looks the same at every scroll stop",evidence:`${ee.length} stops, the same picture and the same camera at each`,why:"The page scrolls and the 3D does not answer. A scene that ignores the scroll is a wallpaper.",fix:'Drive the camera (or the subject) from the scroll: a key per section, a curve between them, damped. get_guide topic:"site-build".',atScroll:[]})}let yt={high:0,medium:1,low:2};le.sort((O,I)=>(yt[String(O.severity)]??3)-(yt[String(I.severity)]??3));let we=le.filter(O=>O.severity!=="low").length,To={verdict:we?`${we} thing${we===1?"":"s"} to fix before this reads as finished.`:"Nothing measurable is wrong. That is the floor, not the result: judge the pictures.",issues:le,stops:Ie,lookFor:["Is the subject the first thing the eye lands on at every stop, and is it whole (not cut by the frame or hidden under the navigation)?","Does each stop show something the last one did not: a new angle, a detail, a different light?","Is there one clear light direction, a dark side, and a highlight that describes the shape?","Do the materials differ from each other (rough against polished, clear against solid), or is everything one surface?","Does the copy sit on the calm side of the frame with room around it, and is the headline the second thing the eye lands on?","Would this frame pass as a still from a brand film? If not, name what a photographer would change, and change it."],...We?{phone:We}:{},next:we?'Fix the high ones first, in the source. Reload (open_preview again) and run review_site again. get_guide topic:"site-build" has the method for each.':"Answer lookFor from the pictures. Then audit_visuals, audit_camera_motion and get_performance for what is left."};return{content:[{type:"text",text:JSON.stringify(To,null,2)},...T]}}catch(g){return R(g)}}),r.registerTool("set_scroll",{description:"Scroll the site to a position, 0 (top) to 100 (bottom), and return where the site camera is there. Use it to check a scroll-driven scene at several points.",inputSchema:{percent:s.number().min(0).max(100)}},async c=>n("scroll",c,12e3)),r.registerTool("set_time",{description:'Hold, step or release the site\'s animation. "pause" freezes the page\'s clock and its animation frames; "step" moves it on by `frames` frames of `stepMs` each (default 1 frame of 16.67 ms) so you can look at one exact moment; "resume" lets it run again without a jump. Always resume when done.',inputSchema:{action:s.enum(["pause","step","resume"]),frames:s.number().int().min(1).max(600).optional(),stepMs:s.number().min(.1).max(1e3).optional()}},async c=>n("time",c)),r.registerTool("get_animated_values",{description:"Which values the site's own code is moving: `overTime` lists what changes by itself while you watch, `onScroll` what changes when the page scrolls. Also reports animation clips on objects, React Three Fiber useFrame callbacks and GSAP tweens. Call it before writing any position, rotation, scale, opacity or uniform into the source: a value listed here is driven by code, and a constant in JSX would be overwritten.",inputSchema:{seconds:s.number().min(.3).max(4).optional().describe("How long to watch. Default 1."),checkScroll:s.boolean().optional().describe("Also scroll the page to see what follows it, then scroll back. Default true.")}},async c=>n("animated",c,2e4)),r.registerTool("get_camera_path",{description:"How the site camera moves as the page scrolls: position, rotation (quaternion) and field of view at up to 40 scroll positions. Records the path by scrolling the page if it has not been recorded yet.",inputSchema:{record:s.boolean().optional().describe("Record again even if a path exists.")}},async c=>n("cameraPath",c,6e4,()=>'To change this path: edit_camera_path with action "start" turns it into a few keys you (or the developer, by dragging in the view) can move.'));let u=s.array(s.number().finite()).length(3);r.registerTool("get_camera_path_edit",{description:"The scroll camera path as it is being edited in the inspector (by the developer dragging handles, or by you): `keys` (each: scroll `percent` 0-100, camera `position`, look-at `target`, `fov`, world space), the `original` keys from the recording, `changes` as readable lines, where it was saved (`savedTo`), the camera-path.json contents (`json`) and a TypeScript snippet (`code`). Between keys the camera follows a Catmull-Rom curve through the positions and through the targets.",inputSchema:{}},async()=>n("pathEdit",{},void 0,c=>c.editing?`To put it into the project: save_camera_path (a JSON file for useCameraPath), or rewrite the developer's own scroll camera code with these keys (read it first; see the "camera-path" prompt).`:void 0)),r.registerTool("edit_camera_path",{description:'Edit the scroll camera path live, the same as dragging its handles in the inspector. action "start": turn the recorded path into editable keys (or pass `keys`). "set_key": move key `index` (`position`, `target`, `fov`, `percent`). "add_key": a new key at `percent` on the current curve (optionally with `position`/`target`). "remove_key": key `index`. "preview": the site camera follows the edited path (`on`, default true). "reset": back to the recording. "stop": end editing. `scroll` moves the page to a percent afterwards, to look at the result with take_screenshot view:"site". Returns the edit as get_camera_path_edit does.',inputSchema:{action:s.enum(["start","set_key","add_key","remove_key","preview","reset","stop"]),index:s.number().int().min(0).optional(),position:u.optional(),target:u.optional(),fov:s.number().min(1).max(179).optional(),percent:s.number().min(0).max(100).optional(),on:s.boolean().optional(),scroll:s.number().min(0).max(100).optional(),keys:s.array(s.object({percent:s.number().min(0).max(100),position:u,target:u,fov:s.number().min(1).max(179)})).max(200).optional()}},async c=>n("pathAction",c,15e3,d=>d.editing===!1?void 0:d.preview?'Look at it: set_scroll or scroll, then take_screenshot view:"site" compare:true.':'edit_camera_path action "preview" shows the edited path on the live site.'));let p=`Look at it: take_screenshot view:"site" (the page is on that view, through the site camera). When every view is right: save_camera_path, or write the keys into the developer's own camera code (the "camera-views" prompt).`;r.registerTool("get_camera_views",{description:'The camera views of the page: view 1 is what a visitor sees when the page loads (scroll 0), then one view per page section, each with the scroll `percent` where it is reached, the camera `position`, look-at `target` and `fov` there (world space), whether the camera holds still on it (`hold`) and whether it was `changed`. This is the easy way to work on "what shows on load" and "how the camera goes from section to section": set views, and the path between them is made for you. The first call scrolls the page once to find its sections and the camera path (about 10 seconds); it works on a page whose camera does not move yet. `record: true` reads the page again (after the sections changed).',inputSchema:{record:s.boolean().optional().describe("Scroll the page again to re-read its sections.")}},async c=>n("shots",c,6e4,()=>"set_camera_view changes one view: frame { object } to show an object, position/target for exact numbers, fromView: true for what the developer framed by hand. Start with view 1 (the page on load).")),r.registerTool("set_camera_view",{description:'Set what the site camera shows at one view: when the page loads (view 1 or "opening") or at a section (its number, id or label, as get_camera_views lists them). Say what to show in ONE of three ways. `frame`: { object: name (or uuid), from: "front" | "back" | "left" | "right" | "top" | "front-left" | "front-right", fill: 0.05-1 (how much of the screen the object takes, default 0.6) } works the pose out from the object\'s measured size. `position` and/or `target` (world space) set it exactly; one alone keeps the other. `fromView: true` takes the view the developer framed by hand in the inspector ("I moved the camera where I want it, use that for the hero"). Also: `fov`; `hold: true` keeps the camera still while that section scrolls past and travels to the next view after it; `reset: true` puts the view back. The camera path between views is a smooth curve and is rebuilt for you. Afterwards the page is scrolled to the view and drawn by the site camera on the edited path, so take_screenshot view:"site" shows the result (`show: false` skips that). Nothing is written to the source until save_camera_path.',inputSchema:{view:s.union([s.number().int().min(1),s.string().max(120)]).optional().describe("Number (1 = on load), id or section label. Default 1."),frame:s.object({object:s.string().max(200).optional(),uuid:s.string().max(80).optional(),from:s.enum(["front","back","left","right","top","front-left","front-right"]).optional(),fill:s.number().min(.05).max(1).optional()}).optional(),position:u.optional(),target:u.optional(),fromView:s.boolean().optional(),fov:s.number().min(1).max(170).optional(),hold:s.boolean().optional(),reset:s.boolean().optional(),show:s.boolean().optional()}},async c=>n("shotSet",c,6e4,()=>p)),r.registerTool("save_camera_path",{description:"Write the edited camera path into the project as JSON (default src/camera-path.json, or `file`, a .json path inside the project). The site then drives its camera with `useCameraPath(path)` from depthview-r3f-bridge/camera-path. Use this when the developer wants the file; to keep their own camera code, rewrite that code instead.",inputSchema:{file:s.string().max(512).optional()}},async c=>n("pathSave",c,15e3,d=>{let m=String(d.file??"the file");return`Saved ${m}. If the project does not use it yet: import path from './${m.split("/").pop()}' and call useCameraPath(path) inside <Canvas> in place of the old scroll camera code (ask the developer before removing their code).`}));let f='Look at it: take_screenshot view:"site" compare:true. Then get_realism for what is left. When the developer is happy: save_look.',v=c=>(Array.isArray(c.notes)?c.notes:[]).length?`Read "notes": the page could not do everything asked. ${f}`:f,x=s.string().regex(/^#[0-9a-fA-F]{6}$/),b=s.object({id:s.string().max(40).describe('Stable id, e.g. "key". Keep the ids get_realism returned.'),name:s.string().max(40).optional(),azimuth:s.number().min(-360).max(360).describe("Degrees around the scene: 0 in front (+Z), 90 right (+X), 180 behind."),elevation:s.number().min(-90).max(90).describe("Degrees above the horizon. 90 is overhead."),width:s.number().min(1).max(180).describe("Angular width in degrees."),height:s.number().min(1).max(180),intensity:s.number().min(0).max(100).describe("1 a white wall, 5 a softbox, 15 a bare lamp."),color:x.optional(),softness:s.number().min(0).max(1).optional().describe("Edge softness, 0 hard to 1.")});r.registerTool("get_realism",{description:"The realism check of the live scene: a `score` out of 100, the `issues` holding it back (each with why it matters, and `fixable: true` plus the `fix` patch when Depthview can fix it live), what is already in place, and the current `look` (colour management, render quality, world lighting, shadows, surface materials, bevels, lens effects). Call this before making a scene look more realistic, and after each change. The score says the render settings are in order (tone mapping, lighting, shadows, resolution); it does not judge the picture: a cube on a grey floor scores 97. For whether the page looks finished, review_site.",inputSchema:{}},async()=>n("look",{},15e3,c=>{let d=Array.isArray(c.issues)?c.issues:[],m=d.filter(y=>y.fixable===!0).length;if(m)return`fix_realism applies the ${m} one-click fix${m===1?"":"es"} live (undoable). Then tune with set_look and set_surface, checking each step with take_screenshot view:"site" compare:true.`;if(d.length)return'The remaining issues need a change in the source: read each "detail" and make it in the code.';let g=F(c.performance);return typeof g.fps=="number"&&typeof g.siteFps=="number"&&g.fps<g.siteFps*.8?`The look costs frame rate (${g.fps} fps, ${g.siteFps} without it): measure_look_cost shows which part, lighten_look steps it down.`:"The render settings are in order. That is not yet a good picture: review_site judges the page itself (glare, flat frame, horizon, copy, subject), then tune with set_look and set_surface towards what the developer asked for."})),r.registerTool("fix_realism",{description:"Apply the one-click fixes of the realism check on the live page: filmic tone mapping, full pixel ratio, studio world lighting, soft shadows, bevelled edges, anti-aliasing and ambient occlusion, as far as each is missing. `ids` limits it to some issues (ids from get_realism). Undoable (undo_change). Live only until save_look.",inputSchema:{ids:s.array(s.string().max(40)).max(20).optional()}},async c=>n("lookFix",c,2e4,v)),r.registerTool("set_look",{description:'Change the look of the live scene: a partial patch, merged into the current look. Sections: `color` (tone mapping "site" | "none" | "aces" | "agx" | "neutral" | "reinhard", exposure), `quality` (pixelRatio cap, anisotropy), `world` (preset "site" | "studio" | "softbox" | "sunset" | "overcast" | "night", strength, rotation, background, sky colours, and `boxes`: the studio light boxes, replaced as a whole list), `shadows` (mode "site" | "on" | "off", softness, resolution), `bevel` (mode "off" | "all" | "selected", amount = edge radius as a fraction of the smallest side, segments), `effects` (antialias, ao, bloom, dof, vignette, grain; these need the project\'s dev bridge). A world preset loads its own sky and light boxes; to move or add a light, send the full `boxes` list from get_realism with your change. `reset: true` puts the site back. One undo_change takes the whole call back.',inputSchema:{color:s.object({toneMapping:s.enum(["site","none","linear","reinhard","cineon","aces","agx","neutral"]).optional(),exposure:s.number().min(0).max(10).nullable().optional()}).optional(),quality:s.object({pixelRatio:s.number().min(.5).max(3).nullable().optional(),anisotropy:s.boolean().optional(),supersample:s.boolean().optional().describe("Render 1\xD7 screens at 1.5\xD7 and scale down, so edges do not stair-step or shimmer. No effect on denser screens.")}).optional(),world:s.object({preset:s.enum(["site","studio","softbox","sunset","overcast","night"]).optional(),strength:s.number().min(0).max(10).optional(),rotation:s.number().min(-360).max(360).optional(),background:s.boolean().optional(),sky:s.object({top:x.optional(),horizon:x.optional(),ground:x.optional(),intensity:s.number().min(0).max(10).optional()}).optional(),boxes:s.array(b).max(12).optional()}).optional(),shadows:s.object({mode:s.enum(["site","on","off"]).optional(),softness:s.number().min(0).max(10).optional(),resolution:s.union([s.literal(1024),s.literal(2048),s.literal(4096)]).optional()}).optional(),bevel:s.object({mode:s.enum(["off","all","selected"]).optional(),amount:s.number().min(0).max(.5).optional(),segments:s.number().int().min(1).max(8).optional()}).optional(),effects:s.object({antialias:s.boolean().optional(),ao:s.object({on:s.boolean().optional(),intensity:s.number().min(0).max(3).optional(),radius:s.number().min(.01).max(5).optional()}).optional(),bloom:s.object({on:s.boolean().optional(),strength:s.number().min(0).max(3).optional(),threshold:s.number().min(0).max(5).optional(),radius:s.number().min(0).max(1).optional()}).optional(),dof:s.object({on:s.boolean().optional(),focus:s.number().min(.01).max(1e4).optional().describe("Distance from the camera, scene units."),aperture:s.number().min(0).max(.01).optional(),maxBlur:s.number().min(0).max(.05).optional()}).optional(),vignette:s.number().min(0).max(1).optional(),grain:s.number().min(0).max(1).optional()}).optional(),performance:s.object({adaptive:s.boolean().optional().describe("The saved look steps itself down on devices that cannot hold targetFps."),targetFps:s.union([s.literal(30),s.literal(45),s.literal(60)]).optional()}).optional(),adapt:s.object({follow:s.boolean().optional().describe("Fit shadows, texture sharpness, surfaces and bevels again when objects are added or removed (default true)."),textures:s.boolean().optional().describe("Correct texture colour spaces on physically based materials.")}).optional(),models:s.array(s.object({name:s.string().max(128),uuid:s.string().max(64).optional(),scale:s.number().min(1e-4).max(1e4).optional(),lift:s.number().min(-1e5).max(1e5).optional(),reflection:s.number().min(0).max(10).optional()})).max(200).optional().describe("Size, height (world units) and reflection strength of whole models, replaced as a whole list. adapt_model measures and sets these."),reset:s.boolean().optional().describe("Put the site back as it was (clears the look).")}},async c=>n("lookSet",c,2e4,v)),r.registerTool("set_surface",{description:'Set what one object is made of, as part of the look. `preset`: "polished-metal", "brushed-metal", "gold", "car-paint", "glass", "plastic", "ceramic", "rubber"; and/or single values (they override the preset): color, metalness, roughness, envMapIntensity, and on MeshPhysicalMaterial clearcoat, clearcoatRoughness, transmission, ior, thickness. `bevel: true` rounds this object\'s edges (boxes and cylinders). `clear: true` gives the object its own material back. Metal needs something to reflect: use it with a world (set_look world). Real surfaces are rarely below roughness 0.1.',inputSchema:{...i,preset:s.enum(["polished-metal","brushed-metal","gold","car-paint","glass","plastic","ceramic","rubber"]).optional(),color:x.optional(),metalness:s.number().min(0).max(1).optional(),roughness:s.number().min(0).max(1).optional(),clearcoat:s.number().min(0).max(1).optional(),clearcoatRoughness:s.number().min(0).max(1).optional(),transmission:s.number().min(0).max(1).optional(),ior:s.number().min(1).max(2.333).optional(),thickness:s.number().min(0).max(100).optional(),envMapIntensity:s.number().min(0).max(10).optional(),detail:s.object({pattern:s.enum(["brushed","rings","hammered","knurl","text"]),strength:s.number().min(0).max(2).optional().describe("Depth of the relief. Default 1."),scale:s.number().min(1).max(200).optional().describe("Repeats across the surface: ring count, streak density, grid size."),text:s.string().max(120).optional().describe('For "text": engraved around the centre, like the legend on a coin.')}).nullable().optional().describe("Fine relief as a generated normal map (no extra geometry, sharp at any zoom): a brushed finish, concentric rings, hammered dimples, a knurled grip, or engraved text. null takes it off. The object needs UV coordinates."),bevel:s.boolean().optional(),clear:s.boolean().optional()}},async c=>n("lookSurface",c,2e4,v)),r.registerTool("compare_to_reference",{description:"Compare the live site with a reference picture of the look the developer wants (a screenshot of another site, a render, a photo). `file`: a .png, .jpg or .webp inside the project; leave it out to use the picture the developer dropped into the inspector (Realism \u203A Match a reference), or to compare again after a change. Returns `match` (0-100) and the `differences`, biggest first: brightness, contrast, shadow depth, highlights, warmth, saturation, vignette, sharpness, each with the two measured numbers, `advice`, and where the look can close the gap a `patch` for set_look. It measures light and colour, not shapes: use it to match a mood and a grade, then judge composition yourself with take_screenshot.",inputSchema:{file:s.string().max(512).optional()}},async({file:c})=>{try{let d=c?o.readImage(c):null,m=F(await e.rpc("lookReference",d?{image:d.dataUrl,name:d.name}:{},4e4)),g=Array.isArray(m.differences)?m.differences:[],y=g.find(T=>T.patch);return E(eo(m,g.length===0?'Light and colour match the reference. Compare composition and materials by eye: take_screenshot view:"site".':y?`Close the biggest gap first: set_look with the patch of "${String(y.id)}", then compare_to_reference again (no file needed). Change one thing per round; stop when match stops rising.`:'None of these can be closed by the look alone: follow each "advice" in the scene or the page.'))}catch(d){return R(d)}}),r.registerTool("measure_look_cost",{description:"What the look costs in frame time: the frame rate with the look (`fps`) and of the site alone (`siteFps`), and per heavy part (full resolution, shadows, smooth edges, ambient occlusion, bloom, depth of field, bevels) the milliseconds it adds, most expensive first. Each part is switched off in turn on the live page, so it takes a few seconds; the page is left as it was. Numbers are for this machine with the inspector open: compare fps with siteFps.",inputSchema:{}},async()=>n("lookCost",{},6e4,c=>typeof c.fps=="number"&&typeof c.siteFps=="number"&&c.fps<c.siteFps*.8?"The look costs more than a fifth of the frame rate. lighten_look steps it down, or turn off the most expensive part yourself with set_look.":"The look is within budget on this machine. For phones, set_look performance { adaptive: true } lets the saved look step itself down.")),r.registerTool("adapt_model",{description:"Fit the look to a model that was added to the scene (an imported glTF, a new mesh), from measurements on the live page. Changes what the numbers decide: soft shadows that every mesh casts and receives with the shadow area fitted to the scene, texture colour spaces (colour maps sRGB, data maps plain), anisotropic filtering, a studio world when there is nothing to reflect, depth-of-field focus at the model, ambient-occlusion radius at the size of the scene, reflections turned down when the model clips to white on screen, and the look lightened when the frame rate dropped. Returns `changes` (each with the measurement behind it), `advice` and `modelsInScene` (size, triangles, textures, `gap` above the surface under it, `relativeSize` against the other models). Scale and grounding depend on intent, so they come back as advice with an `option`: call again with `scale` or `ground: true` and the model `name` to do them. Without `name` it fits the models that arrived since the inspector opened, or all of them. A model is a top-level object of the scene. One undo_change takes the whole call back; save_look keeps it.",inputSchema:{name:s.string().max(128).optional().describe("Name of the model (a top-level object)."),uuid:s.string().max(64).optional(),ground:s.boolean().optional().describe("Move the model straight down (or up) onto the surface under it."),scale:s.number().min(1e-4).max(1e4).optional().describe("Multiply the model's size, e.g. 0.01 for a model made in centimetres."),lighten:s.boolean().optional().describe("false: report the frame rate but leave the look as heavy as it is.")}},async c=>n("lookAdapt",c,9e4,d=>{let g=(Array.isArray(d.advice)?d.advice:[]).filter(y=>y.option);return g.length?`Tell the developer what was measured and ask before acting on: ${g.map(y=>String(y.title)).join("; ")}. Then take_screenshot view:"site" to check the result.`:'Check the result with take_screenshot view:"site". The fit is live only: save_look keeps it, and the saved look fits itself again when models load on the real site.'})),r.registerTool("lighten_look",{description:"Step the look down until the page holds a frame rate: shadow detail, pixel ratio, depth of field, ambient occlusion, bloom, smooth edges, in that order (what costs most for the least visible difference goes first). `targetFps` defaults to nine tenths of what the site runs at without the look. Returns the `steps` taken and the look after. One undo_change takes it back.",inputSchema:{targetFps:s.number().min(5).max(240).optional()}},async c=>n("lookLighten",c,6e4,v)),r.registerTool("save_look",{description:"Write the look into the project as JSON (default src/depthview-look.json, or `file`, a .json path inside the project). The result has `usage`: how the site applies it, with <DepthviewLook look={look} /> from depthview-r3f-bridge/look/react inside <Canvas>, or applyLook({ renderer, scene, camera }, look) from depthview-r3f-bridge/look in plain three.js (three >= 0.160). Materials and bevels are matched by object name: name the objects in the code first if they have none.",inputSchema:{file:s.string().max(512).optional()}},async c=>n("lookSave",c,15e3,d=>`Saved ${String(d.file??"the file")}. If the project does not apply it yet, add the code from "usage" (ask before replacing the developer's own lighting or effect code), make sure depthview-r3f-bridge is a dependency, then reload and compare with take_screenshot view:"site".`)),r.registerTool("get_site_controls",{description:'Controls the site itself declares with depthviewControls(group, schema) or useDepthviewControls (from depthview-r3f-bridge/controls): each with its group, key, type, current `value`, the `initial` value written in the code, and min/max. Empty when the site declares none: add some for the values the developer keeps tuning (see the "realism" prompt), then reload.',inputSchema:{}},async()=>n("controls",{},8e3,c=>Array.isArray(c.controls)&&c.controls.length?"set_site_control changes one live. save_site_controls writes the changed values into the source.":'None declared. To add some: import { depthviewControls } from "depthview-r3f-bridge/controls" (or useDepthviewControls from ".../controls/react") and read the returned values where the scene uses them.')),r.registerTool("set_site_control",{description:"Set one of the site's own controls on the live page (group and key from get_site_controls). The site reacts at once, through its own code. Live until save_site_controls.",inputSchema:{group:s.string().max(128),key:s.string().max(128),value:s.union([s.number().finite(),s.boolean(),s.string().max(512)])}},async c=>n("controlSet",c,8e3,()=>'Check it: take_screenshot view:"site" compare:true. When it is right: save_site_controls.')),r.registerTool("save_site_controls",{description:"Write every control value changed in the inspector (by you or the developer) back into the depthviewControls(...) call that declares it: only the literal changes. Returns one result per value with file and line, or why it could not be written (for example, the value is computed).",inputSchema:{}},async()=>n("controlsSave",{},15e3)),r.registerTool("create_scene",{description:`Write a working, good-looking starter scene into the project, so a 3D page does not begin from an empty file. Templates: ${Object.entries(de).map(([c,d])=>`"${c}" (${d.description})`).join(" ")} \`framework\`: "r3f" (React Three Fiber, a Scene.tsx) or "three" (plain three.js, a scene.ts with createScene(canvas)). Writes the scene file, look.json (studio lighting, soft shadows, bevels, adaptive quality) and camera-path.json into \`folder\` (default src/<template>), and returns \`mount\`: how to put it on a page. Never overwrites a file. Needs depthview-r3f-bridge and three >= 0.160 as dependencies (and @react-three/fiber for "r3f"). Works without the browser paired.`,inputSchema:{template:s.enum(["product-hero","scroll-journey"]),framework:s.enum(["r3f","three"]),folder:s.string().max(256).optional()}},async({template:c,framework:d,folder:m})=>{try{let g=Ht(o.root,c,d,m);return E({...g,next:'Check package.json: add depthview-r3f-bridge (and three >= 0.160) if missing, asking before installing. Mount the scene with the code in "mount", start the dev server, and ask the developer to open the page with Depthview. The starter is a scaffold with placeholder blocks, not a finished page: review_site will say so. Make it a site with get_guide topic:"site-build": model the subject (topic "modeling") or import_asset, build the page and its type around the canvas, give the set a glow and no horizon, then review_site until it is clean.'})}catch(g){return R(g)}});let S=new ke(o.root),w=s.enum(["model","texture","hdri"]);r.registerTool("find_assets",{description:'Search a free library (Poly Haven, all CC0: no attribution, fine for commercial sites) for real assets: `type` "model" (glTF objects, with triangle counts), "texture" (scanned surfaces: colour, normal and roughness maps) or "hdri" (lighting panoramas). `query` is matched against names, tags and categories ("brushed metal", "wooden chair", "studio"). Use it when a scene needs detail that boxes and spheres cannot give. Only the search words leave the machine.',inputSchema:{query:s.string().max(120),type:w,limit:s.number().int().min(1).max(25).optional()}},async({query:c,type:d,limit:m})=>{try{let g=await S.search(c,d,m);return E({results:g,next:g.length?'Show the developer the candidates (each has a `page` with pictures) and ask which to use, then import_asset with its id. Start at resolution "1k".':"Nothing matched: try fewer or more general words."})}catch(g){return R(g)}}),r.registerTool("import_asset",{description:'Download one asset from find_assets into the project (public/assets/<id>/ when there is a public folder) and get the code that loads it, for React Three Fiber and plain three.js. `resolution` "1k" (default, right for most web scenes), "2k" or "4k". Refuses when the files are over `maxBytes` (default 12 MB) instead of bloating the page: pick a lower resolution. Textures come as web-ready JPG colour, normal and packed occlusion/roughness/metalness maps. Ask the developer before importing: it writes files into their project.',inputSchema:{id:s.string().regex(/^[\w-]{1,80}$/),type:w,resolution:s.enum(["1k","2k","4k"]).optional(),folder:s.string().max(256).optional().describe("Folder inside the project to put the asset folder in. Default public/assets."),maxBytes:s.number().int().min(1e5).max(200*1024*1024).optional().describe(`Size budget for this asset. Default ${Ye}.`)}},async c=>{try{let d=await S.import(c);return E({...d,next:`Add the code from "usage" where the scene is built (keep the developer's structure), reload, then take_screenshot view:"site" and tune it with the look. After adding a model: get_performance, to see what it costs.`})}catch(d){return R(d)}}),r.registerTool("add_object",{description:'Add an object to the live scene and get its React Three Fiber JSX back. `copyOf` duplicates an existing object (always works). `kind` makes a new one: "box", "sphere", "plane" (unit-sized meshes), "Group", or a light type the page already uses, such as "PointLight" (the classes are taken from the site\'s own three.js, so a light type the site never created cannot be made: the error lists what can). Live only: it is gone after a reload until the JSX is in the source.',inputSchema:{kind:s.string().max(40).optional(),copyOf:s.string().max(64).optional().describe("uuid of the object to duplicate."),parent:s.string().max(64).optional().describe("uuid of the parent. Default: the scene."),objectName:s.string().max(80).optional().describe("Name for the new object."),position:s.array(s.number().finite()).length(3).optional(),color:s.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),intensity:s.number().finite().optional()}},async c=>n("add",c)),r.registerTool("remove_object",{description:"Take an object (and its children) out of the live scene, to see the scene without it or measure what it costs. Returns its source location when known. Live only: reset_changes puts it back.",inputSchema:i},async c=>n("remove",c)),r.registerTool("set_viewport",{description:"Responsive check. `width` and `height` resize the browser window so the page gets that size, and the site's own resize code runs; the result says the size really reached (a window cannot go below about 500 px wide). `pixelRatio` sets the renderer's pixel ratio live, to measure what a 2x or 3x phone screen costs with get_performance. `reset: true` puts the window and the pixel ratio back: always do that when done.",inputSchema:{width:s.number().int().min(200).max(7680).optional(),height:s.number().int().min(200).max(4320).optional(),pixelRatio:s.number().min(.25).max(4).optional(),devicePixelRatio:s.number().min(1).max(4).optional().describe("Headless preview only: the device pixel ratio of the emulated screen (3 for a phone). The site then sizes itself as on that device."),reset:s.boolean().optional()}},async c=>n("viewport",c,12e3));for(let c of Nt){let d=c.argument;d?r.registerPrompt(c.name,{title:c.title,description:c.description,argsSchema:{[d.name]:s.string().optional().describe(d.description)}},m=>no(c.text(m[d.name]))):r.registerPrompt(c.name,{title:c.title,description:c.description},()=>no(c.text(void 0)))}let j=(c,d,m,g)=>{r.registerResource(c,d,{title:c,description:m,mimeType:"application/json"},async()=>{let y;try{y=await g()}catch(T){y={error:T instanceof Error?T.message:String(T)}}return{contents:[{uri:d,mimeType:"application/json",text:JSON.stringify(y,null,2)}]}})};return j("status","depthview://status","Paired? Which page, what is selected, how many values are changed.",async()=>e.extensionConnected?{paired:!0,...F(await e.rpc("status"))}:{paired:!1,pairingCode:e.code}),j("scene","depthview://scene","Summary of the live scene: scale, camera, lights, object counts.",()=>e.rpc("describe")),j("selection","depthview://selection","The object selected in the inspector, with its editable values and bounds.",()=>e.rpc("object")),j("changes","depthview://changes","Everything changed on the live page, with source locations.",()=>e.rpc("changes")),t.includePairingCode&&r.registerTool("get_pairing_code",{description:"One-time code the developer types into the Depthview extension to pair it with this server.",inputSchema:{}},async()=>E({code:e.code,paired:e.extensionConnected})),r}import{randomInt as an,timingSafeEqual as ln}from"node:crypto";import{createServer as cn}from"node:http";import{StreamableHTTPServerTransport as hn}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{WebSocketServer as un}from"ws";import{z as D}from"zod";import{randomUUID as qr}from"node:crypto";import{EventEmitter as Jr}from"node:events";import{existsSync as at,readdirSync as Xr,readFileSync as fe,realpathSync as Ce,statSync as lt,writeFileSync as Ae}from"node:fs";import{basename as ct,dirname as ho,isAbsolute as ht,relative as ge,resolve as Q,sep as ve}from"node:path";import{z as _}from"zod";import{parse as Hr,parseExpression as Vr}from"@babel/parser";import Z from"recast";var C=Z.types.builders,so={parse:e=>Hr(e,{sourceType:"module",tokens:!0,allowReturnOutsideFunction:!0,plugins:["jsx","typescript"]})},it=e=>{let t=Math.round(e*1e3)/1e3;return Object.is(t,-0)?0:t},Me=e=>{let t=it(e);return t<0?C.unaryExpression("-",C.numericLiteral(-t)):C.numericLiteral(t)};function V(e){if(e)switch(e.type){case"NumericLiteral":return e.value;case"Literal":return typeof e.value=="number"?e.value:void 0;case"UnaryExpression":{let t=V(e.argument);return t===void 0?void 0:e.operator==="-"?-t:e.operator==="+"?t:void 0}case"BinaryExpression":{let t=V(e.left),o=V(e.right);return t===void 0||o===void 0?void 0:e.operator==="+"?t+o:e.operator==="-"?t-o:e.operator==="*"?t*o:e.operator==="/"?t/o:void 0}case"MemberExpression":return!e.computed&&e.object?.type==="Identifier"&&e.object.name==="Math"&&e.property?.name==="PI"?Math.PI:void 0;case"ParenthesizedExpression":case"TSAsExpression":case"TSNonNullExpression":return V(e.expression);default:return}}var io=e=>["StringLiteral","BooleanLiteral","NullLiteral","Literal"].includes(e?.type)||V(e)!==void 0;function Re(e){return typeof e=="number"?Me(e):typeof e=="boolean"?C.booleanLiteral(e):typeof e=="string"?C.stringLiteral(e):C.arrayExpression(e.map(Me))}function nt(e){return e===!0?null:typeof e=="string"?C.stringLiteral(e):C.jsxExpressionContainer(Re(e))}var me=e=>({ok:!1,needsAgent:!0,reason:e});function ao(e,t){let o;try{o=Z.parse(e,{parser:so})}catch(b){return me(`Could not parse the file: ${b instanceof Error?b.message:String(b)}`)}let r=[];Z.types.visit(o,{visitJSXOpeningElement(b){let S=b.node.loc;S&&S.start.line===t.line&&r.push(b.node),this.traverse(b)}});let n=r.find(b=>b.loc.start.column===t.column)??(r.length===1?r[0]:void 0);if(!n)return me(`No JSX element starts at line ${t.line}, column ${t.column}. The file may have changed since the page loaded.`);let i=n.attributes,a=i.find(b=>b.type==="JSXAttribute"&&b.name?.type==="JSXIdentifier"&&b.name.name===t.prop),l=i.some(b=>b.type==="JSXSpreadAttribute"),h=a?.value?.type==="StringLiteral"&&typeof a.value.start=="number"?e[a.value.start]:void 0,u=b=>{let S=Z.print(o,{quote:h==="'"?"single":"double"}).code;return{ok:!0,code:S,changed:S!==e,note:b}};if(t.expression!==void 0){let b;try{b=Vr(t.expression,{plugins:["jsx","typescript"]})}catch(w){return{ok:!1,needsAgent:!1,reason:`Invalid expression: ${w instanceof Error?w.message:String(w)}`}}let S=C.jsxExpressionContainer(b);return a?a.value=S:i.push(C.jsxAttribute(C.jsxIdentifier(t.prop),S)),u()}let p=t.newValue;if(!a)return l?me(`\`${t.prop}\` is not written on this element and the element spreads props from a variable.`):(i.push(C.jsxAttribute(C.jsxIdentifier(t.prop),nt(p))),u(`Added the \`${t.prop}\` prop (it was not set in source).`));if(a.value===null||a.value===void 0)return p===!0||(a.value=nt(p)),u();if(a.value.type==="StringLiteral"||a.value.type==="Literal")return a.value=nt(p),u();if(a.value.type!=="JSXExpressionContainer")return me(`Unsupported value for \`${t.prop}\`.`);let f=a.value.expression,v=typeof f.start=="number"?e.slice(f.start,f.end):f.type,x=()=>me(`\`${t.prop}\` is computed in code (\`${v}\`), not a literal.`);if(Array.isArray(p)){if(f.type==="ArrayExpression"){let S=f.elements.map(V);return S.some(w=>w===void 0)?x():(S.length!==p.length?a.value.expression=Re(p):p.forEach((w,j)=>{Math.abs(S[j]-w)>5e-4&&(f.elements[j]=Me(w))}),u())}if(V(f)===void 0)return x();let b=p.every(S=>it(S)===it(p[0]));return a.value.expression=b&&t.prop==="scale"?Me(p[0]):Re(p),u()}if(!io(f))return x();if(typeof p=="number"){let b=V(f);if(b!==void 0&&Math.abs(b-p)<=5e-4)return u()}return a.value.expression=Re(p),u()}var Gr=new Set(["depthviewControls","useDepthviewControls"]),st=e=>e?.type==="Identifier"?e.name:e?.type==="StringLiteral"||e?.type==="Literal"?String(e.value):void 0;function lo(e,t){let o;try{o=Z.parse(e,{parser:so})}catch(n){return{ok:!1,found:!1,reason:`Could not parse the file: ${n instanceof Error?n.message:String(n)}`}}let r=[];if(Z.types.visit(o,{visitCallExpression(n){let i=n.node,a=i.callee,l=a?.type==="Identifier"?a.name:a?.type==="MemberExpression"?a.property?.name:void 0;Gr.has(l)&&st(i.arguments?.[0])===t.group&&r.push(i),this.traverse(n)}}),!r.length)return{ok:!1,found:!1,reason:`No depthviewControls('${t.group}', \u2026) call.`};for(let n of r){let i=n.arguments[1];if(i?.type!=="ObjectExpression")continue;let a=i.properties.find(b=>(b.type==="ObjectProperty"||b.type==="Property")&&st(b.key)===t.key);if(!a)continue;let l=a;if(a.value?.type==="ObjectExpression"){let b=a.value.properties.find(S=>(S.type==="ObjectProperty"||S.type==="Property")&&st(S.key)==="value");if(!b)return{ok:!1,found:!0,reason:`"${t.group}.${t.key}" has no \`value\` field in its declaration.`};l=b}let h=l.value,u=typeof h?.start=="number"?e.slice(h.start,h.end):h?.type;if(!io(h))return{ok:!1,found:!0,reason:`"${t.group}.${t.key}" is computed in code (\`${u}\`), not a literal.`};let p=h.type==="StringLiteral"&&e[h.start]==="'"?"single":"double",f=a.loc?.start.line??0,v=typeof t.value=="number"?Math.abs((V(h)??NaN)-t.value)<=5e-7:h.value===t.value;v||(l.value=typeof t.value=="number"?C.numericLiteral(Math.round(t.value*1e6)/1e6):typeof t.value=="boolean"?C.booleanLiteral(t.value):C.stringLiteral(t.value)),!v&&typeof t.value=="number"&&t.value<0&&(l.value=C.unaryExpression("-",C.numericLiteral(Math.round(-t.value*1e6)/1e6)));let x=Z.print(o,{quote:p}).code;return{ok:!0,code:x,changed:x!==e,line:f}}return{ok:!1,found:!0,reason:`depthviewControls('${t.group}', \u2026) has no "${t.key}" key written as a literal object.`}}function co(e,t,o=12){let r=e.split(`
|
|
1027
|
+
`),n=Math.max(1,t-o),i=Math.min(r.length,t+o),a=String(i).length;return r.slice(n-1,i).map((l,h)=>`${n+h===t?">":" "} ${String(n+h).padStart(a)} | ${l}`).join(`
|
|
1028
|
+
`)}var uo=_.union([_.number().finite(),_.boolean(),_.string().max(128),_.array(_.number().finite()).min(2).max(4)]),fo=_.object({file:_.string().min(1).max(1024),line:_.number().int().min(1),column:_.number().int().min(0),component:_.string().max(128).default(""),prop:_.string().regex(/^[A-Za-z_$][\w$-]{0,63}$/),oldValue:uo,newValue:uo}),po=/\.(jsx|tsx|js|ts|mjs)$/,mo=_.tuple([_.number().finite(),_.number().finite(),_.number().finite()]),ut=_.object({version:_.literal(1),keys:_.array(_.object({percent:_.number().min(0).max(100),position:mo,target:mo,fov:_.number().min(1).max(179)})).min(1).max(200)}),dt=_.object({version:_.literal(1)}).passthrough().refine(e=>JSON.stringify(e).length<2e5,"The look is too large."),go=_.array(_.object({group:_.string().min(1).max(128),key:_.string().min(1).max(128),value:_.union([_.number().finite(),_.boolean(),_.string().max(512)])})).min(1).max(200),Kr=new Set(["node_modules","dist","build","out","coverage",".next",".git"]),Le=class extends Jr{root;edits=new Map;snapshot=null;constructor(t){super(),this.root=Ce(Q(t))}resolveFile(t){let o=Ce(ht(t)?t:Q(this.root,t));if(!o.startsWith(this.root+ve))throw new Error("File is outside the project root");if(o.split(ve).includes("node_modules"))throw new Error("Files in node_modules are not edited");if(!po.test(o))throw new Error("Not a JavaScript/TypeScript source file");return o}jsonTarget(t,o,r){let n=r&&r.trim()?r.trim():at(Q(this.root,"src"))?`src/${t}`:t;if(!/^[\w.-]+\.json$/.test(ct(n)))throw new Error(`The ${o} file must be a .json file name (letters, digits, - _ .).`);let i=ht(n)?n:Q(this.root,n),a;try{a=Ce(ho(i))}catch{throw new Error(`The folder ${ge(this.root,ho(i))||"."} does not exist.`)}if(a!==this.root&&!a.startsWith(this.root+ve))throw new Error("File is outside the project root");if(a.split(ve).includes("node_modules"))throw new Error("Files in node_modules are not edited");let l=Q(a,ct(i));if(at(l)&&!lt(l).isFile())throw new Error("Not a file");return l}writeCameraPath(t,o){let r=this.jsonTarget("camera-path.json","camera path",o);return Ae(r,`${JSON.stringify(ut.parse(t),null,2)}
|
|
1029
|
+
`),this.cameraPath={file:ge(this.root,r),savedAt:Date.now()},this.cameraPath.file}writeLook(t,o){let r=this.jsonTarget("depthview-look.json","look",o),n=Te(ue(dt.parse(t)));return Ae(r,`${JSON.stringify(n,null,2)}
|
|
1030
|
+
`),this.look={file:ge(this.root,r),savedAt:Date.now()},this.look.file}readImage(t){let o=ht(t)?t:Q(this.root,t);if(!at(o))throw new Error(`No file ${t} in the project.`);let r=Ce(o);if(!r.startsWith(this.root+ve))throw new Error("File is outside the project root");let n={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp"}[r.split(".").pop().toLowerCase()];if(!n)throw new Error("The reference must be a .png, .jpg or .webp picture.");if(lt(r).size>6e6)throw new Error("The reference picture is larger than 6 MB. Save a smaller copy.");return{dataUrl:`data:${n};base64,${fe(r).toString("base64")}`,name:ct(r)}}look=null;controlFiles(t=400){let o=[],r=0,n=(i,a)=>{if(a>8||o.length>=t||r>2e4)return;let l;try{l=Xr(i,{withFileTypes:!0})}catch{return}for(let h of l){if(h.name.startsWith(".")||Kr.has(h.name))continue;let u=Q(i,h.name);if(h.isDirectory())n(u,a+1);else if(h.isFile()&&po.test(h.name)){r++;try{if(lt(u).size>6e5)continue;fe(u,"utf8").includes("epthviewControls(")&&o.push(u)}catch{}}}};return n(this.root,0),o}saveControls(t){let o=this.controlFiles();return t.map(r=>{let n=o.length?`No depthviewControls('${r.group}', \u2026) call was found in the project.`:"No file in the project calls depthviewControls or useDepthviewControls.";for(let i of o){let a=fe(i,"utf8"),l=lo(a,r);if(l.ok)return l.changed&&Ae(i,l.code),{...r,ok:!0,file:ge(this.root,i),line:l.line};if(l.found){n=`${ge(this.root,i)}: ${l.reason}`;break}}return{...r,ok:!1,error:n}})}cameraPath=null;tryApply(t,o){let r;try{r=this.resolveFile(t.file)}catch(a){t.status="failed",t.message=a instanceof Error?a.message:String(a);return}let n=fe(r,"utf8"),i=ao(n,{line:t.line,column:t.column,prop:t.prop,newValue:t.newValue,expression:o});i.ok?(i.changed&&Ae(r,i.code),t.status="applied",t.message=i.note):(t.status=i.needsAgent?"queued":"failed",t.message=i.reason)}submit(t){let o=t.map(r=>({...r,id:qr().slice(0,8),status:"queued"}));for(let r of[...o].sort((n,i)=>n.file===i.file?i.line-n.line||i.column-n.column:0))this.tryApply(r),this.edits.set(r.id,r);return o}list(t){let o=[...this.edits.values()];return t?o.filter(r=>r.status===t):o}get(t){let o=this.edits.get(t);if(!o)throw new Error(`Unknown edit id: ${t}`);return o}context(t,o=12){let r=this.get(t),n=this.resolveFile(r.file);return{edit:r,file:n,source:co(fe(n,"utf8"),r.line,o)}}apply(t,o){let r=this.get(t);return this.tryApply(r,o),this.emit("change",r),r}markDone(t,o,r){let n=this.get(t);return n.status=o,r&&(n.message=r),this.emit("change",n),n}};import{spawn as Yr,spawnSync as Zr}from"node:child_process";import{existsSync as De,mkdtempSync as Qr,readFileSync as vo,rmSync as en}from"node:fs";import{tmpdir as tn}from"node:os";import{dirname as on,join as ft}from"node:path";import{fileURLToPath as rn}from"node:url";import{WebSocket as pt}from"ws";var nn={darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"],win32:["C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe","C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"],linux:["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge"]};function sn(){let e=process.env.DEPTHVIEW_CHROME??process.env.CHROME_PATH;if(e)return De(e)?e:null;for(let t of nn[process.platform]??[]){if(t.includes("/")||t.includes("\\")){if(De(t))return t;continue}let o=Zr("which",[t],{encoding:"utf8"}),r=o.status===0?o.stdout.trim():"";if(r)return r}return null}function mt(){return ft(on(rn(import.meta.url)),"..","dist","probe.js")}var Pe=e=>new Promise(t=>setTimeout(t,e)),Fe=class{constructor(t){this.onPageMessage=t}url="";chrome=null;socket=null;profile="";sessionId="";counter=0;pending=new Map;events=new Map;metrics={width:1280,height:800,pixelRatio:1};initial={...this.metrics};problems=[];get open(){return this.socket!==null&&this.socket.readyState===pt.OPEN}get size(){return{...this.metrics}}send(t,o={},r=!0){let n=this.socket;if(!n||n.readyState!==pt.OPEN)return Promise.reject(new Error("The preview browser is not running. Call open_preview."));let i=++this.counter;return new Promise((a,l)=>{this.pending.set(i,{resolve:a,reject:l}),n.send(JSON.stringify({id:i,method:t,params:o,...r?{sessionId:this.sessionId}:{}}))})}once(t,o){return new Promise(r=>{let n=this.events.get(t)??[],i=h=>{clearTimeout(l);let u=n.indexOf(a);u>=0&&n.splice(u,1),r(h)},a=h=>i(h),l=setTimeout(()=>i(null),o);n.push(a),this.events.set(t,n)})}on(t,o){let r=this.events.get(t)??[];r.push(o),this.events.set(t,r)}async start(t){let o=new URL(t.url);if(o.protocol!=="http:"&&o.protocol!=="https:")throw new Error("open_preview takes an http or https address, e.g. http://localhost:5173/.");this.metrics={width:Math.round(t.width??1280),height:Math.round(t.height??800),pixelRatio:t.pixelRatio??1},this.initial={...this.metrics},this.open||await this.launch(),this.problems.length=0,await this.applyMetrics();let r=this.once("Page.loadEventFired",3e4),n=await this.send("Page.navigate",{url:o.href});if(typeof n.errorText=="string"&&n.errorText)throw new Error(`Could not open ${o.href}: ${n.errorText}. Is the dev server running?`);await r||this.problems.push("The page did not finish loading within 30 seconds."),this.url=o.href,await Pe(Math.min(15e3,Math.max(0,t.wait??1500)))}async launch(){let t=sn();if(!t)throw new Error("No Chrome, Chromium, Edge or Brave was found on this machine. Install one, or set DEPTHVIEW_CHROME to its path. (The Depthview extension does not need this.)");if(!De(mt()))throw new Error(`${mt()} is missing: build depthview-mcp first (pnpm build).`);this.profile=Qr(ft(tn(),"depthview-preview-"));let o=Yr(t,["--headless=new","--remote-debugging-port=0",`--user-data-dir=${this.profile}`,"--no-first-run","--no-default-browser-check","--disable-extensions","--disable-background-networking","--disable-sync","--mute-audio","--hide-scrollbars","--ignore-gpu-blocklist","--enable-unsafe-swiftshader","--disable-background-timer-throttling","--disable-renderer-backgrounding","--disable-backgrounding-occluded-windows",`--window-size=${this.metrics.width},${this.metrics.height}`,"about:blank"],{stdio:"ignore"});this.chrome=o,o.on("exit",()=>this.dispose());let r=ft(this.profile,"DevToolsActivePort"),n="";for(let h=0;h<100&&!n&&(await Pe(100),o.exitCode===null);h++){if(!De(r))continue;let[u,p]=vo(r,"utf8").trim().split(`
|
|
1031
|
+
`);u&&p&&(n=`ws://127.0.0.1:${u}${p}`)}if(!n)throw this.dispose(),new Error(`${t} did not start in headless mode.`);let i=new pt(n,{perMessageDeflate:!1});await new Promise((h,u)=>{i.once("open",()=>h()),i.once("error",p=>u(p))}),this.socket=i,i.on("close",()=>this.dispose()),i.on("message",h=>{let u;try{u=JSON.parse(String(h))}catch{return}if(typeof u.id=="number"){let p=this.pending.get(u.id);if(!p)return;this.pending.delete(u.id);let f=u.error;f?p.reject(new Error(f.message??"Browser error")):p.resolve(u.result??{})}else if(typeof u.method=="string")for(let p of(this.events.get(u.method)??[]).slice())p(u.params??{})});let a=await this.send("Target.createTarget",{url:"about:blank"},!1),l=await this.send("Target.attachToTarget",{targetId:a.targetId,flatten:!0},!1);this.sessionId=String(l.sessionId),await this.send("Page.enable"),await this.send("Runtime.enable"),await this.send("Runtime.addBinding",{name:"__depthviewSend"}),await this.send("Page.addScriptToEvaluateOnNewDocument",{source:vo(mt(),"utf8")}),this.on("Runtime.bindingCalled",h=>{h.name==="__depthviewSend"&&this.fromPage(String(h.payload))}),this.on("Runtime.exceptionThrown",h=>{let u=h.exceptionDetails,p=u?.exception?.description??u?.text;p&&this.problems.length<30&&this.problems.push(p.split(`
|
|
1032
|
+
`)[0])})}async fromPage(t){let o="",r=null;try{let n=JSON.parse(t);o=String(n.id??"");let i=n.payload??{};r=i.type==="screenshot"?await this.screenshot():await this.onPageMessage(i)}catch(n){r={ok:!1,error:n instanceof Error?n.message:String(n)}}o&&await this.send("Runtime.evaluate",{expression:`window.__depthviewResolve(${JSON.stringify(o)}, ${JSON.stringify(JSON.stringify(r))})`}).catch(()=>{})}applyMetrics(){return this.send("Emulation.setDeviceMetricsOverride",{width:this.metrics.width,height:this.metrics.height,deviceScaleFactor:this.metrics.pixelRatio,mobile:!1})}async screenshot(){let{width:t,height:o,pixelRatio:r}=this.metrics,n=Math.min(1,1600/(Math.max(t,o)*r)),i=await this.send("Page.getLayoutMetrics",{}),a=Number(i.cssVisualViewport?.pageX)||0,l=Number(i.cssVisualViewport?.pageY)||0,h=await this.send("Page.captureScreenshot",{format:"jpeg",quality:82,clip:{x:a,y:l,width:t,height:o,scale:n}});return{data:String(h.data??""),mimeType:"image/jpeg",width:Math.round(t*r*n),height:Math.round(o*r*n)}}async page(t,o,r){let n=`window.__depthviewAgent ? window.__depthviewAgent(${JSON.stringify(t)}, ${JSON.stringify(JSON.stringify(o))}) : ""`,i=await Promise.race([this.send("Runtime.evaluate",{expression:n,awaitPromise:!0,returnByValue:!0}),Pe(r).then(()=>null)]);if(!i)throw new Error("The preview page did not answer in time.");let a=i.result?.value;if(typeof a!="string"||!a)throw new Error("The preview page is not ready (it may have navigated away). Call open_preview again.");let l=JSON.parse(a);if(!l.ok)throw new Error(l.error??"Failed");return l.data}async rpc(t,o,r=8e3){if(t==="screenshot")return await Pe(120),this.screenshot();t==="viewport"&&(o.reset===!0?this.metrics={...this.initial}:typeof o.width=="number"&&typeof o.height=="number"&&(this.metrics={...this.metrics,width:o.width,height:o.height}),typeof o.devicePixelRatio=="number"&&(this.metrics={...this.metrics,pixelRatio:o.devicePixelRatio}),await this.applyMetrics());let n=await this.page(t,o,r);return t==="performance"&&n&&typeof n=="object"?{...n,note:"Measured in the headless preview, which may draw with software and at its own frame rate: compare before and after here, do not read the numbers as what a visitor gets. Draw calls, triangles and passes are exact."}:t==="status"&&n&&typeof n=="object"?{...n,inspectorOpen:!1,preview:{url:this.url,...this.metrics},...this.problems.length?{loadProblems:this.problems.slice(0,10)}:{}}:n}dispose(){for(let r of this.pending.values())r.reject(new Error("The preview browser closed."));this.pending.clear(),this.events.clear();let t=this.socket;this.socket=null;try{t?.terminate()}catch{}let o=this.chrome;this.chrome=null;try{o&&o.exitCode===null&&o.kill()}catch{}if(this.profile){let r=this.profile;this.profile="",setTimeout(()=>{try{en(r,{recursive:!0,force:!0,maxRetries:3})}catch{}},400).unref()}}async stop(){this.open&&await this.send("Browser.close",{},!1).catch(()=>{}),this.dispose()}};var wo=new Set(["127.0.0.1","::1","::ffff:127.0.0.1"]),dn=5,bo=D.object({type:D.literal("edits"),requestId:D.string().max(64),edits:D.array(fo).max(200)}),yo=D.object({type:D.literal("path_file"),requestId:D.string().max(64),file:D.string().max(512).optional(),path:ut}),xo=D.object({type:D.literal("look_file"),requestId:D.string().max(64),file:D.string().max(512).optional(),look:dt}),ko=D.object({type:D.literal("controls_file"),requestId:D.string().max(64),values:go}),So=()=>String(an(0,1e6)).padStart(6,"0"),Oe=class{constructor(t){this.options=t;this.core=new Le(t.root),this.core.on("change",o=>this.broadcast({type:"edit_status",edits:[o]})),this.http=cn((o,r)=>void this.onRequest(o,r)),this.http.on("upgrade",(o,r,n)=>{let i=o.headers.origin;if(!(wo.has(o.socket.remoteAddress??"")&&(o.url??"").split("?")[0]==="/ws"&&(i===void 0||/^(chrome|moz)-extension:\/\//.test(i)))){r.destroy();return}this.wss.handleUpgrade(o,r,n,l=>this.onSocket(l))})}core;code=So();http;wss=new un({noServer:!0,maxPayload:4*1024*1024});paired=new Set;failures=0;snapshotWaiters=new Map;rpcWaiters=new Map;counter=0;lastShots=new Map;preview=null;listen(){return new Promise((t,o)=>{this.http.once("error",o),this.http.listen(this.options.port,"127.0.0.1",()=>t(this.http.address().port))})}close(){this.closePreview();for(let t of this.wss.clients)t.terminate();return this.wss.close(),new Promise(t=>this.http.close(()=>t()))}get extensionConnected(){return this.paired.size>0}get liveMode(){return this.extensionConnected?"extension":this.previewOpen?"preview":"none"}get previewOpen(){return this.preview?.open===!0}get liveConnected(){return this.extensionConnected||this.previewOpen}get previewUrl(){return this.previewOpen?this.preview.url:null}async openPreview(t){return this.preview??=new Fe(o=>this.fromPreview(o)),await this.preview.start(t),this.lastShots.clear(),this.options.log(`preview ${this.preview.url}`),{url:this.preview.url,...this.preview.size,loadProblems:this.preview.problems}}async closePreview(){let t=this.previewOpen;return await this.preview?.stop(),this.preview=null,t}fromPreview(t){let o={...t,requestId:"preview"};try{if(t.type==="edits"){let r=bo.safeParse(o);return r.success?{edits:this.core.submit(r.data.edits)}:{edits:[],error:"Malformed edit request"}}if(t.type==="path_file"){let r=yo.safeParse(o);return r.success?{ok:!0,file:this.core.writeCameraPath(r.data.path,r.data.file)}:{ok:!1,error:"Malformed camera path"}}if(t.type==="look_file"){let r=xo.safeParse(o);return r.success?{ok:!0,file:this.core.writeLook(r.data.look,r.data.file)}:{ok:!1,error:"Malformed look"}}if(t.type==="controls_file"){let r=ko.safeParse(o);return r.success?{ok:!0,results:this.core.saveControls(r.data.values)}:{ok:!1,error:"Malformed controls"}}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}return null}rotateCode(t){this.code=So(),this.failures=0,this.options.log(`${t} New pairing code: ${this.code}`)}broadcast(t){let o=JSON.stringify(t);for(let r of this.paired)r.readyState===r.OPEN&&r.send(o)}onSocket(t){let o=r=>t.send(JSON.stringify(r));t.on("close",()=>this.paired.delete(t)),t.on("error",()=>this.paired.delete(t)),t.on("message",r=>{let n;try{n=JSON.parse(String(r))}catch{return}if(!this.paired.has(t)){if(n.type!=="pair"||typeof n.code!="string"){t.close(1008,"pair first");return}let i=Buffer.from(n.code.padEnd(6).slice(0,6));n.code.length===6&&ln(i,Buffer.from(this.code))?(this.paired.add(t),o({type:"paired"}),this.rotateCode("Extension paired.")):(o({type:"error",message:"Wrong pairing code"}),t.close(1008,"wrong code"),++this.failures>=dn&&this.rotateCode("Too many wrong codes."));return}if(n.type==="ping")o({type:"pong"});else if(n.type==="edits"){let i=bo.safeParse(n);if(!i.success){o({type:"edits_result",requestId:String(n.requestId??""),edits:[],error:"Malformed edit request"});return}let a=this.core.submit(i.data.edits);for(let l of a)this.options.log(`${l.status.padEnd(7)} ${l.file.replace(this.core.root,".")}:${l.line} ${l.prop}${l.message?` (${l.message})`:""}`);o({type:"edits_result",requestId:i.data.requestId,edits:a})}else if(n.type==="path_file"){let i=yo.safeParse(n),a=String(n.requestId??"");if(!i.success){o({type:"path_file_result",requestId:a,ok:!1,error:"Malformed camera path"});return}try{let l=this.core.writeCameraPath(i.data.path,i.data.file);this.options.log(`camera path ${l} (${i.data.path.keys.length} keys)`),o({type:"path_file_result",requestId:a,ok:!0,file:l})}catch(l){o({type:"path_file_result",requestId:a,ok:!1,error:l instanceof Error?l.message:String(l)})}}else if(n.type==="look_file"){let i=xo.safeParse(n),a=String(n.requestId??"");if(!i.success){o({type:"look_file_result",requestId:a,ok:!1,error:"Malformed look"});return}try{let l=this.core.writeLook(i.data.look,i.data.file);this.options.log(`look ${l}`),o({type:"look_file_result",requestId:a,ok:!0,file:l})}catch(l){o({type:"look_file_result",requestId:a,ok:!1,error:l instanceof Error?l.message:String(l)})}}else if(n.type==="controls_file"){let i=ko.safeParse(n),a=String(n.requestId??"");if(!i.success){o({type:"controls_file_result",requestId:a,ok:!1,error:"Malformed controls"});return}try{let l=this.core.saveControls(i.data.values);for(let h of l)this.options.log(`control ${h.group}.${h.key} = ${JSON.stringify(h.value)} ${h.ok?`${h.file}:${h.line}`:`(${h.error})`}`);o({type:"controls_file_result",requestId:a,ok:!0,results:l})}catch(l){o({type:"controls_file_result",requestId:a,ok:!1,error:l instanceof Error?l.message:String(l)})}}else if(n.type==="snapshot"){n.snapshot&&(this.core.snapshot=n.snapshot);let i=this.snapshotWaiters.get(String(n.requestId??""));i&&i(this.core.snapshot)}else if(n.type==="rpc_result"){let i=this.rpcWaiters.get(String(n.requestId??""));if(!i)return;n.ok===!0?i.resolve(n.data):i.reject(new Error(typeof n.error=="string"?n.error:"Failed"))}})}requestSnapshot(t=3e3){if(!this.extensionConnected)return this.preview?.open?this.preview.rpc("describe",{},t).catch(()=>this.core.snapshot):Promise.resolve(this.core.snapshot);let o=`s${++this.counter}`;return new Promise(r=>{let n=setTimeout(()=>{this.snapshotWaiters.delete(o),r(this.core.snapshot)},t);this.snapshotWaiters.set(o,i=>{clearTimeout(n),this.snapshotWaiters.delete(o),r(i)}),this.broadcast({type:"request_snapshot",requestId:o})})}rpc(t,o={},r=8e3){if(!this.extensionConnected)return this.preview?.open?this.preview.rpc(t,o,r):Promise.reject(new Error('No page is connected. Either call open_preview with the address of the dev server (the page is opened in a headless browser and the live tools work on it), or ask the developer to open Depthview on their page and enter the pairing code under "AI agent & code sync".'));let n=`c${++this.counter}`;return new Promise((i,a)=>{let l=()=>{clearTimeout(h),this.rpcWaiters.delete(n)},h=setTimeout(()=>{l(),a(new Error("The Depthview inspector did not answer. It must be open on the page (click the extension icon) and the tab must be in front."))},r);this.rpcWaiters.set(n,{resolve:u=>{l(),i(u)},reject:u=>{l(),a(u)}}),this.broadcast({type:"rpc",requestId:n,method:t,params:o})})}async onRequest(t,o){let r=(n,i)=>{o.writeHead(n,{"content-type":"application/json"}),o.end(JSON.stringify(i))};try{let n=(t.headers.host??"").replace(/:\d+$/,""),i=t.headers.origin;if(!wo.has(t.socket.remoteAddress??"")||!["127.0.0.1","localhost","[::1]"].includes(n))return r(403,{error:"Local connections only"});if(i!==void 0&&!/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/.test(i))return r(403,{error:"Origin not allowed"});let a=(t.url??"/").split("?")[0];if(a==="/health")return r(200,{name:"depthview-mcp",extensionConnected:this.extensionConnected});if(a!=="/mcp"||!this.options.mcpHttp)return r(404,{error:"Not found"});if(t.method!=="POST")return r(405,{jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed"},id:null});let l=[],h=0;for await(let v of t){if(h+=v.length,h>4*1024*1024)return r(413,{error:"Request too large"});l.push(v)}let u=JSON.parse(Buffer.concat(l).toString("utf8")),p=je(this,{includePairingCode:!1}),f=new hn({sessionIdGenerator:void 0});o.on("close",()=>{f.close(),p.close()}),await p.connect(f),await f.handleRequest(t,o,u)}catch(n){o.headersSent||r(400,{jsonrpc:"2.0",error:{code:-32700,message:n instanceof Error?n.message:"Bad request"},id:null})}}};var Sn=`Depthview MCP server
|
|
1146
1033
|
|
|
1147
1034
|
npx depthview-mcp [--root <dir>] [--port <n>] [--stdio]
|
|
1148
1035
|
npx depthview-mcp init [--root <dir>]
|
|
@@ -1154,80 +1041,8 @@ var HELP = `Depthview MCP server
|
|
|
1154
1041
|
--port Port on 127.0.0.1. Default: 7411.
|
|
1155
1042
|
--stdio Speak MCP on stdin/stdout (for clients that start the server themselves).
|
|
1156
1043
|
Without it, MCP is served at http://127.0.0.1:<port>/mcp.
|
|
1157
|
-
`;
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
}
|
|
1162
|
-
function init(root) {
|
|
1163
|
-
const out = (line) => void process.stdout.write(`${line}
|
|
1164
|
-
`);
|
|
1165
|
-
const cli = fileURLToPath(import.meta.url);
|
|
1166
|
-
const installed = cli.split(sep2).includes("node_modules");
|
|
1167
|
-
const entry = installed ? { command: "npx", args: ["-y", "depthview-mcp", "--stdio"] } : { command: "node", args: [cli, "--stdio"] };
|
|
1168
|
-
const configPath = join(root, ".mcp.json");
|
|
1169
|
-
let config = {};
|
|
1170
|
-
if (existsSync(configPath)) {
|
|
1171
|
-
try {
|
|
1172
|
-
config = JSON.parse(readFileSync2(configPath, "utf8"));
|
|
1173
|
-
} catch {
|
|
1174
|
-
throw new Error(`${configPath} is not valid JSON. Fix it, then run init again.`);
|
|
1175
|
-
}
|
|
1176
|
-
if (typeof config !== "object" || config === null || Array.isArray(config))
|
|
1177
|
-
throw new Error(`${configPath} is not a JSON object. Fix it, then run init again.`);
|
|
1178
|
-
}
|
|
1179
|
-
config.mcpServers = { ...config.mcpServers, depthview: entry };
|
|
1180
|
-
writeFileSync2(configPath, `${JSON.stringify(config, null, 2)}
|
|
1181
|
-
`);
|
|
1182
|
-
out(`wrote ${configPath}`);
|
|
1183
|
-
const skill = join(dirname(cli), "..", "skill", "SKILL.md");
|
|
1184
|
-
const skillPath = join(root, ".claude", "skills", "depthview", "SKILL.md");
|
|
1185
|
-
mkdirSync(dirname(skillPath), { recursive: true });
|
|
1186
|
-
writeFileSync2(skillPath, readFileSync2(skill));
|
|
1187
|
-
out(`wrote ${skillPath}`);
|
|
1188
|
-
out("");
|
|
1189
|
-
out("Next:");
|
|
1190
|
-
out(' 1. Start (or restart) Claude Code in this project and allow the "depthview" server.');
|
|
1191
|
-
out(" 2. Open your dev site in Chrome and click the Depthview icon.");
|
|
1192
|
-
out(' 3. Ask Claude: "pair with Depthview". Type the code it gives into the side panel,');
|
|
1193
|
-
out(' under "AI agent & code sync".');
|
|
1194
|
-
out(" For exact source edits, add @depthview/r3f-bridge to the project.");
|
|
1195
|
-
}
|
|
1196
|
-
async function main() {
|
|
1197
|
-
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
1198
|
-
process.stdout.write(HELP);
|
|
1199
|
-
return;
|
|
1200
|
-
}
|
|
1201
|
-
const stdio = process.argv.includes("--stdio");
|
|
1202
|
-
const root = resolve2(option("root") ?? process.cwd());
|
|
1203
|
-
if (process.argv[2] === "init") {
|
|
1204
|
-
init(root);
|
|
1205
|
-
return;
|
|
1206
|
-
}
|
|
1207
|
-
const port = Number(option("port") ?? process.env.DEPTHVIEW_PORT ?? 7411);
|
|
1208
|
-
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
1209
|
-
throw new Error(`Invalid port: ${option("port")}`);
|
|
1210
|
-
const log = (line) => void process.stderr.write(`[depthview] ${line}
|
|
1211
|
-
`);
|
|
1212
|
-
const server = new DepthviewServer({ root, port, mcpHttp: !stdio, log });
|
|
1213
|
-
const actualPort = await server.listen();
|
|
1214
|
-
log(`project root ${root}`);
|
|
1215
|
-
log(`extension ws://127.0.0.1:${actualPort}/ws`);
|
|
1216
|
-
if (!stdio) {
|
|
1217
|
-
log(`MCP (http) http://127.0.0.1:${actualPort}/mcp`);
|
|
1218
|
-
log(
|
|
1219
|
-
` claude mcp add --transport http depthview http://127.0.0.1:${actualPort}/mcp`
|
|
1220
|
-
);
|
|
1221
|
-
}
|
|
1222
|
-
log(`pairing code ${server.code} (type it into the Depthview side panel)`);
|
|
1223
|
-
if (stdio)
|
|
1224
|
-
await buildMcpServer(server, { includePairingCode: true }).connect(new StdioServerTransport());
|
|
1225
|
-
const stop = () => void server.close().then(() => process.exit(0));
|
|
1226
|
-
process.on("SIGINT", stop);
|
|
1227
|
-
process.on("SIGTERM", stop);
|
|
1228
|
-
}
|
|
1229
|
-
main().catch((err) => {
|
|
1230
|
-
process.stderr.write(`[depthview] ${err instanceof Error ? err.message : String(err)}
|
|
1231
|
-
`);
|
|
1232
|
-
process.exit(1);
|
|
1233
|
-
});
|
|
1044
|
+
`;function gt(e){let t=process.argv.indexOf(`--${e}`);return t>=0?process.argv[t+1]:void 0}function _n(e){let t=u=>void process.stdout.write(`${u}
|
|
1045
|
+
`),o=kn(import.meta.url),n=o.split(xn).includes("node_modules")?{command:"npx",args:["-y","depthview-mcp","--stdio"]}:{command:"node",args:[o,"--stdio"]},i=ze(e,".mcp.json"),a={};if(fn(i)){try{a=JSON.parse(vn(i,"utf8"))}catch{throw new Error(`${i} is not valid JSON. Fix it, then run init again.`)}if(typeof a!="object"||a===null||Array.isArray(a))throw new Error(`${i} is not a JSON object. Fix it, then run init again.`)}a.mcpServers={...a.mcpServers,depthview:n},wn(i,`${JSON.stringify(a,null,2)}
|
|
1046
|
+
`),t(`wrote ${i}`);let l=ze(bn(o),"..","skill"),h=ze(e,".claude","skills","depthview");gn(h,{recursive:!0}),mn(l,h,{recursive:!0}),t(`wrote ${ze(h,"SKILL.md")} and references/`),t(""),t("Next:"),t(' 1. Start (or restart) Claude Code in this project and allow the "depthview" server.'),t(" 2. Open your dev site in Chrome and click the Depthview icon."),t(' 3. Ask Claude: "pair with Depthview". Type the code it gives into the side panel,'),t(' under "AI agent & code sync".'),t(" For exact source edits, add depthview-r3f-bridge to the project.")}async function Tn(){if(process.argv.includes("--help")||process.argv.includes("-h")){process.stdout.write(Sn);return}let e=process.argv.includes("--stdio"),t=yn(gt("root")??process.cwd());if(process.argv[2]==="init"){_n(t);return}let o=Number(gt("port")??process.env.DEPTHVIEW_PORT??7411);if(!Number.isInteger(o)||o<0||o>65535)throw new Error(`Invalid port: ${gt("port")}`);let r=l=>void process.stderr.write(`[depthview] ${l}
|
|
1047
|
+
`),n=new Oe({root:t,port:o,mcpHttp:!e,log:r}),i=await n.listen();r(`project root ${t}`),r(`extension ws://127.0.0.1:${i}/ws`),e||(r(`MCP (http) http://127.0.0.1:${i}/mcp`),r(` claude mcp add --transport http depthview http://127.0.0.1:${i}/mcp`)),r(`pairing code ${n.code} (type it into the Depthview side panel)`),e&&await je(n,{includePairingCode:!0}).connect(new pn);let a=()=>void n.close().then(()=>process.exit(0));process.on("SIGINT",a),process.on("SIGTERM",a)}Tn().catch(e=>{process.stderr.write(`[depthview] ${e instanceof Error?e.message:String(e)}
|
|
1048
|
+
`),process.exit(1)});
|