@babylonjs-toolkit/agent 1.2.10 → 1.2.12

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.
@@ -33,10 +33,64 @@ function change(before, after, digits = 0) {
33
33
  /** How many owners and repeated shapes each pin's accounting tables list. */
34
34
  const DRAW_OWNER_ROWS = 12;
35
35
 
36
+ /** The owner name profile-browser.mjs gives main-pass draws no scene object's render call made. */
37
+ const UNOWNED = "(unowned)";
38
+
39
+ /**
40
+ * Whether a run's accounting measured its draws per render call (profiles from before that have no frameMainDraws
41
+ * and no "(unowned)" entry, so a missing owner there means "not measured", not "no draws").
42
+ * @param {object|null} accounting - one run's drawOwners at a pin
43
+ */
44
+ function isMeasured(accounting) {
45
+ return accounting != null && accounting.frameMainDraws != null;
46
+ }
47
+
48
+ /**
49
+ * The owner names one pin's table lists: the top DRAW_OWNER_ROWS of every run, plus "(unowned)" whenever a run
50
+ * measured its draws, so a draw no object owns is never cut off the table (and a measured 0 shows every draw owned).
51
+ * @param {(object|null)[]} accountings - each run's drawOwners at this pin (null when the run has none)
52
+ * @returns {string[]} the owner names, in first-seen order
53
+ */
54
+ function tableOwnerNames(accountings) {
55
+ const present = accountings.filter(Boolean);
56
+ const topOwners = present.flatMap((accounting) => accounting.owners.slice(0, DRAW_OWNER_ROWS).map((owner) => owner.owner));
57
+ const showUnowned = present.some((accounting) => isMeasured(accounting) || accounting.owners.some((owner) => owner.owner === UNOWNED));
58
+ return [...new Set(showUnowned ? [...topOwners, UNOWNED] : topOwners)];
59
+ }
60
+
61
+ /**
62
+ * One run's draws for one owner: its draws, 0 when the run lists no such owner, "—" when the run has no accounting
63
+ * (or, for "(unowned)", did not measure draws per render call).
64
+ * @param {object|null} accounting - the run's drawOwners at this pin
65
+ * @param {string} ownerName - the owner of this table row
66
+ * @returns {number|string} the cell value
67
+ */
68
+ function ownerDrawsCell(accounting, ownerName) {
69
+ if (accounting == null) return "—";
70
+ const owner = accounting.owners.find((candidate) => candidate.owner === ownerName);
71
+ if (owner) return owner.draws;
72
+ if (ownerName === UNOWNED && !isMeasured(accounting)) return "—";
73
+ return 0;
74
+ }
75
+
76
+ /**
77
+ * The last run's description column for one owner: its skinned / instanced / lightmapped mesh counts, or for
78
+ * "(unowned)" the classes whose render made those draws.
79
+ * @param {object|undefined} latest - the owner's entry in the last run, if it has one
80
+ * @returns {string} the cell text
81
+ */
82
+ function ownerKinds(latest) {
83
+ if (!latest) return "—";
84
+ if (latest.sources) return `made by ${latest.sources.join(", ")}`;
85
+ return `${latest.skinned} / ${latest.instances} / ${latest.lightmapped}`;
86
+ }
87
+
36
88
  /**
37
- * Appends, per pinned view, the main-pass draws by owning scene object for every run side by side, then the last
38
- * run's repeated shapes that still cost one draw per copy and why. Runs profiled before draw accounting existed
39
- * are skipped.
89
+ * Appends, per pinned view, the main-pass draws by owning scene object for every run side by side (with any
90
+ * "(unowned)" draws), the accounted total beside the frame's measured main-pass draws, then the last run's repeated
91
+ * shapes that still cost one draw per copy and why. A pin the last run has no accounting for is skipped, and a run
92
+ * without accounting shows "—"; runs profiled before draws were measured per render call have no frameMainDraws (and
93
+ * no "(unowned)" entry) and show "—" in those rows.
40
94
  * @param {string[]} lines - the report lines to append to
41
95
  * @param {object[]} runs - the parsed profile runs, in label order
42
96
  * @param {(index: number) => string} name - the label of run `index`
@@ -47,18 +101,17 @@ function appendDrawOwners(lines, runs, name) {
47
101
  const accountings = runs.map((run) => (run.pins || []).find((candidate) => candidate.atSeconds === pin.atSeconds)?.drawOwners ?? null);
48
102
  const lastAccounting = accountings[accountings.length - 1];
49
103
  if (lastAccounting == null) continue;
50
- const ownerNames = [...new Set(accountings.filter(Boolean).flatMap((accounting) => accounting.owners.slice(0, DRAW_OWNER_ROWS).map((owner) => owner.owner)))];
51
104
  lines.push(`**Main-pass draws by owner — ${pin.atSeconds} s view**`);
52
105
  lines.push("");
53
106
  lines.push(`| Owner | ${runs.map((_, index) => name(index)).join(" | ")} | Skinned / instanced / lightmapped meshes (${name(runs.length - 1)}) | Shadow-map casters (${name(runs.length - 1)}) |`);
54
107
  lines.push(`|---|${runs.map(() => "---").join("|")}|---|---|`);
55
- for (const ownerName of ownerNames) {
56
- const cells = accountings.map((accounting) => accounting?.owners.find((owner) => owner.owner === ownerName)?.draws ?? (accounting ? 0 : "—"));
108
+ for (const ownerName of tableOwnerNames(accountings)) {
109
+ const cells = accountings.map((accounting) => ownerDrawsCell(accounting, ownerName));
57
110
  const latest = lastAccounting.owners.find((owner) => owner.owner === ownerName);
58
- const kinds = latest ? `${latest.skinned} / ${latest.instances} / ${latest.lightmapped}` : "—";
59
- lines.push(`| ${ownerName} | ${cells.join(" | ")} | ${kinds} | ${latest ? latest.shadowCasters : "—"} |`);
111
+ lines.push(`| ${ownerName} | ${cells.join(" | ")} | ${ownerKinds(latest)} | ${latest?.shadowCasters ?? "—"} |`);
60
112
  }
61
- lines.push(`| **All main-pass draws** | ${accountings.map((accounting) => (accounting ? `**${accounting.mainDraws}**` : "—")).join(" | ")} | | |`);
113
+ lines.push(`| **All main-pass draws** (mainDraws) | ${accountings.map((accounting) => (accounting ? `**${accounting.mainDraws}**` : "—")).join(" | ")} | | |`);
114
+ lines.push(`| Main-pass draws of the same frame (frameMainDraws) | ${accountings.map((accounting) => accounting?.frameMainDraws ?? "—").join(" | ")} | | |`);
62
115
  lines.push("");
63
116
  const costly = lastAccounting.repeats.filter((repeat) => repeat.blocker != null).slice(0, DRAW_OWNER_ROWS);
64
117
  if (costly.length === 0) continue;
@@ -9,6 +9,7 @@
9
9
  * node profile-browser.mjs --scene level.gltf --pin 20,35 --toggles dpr,taa,motionblur,bloom,post,shadows,lights
10
10
  * node profile-browser.mjs --scene optimized.gltf --poses ./before-pinned.json --toggles none (same views as an earlier run)
11
11
  * [--headed true] [--dpr 2] [--window 3] [--settle 4] [--shots ./shots] [--cpuprofile true] [--toggles none]
12
+ * [--casters true] (with --pin / --poses: each pin also records every shadow map's casters per cascade, `shadowCasters`)
12
13
  */
13
14
  import fs from "node:fs";
14
15
  import os from "node:os";
@@ -345,37 +346,336 @@ function installProbe() {
345
346
  shadowedBoundPerMesh: +(shadowed / Math.max(1, meshes)).toFixed(2), mostBound: Object.entries(names).sort((a, b) => b[1] - a[1]).slice(0, 6) };
346
347
  };
