@fleox/agent3d 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +20 -13
  2. package/changelog.json +26 -0
  3. package/dist/agent/agent3d.mjs +228 -53
  4. package/dist/agent/chunks/{assets-BUUM9TUB.mjs → assets-YBkgdfgy.mjs} +27 -8
  5. package/dist/agent/chunks/{browser-Br1tURgt.mjs → browser-Dil7VM5m.mjs} +1 -1
  6. package/dist/agent/chunks/{cdp-Bdtm4fBN.mjs → cdp-DLEis_Z3.mjs} +1 -1
  7. package/dist/agent/chunks/{check-CfZcfaPs.mjs → check-DP9fRYbK.mjs} +64 -4
  8. package/dist/agent/chunks/depth-BZT4gseQ.mjs +483 -0
  9. package/dist/agent/chunks/depth-CD_ql3QJ.mjs +190 -0
  10. package/dist/agent/chunks/{export-BHugc2H7.mjs → export-bJwh2SqG.mjs} +12 -6
  11. package/dist/agent/chunks/{imageCodec-QM0EXQDJ.mjs → imageCodec-DeGfmBp3.mjs} +3 -3
  12. package/dist/agent/chunks/{objects-DBAws7uf.mjs → objects-DuytRxiC.mjs} +3 -3
  13. package/dist/agent/chunks/{optimizeSizing-CkZ3fZRp.mjs → optimizeSizing-B-BBiUkD.mjs} +51 -3
  14. package/dist/agent/chunks/{package-fw4h5vsh.mjs → package-fMbw9UGh.mjs} +2 -1
  15. package/dist/agent/chunks/{render-EHb40avl.mjs → render-B05DU4Q5.mjs} +4 -4
  16. package/dist/agent/chunks/{scene-BgajNvBf.mjs → scene-DWgXH6As.mjs} +2 -2
  17. package/dist/agent/chunks/{server-CACCerkZ.mjs → server-Dt_YFvN7.mjs} +6 -2
  18. package/dist/agent/chunks/{tools-DKxgjQSJ.mjs → tools-Cm4BqDkO.mjs} +60 -6
  19. package/dist/agent/chunks/{tree-BrNYGui2.mjs → tree-CqSj-o8T.mjs} +1 -0
  20. package/dist/agent/ort/LICENSE.txt +9 -0
  21. package/dist/agent/ort/ort-wasm-simd-threaded.wasm +0 -0
  22. package/dist/agent/ort/ort.wasm.bundle.min.mjs +9 -0
  23. package/dist/runtime/agent3d-runtime.js +6 -6
  24. package/dist/runtime/agent3d-runtime.single.js +311 -62
  25. package/dist/runtime/chunks/assets-qnxDnVkj.js +1 -0
  26. package/dist/runtime/chunks/materials-dC4vDNHh.js +107 -0
  27. package/dist/runtime/chunks/{model-DbfZaLni.js → model-BCAl_NRl.js} +1 -1
  28. package/dist/runtime/chunks/photo-DNf14X7B.js +250 -0
  29. package/dist/runtime/chunks/svg-CLUxY6Zy.js +1 -0
  30. package/dist/runtime/chunks/{text-BaON-ISS.js → text-rSo_2Luk.js} +2 -2
  31. package/dist/studio/assets/assets-BW5lQkYR.js +1 -0
  32. package/dist/studio/assets/{camera-Be6lnp3k.js → camera-BgzPVnn-.js} +1 -1
  33. package/dist/studio/assets/{editor-Mpnz-b2E.js → editor-NkBUKsDB.js} +1 -1
  34. package/dist/studio/assets/{game-WMgRSJUD.js → game-DARpu0ah.js} +3 -3
  35. package/dist/studio/assets/{generators-DozXE7ta.js → generators-BjIs-kHx.js} +1 -1
  36. package/dist/studio/assets/index-L-N-e2KM.js +479 -0
  37. package/dist/studio/assets/{model-C2bZTK7-.js → model-CqI8j03Z.js} +1 -1
  38. package/dist/studio/assets/params-DhsDKSDs.js +1 -0
  39. package/dist/studio/assets/photo-DAHd1yNF.js +250 -0
  40. package/dist/studio/assets/{physicsHost-CTRsIvfu.js → physicsHost-tEUto2-_.js} +1 -1
  41. package/dist/studio/assets/{postfx-DQtp0JIy.js → postfx-BGu30OJK.js} +1 -1
  42. package/dist/studio/assets/runtime-C_qkIpAK.js +572 -0
  43. package/dist/studio/assets/{shaders-BOb6Uter.js → shaders-Dt6FGXH_.js} +12 -12
  44. package/dist/studio/assets/svg-ZZt5MdNf.js +2 -0
  45. package/dist/studio/assets/{text-CGIZs8HE.js → text-B-HM422i.js} +2 -2
  46. package/dist/studio/index.html +1 -1
  47. package/package.json +2 -1
  48. package/plugin/.claude-plugin/plugin.json +1 -1
  49. package/plugin/skills/agent3d-assets/SKILL.md +40 -25
  50. package/plugin/skills/agent3d-create/SKILL.md +57 -21
  51. package/plugin/skills/agent3d-create/references/art-direction.md +3 -3
  52. package/plugin/skills/agent3d-create/references/recipes.md +71 -6
  53. package/plugin/skills/agent3d-edit/SKILL.md +22 -22
  54. package/plugin/skills/agent3d-edit/references/patch-ops.md +11 -3
  55. package/plugin/skills/agent3d-game/SKILL.md +7 -7
  56. package/plugin/skills/agent3d-publish/SKILL.md +23 -21
  57. package/plugin/skills/agent3d-publish/references/integrations.md +1 -1
  58. package/templates/hero-photo-3d/README.md +28 -0
  59. package/templates/hero-photo-3d/agent3d.json +8 -0
  60. package/templates/hero-photo-3d/assets/depth/street-depth.png +0 -0
  61. package/templates/hero-photo-3d/assets/manifest.json +25 -0
  62. package/templates/hero-photo-3d/assets/textures/street.webp +0 -0
  63. package/templates/hero-photo-3d/preview.png +0 -0
  64. package/templates/hero-photo-3d/scene.json +120 -0
  65. package/templates/hero-photo-3d/template.json +8 -0
  66. package/dist/runtime/chunks/materials-w3EW0g-7.js +0 -107
  67. package/dist/runtime/chunks/svg-CfPIQnDG.js +0 -1
  68. package/dist/studio/assets/index-tSGZFEt5.js +0 -479
  69. package/dist/studio/assets/runtime-NGp1VdnH.js +0 -572
  70. package/dist/studio/assets/svg-CnUMpv_N.js +0 -2
