@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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,76 @@
1
+ /**
2
+ * bt-profile census template — when the profile says a cheap function runs far too often, count who calls it.
3
+ * Copy to the scratchpad (not the project), adapt `reachTheMoment`, and run it through profile.mjs with --heap false:
4
+ *
5
+ * CENSUS_OUT=/abs/census.json node "$TOOLS/profile.mjs" --url "$URL" --scenario /abs/census.mjs --out /abs/census-run --heap false \
6
+ * --args method=TransformNode.prototype.computeWorldMatrix,seconds=1
7
+ *
8
+ * It wraps the method for `seconds` of play and records, per object (`this.name`, plus "[arg0]" when the first
9
+ * argument is truthy — e.g. a forced recompute), calls per frame and one sample call stack.
10
+ */
11
+
12
+ /** Shown in the report. */
13
+ export const meta = { name: "census", description: "Calls per frame of one prototype method, per object, with a sample stack." };
14
+
15
+ /**
16
+ * Installs the counting wrapper in the page.
17
+ * @param {string} methodPath - "Class.prototype.method" under window.BABYLON (or a full "TOOLKIT.Class.prototype.method")
18
+ */
19
+ function startCensus(methodPath) {
20
+ const parts = methodPath.split(".");
21
+ const root = parts[0] === "TOOLKIT" || parts[0] === "PROJECT" ? window[parts.shift()] : window.BABYLON;
22
+ const methodName = parts.pop();
23
+ const owner = parts.reduce((object, key) => object[key], root);
24
+ const original = owner[methodName];
25
+ const scene = window.BABYLON.EngineStore.LastCreatedScene;
26
+ const census = window.__btCensus = { calls: new Map(), stacks: new Map(), frames: 0 };
27
+ const frameObserver = scene.onAfterRenderObservable.add(() => { census.frames++; });
28
+ owner[methodName] = function (...args) {
29
+ const key = `${this && this.name !== undefined ? this.name : "(no name)"}${args[0] ? " [arg0]" : ""}`;
30
+ census.calls.set(key, (census.calls.get(key) || 0) + 1);
31
+ if (!census.stacks.has(key) && census.stacks.size < 500) census.stacks.set(key, new Error().stack.split("\n").slice(2, 10).map((line) => line.trim()).join(" | "));
32
+ return original.apply(this, args);
33
+ };
34
+ census.stop = () => { owner[methodName] = original; scene.onAfterRenderObservable.remove(frameObserver); };
35
+ }
36
+
37
+ /** Removes the wrapper and returns the per-object counts, busiest first. */
38
+ function stopCensus() {
39
+ const census = window.__btCensus;
40
+ census.stop();
41
+ const frames = Math.max(1, census.frames);
42
+ const total = [...census.calls.values()].reduce((sum, count) => sum + count, 0);
43
+ return {
44
+ frames: census.frames,
45
+ callsPerFrame: +(total / frames).toFixed(1),
46
+ top: [...census.calls].sort((a, b) => b[1] - a[1]).slice(0, 60).map(([key, count]) => ({ key, perFrame: +(count / frames).toFixed(2), stack: census.stacks.get(key) })),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Gets the game to the moment worth counting. Adapt: wait on the game's own state, hold keys like a player.
52
+ * @param {object} context - the bt-profile scenario context
53
+ */
54
+ async function reachTheMoment(context) {
55
+ await context.open();
56
+ await context.waitFor(() => {
57
+ const scene = window.BABYLON && window.BABYLON.EngineStore ? window.BABYLON.EngineStore.LastCreatedScene : null;
58
+ return scene != null && scene.isReady() && scene.activeCamera != null;
59
+ });
60
+ await context.waitForFrames(120);
61
+ }
62
+
63
+ /**
64
+ * Runs the census.
65
+ * @param {object} context - the bt-profile scenario context
66
+ */
67
+ export async function run(context) {
68
+ const methodPath = context.options.method || "TransformNode.prototype.computeWorldMatrix";
69
+ await reachTheMoment(context);
70
+ await context.evaluate(startCensus, methodPath);
71
+ await context.sleep(Number(context.options.seconds || 1));
72
+ const result = await context.evaluate(stopCensus);
73
+ const fs = await import("node:fs");
74
+ if (process.env.CENSUS_OUT) fs.writeFileSync(process.env.CENSUS_OUT, JSON.stringify(result, null, 1));
75
+ context.log(`census ${methodPath}: ${result.callsPerFrame} calls per frame over ${result.frames} frames; top: ${result.top.slice(0, 5).map((entry) => `${entry.key} ${entry.perFrame}/f`).join(", ")}`);
76
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * bt-profile scenario template — copy to `<project>/.agents/profile/<slug>/data/scenario.mjs` and make it play the
3
+ * moment the user says is slow (a cold load, a level start, a boss fight, a menu → game transition).
4
+ *
5
+ * The capture script calls `run(context)` with:
6
+ * context.open(urlOrPath?) navigate (default: the --url given to profile.mjs)
7
+ * context.expectNavigation() call before a click that loads a new page (so it is not reported as a reload)
8
+ * context.mark(name) start a named phase (the report splits every number by phase)
9
+ * context.waitFor(fn, { timeout, polling, args }) wait until a page function returns truthy
10
+ * context.waitForFrames(count) wait until Babylon has rendered `count` frames
11
+ * context.evaluate(fn, ...args) run a function in the page (window.BABYLON, window.TOOLKIT, window.PROJECT)
12
+ * context.keyDown(key) / keyUp(key) / press(key) keyboard input ("ArrowUp", "w", "Space", …)
13
+ * context.sleep(seconds)
14
+ * context.shot(name) screenshot — only with --snapshots true, otherwise a no-op
15
+ * context.options --args key=value,… parsed into strings
16
+ * context.log(message)
17
+ *
18
+ * Rules that keep captures comparable run to run:
19
+ * - Drive the game the way a player would (keys, the game's own components), never by skipping work.
20
+ * - Wait on game state (a phase, a component flag), not on fixed sleeps, for anything that loads.
21
+ * - Mark every phase the user cares about; keep the names stable between runs (before / after compares by name).
22
+ */
23
+
24
+ /** Shown in the report. */
25
+ export const meta = {
26
+ name: "my-scenario",
27
+ description: "Cold load of the game page, then N seconds of play.",
28
+ };
29
+
30
+ /** Seconds recorded after the scene is running, unless --args play=<seconds> overrides it. */
31
+ const DEFAULT_PLAY_SECONDS = 60;
32
+
33
+ /**
34
+ * Plays the scenario.
35
+ * @param {object} context - the bt-profile scenario context
36
+ */
37
+ export async function run(context) {
38
+ const playSeconds = Number(context.options.play || DEFAULT_PLAY_SECONDS);
39
+ await context.open();
40
+ await context.mark("load");
41
+ await context.waitFor(() => {
42
+ const scene = window.BABYLON && window.BABYLON.EngineStore ? window.BABYLON.EngineStore.LastCreatedScene : null;
43
+ return scene != null && scene.isReady() && scene.activeCamera != null;
44
+ });
45
+ await context.waitForFrames(30);
46
+ // An empty scene is "ready" too (a game that loads its level later): wait until something is drawn.
47
+ try {
48
+ await context.waitFor(() => {
49
+ const scene = window.BABYLON.EngineStore.LastCreatedScene;
50
+ return scene != null && scene.getActiveMeshes().length > 0;
51
+ }, { timeout: 120000 });
52
+ } catch {
53
+ context.log("nothing was drawn within 120 s — check the smoke run's screenshots (a content server down? a menu to click through?)");
54
+ }
55
+ // Hitches behind the loading screen are load time, not stutter the player sees: mark the moment it goes away.
56
+ // (A toolkit splash fades through opacity 0; adapt the check to the game's own loading screen.)
57
+ try {
58
+ await context.waitFor(() => {
59
+ const splash = document.getElementById("xbabylonjsSplashScreen");
60
+ return splash == null || splash.style.opacity === "0" || getComputedStyle(splash).display === "none";
61
+ }, { timeout: 60000 });
62
+ } catch {
63
+ context.log("the loading screen did not go away within 60 s — adapt the reveal check to this game");
64
+ }
65
+ await context.mark("running");
66
+ await context.shot("running");
67
+ await context.sleep(playSeconds);
68
+ await context.shot("end-of-play");
69
+ }