347
348
 
349
+ /** Babylon classes whose render call draws for one scene object, mapped to the kind of object each draws for. */
350
+ const DRAW_OWNER_CLASSES = { Mesh: "mesh", ParticleSystem: "particles", GPUParticleSystem: "particles", SpriteManager: "sprites", Layer: "layer" };
351
+
352
+ /** Classes whose render call only hands the frame to other render calls, so they never name an unowned draw. */
353
+ const DISPATCHER_CLASSES = new Set(["Scene", "RenderingManager", "RenderingGroup", "SubMesh"]);
354
+
355
+ /** The owner name that collects main-pass draws no wrapped render call made. */
356
+ const UNOWNED = "(unowned)";
357
+
358
+ /** Position of Mesh.render's effectiveMeshReplacement argument (the instance drawn as a regular mesh, if any). */
359
+ const MESH_RENDER_EFFECTIVE_MESH_ARGUMENT = 2;
360
+
361
+ /** Longest drawOwners waits for the scene to render the frame it records, in milliseconds. */
362
+ const DRAW_OWNER_FRAME_TIMEOUT_MS = 10000;
363
+
364
+ /**
365
+ * Stack frames of the draw counter's own path (this probe, the engine's draw calls, WebGPU's internal _draw),
366
+ * skipped when naming the code behind an unowned draw.
367
+ */
368
+ const DRAW_COUNTER_FRAME = /countDraws|chargeDraws|describeDrawCaller|addCount|_reportDrawCall|drawElementsType|drawArraysType|\._draw \(|^Error/;
369
+
370
+ /**
371
+ * The scene object that owns a node: the child of the scene root it sits under (a root node owns itself).
372
+ * @param {any} node - a mesh, transform node or particle emitter
373
+ * @returns {string} the owner's name
374
+ */
375
+ state.ownerOf = (node) => {
376
+ let current = node;
377
+ while (current.parent && current.parent.parent) current = current.parent;
378
+ return current.parent ? current.name : node.name;
379
+ };
380
+
381
+ /**
382
+ * Names the code that drew outside every wrapped render call: the first stack frame past the draw counter's path.
383
+ * @returns {string} "(no render call) <function and script position>"
384
+ */
385
+ const describeDrawCaller = () => {
386
+ const stackLines = (new Error().stack || "").split("\n").map((line) => line.trim().replace(/^at /, ""));
387
+ const caller = stackLines.find((line) => line.length > 0 && !DRAW_COUNTER_FRAME.test(line));
388
+ return caller ? "(no render call) " + caller : "(no render call)";
389
+ };
390
+
391
+ /**
392
+ * Charges draws the engine just counted to the frame being recorded: to the innermost owning render call on the
393
+ * call stack, or else to "(unowned)" under the innermost render call's class (or, with none, the calling code).
394
+ * Draws outside the main draw phase, or while no frame is armed, are not charged.
395
+ * @param {number} added - how much the engine's draw counter just went up
396
+ */
397
+ const chargeDraws = (added) => {
398
+ const frame = state.drawOwnerFrame;
399
+ if (!frame || !frame.inDrawPhase || added <= 0) return;
400
+ const owningCall = frame.callStack.findLast((call) => call.renderer !== undefined);
401
+ if (owningCall) {
402
+ owningCall.draws += added;
403
+ return;
404
+ }
405
+ const sourceCall = frame.callStack.findLast((call) => call.source !== undefined);
406
+ const source = sourceCall ? sourceCall.source : describeDrawCaller();
407
+ frame.unownedSources.set(source, (frame.unownedSources.get(source) || 0) + added);
408
+ };
409
+
410
+ /**
411
+ * The node a render call draws for, which decides its owner: a mesh's effective mesh (an instance that acts as a
412
+ * regular mesh, else the mesh), a particle system's emitter when it is a node, nothing for sprites and layers.
413
+ * @param {any} renderer - the object whose render was called
414
+ * @param {string} kind - its DRAW_OWNER_CLASSES kind
415
+ * @param {any[]} renderArguments - the render call's arguments (Mesh.render's third is the effective mesh)
416
+ * @returns {any|null} the node, or null when the renderer is not attached to one
417
+ */
418
+ const drawnNodeOf = (renderer, kind, renderArguments) => {
419
+ if (kind === "mesh") return renderArguments[MESH_RENDER_EFFECTIVE_MESH_ARGUMENT] || renderer;
420
+ if (kind === "particles" && renderer.emitter instanceof BABYLON.Node) return renderer.emitter;
421
+ return null;
422
+ };
423
+
424
+ /**
425
+ * The recorded frame's draw record for one renderer, created on its first render call.
426
+ * @returns {{kind: string, renderer: any, drawnNode: any, draws: number, calls: number}} the record
427
+ */
428
+ const rendererRecord = (frame, renderer, kind, renderArguments) => {
429
+ if (!frame.renderers.has(renderer)) {
430
+ frame.renderers.set(renderer, { kind, renderer, drawnNode: drawnNodeOf(renderer, kind, renderArguments), draws: 0, calls: 0 });
431
+ }
432
+ return frame.renderers.get(renderer);
433
+ };
434
+
435
+ /**
436
+ * Calls a wrapped function with a context on the recorded frame's call stack, so draws it makes are charged to
437
+ * that context (an owning renderer's record, or a named source), and takes the context off again afterwards.
438
+ * @returns {any} what the original function returned
439
+ */
440
+ const callInContext = (frame, context, original, receiver, callArguments) => {
441
+ frame.callStack.push(context);
442
+ try {
443
+ return original.apply(receiver, callArguments);
444
+ } finally {
445
+ frame.callStack.pop();
446
+ }
447
+ };
448
+
449
+ /**
450
+ * Wraps an owning class's render so each call inside a recorded draw phase sits on the frame's call stack,
451
+ * collecting the draws it makes.
452
+ * @param {object} prototype - the class prototype (marked __btDrawOwnerWrapped)
453
+ * @param {string} kind - the DRAW_OWNER_CLASSES kind of the objects it draws for
454
+ */
455
+ const wrapOwnerRender = (prototype, kind) => {
456
+ prototype.__btDrawOwnerWrapped = true;
457
+ const original = prototype.render;
458
+ prototype.render = function (...renderArguments) {
459
+ const frame = state.drawOwnerFrame;
460
+ if (!frame || !frame.inDrawPhase) return original.apply(this, renderArguments);
461
+ const record = rendererRecord(frame, this, kind, renderArguments);
462
+ record.calls++;
463
+ return callInContext(frame, record, original, this, renderArguments);
464
+ };
465
+ };
466
+
467
+ /**
468
+ * Wraps any other class's render so draws it makes outside an owning call are named by its class name.
469
+ * @param {object} prototype - the class prototype (marked __btDrawOwnerWrapped)
470
+ * @param {string} exportName - the class's BABYLON export name, used when an instance has no getClassName
471
+ */
472
+ const wrapSourceRender = (prototype, exportName) => {
473
+ prototype.__btDrawOwnerWrapped = true;
474
+ const original = prototype.render;
475
+ prototype.render = function (...renderArguments) {
476
+ const frame = state.drawOwnerFrame;
477
+ if (!frame || !frame.inDrawPhase) return original.apply(this, renderArguments);
478
+ const source = typeof this.getClassName === "function" ? this.getClassName() : exportName;
479
+ return callInContext(frame, { source }, original, this, renderArguments);
480
+ };
481
+ };
482
+
483
+ /**
484
+ * Whether a BABYLON export is a class with its own render method that may draw for no scene object
485
+ * (a bounding-box, edges, outline or lens-flare renderer, an effect layer…) and is not wrapped yet.
486
+ */
487
+ const isSourceClass = (exportName, value) => {
488
+ if (typeof value !== "function" || !value.prototype) return false;
489
+ if (DISPATCHER_CLASSES.has(exportName) || exportName.endsWith("Engine")) return false;
490
+ if (Object.hasOwn(value.prototype, "__btDrawOwnerWrapped")) return false;
491
+ const descriptor = Object.getOwnPropertyDescriptor(value.prototype, "render");
492
+ return descriptor !== undefined && typeof descriptor.value === "function" && descriptor.writable === true;
493
+ };
494
+
495
+ /** Wraps the owning classes' render calls, then every other BABYLON class's own render as a named source. */
496
+ const wrapRenderClasses = () => {
497
+ for (const [className, kind] of Object.entries(DRAW_OWNER_CLASSES)) {
498
+ const ownerClass = BABYLON[className];
499
+ if (!ownerClass || typeof ownerClass.prototype.render !== "function") continue;
500
+ if (Object.hasOwn(ownerClass.prototype, "__btDrawOwnerWrapped")) continue;
501
+ wrapOwnerRender(ownerClass.prototype, kind);
502
+ }
503
+ for (const exportName of Object.keys(BABYLON)) {
504
+ const value = BABYLON[exportName];
505
+ if (isSourceClass(exportName, value)) wrapSourceRender(value.prototype, exportName);
506
+ }
507
+ };
508
+
509
+ /**
510
+ * Wraps one scene stage step (a scene component's hook into the frame) as a source named by its component.
511
+ * @param {{component: any, action: Function}} step - the step (marked __btDrawOwnerWrapped)
512
+ */
513
+ const wrapStageStep = (step) => {
514
+ if (step.__btDrawOwnerWrapped || typeof step.action !== "function") return;
515
+ step.__btDrawOwnerWrapped = true;
516
+ const original = step.action;
517
+ const component = step.component;
518
+ const source = (component && component.name) || "SceneComponent";
519
+ step.action = function (...stepArguments) {
520
+ const frame = state.drawOwnerFrame;
521
+ if (!frame || !frame.inDrawPhase) return original.apply(this, stepArguments);
522
+ return callInContext(frame, { source }, original, this, stepArguments);
523
+ };
524
+ };
525
+
526
+ /**
527
+ * Wraps every step of the scene's stages (bounding boxes, effect layers, outlines, layers…) not wrapped yet. A
528
+ * scene component registers a bound copy of its method, so a prototype wrapper installed after the scene loaded
529
+ * never sees those calls: without this, a bounding-box draw would be unowned with no class to name it. A Stage is
530
+ * an array-like made by Stage.Create (Array.isArray is false), so stages are found by their registerStep method.
531
+ * @param {any} scene - the scene whose `_…Stage` lists to scan
532
+ */
533
+ const wrapSceneStages = (scene) => {
534
+ for (const key of Object.keys(scene)) {
535
+ const stage = scene[key];
536
+ if (!key.endsWith("Stage") || !stage || typeof stage.registerStep !== "function") continue;
537
+ for (let i = 0; i < stage.length; i++) wrapStageStep(stage[i]);
538
+ }
539
+ };
540
+
541
+ /**
542
+ * Wraps the engine's draw counter so every increment is charged to the recorded frame as it happens.
543
+ * @param {any} counter - engine._drawCalls (marked __btDrawOwnerWrapped)
544
+ */
545
+ const wrapDrawCounter = (counter) => {
546
+ counter.__btDrawOwnerWrapped = true;
547
+ const originalAddCount = counter.addCount;
548
+ counter.addCount = function countDraws(count, fetchResult) {
549
+ const before = this._current;
550
+ const result = originalAddCount.call(this, count, fetchResult);
551
+ chargeDraws(this._current - before);
552
+ return result;
553
+ };
554
+ };
555
+
556
+ /**
557
+ * Drives the armed frame through the scene: it starts at the next main draw phase, counts each phase's draws on
558
+ * the engine's counter (frameMainDraws, as passes.main measures it) and resolves at the end of that frame.
559
+ * @param {any} scene - the scene (marked __btDrawOwnerWrapped)
560
+ * @param {any} counter - engine._drawCalls
561
+ */
562
+ const watchDrawPhases = (scene, counter) => {
563
+ scene.__btDrawOwnerWrapped = true;
564
+ scene.onBeforeDrawPhaseObservable.add(() => {
565
+ const frame = state.drawOwnerFrame;
566
+ if (!frame) return;
567
+ frame.started = true;
568
+ frame.inDrawPhase = true;
569
+ frame.phaseStart = counter._current;
570
+ });
571
+ scene.onAfterDrawPhaseObservable.add(() => {
572
+ const frame = state.drawOwnerFrame;
573
+ if (!frame || !frame.inDrawPhase) return;
574
+ frame.inDrawPhase = false;
575
+ frame.frameMainDraws += counter._current - frame.phaseStart;
576
+ });
577
+ scene.getEngine().onEndFrameObservable.add(() => {
578
+ const frame = state.drawOwnerFrame;
579
+ if (!frame || !frame.started) return;
580
+ state.drawOwnerFrame = null;
581
+ frame.resolve(frame);
582
+ });
583
+ };
584
+
585
+ /**
586
+ * Installs the draw-ownership wrappers once per page: the render calls, the engine's draw counter and the
587
+ * scene's draw-phase observers. Scene stage steps registered since the last call are wrapped on every call.
588
+ * They record nothing until a frame is armed.
589
+ * @returns {boolean} false when the engine has no draw counter to measure
590
+ */
591
+ state.installDrawOwnerWrappers = () => {
592
+ const scene = state.scene();
593
+ const counter = scene.getEngine()._drawCalls;
594
+ if (!counter) return false;
595
+ if (!Object.hasOwn(BABYLON.Mesh.prototype, "__btDrawOwnerWrapped")) wrapRenderClasses();
596
+ if (!counter.__btDrawOwnerWrapped) wrapDrawCounter(counter);
597
+ if (!scene.__btDrawOwnerWrapped) watchDrawPhases(scene, counter);
598
+ wrapSceneStages(scene);
599
+ return true;
600
+ };
601
+
602
+ /**
603
+ * Arms state.drawOwnerFrame and resolves with it once the next frame's main draw phase has rendered.
604
+ * @returns {Promise<{frameMainDraws: number, renderers: Map<any, object>, unownedSources: Map<string, number>}>}
605
+ */
606
+ state.recordDrawOwnerFrame = () => new Promise((resolve, reject) => {
607
+ const frame = { started: false, inDrawPhase: false, phaseStart: 0, frameMainDraws: 0, renderers: new Map(), unownedSources: new Map(), callStack: [], resolve };
608
+ state.drawOwnerFrame = frame;
609
+ setTimeout(() => {
610
+ if (state.drawOwnerFrame !== frame) return;
611
+ state.drawOwnerFrame = null;
612
+ reject(new Error(`drawOwners: no frame rendered within ${DRAW_OWNER_FRAME_TIMEOUT_MS} ms`));
613
+ }, DRAW_OWNER_FRAME_TIMEOUT_MS);
614
+ });
615
+
616
+ /**
617
+ * The owner a renderer's measured draws go to. A mesh's go to the owner of the first active mesh drawn through it
618
+ * (the source itself or its first visible instance, the rule the active-mesh census uses); otherwise to the
619
+ * owner of the node it draws for, or to its own name.
620
+ */
621
+ const ownerOfRenderer = (record, firstOwnerBySource) => {
622
+ if (record.kind === "mesh" && firstOwnerBySource.has(record.renderer)) return firstOwnerBySource.get(record.renderer);
623
+ if (record.drawnNode) return state.ownerOf(record.drawnNode);
624
+ return record.renderer.name || record.renderer.getClassName();
625
+ };
626
+
348
627
  /**
349
- * Accounts for every main-pass draw: the active meshes grouped by the scene object that owns them (the child of the
350
- * scene root they sit under), and every shape drawn more than once with what stops its copies from sharing one
351
- * instanced draw. Also counts each owner's meshes in the shadow maps' caster lists. Per-pass totals say where the
352
- * frame goes; this says which objects to fix, so no group of draws is skipped unexamined.
353
- * @returns {{owners: object[], repeats: object[], mainDraws: number}} the draw accounting at the current view
628
+ * Explains a mesh that made more draws than it has sub-meshes, or null when it made no more.
629
+ * @returns {string|null} e.g. "Tree_Mesh0: 2 draws from 1 sub-mesh in 2 render calls (a split instance batch)"
354
630
  */
355
- state.drawOwners = () => {
631
+ const extraDrawsNote = (record, subMeshCount) => {
632
+ if (record.kind !== "mesh" || record.draws <= subMeshCount) return null;
633
+ const instanced = record.renderer.instances && record.renderer.instances.length > 0;
634
+ const counts = `${record.renderer.name}: ${record.draws} draws from ${subMeshCount} sub-mesh(es) in ${record.calls} render calls`;
635
+ if (record.calls > subMeshCount) return counts + (instanced ? " (a split instance batch)" : " (rendered more than once)");
636
+ return counts + " (more than one draw per render call: outline, edges or a multi-pass material)";
637
+ };
638
+
639
+ /**
640
+ * Accounts for every main-pass draw by measuring it: during the next rendered frame each draw the engine counts in
641
+ * the main draw phase is charged to the render call that made it — a mesh, particle system, sprite manager or
642
+ * layer — and from there to the scene object that owns it (the child of the scene root it sits under). Draws no
643
+ * such call made go to "(unowned)", named by the class (or code) that made them. The active meshes give each
644
+ * owner's mesh census and every shape drawn more than once, with what stops its copies from sharing one instanced
645
+ * draw (inferred, as the repeats always were). Also counts each owner's meshes in the shadow maps' caster lists.
646
+ * Per-pass totals say where the frame goes; this says which objects to fix, so no group of draws is skipped
647
+ * unexamined.
648
+ * @returns {Promise<{owners: object[], repeats: object[], mainDraws: number, frameMainDraws: number}|null>} the draw
649
+ * accounting at the current view, or null when the engine has no draw counter. `mainDraws` is the sum of every
650
+ * owner's measured `draws` (including "(unowned)"); `frameMainDraws` is the same frame's main-phase draw counter
651
+ * (what passes.main measures), so the two are equal when every draw is accounted for. Each owner is
652
+ * {owner, meshes, draws, skinned, instances, lightmapped, uniqueShapes, shadowCasters, examples}, where
653
+ * `examples` also notes any mesh that made more draws than its sub-meshes; the unowned entry is
654
+ * {owner: "(unowned)", draws, sources: [class or calling-code names, most draws first]}.
655
+ */
656
+ state.drawOwners = async () => {
657
+ if (!state.installDrawOwnerWrappers()) return null;
658
+ const frame = await state.recordDrawOwnerFrame();
356
659
  const scene = state.scene();
357
660
  const activeMeshes = scene.getActiveMeshes().data.slice(0, scene.getActiveMeshes().length);
358
- const ownerOf = (node) => {
359
- let current = node;
360
- while (current.parent && current.parent.parent) current = current.parent;
361
- return current.parent ? current.name : node.name;
362
- };
363
661
  const subMeshDraws = (mesh) => (mesh.subMeshes ? mesh.subMeshes.length : 1);
364
662
  const owners = new Map();
663
+ const ownerEntry = (ownerName) => {
664
+ if (!owners.has(ownerName)) owners.set(ownerName, { owner: ownerName, meshes: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0, geometries: new Set(), examples: [] });
665
+ return owners.get(ownerName);
666
+ };
365
667
  const repeats = new Map();
366
668
  const drawnSources = new Set();
367
- let mainDraws = 0;
669
+ const firstOwnerBySource = new Map();
368
670
  for (const mesh of activeMeshes) {
369
671
  const source = mesh.isAnInstance ? mesh.sourceMesh : mesh;
370
- // Instances draw in their source's single instanced call: count that call once.
371
- const draws = mesh.isAnInstance ? (drawnSources.has(source) ? 0 : subMeshDraws(source)) : subMeshDraws(mesh);
672
+ // Instances draw in their source's single instanced call: the inferred repeat count takes that call once.
673
+ const inferredDraws = mesh.isAnInstance ? (drawnSources.has(source) ? 0 : subMeshDraws(source)) : subMeshDraws(mesh);
372
674
  drawnSources.add(source);
373
- mainDraws += draws;
374
- const ownerName = ownerOf(mesh);
375
- if (!owners.has(ownerName)) owners.set(ownerName, { owner: ownerName, meshes: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0, geometries: new Set(), examples: [] });
376
- const owner = owners.get(ownerName);
675
+ const ownerName = state.ownerOf(mesh);
676
+ if (!firstOwnerBySource.has(source)) firstOwnerBySource.set(source, ownerName);
677
+ const owner = ownerEntry(ownerName);
377
678
  owner.meshes++;
378
- owner.draws += draws;
379
679
  if (source.skeleton) owner.skinned++;
380
680
  if (mesh.isAnInstance) owner.instances++;
381
681
  if (mesh.material && mesh.material.lightmapTexture) owner.lightmapped++;
@@ -386,16 +686,23 @@ function installProbe() {
386
686
  if (!repeats.has(repeatKey)) repeats.set(repeatKey, { shape: source.name, owner: ownerName, copies: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0 });
387
687
  const repeat = repeats.get(repeatKey);
388
688
  repeat.copies++;
389
- repeat.draws += draws;
689
+ repeat.draws += inferredDraws;
390
690
  if (source.skeleton) repeat.skinned++;
391
691
  if (mesh.isAnInstance) repeat.instances++;
392
692
  if (mesh.material && mesh.material.lightmapTexture) repeat.lightmapped++;
393
693
  }
694
+ for (const record of frame.renderers.values()) {
695
+ if (record.draws === 0) continue;
696
+ const owner = ownerEntry(ownerOfRenderer(record, firstOwnerBySource));
697
+ owner.draws += record.draws;
698
+ const note = extraDrawsNote(record, subMeshDraws(record.renderer));
699
+ if (note) owner.examples.push(note);
700
+ }
394
701
  const shadowCasters = new Map();
395
702
  for (const light of scene.lights) {
396
703
  const generator = light.getShadowGenerator && light.getShadowGenerator();
397
704
  const renderList = generator && generator.getShadowMap() ? generator.getShadowMap().renderList || [] : [];
398
- for (const caster of renderList) shadowCasters.set(ownerOf(caster), (shadowCasters.get(ownerOf(caster)) || 0) + 1);
705
+ for (const caster of renderList) shadowCasters.set(state.ownerOf(caster), (shadowCasters.get(state.ownerOf(caster)) || 0) + 1);
399
706
  }
400
707
  const blockerOf = (repeat) => {
401
708
  if (repeat.skinned > 0) return "skinned: every copy is its own draw (Babylon cannot instance separately animated skinned meshes)";
@@ -403,17 +710,69 @@ function installProbe() {
403
710
  if (repeat.instances < repeat.copies - 1) return "separate meshes of one shape: not exported as instances (material split by reflection probe or lightmap index?)";
404
711
  return null;
405
712
  };
713
+ const ownerRows = [...owners.values()].map((owner) => ({
714
+ owner: owner.owner, meshes: owner.meshes, draws: owner.draws, skinned: owner.skinned, instances: owner.instances, lightmapped: owner.lightmapped,
715
+ uniqueShapes: owner.geometries.size, shadowCasters: shadowCasters.get(owner.owner) || 0, examples: owner.examples,
716
+ }));
717
+ const unownedSources = [...frame.unownedSources.entries()].map(([source, draws]) => ({ source, draws })).sort((first, second) => second.draws - first.draws);
718
+ const unownedDraws = unownedSources.reduce((sum, entry) => sum + entry.draws, 0);
719
+ if (unownedDraws > 0) ownerRows.push({ owner: UNOWNED, draws: unownedDraws, sources: unownedSources.map((entry) => entry.source) });
406
720
  return {
407
- mainDraws,
408
- owners: [...owners.values()].sort((first, second) => second.draws - first.draws).map((owner) => ({
409
- owner: owner.owner, meshes: owner.meshes, draws: owner.draws, skinned: owner.skinned, instances: owner.instances, lightmapped: owner.lightmapped,
410
- uniqueShapes: owner.geometries.size, shadowCasters: shadowCasters.get(owner.owner) || 0, examples: owner.examples,
411
- })),
721
+ mainDraws: ownerRows.reduce((sum, owner) => sum + owner.draws, 0),
722
+ frameMainDraws: frame.frameMainDraws,
723
+ owners: ownerRows.sort((first, second) => second.draws - first.draws),
412
724
  repeats: [...repeats.values()].filter((repeat) => repeat.copies > 1).sort((first, second) => second.draws - first.draws).slice(0, 25)
413
725
  .map((repeat) => ({ ...repeat, blocker: blockerOf(repeat) })),
414
726
  };
415
727
  };
416
728
 
729
+ /**
730
+ * Records, over the next rendered frame, which meshes every shadow generator draws and in which cascade, by wrapping
731
+ * each generator's per-sub-mesh shadow render. Shadow maps are often the largest pass once repeats instance, and a
732
+ * caster whose shadow lands on nothing the camera sees (roads, flat ground, water, far backdrops) is pure cost — this
733
+ * names them, with their draws per cascade, so they can be pruned and proven by capture.
734
+ * @returns {Promise<{lights: {light: string, cascades: number, draws: number, casters: {mesh: string, owner: string, perCascade: number[], draws: number}[]}[]}>}
735
+ */
736
+ state.shadowCasters = () => new Promise((resolve, reject) => {
737
+ const scene = state.scene();
738
+ const generators = scene.lights
739
+ .map((light) => ({ light, generator: light.getShadowGenerator && light.getShadowGenerator() }))
740
+ .filter((entry) => entry.generator && typeof entry.generator._renderSubMeshForShadowMap === "function");
741
+ const records = generators.map(({ light, generator }) => ({ light: light.name, generator, cascades: generator.numCascades || 1, casters: new Map() }));
742
+ let recording = false;
743
+ const originals = records.map((record) => {
744
+ const original = record.generator._renderSubMeshForShadowMap;
745
+ record.generator._renderSubMeshForShadowMap = function (subMesh, ...rest) {
746
+ if (recording) {
747
+ const mesh = subMesh.getMesh();
748
+ if (!record.casters.has(mesh)) record.casters.set(mesh, new Array(record.cascades).fill(0));
749
+ const cascade = Math.min(record.cascades - 1, Math.max(0, record.generator._currentLayer || 0));
750
+ record.casters.get(mesh)[cascade]++;
751
+ }
752
+ return original.call(this, subMesh, ...rest);
753
+ };
754
+ return original;
755
+ });
756
+ const restore = () => records.forEach((record, index) => { record.generator._renderSubMeshForShadowMap = originals[index]; });
757
+ const timeout = setTimeout(() => { restore(); reject(new Error(`shadowCasters: no frame rendered within ${DRAW_OWNER_FRAME_TIMEOUT_MS} ms`)); }, DRAW_OWNER_FRAME_TIMEOUT_MS);
758
+ scene.onBeforeRenderObservable.addOnce(() => {
759
+ recording = true;
760
+ scene.onAfterRenderObservable.addOnce(() => {
761
+ recording = false;
762
+ clearTimeout(timeout);
763
+ restore();
764
+ resolve({
765
+ lights: records.map((record) => {
766
+ const casters = [...record.casters.entries()].map(([mesh, perCascade]) => ({
767
+ mesh: mesh.name, owner: state.ownerOf(mesh), perCascade, draws: perCascade.reduce((sum, count) => sum + count, 0),
768
+ })).sort((first, second) => second.draws - first.draws);
769
+ return { light: record.light, cascades: record.cascades, draws: casters.reduce((sum, caster) => sum + caster.draws, 0), casters };
770
+ }),
771
+ });
772
+ });
773
+ });
774
+ });
775
+
417
776
  /**
418
777
  * Switches one runtime cost off (on = false) or back on (on = true).
419
778
  * Keys: dpr, taa, motionblur, bloom, post (every camera post-process), shadows, lights (every point / spot light).
@@ -590,7 +949,9 @@ async function main() {
590
949
  process.stderr.write(`WARNING pin ${seconds}s drifted: target ${JSON.stringify(pinned)} actual ${JSON.stringify(poseBefore)} -> ${JSON.stringify(poseAfter)}\n`);
591
950
  const cpu = flags.cpuprofile === "true" ? await cpuProfile(page, windowSeconds) : null;
592
951
  const lightAudit = await page.evaluate(() => window.__btProfile.lightAudit());
952
+ // drawOwners is async: it measures the next rendered frame, and page.evaluate waits for that promise.
593
953
  const drawOwners = await page.evaluate(() => window.__btProfile.drawOwners());
954
+ const shadowCasters = flags.casters === "true" ? await page.evaluate(() => window.__btProfile.shadowCasters()) : null;
594
955
  const steps = [];
595
956
  for (const key of toggles) {
596
957
  const change = await page.evaluate((k) => window.__btProfile.toggle(k, false), key);
@@ -601,7 +962,7 @@ async function main() {
601
962
  steps.push({ off: key, change, fps: off.fps, p50Ms: off.p50Ms, drawCalls: off.drawCalls, passes: off.passes, cpuRenderMs: off.cpuRenderMs, cpuFrameMs: off.cpuFrameMs });
602
963
  }
603
964
  const after = await measure(page, windowSeconds);
604
- report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, drawOwners, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
965
+ report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, drawOwners, shadowCasters, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
605
966
  await page.close();
606
967
  }
607
968
  }
@@ -12,6 +12,7 @@ Turn a feature spec into `.agents/specs/<slug>/documents/<slug>_plan.md`: an ord
12
12
  /bt-plan @.agents/specs/mute-game-audio/documents/mute-game-audio_spec.md
13
13
  /bt-plan "add a settings toggle to mute all game audio" # no spec file → Quick Plan: short interview, creates the feature folder, then plans
14
14
  /bt-plan Fix F3 from @.agents/specs/<slug>/documents/<slug>_followups.md # Quick Plan for a finished feature's follow-ups (its dashboard's copy buttons)
15
+ /bt-plan "optimize Assets/Scenes/Level01.unity" # Quick Plan of a scene optimization: bt-optimize's playbook, no interview
15
16
  /bt-plan --heavy @.agents/specs/<slug>/documents/<slug>_spec.md # decision-complete plan for a long or cheaper-model run
16
17
  /bt-plan --heavy --parity @.agents/specs/<slug>/documents/<slug>_spec.md # numeric parity gates against the reference (slow)
17
18
  /bt-plan --no-time-limit @.agents/specs/<slug>/documents/<slug>_spec.md # turn off the default TIME MATTERS mode
@@ -33,13 +34,15 @@ Turn a feature spec into `.agents/specs/<slug>/documents/<slug>_plan.md`: an ord
33
34
  1. Read the feature spec in full, and `SPEC.md`'s headings, Architecture, Conventions and the systems the feature touches. The plan must conform to SPEC.md — **if it would conflict, stop and tell the user.** Verification procedures described in SPEC.md are tooling you may reuse, not a bar the plan must meet. Note the spec's `spec_impact`, `size` and `proof`.
34
35
  2. **Start from the spec's `## Research Notes`, and any bt-recon doc it cites (the feature's own `recon/` copies, or `.agents/recon/*_recon.md`) or whose scope covers the systems the feature touches** — its Extension Points and End-to-End Flows usually name the integration points directly. Spot-check that the paths exist, then research only what a plan needs beyond them: how the app is built and tested, the real conventions and the closest feature to mirror, the concrete files and integration points, available dependencies, constraints from the agent instructions.
35
36
  3. Size the research: `small` → inline; `medium` / `large` (or no Research Notes) → up to 3 **read-only** subagents returning findings and paths, not file dumps. Tell each one verbatim: *"Read-only: you may read, search and report. Do not edit or create files, and do not run builds, tests or any command that writes — not even into a build folder. If a fact needs a build or a test run to establish, report it as unknown and say which command would settle it."*
36
- 4. Sibling-skill pattern (e.g. bt-design's 3D-Hero-Scroll): read that skill's reference **and templates** *(where skills load through a tool: `load_skill` + `read_skill_resource`, never a guessed path; where they are files: the skills directory this skill was loaded from, e.g. `~/.claude/skills/`, `~/.agents/skills/` or the project's equivalent)*. The plan **copies and configures the template engine — never re-implements it**; each behavioral option the spec records (e.g. `sweep: page`) becomes an Acceptance item stated in observable terms. Prefer copying and wiring the template as the first task, so later tasks only configure it.
37
+ 4. Sibling-skill pattern (e.g. bt-design's 3D-Hero-Scroll, bt-optimize's scene optimization): read that skill's reference **and templates** *(where skills load through a tool: `load_skill` + `read_skill_resource`, never a guessed path; where they are files: the skills directory this skill was loaded from, e.g. `~/.claude/skills/`, `~/.agents/skills/` or the project's equivalent)*. The plan **copies and configures the template engine — never re-implements it**; each behavioral option the spec records (e.g. `sweep: page`) becomes an Acceptance item stated in observable terms. Prefer copying and wiring the template as the first task, so later tasks only configure it.
37
38
  5. Too ambiguous to plan responsibly → ask the user. **Already built?** If the research shows some or all of the feature already exists, say so first and plan only what is missing (often just tests and the live check).
38
39
 
39
40
  **Quick Plan (no spec file):** after the analysis, ask a small round of high-leverage questions (scope, behavior, edge cases, which systems it touches); skip anything the brief or code already answers. Unanswered items fall back to: feature name from the brief — the `<slug>`: lowercase kebab-case, `a-z 0-9 -` only, max 40 chars, with `-02`, `-03` … appended if a folder of that name already exists in `.agents/specs/`, `.agents/complete/`, `.agents/followup/` or anywhere under `.agents/archived/`; `spec_impact` and `size` inferred from the analysis; `proof: functional` unless `--parity`. List the assumptions in Codebase Analysis. **A Quick Plan is a creation point:** it first makes sure the default `.agents` folders exist — `.agents/specs/`, `.agents/complete/`, `.agents/archived/`, `.agents/followup/`, `.agents/profile/` and `.agents/recon/`, each with an empty `.gitkeep` (write only the ones missing; never touch what a folder holds), then creates the feature folder `.agents/specs/<slug>/` (with `documents/`), exactly as bt-spec would, and the plan, report and tests live there.
40
41
 
41
42
  **A Quick Plan of follow-ups** (`Fix F3 from @<source-folder>/documents/<slug>_followups.md`, the dashboard's Quick Plan copy command): the cited follow-ups are the brief, read in full with what they point at in the source feature (its plan's Decisions, the run-log lines and files named, its `recon/` copies when they touch that code). Plan only them, as one new feature named for what they fix, never `fix-f3` or the source's slug. The plan's opening paragraph names them with the file: `Quick Plan for follow-up **F3** of <source title> (\`<source-folder>/documents/<slug>_followups.md\`).` — the helper's `check` links an unlinked feature from that line, so it must be there. A cited id the file lacks: list the ids it has, and stop. A cited follow-up whose **Status** line says a later feature already addresses it (anything but *partly done*): name that feature and ask before planning it again. Step 4 links the new feature to them.
42
43
 
44
+ **A plan that optimizes a Unity scene** — a Quick Plan brief or a spec asking to make a scene run faster or lighter in the browser ("optimize `Level01.unity`", "cut the level's draw calls", "this track runs at 30 FPS"): read bt-optimize's `SKILL.md` and **`planning.md`** *(same lookup as step 4)* before anything else. The plan adopts its standard decisions **O1–O11** (in Codebase Analysis, or the Decisions log under `--heavy`; a spec's own choices win), follows its standard task list — baseline, then the working-copy pass, then shadow casters and the final proof in the game — and its tasks run bt-optimize's phases and scripts, never re-implement them. Find the scene, its export, the game code that loads it and any earlier `.agents/optimize/` run in the project; never ask about them. A Quick Plan asks **no** interview round: at most the one question `planning.md` allows (keep the current lighting exactly, or allow the re-bake merging needs), only when the brief and project leave it open — otherwise apply its default and list it as an assumption. The plan never edits the source scene, never deletes an earlier copy, and names the scene to export in its last task's Acceptance.
45
+
43
46
  **A Quick Plan of profile fixes** (`Fix F1 and F3 from @.agents/profile/<slug>/findings.md using @<recon>`, bt-profile's Quick Plan copy command): the cited fixes in `findings.md` are the brief — each one's cause, evidence, code, proposed fix, gain, risk and how to verify it, and the Verify becomes the task's proof. Read every cited recon in full, whatever its scope says, and **copy each into the new feature's `recon/` folder** (as bt-spec does), so the feature holds what it rests on after the profile is archived; turn what a recon says must not break into Acceptance or named tests. A cited recon that does not exist yet: say so, give its `/bt-recon` command (the report's **Copy recon command**), and carry on with your own analysis. Plan only the cited fixes, as one new feature named for what they fix, never `fix-f1` or the profile's slug; the plan's opening paragraph names them with the file (`Quick Plan for fixes **F1** and **F3** of profile <slug> (\`.agents/profile/<slug>/findings.md\`).`). Add a last task that re-profiles the same scenario (`/bt-profile --slug:<slug>`) and compares the phases the findings name — that re-measure is how the profile learns the fixes worked.
44
47
 
45
48
  **The feature folder.** Every feature has one: `.agents/specs/<slug>/` holding `dashboard.html` (the feature dashboard), `documents/` (`<slug>_spec.md`, `<slug>_plan.md`, bt-execute's `<slug>_autopilot.md`, the dashboard data `<slug>_dashboard.js` and live status `<slug>_live.js`), `snapshots/` and `tests/`. From a spec, `<slug>` is its folder name. A **legacy flat spec** (`.agents/specs/<slug>_spec.md`) is read where it is and left there; the plan and report still go into the new `.agents/specs/<slug>/` folder, and the report's Spec link points back to the flat file.
@@ -48,7 +48,7 @@ From the flag-stripped brief derive `feature_title` (Title Case), `feature_slug`
48
48
 
49
49
  ## Step 3. Sibling-skill patterns
50
50
 
51
- If the feature is built on a pattern owned by another skill (bt-design's 3D-Hero-Scroll, bt-atlas, bt-convert …), or the brief names a builder skill ("using bt-hero …", "using bt-prototype …"), **read that skill's SKILL.md and relevant reference before writing requirements.** *(Where skills load through a tool: `load_skill('<name>')`, then `read_skill_resource` with the paths it returns — never a guessed path. Where skills are files on disk: read them from the skills directory this skill was loaded from — e.g. `~/.claude/skills/`, `~/.agents/skills/`, or the project's `.claude/skills/` / `.agents/skills/`.)* For 3D-scroll / scroll-scrubbed / cinematic-hero features that is bt-design's `references/3d-hero-scroll.md`.
51
+ If the feature is built on a pattern owned by another skill (bt-design's 3D-Hero-Scroll, bt-atlas, bt-convert …), or the brief names a builder skill ("using bt-hero …", "using bt-prototype …"), **read that skill's SKILL.md and relevant reference before writing requirements.** *(Where skills load through a tool: `load_skill('<name>')`, then `read_skill_resource` with the paths it returns — never a guessed path. Where skills are files on disk: read them from the skills directory this skill was loaded from — e.g. `~/.claude/skills/`, `~/.agents/skills/`, or the project's `.claude/skills/` / `.agents/skills/`.)* For 3D-scroll / scroll-scrubbed / cinematic-hero features that is bt-design's `references/3d-hero-scroll.md`. **To make a Unity scene run faster or lighter in the browser** ("spec out optimizing `Level01.unity`", "cut the level's draw calls") that is bt-optimize's `SKILL.md` and `planning.md`: the spec records its standard decisions O1–O11 as Functional Requirements / Decisions (with any the user changed), its measured outcomes as Acceptance Criteria (draws and FPS before → after at the same pinned poses, every draw owner of 5%+ accounted for, `Verify` problems=0, the same look in Unity, the browser and the game, the scene to export named), and the scene, its export and the game code that loads it in Research Notes — found in the project, never asked. Cite an earlier run's `.agents/optimize/<Scene>/survey.md` when one exists.
52
52
 
53
53
  - Record the pattern's behavioral config as explicit Functional Requirements, using the sub-skill's **own names and defaults, unchanged** (e.g. 3D-Hero-Scroll `sweep: page` — PLAY glides to the document bottom and END jumps there). State any override and why.
54
54
  - Keep a behavioral option separate from the feature's route/DOM scope — `sweep` is not "which page it lives on".