@@ -0,0 +1,483 @@
1
+ import { createRequire as __a3dRequire } from "node:module";
2
+ import { fileURLToPath as __a3dPath } from "node:url";
3
+ import { dirname as __a3dDirname } from "node:path";
4
+ __a3dRequire(import.meta.url);
5
+ const __filename = __a3dPath(import.meta.url);
6
+ __a3dDirname(__filename);
7
+ import { t as __exportAll } from "./rolldown-runtime-ebOQtxsr.mjs";
8
+ import { A as OpsError, I as normalizePath, S as libraryId, b as findLibraryAsset, x as isLibraryRef } from "../agent3d.mjs";
9
+ import { c as readAssetManifest, m as crc32, t as addAsset } from "./assets-YBkgdfgy.mjs";
10
+ import { n as imageHeader } from "./optimizeSizing-B-BBiUkD.mjs";
11
+ // src/ops/pngEncode.ts
12
+ async function deflateZlib(data, deflate) {
13
+ if (deflate) return deflate(data);
14
+ const CS = globalThis.CompressionStream;
15
+ if (!CS) throw new Error("No deflate available: pass `deflate` (CompressionStream is missing).");
16
+ const stream = new Blob([data]).stream().pipeThrough(new CS("deflate"));
17
+ return new Uint8Array(await new Response(stream).arrayBuffer());
18
+ }
19
+ async function encodePng(rgba, width, height, opts = {}) {
20
+ if (rgba.length !== width * height * 4) throw new Error(`encodePng: expected ${width * height * 4} bytes, got ${rgba.length}`);
21
+ let channels = opts.channels ?? "auto";
22
+ if (channels === "auto") {
23
+ let grey = true;
24
+ let opaque = true;
25
+ for (let i = 0; i < rgba.length && (grey || opaque); i += 4) {
26
+ if (rgba[i] !== rgba[i + 1] || rgba[i] !== rgba[i + 2]) grey = false;
27
+ if (rgba[i + 3] !== 255) opaque = false;
28
+ }
29
+ channels = grey ? opaque ? 1 : 2 : opaque ? 3 : 4;
30
+ }
31
+ const colorType = {
32
+ 1: 0,
33
+ 2: 4,
34
+ 3: 2,
35
+ 4: 6
36
+ }[channels];
37
+ const stride = width * channels;
38
+ const raw = new Uint8Array((stride + 1) * height);
39
+ const row = new Uint8Array(stride);
40
+ const prev = new Uint8Array(stride);
41
+ const cand = new Uint8Array(stride);
42
+ for (let y = 0; y < height; y++) {
43
+ for (let x = 0; x < width; x++) {
44
+ const s = (y * width + x) * 4;
45
+ const d = x * channels;
46
+ if (channels === 1) row[d] = rgba[s];
47
+ else if (channels === 2) row[d] = rgba[s], row[d + 1] = rgba[s + 3];
48
+ else for (let c = 0; c < channels; c++) row[d + c] = rgba[s + c];
49
+ }
50
+ let best = 0;
51
+ let bestScore = Infinity;
52
+ const out = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
53
+ for (let f = 0; f < 5; f++) {
54
+ let score = 0;
55
+ for (let i = 0; i < stride; i++) {
56
+ const a = i >= channels ? row[i - channels] : 0;
57
+ const b = prev[i];
58
+ const c = i >= channels ? prev[i - channels] : 0;
59
+ let p;
60
+ if (f === 0) p = 0;
61
+ else if (f === 1) p = a;
62
+ else if (f === 2) p = b;
63
+ else if (f === 3) p = a + b >> 1;
64
+ else {
65
+ const pa = Math.abs(b - c);
66
+ const pb = Math.abs(a - c);
67
+ const pc = Math.abs(a + b - 2 * c);
68
+ p = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
69
+ }
70
+ const v = row[i] - p & 255;
71
+ cand[i] = v;
72
+ score += v < 128 ? v : 256 - v;
73
+ if (score >= bestScore) break;
74
+ }
75
+ if (score < bestScore) {
76
+ bestScore = score;
77
+ best = f;
78
+ out.set(cand);
79
+ }
80
+ }
81
+ raw[y * (stride + 1)] = best;
82
+ prev.set(row);
83
+ }
84
+ const idat = await deflateZlib(raw, opts.deflate);
85
+ const ihdr = /* @__PURE__ */ new Uint8Array(13);
86
+ const dv = new DataView(ihdr.buffer);
87
+ dv.setUint32(0, width);
88
+ dv.setUint32(4, height);
89
+ ihdr[8] = 8;
90
+ ihdr[9] = colorType;
91
+ const chunks = [
92
+ chunk("IHDR", ihdr),
93
+ chunk("IDAT", idat),
94
+ chunk("IEND", /* @__PURE__ */ new Uint8Array(0))
95
+ ];
96
+ const sig = [
97
+ 137,
98
+ 80,
99
+ 78,
100
+ 71,
101
+ 13,
102
+ 10,
103
+ 26,
104
+ 10
105
+ ];
106
+ const total = 8 + chunks.reduce((n, c) => n + c.length, 0);
107
+ const png = new Uint8Array(total);
108
+ png.set(sig, 0);
109
+ let o = 8;
110
+ for (const c of chunks) png.set(c, o), o += c.length;
111
+ return png;
112
+ }
113
+ function chunk(type, data) {
114
+ const out = new Uint8Array(12 + data.length);
115
+ const dv = new DataView(out.buffer);
116
+ dv.setUint32(0, data.length);
117
+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
118
+ out.set(data, 8);
119
+ dv.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
120
+ return out;
121
+ }
122
+ // src/ops/depth.ts
123
+ var depth_exports = /* @__PURE__ */ __exportAll({
124
+ checkDepthRequest: () => checkDepthRequest,
125
+ estimateDepth: () => estimateDepth
126
+ });
127
+ var DA_REVISION = "4472b7362082ad9968fee890ca0f1e5aca36b93d";
128
+ var DEPTH_MODEL = {
129
+ id: "depth-anything-v2-small",
130
+ title: "Depth Anything V2 Small (ONNX, quantized)",
131
+ repo: "onnx-community/depth-anything-v2-small",
132
+ file: "onnx/model_quantized.onnx",
133
+ revision: DA_REVISION,
134
+ url: `https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/${DA_REVISION}/onnx/model_quantized.onnx`,
135
+ bytes: 27258801,
136
+ sha256: "fcf51f1b230362b28690bb9d1809bf0431f29cad20534e3f589bd7285547f20d",
137
+ license: "Apache-2.0",
138
+ author: "Depth Anything V2 (Yang et al.)",
139
+ pageUrl: "https://huggingface.co/onnx-community/depth-anything-v2-small",
140
+ attribution: "Depth Anything V2 Small by Lihe Yang, Bingyi Kang, Zilong Huang, Zhen Zhao, Xiaogang Xu, Jiashi Feng, Hengshuang Zhao (https://github.com/DepthAnything/Depth-Anything-V2), licensed under Apache-2.0.",
141
+ defaultSize: 518,
142
+ multipleOf: 14,
143
+ mean: [
144
+ .485,
145
+ .456,
146
+ .406
147
+ ],
148
+ std: [
149
+ .229,
150
+ .224,
151
+ .225
152
+ ],
153
+ inputName: "pixel_values",
154
+ outputName: "predicted_depth"
155
+ };
156
+ var DEPTH_MODEL_FILE = "model_quantized.onnx";
157
+ function depthModelDir(model = DEPTH_MODEL) {
158
+ return `${model.id}/${model.revision}`;
159
+ }
160
+ var DEPTH_SIZE_MAX = 1036;
161
+ function planDepthInput(width, height, opts = {}) {
162
+ const model = opts.model ?? DEPTH_MODEL;
163
+ const m = model.multipleOf;
164
+ if (!(width > 0 && height > 0)) throw new OpsError("invalid", `Invalid image size ${width}x${height}.`);
165
+ const req = opts.size ?? model.defaultSize;
166
+ if (!Number.isFinite(req) || req < 140 || req > 1036) throw new OpsError("invalid", `size must be between 140 and ${DEPTH_SIZE_MAX} (got ${req}).`, `Use the default ${model.defaultSize} (fast, enough for web photos), or up to 1036 for finer edges (≈ 4× slower).`);
167
+ const long = Math.max(m, Math.round(req / m) * m);
168
+ const scale = long / Math.max(width, height);
169
+ const round = (v) => Math.max(m, Math.round(v * scale / m) * m);
170
+ return width >= height ? {
171
+ width: long,
172
+ height: round(height),
173
+ size: long
174
+ } : {
175
+ width: round(width),
176
+ height: long,
177
+ size: long
178
+ };
179
+ }
180
+ function percentile(sorted, p) {
181
+ if (!sorted.length) return 0;
182
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.round(p * (sorted.length - 1))))];
183
+ }
184
+ function postprocessDepth(raw, w, h, opts = {}) {
185
+ if (raw.length !== w * h || w < 1 || h < 1) throw new OpsError("invalid", `Depth output has ${raw.length} values, expected ${w}x${h}.`);
186
+ const n = w * h;
187
+ const finite = raw.filter((v) => Number.isFinite(v));
188
+ finite.sort();
189
+ const low = percentile(finite, opts.lowPercentile ?? .01);
190
+ const high = percentile(finite, opts.highPercentile ?? .99);
191
+ const span = high - low;
192
+ let d = new Float32Array(n);
193
+ for (let i = 0; i < n; i++) {
194
+ const v = raw[i];
195
+ d[i] = !Number.isFinite(v) ? 0 : span > 1e-12 ? Math.min(1, Math.max(0, (v - low) / span)) : .5;
196
+ }
197
+ const passes = Math.max(0, Math.round(opts.smooth ?? 1));
198
+ const sr = .0072;
199
+ const spatial = [];
200
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) spatial.push(Math.exp(-(dx * dx + dy * dy) / 4.5));
201
+ for (let p = 0; p < passes; p++) {
202
+ const o = new Float32Array(n);
203
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
204
+ const c = d[y * w + x];
205
+ let sum = 0;
206
+ let wsum = 0;
207
+ let k = 0;
208
+ for (let dy = -2; dy <= 2; dy++) {
209
+ const yy = Math.min(h - 1, Math.max(0, y + dy));
210
+ for (let dx = -2; dx <= 2; dx++, k++) {
211
+ const xx = Math.min(w - 1, Math.max(0, x + dx));
212
+ const v = d[yy * w + xx];
213
+ const diff = v - c;
214
+ const wt = spatial[k] * Math.exp(-(diff * diff) / sr);
215
+ sum += v * wt;
216
+ wsum += wt;
217
+ }
218
+ }
219
+ o[y * w + x] = sum / wsum;
220
+ }
221
+ d = o;
222
+ }
223
+ const r = Math.max(0, Math.round(opts.dilate ?? 1));
224
+ if (r > 0) {
225
+ const tmp = new Float32Array(n);
226
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
227
+ let m = 0;
228
+ for (let dx = -r; dx <= r; dx++) m = Math.max(m, d[y * w + Math.min(w - 1, Math.max(0, x + dx))]);
229
+ tmp[y * w + x] = m;
230
+ }
231
+ const o = new Float32Array(n);
232
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
233
+ let m = 0;
234
+ for (let dy = -r; dy <= r; dy++) m = Math.max(m, tmp[Math.min(h - 1, Math.max(0, y + dy)) * w + x]);
235
+ o[y * w + x] = m;
236
+ }
237
+ d = o;
238
+ }
239
+ const threshold = opts.edgeThreshold ?? .08;
240
+ const mask = new Float32Array(n).fill(1);
241
+ let edgePixels = 0;
242
+ if (threshold > 0) for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
243
+ const c = d[y * w + x];
244
+ let g = 0;
245
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
246
+ const xx = x + dx;
247
+ const yy = y + dy;
248
+ if (xx < 0 || yy < 0 || xx >= w || yy >= h) continue;
249
+ g = Math.max(g, Math.abs(d[yy * w + xx] - c));
250
+ }
251
+ if (g > threshold) {
252
+ mask[y * w + x] = 0;
253
+ edgePixels++;
254
+ }
255
+ }
256
+ const W = Math.max(1, Math.round(opts.width ?? w));
257
+ const H = Math.max(1, Math.round(opts.height ?? h));
258
+ const out = new Uint8Array(W * H * 4);
259
+ const sxk = w / W;
260
+ const syk = h / H;
261
+ for (let y = 0; y < H; y++) {
262
+ const fy = Math.min(h - 1, Math.max(0, (y + .5) * syk - .5));
263
+ const y0 = Math.floor(fy);
264
+ const y1 = Math.min(h - 1, y0 + 1);
265
+ const ty = fy - y0;
266
+ for (let x = 0; x < W; x++) {
267
+ const fx = Math.min(w - 1, Math.max(0, (x + .5) * sxk - .5));
268
+ const x0 = Math.floor(fx);
269
+ const x1 = Math.min(w - 1, x0 + 1);
270
+ const tx = fx - x0;
271
+ const i00 = y0 * w + x0;
272
+ const i01 = y0 * w + x1;
273
+ const i10 = y1 * w + x0;
274
+ const i11 = y1 * w + x1;
275
+ const v = (d[i00] * (1 - tx) + d[i01] * tx) * (1 - ty) + (d[i10] * (1 - tx) + d[i11] * tx) * ty;
276
+ const a = (mask[i00] * (1 - tx) + mask[i01] * tx) * (1 - ty) + (mask[i10] * (1 - tx) + mask[i11] * tx) * ty;
277
+ const o = (y * W + x) * 4;
278
+ const g = Math.round(v * 255);
279
+ out[o] = g;
280
+ out[o + 1] = g;
281
+ out[o + 2] = g;
282
+ out[o + 3] = Math.round(a * 255);
283
+ }
284
+ }
285
+ return {
286
+ data: out,
287
+ width: W,
288
+ height: H,
289
+ range: {
290
+ low,
291
+ high
292
+ },
293
+ edgePixels
294
+ };
295
+ }
296
+ function depthModelNotice(model = DEPTH_MODEL) {
297
+ return [
298
+ `${model.title}`,
299
+ `Source: ${model.pageUrl} (revision ${model.revision}, file ${model.file})`,
300
+ `Licence: ${model.license}`,
301
+ "",
302
+ model.attribution,
303
+ "",
304
+ "Downloaded once by Agent3D (`agent3d assets depth`) to estimate depth maps at authoring time.",
305
+ "The model is never shipped in exports: scenes only carry the depth PNG it produced.",
306
+ "Apache License 2.0: https://www.apache.org/licenses/LICENSE-2.0",
307
+ ""
308
+ ].join("\n");
309
+ }
310
+ var DOWNLOAD_HINT = (model, dest) => `Connect to the internet once (the model is ${Math.round(model.bytes / 1e6)} MB, downloaded once, no account), or download ${model.url} yourself to ${dest}. You can also paint or export a depth map by hand (grey PNG, white = near, same aspect as the photo) and set it as the photo object's \`depth\`.`;
311
+ async function sha256Hex(bytes) {
312
+ const subtle = globalThis.crypto?.subtle;
313
+ if (!subtle) return null;
314
+ const h = new Uint8Array(await subtle.digest("SHA-256", bytes));
315
+ return Array.from(h, (b) => b.toString(16).padStart(2, "0")).join("");
316
+ }
317
+ async function ensureDepthModel(cache, fetchImpl, opts = {}) {
318
+ const model = opts.model ?? DEPTH_MODEL;
319
+ const dir = depthModelDir(model);
320
+ const rel = `${dir}/${DEPTH_MODEL_FILE}`;
321
+ const have = await cache.size(rel);
322
+ if (have === model.bytes) return {
323
+ path: cache.location(rel),
324
+ dir: cache.location(dir),
325
+ downloaded: false,
326
+ bytes: have
327
+ };
328
+ const dest = cache.location(rel);
329
+ if (!fetchImpl) throw new OpsError("io", `The depth model is not downloaded yet (${dest}) and this host has no network access.`, DOWNLOAD_HINT(model, dest));
330
+ opts.log?.(`[agent3d depth] downloading ${model.title} (${Math.round(model.bytes / 1e6)} MB, once) from ${model.url}`);
331
+ let res;
332
+ try {
333
+ res = await fetchImpl(model.url);
334
+ } catch (e) {
335
+ throw new OpsError("io", `Could not download the depth model (offline?): ${e.message}`, DOWNLOAD_HINT(model, dest));
336
+ }
337
+ if (!res.ok) throw new OpsError("io", `Could not download the depth model: HTTP ${res.status} for ${model.url}.`, DOWNLOAD_HINT(model, dest));
338
+ let bytes;
339
+ try {
340
+ bytes = new Uint8Array(await res.arrayBuffer());
341
+ } catch (e) {
342
+ throw new OpsError("io", `The depth model download was interrupted: ${e.message}`, DOWNLOAD_HINT(model, dest));
343
+ }
344
+ if (bytes.byteLength !== model.bytes) throw new OpsError("io", `The downloaded depth model has ${bytes.byteLength} bytes, expected ${model.bytes} (truncated download or changed file).`, `Try again. ${DOWNLOAD_HINT(model, dest)}`);
345
+ const sha = await sha256Hex(bytes);
346
+ if (sha && sha !== model.sha256) throw new OpsError("io", `The downloaded depth model does not match its pinned checksum (sha256 ${sha}).`, `Try again later. Expected sha256 ${model.sha256} for ${model.url}.`);
347
+ await cache.write(rel, bytes);
348
+ await cache.writeText(`${dir}/NOTICE.txt`, depthModelNotice(model));
349
+ await cache.writeText(`${dir}/LICENSE.txt`, `Licensed under the Apache License, Version 2.0 (${model.license}).\nFull text: https://www.apache.org/licenses/LICENSE-2.0\n\n${model.attribution}\n`);
350
+ opts.log?.(`[agent3d depth] model saved to ${dest}`);
351
+ return {
352
+ path: dest,
353
+ dir: cache.location(dir),
354
+ downloaded: true,
355
+ bytes: bytes.byteLength
356
+ };
357
+ }
358
+ function depthOutPath(image) {
359
+ return `assets/depth/${image.replace(/^library:/, "").split("/").pop().replace(/\.[^.]+$/, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "image"}-depth.png`;
360
+ }
361
+ async function readImage(fs, image, library) {
362
+ if (isLibraryRef(image)) {
363
+ const id = libraryId(image);
364
+ if (!library) throw new OpsError("invalid", `Library assets are not available in this host (${image}).`, "Copy the image into the project (assets add) and pass its project path.");
365
+ const asset = findLibraryAsset(library.index, id);
366
+ if (!asset) throw new OpsError("notFound", `No library asset "${id}".`, "List images with library_list { kind: \"texture\" } (CLI: agent3d assets library --kind texture).");
367
+ return {
368
+ bytes: await library.read(id),
369
+ entry: {
370
+ license: asset.license,
371
+ author: asset.author,
372
+ attribution: asset.attribution,
373
+ sourceUrl: asset.sourceUrl
374
+ }
375
+ };
376
+ }
377
+ let path;
378
+ try {
379
+ path = normalizePath(image.replace(/^\.\//, ""));
380
+ } catch {
381
+ throw new OpsError("invalid", `Invalid image path "${image}".`, "Use a project path, e.g. \"assets/textures/photo.jpg\".");
382
+ }
383
+ if (!await fs.exists(path)) {
384
+ const images = (await fs.list("assets/")).filter((f) => /\.(png|jpe?g|webp)$/i.test(f));
385
+ throw new OpsError("notFound", `Image "${image}" not found in the project.`, images.length ? `Images in the project: ${images.slice(0, 8).join(", ")}${images.length > 8 ? ", …" : ""}.` : "Add the photo first: assets_add { file } (CLI: agent3d assets add <photo.jpg> --license …), then pass its project path.");
386
+ }
387
+ const entry = (await readAssetManifest(fs)).assets.find((a) => a.path === path);
388
+ return {
389
+ bytes: await fs.readBytes(path),
390
+ entry
391
+ };
392
+ }
393
+ async function checkDepthRequest(fs, opts) {
394
+ if (!opts.image?.trim()) throw new OpsError("invalid", "Depth estimation needs an image.", "Pass image: a project path (\"assets/textures/photo.jpg\") or \"library:<id>\".");
395
+ const out = depthOutput(opts);
396
+ const { bytes } = await readImage(fs, opts.image, opts.library);
397
+ const header = imageHeader(bytes);
398
+ if (!header) throw new OpsError("invalid", `"${opts.image}" is not a PNG, JPEG or WebP image.`, "Depth estimation reads .png, .jpg and .webp photos.");
399
+ return {
400
+ out,
401
+ width: header.width,
402
+ height: header.height,
403
+ input: planDepthInput(header.width, header.height, { size: opts.size })
404
+ };
405
+ }
406
+ function depthOutput(opts) {
407
+ let out = opts.out ?? depthOutPath(opts.image);
408
+ try {
409
+ out = normalizePath(out.replace(/^\.\//, ""));
410
+ } catch {
411
+ throw new OpsError("invalid", `Invalid output path "${opts.out}".`, "Use e.g. \"assets/depth/photo-depth.png\".");
412
+ }
413
+ if (!out.startsWith("assets/") || !/\.png$/i.test(out)) throw new OpsError("invalid", `The depth map must be a .png under assets/ (got "${out}").`, `Use e.g. "${depthOutPath(opts.image)}".`);
414
+ return out;
415
+ }
416
+ async function estimateDepth(fs, opts, estimator) {
417
+ if (!opts.image?.trim()) throw new OpsError("invalid", "Depth estimation needs an image.", "Pass image: a project path (\"assets/textures/photo.jpg\") or \"library:<id>\".");
418
+ const out = depthOutput(opts);
419
+ const { bytes, entry } = await readImage(fs, opts.image, opts.library);
420
+ const header = imageHeader(bytes);
421
+ if (!header) throw new OpsError("invalid", `"${opts.image}" is not a PNG, JPEG or WebP image.`, "Depth estimation reads .png, .jpg and .webp photos.");
422
+ const input = planDepthInput(header.width, header.height, { size: opts.size });
423
+ const t0 = Date.now();
424
+ const r = await estimator({
425
+ bytes,
426
+ mimeType: header.mimeType,
427
+ width: input.width,
428
+ height: input.height
429
+ });
430
+ const ms = Date.now() - t0;
431
+ if (r.depth.length !== r.width * r.height) throw new OpsError("io", `The depth estimator returned ${r.depth.length} values for ${r.width}x${r.height}.`);
432
+ const srcW = r.srcWidth || header.width;
433
+ const srcH = r.srcHeight || header.height;
434
+ const k = Math.min(opts.maxSize ?? 1024, Math.max(srcW, srcH)) / Math.max(srcW, srcH);
435
+ const map = postprocessDepth(r.depth, r.width, r.height, {
436
+ width: Math.max(1, Math.round(srcW * k)),
437
+ height: Math.max(1, Math.round(srcH * k)),
438
+ smooth: opts.smooth,
439
+ dilate: opts.dilate,
440
+ edgeThreshold: opts.edgeThreshold
441
+ });
442
+ const png = await encodePng(map.data, map.width, map.height, { deflate: opts.deflate });
443
+ const license = entry?.license ?? "derived";
444
+ const what = opts.image.split("/").pop();
445
+ const credit = entry?.attribution ?? (entry?.author ? `"${what}" by ${entry.author}${entry.sourceUrl ? ` (${entry.sourceUrl})` : ""}, licensed under ${license}.` : "");
446
+ const attribution = `Depth map of ${opts.image} estimated with Depth Anything V2 Small (Apache-2.0).${credit ? ` Image: ${credit}` : ""}`;
447
+ const asset = await addAsset(fs, {
448
+ path: out,
449
+ bytes: png,
450
+ kind: "texture",
451
+ source: DEPTH_MODEL.id,
452
+ license,
453
+ author: entry?.author,
454
+ sourceUrl: DEPTH_MODEL.pageUrl,
455
+ attribution
456
+ });
457
+ return {
458
+ path: asset.path,
459
+ image: opts.image,
460
+ width: map.width,
461
+ height: map.height,
462
+ input: {
463
+ width: r.width,
464
+ height: r.height
465
+ },
466
+ ms,
467
+ kb: Math.round(png.byteLength / 102.4) / 10,
468
+ license,
469
+ model: {
470
+ id: DEPTH_MODEL.id,
471
+ revision: DEPTH_MODEL.revision,
472
+ license: DEPTH_MODEL.license,
473
+ ...r.backend ? { backend: r.backend } : {}
474
+ },
475
+ edgePixels: map.edgePixels,
476
+ suggestion: {
477
+ kind: "photo",
478
+ src: opts.image,
479
+ depth: asset.path
480
+ }
481
+ };
482
+ }
483
+ export { estimateDepth as a, ensureDepthModel as i, checkDepthRequest as n, depth_exports as r, DEPTH_MODEL as t };
@@ -0,0 +1,190 @@
1
+ import { createRequire as __a3dRequire } from "node:module";
2
+ import { fileURLToPath as __a3dPath } from "node:url";
3
+ import { dirname as __a3dDirname, dirname, join, resolve } from "node:path";
4
+ __a3dRequire(import.meta.url);
5
+ const __filename = __a3dPath(import.meta.url);
6
+ __a3dDirname(__filename);
7
+ import { i as ensureDepthModel, t as DEPTH_MODEL } from "./depth-BZT4gseQ.mjs";
8
+ import { H as CliError, L as ORT_FILES, r as startLocalServer, t as mimeOf, z as ortDir } from "../agent3d.mjs";
9
+ import { launchBrowser, requireBrowser } from "./browser-Dil7VM5m.mjs";
10
+ import { t as CdpClient } from "./cdp-DLEis_Z3.mjs";
11
+ import { createReadStream, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ // agent/render/depth.ts
14
+ function modelsDir() {
15
+ return process.env.AGENT3D_MODELS ? resolve(process.env.AGENT3D_MODELS) : join(homedir(), ".agent3d", "models");
16
+ }
17
+ function nodeModelCache(root = modelsDir()) {
18
+ const abs = (rel) => join(root, ...rel.split("/"));
19
+ const atomic = (rel, data) => {
20
+ const file = abs(rel);
21
+ mkdirSync(dirname(file), { recursive: true });
22
+ const tmp = `${file}.${process.pid}.tmp`;
23
+ writeFileSync(tmp, data);
24
+ renameSync(tmp, file);
25
+ };
26
+ return {
27
+ location: abs,
28
+ async size(rel) {
29
+ try {
30
+ const s = statSync(abs(rel));
31
+ return s.isFile() ? s.size : null;
32
+ } catch {
33
+ return null;
34
+ }
35
+ },
36
+ async write(rel, bytes) {
37
+ atomic(rel, bytes);
38
+ },
39
+ async writeText(rel, text) {
40
+ atomic(rel, text);
41
+ }
42
+ };
43
+ }
44
+ var PAGE = (threads) => `<!doctype html><meta charset="utf-8"><title>agent3d depth</title>
45
+ <script type="module">
46
+ window.__depth = { ready: false, error: null };
47
+ try {
48
+ const ort = await import("/ort/ort.wasm.bundle.min.mjs");
49
+ ort.env.wasm.wasmPaths = { wasm: "/ort/ort-wasm-simd-threaded.wasm" };
50
+ ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.max(1, Math.min(${threads}, navigator.hardwareConcurrency || 1)) : 1;
51
+ ort.env.logLevel = "error";
52
+ const session = await ort.InferenceSession.create("/model/model.onnx", { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
53
+ window.__depthRun = async (b64, mime, W, H, mean, std) => {
54
+ const bin = atob(b64);
55
+ const bytes = new Uint8Array(bin.length);
56
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
57
+ const bmp = await createImageBitmap(new Blob([bytes], { type: mime }), { colorSpaceConversion: "none", premultiplyAlpha: "none" });
58
+ const canvas = new OffscreenCanvas(W, H);
59
+ const g = canvas.getContext("2d", { willReadFrequently: true });
60
+ g.imageSmoothingEnabled = true;
61
+ g.imageSmoothingQuality = "high";
62
+ g.fillStyle = "#808080";
63
+ g.fillRect(0, 0, W, H);
64
+ g.drawImage(bmp, 0, 0, W, H);
65
+ const px = g.getImageData(0, 0, W, H).data;
66
+ const n = W * H;
67
+ const input = new Float32Array(3 * n);
68
+ for (let i = 0; i < n; i++)
69
+ for (let c = 0; c < 3; c++) input[c * n + i] = (px[i * 4 + c] / 255 - mean[c]) / std[c];
70
+ const out = await session.run({ [session.inputNames[0]]: new ort.Tensor("float32", input, [1, 3, H, W]) });
71
+ const t = out[session.outputNames[0]];
72
+ const dims = t.dims;
73
+ const data = t.data instanceof Float32Array ? t.data : Float32Array.from(t.data);
74
+ const buf = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
75
+ let s = "";
76
+ for (let i = 0; i < buf.length; i += 0x8000) s += String.fromCharCode.apply(null, buf.subarray(i, i + 0x8000));
77
+ return { b64: btoa(s), width: dims[dims.length - 1], height: dims[dims.length - 2], srcWidth: bmp.width, srcHeight: bmp.height };
78
+ };
79
+ window.__depth = { ready: true, error: null, threads: ort.env.wasm.numThreads, isolated: self.crossOriginIsolated };
80
+ } catch (e) {
81
+ window.__depth = { ready: false, error: String((e && e.stack) || e) };
82
+ }
83
+ <\/script>`;
84
+ var ISOLATION_HEADERS = {
85
+ "cross-origin-opener-policy": "same-origin",
86
+ "cross-origin-embedder-policy": "require-corp",
87
+ "cross-origin-resource-policy": "same-origin",
88
+ "cache-control": "no-store",
89
+ "x-content-type-options": "nosniff"
90
+ };
91
+ function sendIsolated(res, file, method) {
92
+ if (!existsSync(file)) return res.writeHead(404, ISOLATION_HEADERS).end("Not found"), true;
93
+ res.writeHead(200, {
94
+ ...ISOLATION_HEADERS,
95
+ "content-type": mimeOf(file),
96
+ "content-length": String(statSync(file).size)
97
+ });
98
+ if (method === "HEAD") res.end();
99
+ else createReadStream(file).on("error", () => res.destroy()).pipe(res);
100
+ return true;
101
+ }
102
+ async function openDepthEstimator(opts = {}) {
103
+ const ort = ortDir();
104
+ if (!ort) throw new CliError("depth-runtime-missing", `onnxruntime-web is missing (${ORT_FILES.join(", ")} not found next to the CLI).`, "Reinstall @fleox/agent3d (the files ship in dist/agent/ort/); in a clone run `npm install` then `npm run build:agent`.");
105
+ const info = requireBrowser();
106
+ const model = await ensureDepthModel(opts.cache ?? nodeModelCache(), opts.fetch ?? globalThis.fetch, { log: opts.log });
107
+ let server = null;
108
+ let browser = null;
109
+ let client = null;
110
+ const close = async () => {
111
+ try {
112
+ client?.close();
113
+ } catch {}
114
+ await browser?.close().catch(() => void 0);
115
+ await server?.close().catch(() => void 0);
116
+ };
117
+ let page;
118
+ let backend = "wasm";
119
+ try {
120
+ const html = PAGE(opts.threads ?? 4);
121
+ server = await startLocalServer({
122
+ mounts: {},
123
+ routes: [(req, res, url) => {
124
+ if (url.pathname === "/" || url.pathname === "/depth.html") return res.writeHead(200, {
125
+ ...ISOLATION_HEADERS,
126
+ "content-type": "text/html; charset=utf-8"
127
+ }).end(html), true;
128
+ if (url.pathname === "/model/model.onnx") return sendIsolated(res, model.path, req.method);
129
+ const m = /^\/ort\/([\w.-]+)$/.exec(url.pathname);
130
+ if (m && ORT_FILES.includes(m[1])) return sendIsolated(res, join(ort, m[1]), req.method);
131
+ return false;
132
+ }]
133
+ });
134
+ opts.log?.(`[agent3d depth] ${info.name}: ${info.path}`);
135
+ browser = await launchBrowser(info);
136
+ client = await CdpClient.connect(browser.wsUrl);
137
+ page = await client.newPage();
138
+ await page.send("Runtime.enable");
139
+ await page.send("Page.enable");
140
+ await page.send("Page.navigate", { url: `${server.url}/depth.html` });
141
+ const deadline = Date.now() + 12e4;
142
+ let state = null;
143
+ for (;;) {
144
+ state = await page.evaluate("window.__depth ?? null", 1e4).catch(() => null);
145
+ if (state?.ready || state?.error || Date.now() > deadline) break;
146
+ await new Promise((r) => setTimeout(r, 100));
147
+ }
148
+ if (!state?.ready) throw new CliError("depth-failed", `The depth model could not start in headless ${info.name}: ${(state?.error ?? "timed out after 120 s").split("\n")[0]}`, `The cached model may be corrupt: delete ${model.dir} to download it again. Otherwise update the browser or point AGENT3D_CHROME at Google Chrome; you can also provide a depth map by hand (grey PNG, white = near).`, 1, { error: state?.error ?? null });
149
+ backend = `wasm (${state.threads ?? 1} thread${(state.threads ?? 1) > 1 ? "s" : ""})`;
150
+ } catch (e) {
151
+ await close();
152
+ throw e;
153
+ }
154
+ const estimator = async (input) => {
155
+ const r = await page.send("Runtime.evaluate", {
156
+ expression: `window.__depthRun(${JSON.stringify(Buffer.from(input.bytes).toString("base64"))}, ${JSON.stringify(input.mimeType)}, ${input.width}, ${input.height}, ${JSON.stringify(DEPTH_MODEL.mean)}, ${JSON.stringify(DEPTH_MODEL.std)})`,
157
+ awaitPromise: true,
158
+ returnByValue: true
159
+ }, 18e4);
160
+ if (r.exceptionDetails || !r.result.value) throw new CliError("image-decode", `Depth estimation failed for this ${input.mimeType} image: ${(r.exceptionDetails?.exception?.description ?? r.exceptionDetails?.text ?? "no result").split("\n")[0]}`, "The file may be corrupt or in an unsupported format (use .jpg, .png or .webp).");
161
+ const v = r.result.value;
162
+ const buf = Buffer.from(v.b64, "base64");
163
+ return {
164
+ depth: new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)),
165
+ width: v.width,
166
+ height: v.height,
167
+ srcWidth: v.srcWidth,
168
+ srcHeight: v.srcHeight,
169
+ backend
170
+ };
171
+ };
172
+ return {
173
+ estimator,
174
+ backend,
175
+ model: {
176
+ path: model.path,
177
+ downloaded: model.downloaded
178
+ },
179
+ close
180
+ };
181
+ }
182
+ async function withDepthEstimator(fn, opts = {}) {
183
+ const e = await openDepthEstimator(opts);
184
+ try {
185
+ return await fn(e.estimator);
186
+ } finally {
187
+ await e.close();
188
+ }
189
+ }
190
+ export { withDepthEstimator };