@fleox/agent3d 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -13
- package/changelog.json +15 -0
- package/dist/agent/agent3d.mjs +228 -53
- package/dist/agent/chunks/{assets-BUUM9TUB.mjs → assets-YBkgdfgy.mjs} +27 -8
- package/dist/agent/chunks/{browser-Br1tURgt.mjs → browser-Dil7VM5m.mjs} +1 -1
- package/dist/agent/chunks/{cdp-Bdtm4fBN.mjs → cdp-DLEis_Z3.mjs} +1 -1
- package/dist/agent/chunks/{check-CfZcfaPs.mjs → check-DP9fRYbK.mjs} +64 -4
- package/dist/agent/chunks/depth-0bZsQn6N.mjs +190 -0
- package/dist/agent/chunks/depth-Dih8jLqx.mjs +483 -0
- package/dist/agent/chunks/{export-BHugc2H7.mjs → export-Cdqt3mt_.mjs} +8 -4
- package/dist/agent/chunks/{imageCodec-QM0EXQDJ.mjs → imageCodec-DeGfmBp3.mjs} +3 -3
- package/dist/agent/chunks/{objects-DBAws7uf.mjs → objects-DuytRxiC.mjs} +3 -3
- package/dist/agent/chunks/{optimizeSizing-CkZ3fZRp.mjs → optimizeSizing-B-BBiUkD.mjs} +51 -3
- package/dist/agent/chunks/{package-fw4h5vsh.mjs → package-d5e08XSG.mjs} +2 -1
- package/dist/agent/chunks/{render-EHb40avl.mjs → render-B05DU4Q5.mjs} +4 -4
- package/dist/agent/chunks/{scene-BgajNvBf.mjs → scene-DWgXH6As.mjs} +2 -2
- package/dist/agent/chunks/{server-CACCerkZ.mjs → server-Dt_YFvN7.mjs} +6 -2
- package/dist/agent/chunks/{tools-DKxgjQSJ.mjs → tools-Cv6N_YBI.mjs} +60 -6
- package/dist/agent/chunks/{tree-BrNYGui2.mjs → tree-CqSj-o8T.mjs} +1 -0
- package/dist/agent/ort/LICENSE.txt +9 -0
- package/dist/agent/ort/ort-wasm-simd-threaded.wasm +0 -0
- package/dist/agent/ort/ort.wasm.bundle.min.mjs +9 -0
- package/dist/runtime/agent3d-runtime.js +6 -6
- package/dist/runtime/agent3d-runtime.single.js +311 -62
- package/dist/runtime/chunks/assets-qnxDnVkj.js +1 -0
- package/dist/runtime/chunks/materials-dC4vDNHh.js +107 -0
- package/dist/runtime/chunks/{model-DbfZaLni.js → model-BCAl_NRl.js} +1 -1
- package/dist/runtime/chunks/photo-BlDYgYFM.js +250 -0
- package/dist/runtime/chunks/svg-CLUxY6Zy.js +1 -0
- package/dist/runtime/chunks/{text-BaON-ISS.js → text-rSo_2Luk.js} +2 -2
- package/dist/studio/assets/assets-BFJsr9Oo.js +1 -0
- package/dist/studio/assets/{camera-Be6lnp3k.js → camera-DT0xHipx.js} +1 -1
- package/dist/studio/assets/{editor-Mpnz-b2E.js → editor-BjgHj9g8.js} +1 -1
- package/dist/studio/assets/{game-WMgRSJUD.js → game-BXZEc9HN.js} +3 -3
- package/dist/studio/assets/{generators-DozXE7ta.js → generators-DqkPMEzm.js} +1 -1
- package/dist/studio/assets/index-DVTzVcBD.js +479 -0
- package/dist/studio/assets/{model-C2bZTK7-.js → model-BqQW4Dg-.js} +1 -1
- package/dist/studio/assets/params-gVpEEiSK.js +1 -0
- package/dist/studio/assets/photo-DRoVO5iZ.js +250 -0
- package/dist/studio/assets/{physicsHost-CTRsIvfu.js → physicsHost-DNdZ7AsT.js} +1 -1
- package/dist/studio/assets/{postfx-DQtp0JIy.js → postfx-JFUGdY0d.js} +1 -1
- package/dist/studio/assets/runtime-CMAP4azF.js +572 -0
- package/dist/studio/assets/{shaders-BOb6Uter.js → shaders-C7u6rN_6.js} +12 -12
- package/dist/studio/assets/svg-DkIOJjzS.js +2 -0
- package/dist/studio/assets/{text-CGIZs8HE.js → text-LISSAism.js} +2 -2
- package/dist/studio/index.html +1 -1
- package/package.json +2 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/skills/agent3d-assets/SKILL.md +40 -25
- package/plugin/skills/agent3d-create/SKILL.md +56 -21
- package/plugin/skills/agent3d-create/references/art-direction.md +3 -3
- package/plugin/skills/agent3d-create/references/recipes.md +71 -6
- package/plugin/skills/agent3d-edit/SKILL.md +22 -22
- package/plugin/skills/agent3d-edit/references/patch-ops.md +11 -3
- package/plugin/skills/agent3d-game/SKILL.md +7 -7
- package/plugin/skills/agent3d-publish/SKILL.md +23 -21
- package/plugin/skills/agent3d-publish/references/integrations.md +1 -1
- package/templates/hero-photo-3d/README.md +28 -0
- package/templates/hero-photo-3d/agent3d.json +8 -0
- package/templates/hero-photo-3d/assets/depth/street-depth.png +0 -0
- package/templates/hero-photo-3d/assets/manifest.json +25 -0
- package/templates/hero-photo-3d/assets/textures/street.jpg +0 -0
- package/templates/hero-photo-3d/preview.png +0 -0
- package/templates/hero-photo-3d/scene.json +120 -0
- package/templates/hero-photo-3d/template.json +8 -0
- package/dist/runtime/chunks/materials-w3EW0g-7.js +0 -107
- package/dist/runtime/chunks/svg-CfPIQnDG.js +0 -1
- package/dist/studio/assets/index-tSGZFEt5.js +0 -479
- package/dist/studio/assets/runtime-NGp1VdnH.js +0 -572
- package/dist/studio/assets/svg-CnUMpv_N.js +0 -2
|
@@ -5,9 +5,9 @@ __a3dRequire(import.meta.url);
|
|
|
5
5
|
const __filename = __a3dPath(import.meta.url);
|
|
6
6
|
__a3dDirname(__filename);
|
|
7
7
|
import { t as __exportAll } from "./rolldown-runtime-ebOQtxsr.mjs";
|
|
8
|
-
import {
|
|
8
|
+
import { A as OpsError, F as writeJson, I as normalizePath, M as nowIso, N as readJsonOr, O as slugify, d as readSceneFile, f as saveScene, k as KB, o as ASSET_MANIFEST_FILE } from "../agent3d.mjs";
|
|
9
9
|
import { t as closest } from "./suggest-Cpcgv1RP.mjs";
|
|
10
|
-
import { a as collectAssetRefs, i as planTextureSizes, l as visitAssetRefs, n as imageHeader, s as kindFromPath } from "./optimizeSizing-
|
|
10
|
+
import { a as collectAssetRefs, i as planTextureSizes, l as visitAssetRefs, n as imageHeader, s as kindFromPath } from "./optimizeSizing-B-BBiUkD.mjs";
|
|
11
11
|
import { i as modelInfo, r as modelFileBounds } from "./gltf-f_f0-OiV.mjs";
|
|
12
12
|
// src/ops/zip.ts
|
|
13
13
|
var ZipError = class extends Error {
|
|
@@ -1672,6 +1672,10 @@ function decisionFor(plan, path, forced) {
|
|
|
1672
1672
|
uses: []
|
|
1673
1673
|
};
|
|
1674
1674
|
}
|
|
1675
|
+
function isDepthMap(plan, path) {
|
|
1676
|
+
return !!plan.files.get(path)?.uses.some((u) => u.role === "depth");
|
|
1677
|
+
}
|
|
1678
|
+
var DEPTH_KEPT = "Depth map of a 3D photo: only PNG depth maps are resized (losslessly); re-encoding a lossy one adds relief artefacts. Regenerate it as PNG with `agent3d assets depth <photo>`.";
|
|
1675
1679
|
function roleDecision(plan, path, role, forced) {
|
|
1676
1680
|
if (forced) return {
|
|
1677
1681
|
maxSize: forced,
|
|
@@ -1734,6 +1738,13 @@ async function planOptimize(fs, opts) {
|
|
|
1734
1738
|
} else {
|
|
1735
1739
|
const d = decisionFor(sizing, path, opts.maxSize);
|
|
1736
1740
|
const h = imageHeader(bytes);
|
|
1741
|
+
if (isDepthMap(sizing, path) && ext(path) !== "png") {
|
|
1742
|
+
skipped.push({
|
|
1743
|
+
path,
|
|
1744
|
+
reason: DEPTH_KEPT
|
|
1745
|
+
});
|
|
1746
|
+
continue;
|
|
1747
|
+
}
|
|
1737
1748
|
entries.push({
|
|
1738
1749
|
path,
|
|
1739
1750
|
kb,
|
|
@@ -1745,7 +1756,7 @@ async function planOptimize(fs, opts) {
|
|
|
1745
1756
|
height: h.height
|
|
1746
1757
|
} : {},
|
|
1747
1758
|
resize: h ? Math.max(h.width, h.height) > d.maxSize : true,
|
|
1748
|
-
format: format === "auto" ? "webp" : format
|
|
1759
|
+
format: isDepthMap(sizing, path) ? "png" : format === "auto" ? "webp" : format
|
|
1749
1760
|
});
|
|
1750
1761
|
}
|
|
1751
1762
|
}
|
|
@@ -1836,10 +1847,18 @@ async function optimizeAssets(fs, opts, codec) {
|
|
|
1836
1847
|
}
|
|
1837
1848
|
const d = decisionFor(sizing, path, forced);
|
|
1838
1849
|
const mime = IMAGE_EXT[ext(path)];
|
|
1850
|
+
const depthMap = isDepthMap(sizing, path);
|
|
1851
|
+
if (depthMap && mime !== "image/png") {
|
|
1852
|
+
skipped.push({
|
|
1853
|
+
path,
|
|
1854
|
+
reason: DEPTH_KEPT
|
|
1855
|
+
});
|
|
1856
|
+
continue;
|
|
1857
|
+
}
|
|
1839
1858
|
const role = d.uses.some((u) => u.role === "color" || u.role === "background") ? "color" : d.uses.length && d.uses.every((u) => u.role === "data") ? "data" : d.uses.some((u) => u.role === "normal") ? "normal" : "color";
|
|
1840
|
-
let fmt = format;
|
|
1841
|
-
let renameNote;
|
|
1842
|
-
const wanted = format === "auto" || format === "webp" ? "image/webp" : format === "jpeg" ? "image/jpeg" : format === "png" ? "image/png" : mime;
|
|
1859
|
+
let fmt = depthMap ? "keep" : format;
|
|
1860
|
+
let renameNote = depthMap && format !== "keep" && format !== "png" ? "Depth map: kept as lossless PNG." : void 0;
|
|
1861
|
+
const wanted = depthMap ? mime : format === "auto" || format === "webp" ? "image/webp" : format === "jpeg" ? "image/jpeg" : format === "png" ? "image/png" : mime;
|
|
1843
1862
|
if (wanted !== mime) {
|
|
1844
1863
|
const to = path.slice(0, path.lastIndexOf(".") + 1) + EXT_FOR_MIME[wanted];
|
|
1845
1864
|
const blocker = await renameBlocker(fs, scene, path, to);
|
|
@@ -1858,7 +1877,7 @@ async function optimizeAssets(fs, opts, codec) {
|
|
|
1858
1877
|
const ok = worthIt(out, bytes.byteLength);
|
|
1859
1878
|
const image = {
|
|
1860
1879
|
name: "image",
|
|
1861
|
-
role: d.uses.some((u) => u.role === "background") ? "background" : d.uses.length && d.uses.every((u) => u.role === "lighting") ? "lighting" : role,
|
|
1880
|
+
role: depthMap ? "depth" : d.uses.some((u) => u.role === "background") ? "background" : d.uses.length && d.uses.every((u) => u.role === "lighting") ? "lighting" : role,
|
|
1862
1881
|
from: describe(out.srcWidth, out.srcHeight, mime, bytes.byteLength),
|
|
1863
1882
|
to: describe(out.width, out.height, out.mimeType, out.bytes.byteLength),
|
|
1864
1883
|
replaced: ok,
|
|
@@ -2053,7 +2072,7 @@ async function optimizedExportSources(fs, library, opts = {}) {
|
|
|
2053
2072
|
compress: true,
|
|
2054
2073
|
roleSizes: roleSizes ? Object.fromEntries(Object.entries(roleSizes).map(([r, v]) => [r, v.maxSize])) : void 0
|
|
2055
2074
|
}, opts.codec)).bytes;
|
|
2056
|
-
} else if (IMAGE_EXT[e] && opts.codec && d) {
|
|
2075
|
+
} else if (IMAGE_EXT[e] && opts.codec && d && !(isDepthMap(sizing, key) && e !== "png")) {
|
|
2057
2076
|
const role = d.uses.every((u) => u.role === "normal") ? "normal" : "color";
|
|
2058
2077
|
const r = await opts.codec({
|
|
2059
2078
|
bytes,
|
|
@@ -4,7 +4,7 @@ import { dirname as __a3dDirname, delimiter, join } from "node:path";
|
|
|
4
4
|
__a3dRequire(import.meta.url);
|
|
5
5
|
const __filename = __a3dPath(import.meta.url);
|
|
6
6
|
__a3dDirname(__filename);
|
|
7
|
-
import {
|
|
7
|
+
import { H as CliError } from "../agent3d.mjs";
|
|
8
8
|
import { existsSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
9
9
|
import { homedir, tmpdir } from "node:os";
|
|
10
10
|
import { execFile, spawn } from "node:child_process";
|
|
@@ -4,7 +4,7 @@ import { dirname as __a3dDirname } from "node:path";
|
|
|
4
4
|
__a3dRequire(import.meta.url);
|
|
5
5
|
const __filename = __a3dPath(import.meta.url);
|
|
6
6
|
__a3dDirname(__filename);
|
|
7
|
-
import {
|
|
7
|
+
import { H as CliError } from "../agent3d.mjs";
|
|
8
8
|
// agent/render/cdp.ts
|
|
9
9
|
var DEFAULT_TIMEOUT_MS = Number(process.env.AGENT3D_CDP_TIMEOUT_MS) || 6e4;
|
|
10
10
|
var CdpError = class extends Error {
|
|
@@ -5,11 +5,11 @@ __a3dRequire(import.meta.url);
|
|
|
5
5
|
const __filename = __a3dPath(import.meta.url);
|
|
6
6
|
__a3dDirname(__filename);
|
|
7
7
|
import { t as __exportAll } from "./rolldown-runtime-ebOQtxsr.mjs";
|
|
8
|
-
import { C as
|
|
8
|
+
import { C as CATALOG, N as readJsonOr, S as libraryId, T as catalogEntry, _ as validateScene, b as findLibraryAsset, c as SCENE_FILE, d as readSceneFile, k as KB, m as DEFAULT_BUDGET_KB, o as ASSET_MANIFEST_FILE, v as expandPostFx, w as GENERATORS, x as isLibraryRef, y as postfxCost } from "../agent3d.mjs";
|
|
9
9
|
import { t as closest } from "./suggest-Cpcgv1RP.mjs";
|
|
10
|
-
import { o as walkObjects } from "./tree-
|
|
10
|
+
import { o as walkObjects } from "./tree-CqSj-o8T.mjs";
|
|
11
11
|
import { i as modelInfo } from "./gltf-f_f0-OiV.mjs";
|
|
12
|
-
import { a as collectAssetRefs, o as gltfDependencies, r as optimizeSuggestions } from "./optimizeSizing-
|
|
12
|
+
import { a as collectAssetRefs, n as imageHeader, o as gltfDependencies, r as optimizeSuggestions } from "./optimizeSizing-B-BBiUkD.mjs";
|
|
13
13
|
// src/ops/budget.ts
|
|
14
14
|
function evalCost(formula, vars) {
|
|
15
15
|
const src = formula.replace(/~/g, "");
|
|
@@ -148,9 +148,23 @@ function objectTriangles(o, models) {
|
|
|
148
148
|
}
|
|
149
149
|
case "particles": return (o.count ?? 200) * 2;
|
|
150
150
|
case "svg": return 2e3;
|
|
151
|
+
case "photo": return photoTriangles(o);
|
|
151
152
|
default: return 0;
|
|
152
153
|
}
|
|
153
154
|
}
|
|
155
|
+
function photoTriangles(o) {
|
|
156
|
+
if (typeof o.depth !== "string" || !o.depth) return 2;
|
|
157
|
+
const mode = o.mode ?? "parallax";
|
|
158
|
+
if (mode === "layers") return 2 * (typeof o.layers === "number" && o.layers > 0 ? Math.round(o.layers) : 6);
|
|
159
|
+
if (mode === "mesh") {
|
|
160
|
+
const seg = typeof o.segments === "number" && o.segments > 0 ? Math.round(o.segments) : 256;
|
|
161
|
+
const w = Number(o.width);
|
|
162
|
+
const h = Number(o.height);
|
|
163
|
+
const aspect = w > 0 && h > 0 ? Math.min(w, h) / Math.max(w, h) : 1;
|
|
164
|
+
return Math.round(seg * Math.max(1, Math.round(seg * aspect)) * 2 * 1.25);
|
|
165
|
+
}
|
|
166
|
+
return 2;
|
|
167
|
+
}
|
|
154
168
|
function estimateTriangles(scene, opts = {}) {
|
|
155
169
|
const byObject = [];
|
|
156
170
|
walkObjects(scene.objects, (o) => {
|
|
@@ -577,6 +591,7 @@ async function checkProject(fs, opts = {}) {
|
|
|
577
591
|
message: `${l.path} is ${l.license}: it requires attribution.`,
|
|
578
592
|
hint: `Show this credit near the embed (the export's index.html lists it): ${l.attribution}`
|
|
579
593
|
});
|
|
594
|
+
issues.push(...await photoIssues(fs, scene));
|
|
580
595
|
let scriptBytes = 0;
|
|
581
596
|
for (const [i, path] of (scene.scripts ?? []).entries()) {
|
|
582
597
|
if (typeof path !== "string" || !path.startsWith("scripts/")) continue;
|
|
@@ -806,6 +821,50 @@ function passHint(f) {
|
|
|
806
821
|
if (p.contactShadows) parts.push("contactShadows re-draws the casters from below");
|
|
807
822
|
return parts.length ? ` Passes: ${parts.join("; ")}.` : "";
|
|
808
823
|
}
|
|
824
|
+
async function photoIssues(fs, scene) {
|
|
825
|
+
const out = [];
|
|
826
|
+
const photos = [];
|
|
827
|
+
walkObjects(scene.objects, (o) => void (o.kind === "photo" && photos.push(o)));
|
|
828
|
+
const header = async (path) => {
|
|
829
|
+
if (typeof path !== "string" || !path || isLibraryRef(path) || !await fs.exists(path)) return null;
|
|
830
|
+
const bytes = await fs.readBytes(path);
|
|
831
|
+
return {
|
|
832
|
+
bytes: bytes.byteLength,
|
|
833
|
+
h: imageHeader(bytes)
|
|
834
|
+
};
|
|
835
|
+
};
|
|
836
|
+
for (const o of photos) {
|
|
837
|
+
const at = `objects#${o.id}`;
|
|
838
|
+
const src = await header(o.src).catch(() => null);
|
|
839
|
+
if (src && src.bytes > 1572864) out.push({
|
|
840
|
+
severity: "warning",
|
|
841
|
+
code: "photo-heavy",
|
|
842
|
+
path: `${at}.src`,
|
|
843
|
+
message: `Photo "${String(o.src)}" weighs ${KB(src.bytes)} KB${src.h ? ` (${src.h.width}x${src.h.height})` : ""}: slow to load on phones.`,
|
|
844
|
+
hint: `Run \`agent3d assets optimize ${String(o.src)}\` (sized from how big the photo shows on screen, WebP; plan first, then --yes).`
|
|
845
|
+
});
|
|
846
|
+
const depth = await header(o.depth).catch(() => null);
|
|
847
|
+
if (src?.h && depth?.h && src.h.height > 0 && depth.h.height > 0) {
|
|
848
|
+
const a = src.h.width / src.h.height;
|
|
849
|
+
const b = depth.h.width / depth.h.height;
|
|
850
|
+
if (Math.abs(a - b) / a > .02) out.push({
|
|
851
|
+
severity: "warning",
|
|
852
|
+
code: "photo-depth-aspect",
|
|
853
|
+
path: `${at}.depth`,
|
|
854
|
+
message: `Depth map "${String(o.depth)}" is ${depth.h.width}x${depth.h.height} but the photo is ${src.h.width}x${src.h.height}: different aspect ratios, the relief will not line up with the picture.`,
|
|
855
|
+
hint: `Regenerate it from this image: \`agent3d assets depth ${String(o.src)}\` (or crop both the same way).`
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
if (depth?.h && depth.h.mimeType === "image/jpeg") out.push({
|
|
859
|
+
severity: "info",
|
|
860
|
+
code: "photo-depth-lossy",
|
|
861
|
+
path: `${at}.depth`,
|
|
862
|
+
message: `Depth map "${String(o.depth)}" is a JPEG: lossy compression adds steps and noise to the relief and drops the alpha cut-edge mask.`,
|
|
863
|
+
hint: `Use a PNG depth map (\`agent3d assets depth ${String(o.src)}\` writes one).`
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
return out;
|
|
867
|
+
}
|
|
809
868
|
function textureFiles(scene) {
|
|
810
869
|
return [...new Set(collectAssetRefs(scene).filter((r) => r.kind === "texture" || r.kind === "hdri").map((r) => r.path))];
|
|
811
870
|
}
|
|
@@ -835,6 +894,7 @@ function drawCallCauses(scene, shadowLights = 0, prepass = false) {
|
|
|
835
894
|
why.push(`"${o.id}" per-letter text (splitLetters / reveal), ${glyphs} glyphs${layers > 1 ? " × outline" : ""}`);
|
|
836
895
|
} else calls += layers;
|
|
837
896
|
} else if (d.kind === "mesh" || d.kind === "instances" || d.kind === "particles" || d.kind === "svg") calls += 1;
|
|
897
|
+
else if (d.kind === "photo") calls += d.mode === "layers" && d.depth ? typeof d.layers === "number" ? d.layers : 6 : 1;
|
|
838
898
|
else if (d.kind === "model" || d.kind === "generator") {
|
|
839
899
|
calls += d.kind === "model" ? 4 : 2;
|
|
840
900
|
const key = d.kind === "model" ? `model:${String(d.src)}` : `generator:${String(d.generator)}:${JSON.stringify(d.params ?? {})}`;
|
|
@@ -879,7 +939,7 @@ function framingIssues(scene, inspect) {
|
|
|
879
939
|
walkObjects(scene.objects, (o) => {
|
|
880
940
|
declared.add(o.id);
|
|
881
941
|
const def = o;
|
|
882
|
-
if (def.kind === "particles" || def.kind === "generator" && def.generator && scatter.has(def.generator)) spread.add(o.id);
|
|
942
|
+
if (def.kind === "particles" || def.kind === "photo" || def.kind === "generator" && def.generator && scatter.has(def.generator)) spread.add(o.id);
|
|
883
943
|
});
|
|
884
944
|
const animated = /* @__PURE__ */ new Set();
|
|
885
945
|
let cameraMoves = (scene.camera?.shots?.length ?? 0) > 0;
|
|
@@ -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-Dih8jLqx.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 };
|