@babylonjs-toolkit/agent 1.1.52 → 1.1.55

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.
@@ -0,0 +1,164 @@
1
+ /**
2
+ * bt-optimize browser check: loads each exported scene in the toolkit's player page (headless Chrome), captures the
3
+ * same moments after load, and records console errors and load time. Comparing captures of the source scene and the
4
+ * combined scene at the same moment shows whether a merge changed what the player sees (time-driven flythroughs land
5
+ * on the same frame within a second or so; capture a burst to line them up).
6
+ *
7
+ * Usage:
8
+ * node compare-browser.mjs --base http://localhost:8888 --scenes original.gltf,combined.gltf --times 10,15,20,30 --out ./captures
9
+ */
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import puppeteer from "puppeteer-core";
14
+
15
+ /** Default capture moments, in seconds after the page's load event. */
16
+ const DEFAULT_TIMES = "10,15,20,30";
17
+
18
+ /** Viewport used for every capture, in CSS pixels. */
19
+ const VIEWPORT = { width: 1600, height: 900 };
20
+
21
+ /** How long to wait for the player page's load event, in milliseconds. */
22
+ const NAVIGATION_TIMEOUT_MS = 120000;
23
+
24
+ /**
25
+ * Reads `--name value` pairs from the command line.
26
+ * @param {string[]} argv - process.argv.slice(2)
27
+ * @returns {Record<string, string>} the parsed flags
28
+ */
29
+ function parseArguments(argv) {
30
+ const flags = {};
31
+ for (let i = 0; i < argv.length; i += 2) {
32
+ flags[argv[i].replace(/^--/, "")] = argv[i + 1];
33
+ }
34
+ return flags;
35
+ }
36
+
37
+ /**
38
+ * Finds a Chrome or Chromium executable: CHROME_PATH, the usual install locations, then puppeteer's own cache.
39
+ * @returns {string} absolute path of the browser executable
40
+ * @throws {Error} when no browser can be found
41
+ */
42
+ function findChrome() {
43
+ const candidates = [
44
+ process.env.CHROME_PATH,
45
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
46
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
47
+ "/usr/bin/google-chrome",
48
+ "/usr/bin/chromium",
49
+ "/usr/bin/chromium-browser",
50
+ "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
51
+ "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
52
+ ].filter(Boolean);
53
+ const found = candidates.find((candidate) => fs.existsSync(candidate));
54
+ if (found) return found;
55
+ const cacheRoot = path.join(os.homedir(), ".cache", "puppeteer", "chrome");
56
+ if (fs.existsSync(cacheRoot)) {
57
+ for (const version of fs.readdirSync(cacheRoot)) {
58
+ const cached = [
59
+ path.join(cacheRoot, version, "chrome-mac-arm64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
60
+ path.join(cacheRoot, version, "chrome-mac-x64", "Google Chrome for Testing.app", "Contents", "MacOS", "Google Chrome for Testing"),
61
+ path.join(cacheRoot, version, "chrome-linux64", "chrome"),
62
+ path.join(cacheRoot, version, "chrome-win64", "chrome.exe"),
63
+ ].find((candidate) => fs.existsSync(candidate));
64
+ if (cached) return cached;
65
+ }
66
+ }
67
+ throw new Error("No Chrome found. Set CHROME_PATH to a Chrome or Chromium executable.");
68
+ }
69
+
70
+ /**
71
+ * Loads one scene, captures every requested moment, and reports what happened.
72
+ * @param {import("puppeteer-core").Browser} browser - the running browser
73
+ * @param {string} baseUrl - dev server root, e.g. http://localhost:8888
74
+ * @param {string} sceneFile - exported scene file name under scenes/, e.g. Level01.gltf
75
+ * @param {number[]} captureSeconds - moments to capture, in seconds after load, ascending
76
+ * @param {string} outputFolder - where the PNGs are written
77
+ * @returns {Promise<{scene: string, loadMilliseconds: number, captures: string[], consoleErrors: string[]}>}
78
+ */
79
+ async function captureScene(browser, baseUrl, sceneFile, captureSeconds, outputFolder) {
80
+ const page = await browser.newPage();
81
+ await page.setViewport(VIEWPORT);
82
+ const consoleErrors = [];
83
+ page.on("console", (message) => {
84
+ if (message.type() === "error") consoleErrors.push(message.text());
85
+ });
86
+ page.on("pageerror", (error) => consoleErrors.push(String(error)));
87
+
88
+ const loadStart = Date.now();
89
+ await page.goto(`${baseUrl}/index.html?scene=${encodeURIComponent(sceneFile)}`, { waitUntil: "load", timeout: NAVIGATION_TIMEOUT_MS });
90
+ const loadMilliseconds = Date.now() - loadStart;
91
+
92
+ const captures = [];
93
+ const sceneName = path.basename(sceneFile, path.extname(sceneFile));
94
+ let elapsedSeconds = 0;
95
+ for (const seconds of captureSeconds) {
96
+ await new Promise((resolve) => setTimeout(resolve, (seconds - elapsedSeconds) * 1000));
97
+ elapsedSeconds = seconds;
98
+ const capturePath = path.join(outputFolder, `${sceneName}_${seconds}s.png`);
99
+ await page.screenshot({ path: capturePath });
100
+ captures.push(capturePath);
101
+ }
102
+ await page.close();
103
+ return { scene: sceneFile, loadMilliseconds, captures, consoleErrors };
104
+ }
105
+
106
+ /**
107
+ * Writes sheet.html and sheet.png into the output folder: one row per capture moment, one column per scene, so
108
+ * matching views (and a load-time offset between runs) are easy to spot at a glance.
109
+ * @param {import("puppeteer-core").Browser} browser - the running browser
110
+ * @param {{scene: string, captures: string[]}[]} results - captureScene results, in column order
111
+ * @param {number[]} captureSeconds - the capture moments, in row order
112
+ * @param {string} outputFolder - where the sheet is written
113
+ * @returns {Promise<string>} path of sheet.png
114
+ */
115
+ async function writeContactSheet(browser, results, captureSeconds, outputFolder) {
116
+ const header = results.map((result) => `<th>${result.scene}</th>`).join("");
117
+ const rows = captureSeconds.map((seconds, row) => {
118
+ const cells = results.map((result) => `<td><img src="file://${result.captures[row]}"></td>`).join("");
119
+ return `<tr><td>${seconds}s</td>${cells}</tr>`;
120
+ }).join("");
121
+ const html = `<html><body style="margin:0;background:#222;color:#fff;font:14px sans-serif"><table><tr><th></th>${header}</tr>${rows}</table>`
122
+ + "<style>img{width:480px;display:block}</style></body></html>";
123
+ const htmlPath = path.join(outputFolder, "sheet.html");
124
+ const sheetPath = path.join(outputFolder, "sheet.png");
125
+ fs.writeFileSync(htmlPath, html);
126
+ const page = await browser.newPage();
127
+ await page.setViewport({ width: 600, height: 400 });
128
+ await page.goto(`file://${htmlPath}`, { waitUntil: "load" });
129
+ await page.screenshot({ path: sheetPath, fullPage: true });
130
+ await page.close();
131
+ return sheetPath;
132
+ }
133
+
134
+ /** Entry point: captures every scene, writes the contact sheet, and prints a JSON summary. */
135
+ async function main() {
136
+ const flags = parseArguments(process.argv.slice(2));
137
+ const baseUrl = (flags.base || "http://localhost:8888").replace(/\/$/, "");
138
+ const scenes = (flags.scenes || "").split(",").filter(Boolean);
139
+ const captureSeconds = (flags.times || DEFAULT_TIMES).split(",").map(Number).sort((first, second) => first - second);
140
+ const outputFolder = path.resolve(flags.out || "./captures");
141
+ if (scenes.length === 0) throw new Error("Pass --scenes original.gltf,combined.gltf");
142
+ fs.mkdirSync(outputFolder, { recursive: true });
143
+
144
+ const browser = await puppeteer.launch({
145
+ executablePath: findChrome(),
146
+ headless: "new",
147
+ args: ["--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist", "--allow-file-access-from-files"],
148
+ });
149
+ try {
150
+ const results = [];
151
+ for (const sceneFile of scenes) {
152
+ results.push(await captureScene(browser, baseUrl, sceneFile, captureSeconds, outputFolder));
153
+ }
154
+ const sheet = await writeContactSheet(browser, results, captureSeconds, outputFolder);
155
+ process.stdout.write(JSON.stringify({ sheet, results }, null, 2) + "\n");
156
+ } finally {
157
+ await browser.close();
158
+ }
159
+ }
160
+
161
+ main().catch((error) => {
162
+ process.stderr.write(String(error && error.stack ? error.stack : error) + "\n");
163
+ process.exit(1);
164
+ });
@@ -0,0 +1,80 @@
1
+ /**
2
+ * bt-optimize report table: compares profile-browser.mjs runs of the same views (pinned with --poses, or timeline
3
+ * runs with the same --times) and prints a Markdown table — FPS, frame times, draws per pass, active meshes.
4
+ *
5
+ * Usage:
6
+ * node compare-profiles.mjs --label Original,Optimized before-pinned.json after-pinned.json [more.json …]
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+
11
+ /**
12
+ * Reads `--name value` pairs and positional file arguments.
13
+ * @param {string[]} argv - process.argv.slice(2)
14
+ * @returns {{flags: Record<string, string>, files: string[]}}
15
+ */
16
+ function parseArguments(argv) {
17
+ const flags = {};
18
+ const files = [];
19
+ for (let i = 0; i < argv.length; i++) {
20
+ if (argv[i].startsWith("--")) flags[argv[i].slice(2)] = argv[++i];
21
+ else files.push(argv[i]);
22
+ }
23
+ return { flags, files };
24
+ }
25
+
26
+ /** Formats a number change as "a → b (±x%)". */
27
+ function change(before, after, digits = 0) {
28
+ if (before == null || after == null) return "—";
29
+ const percent = before !== 0 ? Math.round(((after - before) / before) * 100) : 0;
30
+ return `${before.toFixed(digits)} → **${after.toFixed(digits)}** (${percent >= 0 ? "+" : ""}${percent}%)`;
31
+ }
32
+
33
+ /** Entry point. */
34
+ function main() {
35
+ const { flags, files } = parseArguments(process.argv.slice(2));
36
+ if (files.length < 2) throw new Error("Pass at least two profile JSON files (before, after).");
37
+ const runs = files.map((file) => JSON.parse(fs.readFileSync(path.resolve(file), "utf8")));
38
+ const labels = (flags.label || "").split(",").filter(Boolean);
39
+ const name = (index) => labels[index] || path.basename(files[index], ".json");
40
+ const lines = [];
41
+
42
+ lines.push(`| | ${runs.map((_, i) => name(i)).join(" | ")} |`);
43
+ lines.push(`|---|${runs.map(() => "---").join("|")}|`);
44
+ const census = (key) => runs.map((run) => (run.census ? run.census[key] : "")).join(" | ");
45
+ lines.push(`| Meshes | ${census("meshes")} |`);
46
+ lines.push(`| Materials | ${census("materials")} |`);
47
+ lines.push(`| Lights / shadow generators | ${runs.map((run) => run.census ? `${run.census.lights.length} / ${run.census.shadows.length}` : "").join(" | ")} |`);
48
+ lines.push(`| Post passes | ${census("postProcesses")} |`);
49
+ lines.push("");
50
+
51
+ const first = runs[0], last = runs[runs.length - 1];
52
+ if (first.pins && last.pins) {
53
+ lines.push(`| View | FPS | p50 frame ms | p95 frame ms | Draws / frame | Shadow-map draws | Depth / other target draws | Main-pass draws | Active meshes |`);
54
+ lines.push(`|---|---|---|---|---|---|---|---|---|`);
55
+ for (const pin of first.pins) {
56
+ const other = last.pins.find((candidate) => candidate.atSeconds === pin.atSeconds);
57
+ if (!other) continue;
58
+ const a = pin.baseline, b = other.baseline;
59
+ lines.push(`| ${pin.atSeconds} s @ ${pin.pinned.position ? pin.pinned.position.map((v) => v.toFixed(1)).join(",") : pin.pinned} | ${change(a.fps, b.fps, 1)} | ${change(a.p50Ms, b.p50Ms, 1)} | ${change(a.p95Ms, b.p95Ms, 1)} | ${change(a.drawCalls, b.drawCalls)} | ${change(a.passes.shadowMaps, b.passes.shadowMaps)} | ${change(a.passes.otherTargets, b.passes.otherTargets)} | ${change(a.passes.main, b.passes.main)} | ${change(a.activeMeshes, b.activeMeshes)} |`);
60
+ }
61
+ lines.push("");
62
+ }
63
+ if (first.samples && last.samples) {
64
+ lines.push(`| Timeline | FPS | p95 frame ms | Worst frame ms | Draws / frame |`);
65
+ lines.push(`|---|---|---|---|---|`);
66
+ for (const sample of first.samples) {
67
+ const other = last.samples.find((candidate) => candidate.atSeconds === sample.atSeconds);
68
+ if (!other) continue;
69
+ lines.push(`| ${sample.atSeconds} s | ${change(sample.fps, other.fps, 1)} | ${change(sample.p95Ms, other.p95Ms)} | ${change(sample.worstMs, other.worstMs)} | ${change(sample.drawCalls, other.drawCalls)} |`);
70
+ }
71
+ const mean = (run, key) => run.samples.reduce((sum, s) => sum + s[key], 0) / run.samples.length;
72
+ const worst = (run) => Math.max(...run.samples.map((s) => s.worstMs));
73
+ lines.push(`| **Average / worst** | ${change(mean(first, "fps"), mean(last, "fps"), 1)} | ${change(mean(first, "p95Ms"), mean(last, "p95Ms"))} | ${change(worst(first), worst(last))} | ${change(mean(first, "drawCalls"), mean(last, "drawCalls"))} |`);
74
+ lines.push("");
75
+ lines.push("Timeline rows are moments after load; a lighter scene loads sooner, so its tour can be ahead — compare pinned views for like-for-like numbers.");
76
+ }
77
+ process.stdout.write(lines.join("\n") + "\n");
78
+ }
79
+
80
+ main();
@@ -0,0 +1,57 @@
1
+ /**
2
+ * bt-optimize export stats: compares exported .gltf scenes — drawn mesh nodes, meshes, primitives (draw calls before
3
+ * LOD selection), materials, textures, drawn vertices and the size on disk of the .gltf plus its buffers.
4
+ *
5
+ * Usage:
6
+ * node gltf-stats.mjs export/scenes/original.gltf export/scenes/combined.gltf
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+
11
+ /** Bytes per megabyte, for readable sizes. */
12
+ const BYTES_PER_MEGABYTE = 1024 * 1024;
13
+
14
+ /**
15
+ * Reads one exported scene and measures it.
16
+ * @param {string} gltfPath - path of the .gltf file
17
+ * @returns {{file: string, nodes: number, drawnMeshNodes: number, meshes: number, primitives: number, materials: number,
18
+ * textures: number, drawnVertices: number, sizeMegabytes: number}} the measurements
19
+ */
20
+ function measure(gltfPath) {
21
+ const gltf = JSON.parse(fs.readFileSync(gltfPath, "utf8"));
22
+ const meshes = gltf.meshes || [];
23
+ const accessors = gltf.accessors || [];
24
+ const nodes = gltf.nodes || [];
25
+ const drawnNodes = nodes.filter((node) => node.mesh !== undefined);
26
+
27
+ const verticesPerMesh = meshes.map((mesh) =>
28
+ mesh.primitives.reduce((total, primitive) => total + (accessors[primitive.attributes.POSITION]?.count || 0), 0));
29
+ const drawnVertices = drawnNodes.reduce((total, node) => total + verticesPerMesh[node.mesh], 0);
30
+
31
+ const folder = path.dirname(gltfPath);
32
+ const bufferBytes = (gltf.buffers || [])
33
+ .filter((buffer) => buffer.uri && !buffer.uri.startsWith("data:"))
34
+ .reduce((total, buffer) => {
35
+ const bufferPath = path.join(folder, decodeURIComponent(buffer.uri));
36
+ return total + (fs.existsSync(bufferPath) ? fs.statSync(bufferPath).size : 0);
37
+ }, 0);
38
+
39
+ return {
40
+ file: path.basename(gltfPath),
41
+ nodes: nodes.length,
42
+ drawnMeshNodes: drawnNodes.length,
43
+ meshes: meshes.length,
44
+ primitives: meshes.reduce((total, mesh) => total + mesh.primitives.length, 0),
45
+ materials: (gltf.materials || []).length,
46
+ textures: (gltf.textures || []).length,
47
+ drawnVertices,
48
+ sizeMegabytes: Number(((fs.statSync(gltfPath).size + bufferBytes) / BYTES_PER_MEGABYTE).toFixed(2)),
49
+ };
50
+ }
51
+
52
+ const files = process.argv.slice(2);
53
+ if (files.length === 0) {
54
+ process.stderr.write("Usage: node gltf-stats.mjs <scene.gltf> [more.gltf ...]\n");
55
+ process.exit(1);
56
+ }
57
+ process.stdout.write(JSON.stringify(files.map(measure), null, 2) + "\n");
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "bt-optimize-qa",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "Browser profiling, comparison and glTF checks for the bt-optimize skill. Installed into <project>/.agents/optimize/.qa-tools, never into the Unity project's own package.json.",
6
+ "dependencies": {
7
+ "puppeteer-core": "23.11.1"
8
+ }
9
+ }