@babylonjs-toolkit/agent 1.2.9 → 1.2.10

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.2.9)
1
+ # Babylon Toolkit Desktop Agent (1.2.10)
2
2
 
3
3
  The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.2.9",
3
+ "version": "1.2.10",
4
4
  "description": "Installs the Babylon Toolkit Desktop Agent for Claude Code, Codex, GitHub Copilot, Gemini CLI and Antigravity.",
5
5
  "keywords": [
6
6
  "babylonjs",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bt-optimize
3
- description: "The Babylon Toolkit Optimize Skill makes an exported Unity scene run fast as BabylonJS web content. It measures the exported scene in the browser first (frame rate, draw calls per pass — shadow maps, depth / velocity buffers, main pass, post — CPU hot spots, light binding), surveys the Unity scene for the causes, then fixes them on a copy of the scene: runtime practical lights baked, realtime point / spot shadows removed, non-moving props marked static, probe-lit props with lightmap UVs lightmapped, no-op post effects removed, and static meshes and LOD groups merged with the Babylon Toolkit MeshCombiner (packed source lightmap UVs, mirrored pieces, LOD clusters with corrected switch distances). It re-bakes, exports, and proves the result — frame rate and draw calls before → after at the same pinned views, and the same look in Unity and in the browser. Every decision is written down with its reason. Use when the user wants a Unity scene to run faster or lighter in the browser, or wants static meshes / LOD groups combined (e.g. `/bt-optimize Assets/Scenes/Garden/GardenScene.unity`, `/bt-optimize --combine-only`)."
3
+ description: "The Babylon Toolkit Optimize Skill makes an exported Unity scene run fast as BabylonJS web content. It measures the exported scene in the browser first (frame rate, draw calls per pass — shadow maps, depth / velocity buffers, main pass, post — CPU hot spots, light binding), accounts for every draw by the object that owns it, surveys the Unity scene for the causes, then fixes them on a copy of the scene: skinned meshes that need no skinning (one-bone DAE / FBX imports — coins, item boxes, trees, signs) turned into plain meshes so repeated props share one instanced draw, runtime practical lights baked, realtime point / spot shadows removed, non-moving props marked static, probe-lit props with lightmap UVs lightmapped, no-op post effects removed, and static meshes and LOD groups merged with the Babylon Toolkit MeshCombiner (packed source lightmap UVs, mirrored pieces, LOD clusters with corrected switch distances). It re-bakes, exports, and proves the result — frame rate and draw calls before → after at the same pinned views, and the same look in Unity and in the browser. Every decision is written down with its reason. Use when the user wants a Unity scene to run faster or lighter in the browser, or wants static meshes / LOD groups combined (e.g. `/bt-optimize Assets/Scenes/Garden/GardenScene.unity`, `/bt-optimize --combine-only`)."
4
4
  allowed-tools: Read, Grep, Glob, Edit, Write, Bash, WebFetch(domain:raw.githubusercontent.com)
5
5
  ---
6
6
 
@@ -14,7 +14,7 @@ Use the user's message after the skill name as the `arguments`.
14
14
 
15
15
  ```
16
16
  /bt-optimize [<scene asset path>] [--out:<asset path>] [--analyze] [--reset]
17
- [--no-combine | --combine-only] [--no-tune:lights,static,lightmaps,post]
17
+ [--no-combine | --combine-only] [--no-tune:unskin,lights,static,lightmaps,post] [--instance-from:4]
18
18
  [--keep-lights:Name1,Prefix*] [--bake-shadowed-lights] [--exclude:Name1,Prefix*] [--only:Path/A,Path/B]
19
19
  [--cell:15] [--spread:3] [--atlas-share:0.45] [--no-shadergraphs] [--no-lods] [--shaders:Name1,Name2]
20
20
  [--textures:ktx2] [--resolution:css] [--no-bake] [--no-export] [--no-browser] [--pins:40,60] [--times:10,20,30,45,60,90]
@@ -26,7 +26,8 @@ Use the user's message after the skill name as the `arguments`.
26
26
  - **`--reset`** — start again from the source (re-copies it over the working copy, deletes the previous merged meshes and reports).
27
27
  - **`--no-combine`** — every optimization except merging meshes.
28
28
  - **`--combine-only`** — only merge static meshes and LOD groups (no light, static, lightmap or post changes).
29
- - **`--no-tune:`** — skip individual tune steps: `lights` (bake practical lights / drop point-spot shadows), `static` (mark non-moving props static), `lightmaps` (probe-lit → lightmapped), `post` (no-op post effects).
29
+ - **`--no-tune:`** — skip individual tune steps: `unskin` (rigid skinned meshes → plain meshes), `lights` (bake practical lights / drop point-spot shadows), `static` (mark non-moving props static), `lightmaps` (probe-lit → lightmapped), `post` (no-op post effects).
30
+ - **`--instance-from:`** — a mesh drawn this many times or more (same mesh and materials) stays light-probe lit so its copies share one instanced draw instead of each getting its own lightmapped mesh (default `4`; `0` turns it off).
30
31
  - **`--keep-lights:`** — light names (or prefixes ending in `*`) that stay realtime / Mixed.
31
32
  - **`--bake-shadowed-lights`** — also bake point / spot lights that cast realtime shadows (default: they stay realtime with their shadows turned off).
32
33
  - **`--exclude:`** — object names (or prefixes) whose subtrees are never tuned or merged. **`--only:`** limits merging to these hierarchy paths.
@@ -44,6 +45,8 @@ Use the user's message after the skill name as the `arguments`.
44
45
  3. **Every decision has a written reason.** `.agents/optimize/<Out>/` holds the survey, the tune plan and log, the merge plan and manifest, verify results, profiles, captures and the report.
45
46
  4. **It looks the same.** Re-baked, then compared in Unity (LOD0 and LOD1) and in the browser at matching views. Expected, stated differences: baked practical lights lose their specular highlights and their realtime shadows on moving objects (they never had flicker or distance culling in the browser — those were Unity-only scripts).
46
47
  5. **No vertex bloat.** Merges use the toolkit's `UnityMeshSimplifier.MeshCombiner` in *Pack Source Lightmap UVs* mode — each source keeps its own lightmap UVs, packed at its original texel density.
48
+ 6. **Every draw is accounted for — ENFORCED.** Per-pass totals say *where* the frame goes; they never say *what* to fix. At every pinned view the profiler's `drawOwners` splits the main-pass draws by the scene object that owns them and lists every shape drawn more than once with why its copies do not share one draw. The plan and the report carry that table. **Every owner group of 5% or more of the main-pass draws is either fixed or has a written, measured reason it cannot be** — "it has an Animator", "it is skinned" or "a rule kept it" is not a reason on its own (see 7). The skill is not done while a large group is unexamined: a run that cut shadow draws but left 129 of 202 main-pass draws to copies of 8 props, all one-bone skinned meshes nobody looked at, was a failed optimization.
49
+ 7. **An Animator or a SkinnedMeshRenderer is evidence to check, never a reason to skip.** Look at what the clip actually animates (`survey.md` → Skinned meshes): a spawn pop that scales the object, a spin, a collider toggle all work on a plain mesh. Only real deformation (animated bones, blend shapes, cloth) needs skinning. Repeated props are the largest draw group in most levels after the level geometry — always check them.
47
50
 
48
51
  # Talk to the user while you work
49
52
 
@@ -60,7 +63,9 @@ Learned on a 2,400-renderer URP garden that ran 8–26 FPS (1–5 FPS in hitches
60
63
  - **Runtime lights that the browser never animates are pure cost.** Unity sample scenes drive lights with MonoBehaviours (`LightFlicker`, `DynamicLightController` distance culling). Without a toolkit TypeScript port those scripts **do not run in the browser**: the lights neither flicker nor cull — they just cost. Baked, their light lives in the lightmaps (static objects) and light probes (moving objects) at zero runtime cost.
61
64
  - **A depth pass appears when anything samples scene depth**: soft particles (`TOOLKIT.ShurikenParticles.SoftParticleDepth`, on by default) and Shader Graph Scene Depth nodes (`ShaderGraphPass.SceneDepth`) create a `DepthRenderer` that re-draws every visible opaque mesh each frame (20–25% of draws in the garden). Report it; merging reduces it; the runtime fix (take depth from the prepass renderer) belongs to the toolkit.
62
65
  - **Zero-intensity post effects may still run.** URP's pipeline-default Volume Profile ships Motion Blur at intensity 0 (off in Unity); older toolkit runtimes still built a motion-blur pass for it.
63
- - **Light binding is range-aware** in the toolkit (a mesh only binds lights whose range reaches it; at most `SceneController.maximumLights`, default 4).
66
+ - **Light binding is NOT range-aware.** BabylonJS's `Light.canAffectMesh` checks only include / exclude lists and layer masks, so every mesh binds up to its cap of runtime lights wherever they are (verified on Mario Circuit: 5 × 5 m item boxes bound 8 lights, 7 out of range). Tighter mesh bounds never lower the bindings — only baking the lights does. The profiler's `lightAudit` clamps each light into the mesh's box, so scene-sized bounds (skinned or track-wide meshes) hide the waste: a low out-of-range share on such a scene is understated.
67
+ - **Skinned meshes never instance.** Copies of a skinned mesh that animate separately each cost their own draw in every pass, and are skinned every frame. DAE and FBX imports routinely make rigid props one-bone skinned meshes: on Mario Circuit, 118 of 135 skinned renderers (coins, item-box parts, trees, track pieces) had one bone moving with the object and 129 of 202 main-pass draws came from 8 such repeated shapes. As plain meshes the exporter writes the copies as glTF instances (`ExportMeshInstances`, default on) — one draw per shape.
68
+ - **Lightmapping a repeated prop costs its instancing.** A lightmapped renderer never shares a cached mesh (each copy gets its own lightmap UVs), so 16 lightmapped trees are 16 draws while 16 probe-lit trees are one. Repeated props stay probe-lit (`instanceRepeatsFrom`); unique geometry gets the lightmaps.
64
69
  - **Materials are cloned per renderer** for each reflection probe / lightmap combination and per LOD cross-fade level. Fewer renderers → fewer clones → fewer first-view shader compiles (hitches).
65
70
  - **Lightmapped renderers never share a cached mesh** (reference §4): repeated lightmapped props are one draw each — merging is the only way to cut them. Probe-lit repeated props stay glTF instances.
66
71
 
@@ -70,6 +75,8 @@ Enforced by `scripts/BtOptimize.cs` (`Tune`). A **browser driver** is anything t
70
75
 
71
76
  | Step | Rule | Why |
72
77
  |---|---|---|
78
+ | Unskin rigid meshes | A SkinnedMeshRenderer with **one weighted bone** that moves with the object (no clip, Timeline, script, constraint or physics body moves the bone apart from the object), no blend shapes, no cloth, and no curve or reference aimed at the SkinnedMeshRenderer component becomes a MeshFilter + MeshRenderer on the same mesh and materials. Animators stay. When the bind pose offsets the mesh, a plain leaf object is moved onto it (the mesh stays shared — verified vertex by vertex); otherwise the offset is baked into one mesh asset shared by every copy with the same offset (`<Out>_UnskinnedMeshes/`). Runs first, so the later steps see the new renderers | Babylon skins a skinned mesh every frame and can never instance its copies. A one-bone import of a rigid prop bought nothing — Mario Circuit's coins, item boxes and trees were 112 draws at the start gate that become instances |
79
+ | Repeated props stay instanceable | A mesh + materials drawn `instanceRepeatsFrom` (4) times or more stays light-probe lit when marked static (still Contribute GI for bounce) and is skipped by the lightmap step | The exporter gives every lightmapped copy its own mesh; probe-lit copies share one instanced draw |
73
80
  | Lights → Baked | Active Realtime / Mixed **point and spot** lights with no browser driver and **no realtime shadows** become Baked. Directional lights (the sun) and `--keep-lights` stay | Practical fill lights cost per-pixel lighting every frame; baked, they cost nothing and still light moving objects through probes |
74
81
  | Shadowed key lights stay runtime, shadows off | A point / spot light that casts realtime shadows (or that a browser driver animates) stays Realtime / Mixed and loses only its realtime shadows. `--bake-shadowed-lights` bakes them too | Each shadowed light re-draws the scene every frame (×6 for a point light) — the shadows are the cost, not the light. Keeping the light realtime keeps its exact look (direct light, specular highlights, light on moving objects) with no bake risk; on Garden, six such lights cost little once their shadow maps were gone. Use `--bake-shadowed-lights` when a scene has many of them and Phase 5 verifies the bake |
75
82
  | Fixture shells stop casting shadows | When a light is baked, the shadow-casting renderers of its own fixture prefab whose bounds hold the light get Cast Shadows Off | A lantern shell around the bulb is clipped by the realtime shadow map's near plane, but the lightmapper traces from the bulb: a shadow-casting shell traps a baked light (lit floor under each lantern, dark walls) |
@@ -79,6 +86,11 @@ Enforced by `scripts/BtOptimize.cs` (`Tune`). A **browser driver** is anything t
79
86
 
80
87
  Kept as they are, by design: wind / vertex-animated vegetation (probe-lit by intent, and unmergeable), props without lightmap UVs (probe-lit), anything a script points at, stencil / depth / VFX utility meshes (no Meta pass), inactive objects.
81
88
 
89
+ Reported, never converted automatically — each with its next step in `survey.md` and `tune.md`:
90
+ - **Rigid, convert by hand:** a single bone that moves apart from its object (parent a plain mesh under the bone), a clip that animates the SkinnedMeshRenderer itself (retarget the curve to MeshRenderer), a component that references the SkinnedMeshRenderer.
91
+ - **Frozen pose:** several weighted bones that nothing animates — bake each copy to a static mesh (`SkinnedMeshRenderer.BakeMesh`).
92
+ - **Really deforming and repeated** (a waving crowd): the toolkit's `AnimatorControlRig` VAT (crowd) mode draws the copies instanced (`unity-authoring-recipes.md` §13). Name the group, its copies and its draws in the report.
93
+
82
94
  **Every tune rule above came from a regression found by comparing Unity captures at the browser's poses** — run Phase 5 every time; a rule that changes what the lightmapper sees can change a whole room.
83
95
 
84
96
  # The merge rules — and why each exists
@@ -127,7 +139,7 @@ OUT=Assets/.../Scene_Optimized.unity # --out, or <source folder>/<SceneNa
127
139
  NAME=$(basename "$OUT" .unity); SRC_NAME=$(basename "$SOURCE" .unity)
128
140
  REPORT="$PROJ/.agents/optimize/$NAME"; QA="$PROJ/.agents/optimize/.qa-tools"
129
141
  MERGE='{"cellSize":15,"maxSpread":3,"maxAtlasShare":0.45,"includeShaderGraphs":true,"combineLods":true,"exclude":[],"only":[],"extraShaders":[]}'
130
- TUNE='{"bakeLights":true,"bakeShadowedLights":false,"keepLights":[],"pointSpotShadowsOff":true,"markStatic":true,"lightmapProbeLit":true,"fixZeroMotionBlur":true,"exclude":[]}'
142
+ TUNE='{"unskinRigid":true,"instanceRepeatsFrom":4,"bakeLights":true,"bakeShadowedLights":false,"keepLights":[],"pointSpotShadowsOff":true,"markStatic":true,"lightmapProbeLit":true,"fixZeroMotionBlur":true,"exclude":[]}'
131
143
 
132
144
  bt_run() { # bt_run <File: BtOptimize|BtCombine> <Method> '<json args array>'
133
145
  unity command run_script --file "AgentScripts/bt-optimize/$1.cs" --entry "$1.$2" --args "$3" \
@@ -137,7 +149,7 @@ bt_run() { # bt_run <File: BtOptimize|BtCombine> <Method> '<json args array>'
137
149
  arg() { python3 -c "import json,sys; print(json.dumps([sys.argv[1]]))" "$1"; } # wraps one JSON options string as a run_script args array
138
150
  ```
139
151
 
140
- Map flags into `MERGE` / `TUNE` (`--exclude:A,B*` → both `"exclude":["A","B*"]`, `--keep-lights:` → `keepLights`, `--no-shadergraphs` → `"includeShaderGraphs":false`, `--no-lods` → `"combineLods":false`, `--no-tune:lights` → `"bakeLights":false,"pointSpotShadowsOff":false`, `--no-tune:static` → `"markStatic":false`, `--no-tune:lightmaps` → `"lightmapProbeLit":false`, `--no-tune:post` → `"fixZeroMotionBlur":false`, `--bake-shadowed-lights` → `"bakeShadowedLights":true`).
152
+ Map flags into `MERGE` / `TUNE` (`--no-tune:unskin` → `"unskinRigid":false`, `--instance-from:N` → `"instanceRepeatsFrom":N`, `--exclude:A,B*` → both `"exclude":["A","B*"]`, `--keep-lights:` → `keepLights`, `--no-shadergraphs` → `"includeShaderGraphs":false`, `--no-lods` → `"combineLods":false`, `--no-tune:lights` → `"bakeLights":false,"pointSpotShadowsOff":false`, `--no-tune:static` → `"markStatic":false`, `--no-tune:lightmaps` → `"lightmapProbeLit":false`, `--no-tune:post` → `"fixZeroMotionBlur":false`, `--bake-shadowed-lights` → `"bakeShadowedLights":true`).
141
153
 
142
154
  ## Phase 0 — Preflight
143
155
 
@@ -166,7 +178,7 @@ node "$QA/profile-browser.mjs" --scene <source>.gltf --pin 40,60,75 --toggles no
166
178
 
167
179
  `--pin` waits the given seconds after the scene is ready, then detaches the camera from its rig and **records its exact pose** (position, rotation and lens — field of view and clip planes, because Timeline / Cinemachine tracks animate the lens too; the lens fields are made read-only while pinned, because a lens track keeps writing them and TAA builds its projection from them before any observer runs). Every later run replays those poses with `--poses before-pinned.json`, so before and after are measured from the same views — pinning by time alone lands on different views, because a lighter scene loads sooner and its tour runs ahead.
168
180
 
169
- Read the JSON: `census` (engine, render size, meshes, materials, lights, shadow generators and their casters, post passes, prepass), `samples` (FPS, p95 / worst frame, draws, active meshes), and per pin `baseline.passes` / `baseline.byTarget` (draws per frame in shadow maps, `DepthRenderer`, main pass, post), `lightAudit`, and `cpu.top`. **Pin inside the scene's own motion** (a flythrough, a spawn view after compile): the first seconds after load are still compiling shaders and are not comparable. To confirm a suspected cost, re-run with `--toggles shadows,lights,motionblur,taa,bloom,dpr` (each switched off alone and settled on `whenReadyAsync` — never compare a window that follows a toggle without that wait: thousands of materials recompile).
181
+ Read the JSON: `census` (engine, render size, meshes, materials, lights, shadow generators and their casters, post passes, prepass), `samples` (FPS, p95 / worst frame, draws, active meshes), and per pin `baseline.passes` / `baseline.byTarget` (draws per frame in shadow maps, `DepthRenderer`, main pass, post), **`drawOwners`** (main-pass draws by owning object — `mainDraws` must equal `baseline.passes.main` — with each owner's skinned / instanced / lightmapped meshes and shadow casters, plus `repeats`: every shape drawn more than once and what stops its copies sharing one draw), `lightAudit`, and `cpu.top`. **Pin inside the scene's own motion** (a flythrough, a spawn view after compile): the first seconds after load are still compiling shaders and are not comparable. To confirm a suspected cost, re-run with `--toggles shadows,lights,motionblur,taa,bloom,dpr` (each switched off alone and settled on `whenReadyAsync` — never compare a window that follows a toggle without that wait: thousands of materials recompile).
170
182
 
171
183
  ## Phase 2 — Survey and plan
172
184
 
@@ -177,7 +189,9 @@ bt_run BtOptimize Tune "$(arg "$(echo "$TUNE" | sed 's/}$/,"dryRun":true}/')")"
177
189
  bt_run BtCombine Analyze "$(arg "$MERGE")" # combine-plan.md (on the source: merges before tune unlocks)
178
190
  ```
179
191
 
180
- Tell the user in a few lines: the measured frame (FPS, draws per pass, the top costs), and the plan with numbers (lights to bake, props to mark static, renderers to lightmap, merges). `--analyze` stops here. Otherwise continue — do not wait for approval; the source is safe.
192
+ **Account for every draw before planning — ENFORCED.** From `before-pinned.json` → `pins[].drawOwners`, write the main-pass draws by owner at each pin into the plan (`node "$QA/compare-profiles.mjs"` prints it), then put each owner group of 5% or more beside its Unity cause and its fix: `survey.md` → *Skinned meshes* (every skinned renderer's verdict — rigid, frozen pose, deforms — with the evidence), *Repeated meshes* (copies, draws now, draws if instanced, what stops sharing), *Renderers*, *Lights*. A group with no fix gets a measured reason. Do not start Phase 3 with a large group unexplained.
193
+
194
+ Tell the user in a few lines: the measured frame (FPS, draws per pass, **the draw owners and the top repeated shapes**, the top costs), and the plan with numbers (rigid skinned meshes to convert, repeated props that will instance, lights to bake, props to mark static, renderers to lightmap, merges). `--analyze` stops here. Otherwise continue — do not wait for approval; the source is safe.
181
195
 
182
196
  ## Phase 3 — Working copy, tune, merge
183
197
 
@@ -306,7 +320,8 @@ Reply in plain language with images, and write `$REPORT/report.md`:
306
320
 
307
321
  - **Result:** FPS and frame time (p50 / p95 / worst) before → after at each pinned view and over the timeline; draws per frame by pass; meshes, primitives, materials, vertices and export size (`gltf-stats`); export time.
308
322
  - **What changed and why:** lights baked (count, which), shadows removed, props marked static, renderers lightmapped, post fixes, merges (static groups, LOD clusters, the biggest by name).
309
- - **What stayed and why:** top kept reasons with counts, and what the user could change (UV2 on props, scripts that point at objects, vegetation by design).
323
+ - **Draws by owner, before → after, at each pin** (`compare-profiles` prints it): every group of 5% or more of the main-pass draws, with what changed it or the measured reason it could not change. The repeated shapes that still cost one draw per copy, and why.
324
+ - **What stayed and why:** top kept reasons with counts, and what the user could change (UV2 on props, scripts that point at objects, vegetation by design, skinned meshes to convert by hand, repeated deforming crowds for the VAT mode).
310
325
  - **Toolkit findings:** costs the scene cannot fix (for example a `DepthRenderer` pass owned by soft particles or a Scene Depth node), with the runtime fix to ask for.
311
326
  - **Checks:** Verify result, Unity captures, browser frames, console errors; anything skipped or unverified, stated as such.
312
327
  - **How to undo:** `--reset`, or delete the working copy, `<Out>_CombinedMeshes/`, `<Out>/` (baked lighting) and `.agents/optimize/<Out>/`; re-tick any Volume Profile override listed in `tune.md`.
@@ -319,6 +334,7 @@ Reply in plain language with images, and write `$REPORT/report.md`:
319
334
  |---|---|
320
335
  | `<out scene>` | the working copy (tuned and merged) |
321
336
  | `<out scene folder>/<Out>_CombinedMeshes/*.asset` | merged meshes |
337
+ | `<out scene folder>/<Out>_UnskinnedMeshes/*.asset` | plain meshes baked from rigid skinned meshes whose bind pose was offset and whose object could not be moved (usually empty) |
322
338
  | `<out scene folder>/<Out>/` | the copy's baked lighting |
323
339
  | `.agents/optimize/<Source>/` | survey, tune plan, merge plan and "before" profiles of the source |
324
340
  | `.agents/optimize/<Out>/` | `working-copy.txt`, `tune.md/json`, `combine-plan.*`, `combine-manifest.json`, `combine-verify.md`, `profile/`, `captures/`, `report.md` |
@@ -231,6 +231,8 @@ public static class BtCombine
231
231
  AssetDatabase.ImportAsset(outputScene, ImportAssetOptions.ForceUpdate);
232
232
  string meshFolder = MeshFolderFor(outputScene);
233
233
  if (AssetDatabase.IsValidFolder(meshFolder)) AssetDatabase.DeleteAsset(meshFolder);
234
+ string unskinnedFolder = UnskinnedMeshFolderFor(outputScene);
235
+ if (AssetDatabase.IsValidFolder(unskinnedFolder)) AssetDatabase.DeleteAsset(unskinnedFolder);
234
236
  string manifest = Path.Combine(ReportFolderFor(outputScene), "combine-manifest.json");
235
237
  if (File.Exists(manifest)) File.Delete(manifest);
236
238
  }
@@ -240,7 +242,7 @@ public static class BtCombine
240
242
  return "opened=" + scene.path + " created=" + !existed + " reset=" + (existed && reset);
241
243
  }
242
244
 
243
- /// <summary>Deletes a working copy, its merged meshes, its baked lighting folder and its report folder.</summary>
245
+ /// <summary>Deletes a working copy, its merged and unskinned meshes, its baked lighting folder and its report folder.</summary>
244
246
  public static string RemoveCopy(string outputScene, string reopenScene)
245
247
  {
246
248
  if (!File.Exists(WorkingCopyMarker(outputScene))) throw new InvalidOperationException(outputScene + " is not a bt-optimize working copy; refusing to delete it.");
@@ -248,6 +250,7 @@ public static class BtCombine
248
250
  EditorSceneManager.OpenScene(reopenScene, OpenSceneMode.Single);
249
251
  bool sceneDeleted = AssetDatabase.DeleteAsset(outputScene);
250
252
  bool meshesDeleted = AssetDatabase.DeleteAsset(MeshFolderFor(outputScene));
253
+ AssetDatabase.DeleteAsset(UnskinnedMeshFolderFor(outputScene));
251
254
  bool lightingDeleted = AssetDatabase.DeleteAsset(Path.ChangeExtension(outputScene, null).Replace('\\', '/'));
252
255
  string reportFolder = ReportFolderFor(outputScene);
253
256
  if (Directory.Exists(reportFolder)) Directory.Delete(reportFolder, true);
@@ -1608,6 +1611,15 @@ public static class BtCombine
1608
1611
  return Path.GetDirectoryName(scenePath).Replace('\\', '/') + "/" + Path.GetFileNameWithoutExtension(scenePath) + "_CombinedMeshes";
1609
1612
  }
1610
1613
 
1614
+ /// <summary>
1615
+ /// Folder for the plain meshes BtOptimize.Tune bakes from rigid skinned meshes whose bind pose is offset from their
1616
+ /// object: &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes. Keep the name in step with BtOptimize.UnskinnedMeshFolder.
1617
+ /// </summary>
1618
+ private static string UnskinnedMeshFolderFor(string scenePath)
1619
+ {
1620
+ return Path.GetDirectoryName(scenePath).Replace('\\', '/') + "/" + Path.GetFileNameWithoutExtension(scenePath) + "_UnskinnedMeshes";
1621
+ }
1622
+
1611
1623
  /// <summary>Folder for a scene's reports: &lt;project&gt;/.agents/optimize/&lt;scene&gt;.</summary>
1612
1624
  private static string ReportFolderFor(string scenePath)
1613
1625
  {
@@ -21,6 +21,33 @@ public static class BtOptimize
21
21
  /// <summary>Render queues from here up are transparent.</summary>
22
22
  private const int FirstTransparentQueue = 2500;
23
23
 
24
+ /// <summary>A rigid skinned mesh keeps its own mesh when its bind pose moves no vertex by more than this many units.</summary>
25
+ private const float RestPoseToleranceUnits = 0.01f;
26
+
27
+ /// <summary>The rest-pose tolerance as a share of the mesh's size, for meshes too large for the fixed tolerance.</summary>
28
+ private const float RestPoseRelativeTolerance = 0.0005f;
29
+
30
+ /// <summary>Skinning verdict: one bone that moves with the object — converts to MeshFilter + MeshRenderer.</summary>
31
+ private const string SkinRigid = "rigid — needs no skinning";
32
+
33
+ /// <summary>
34
+ /// Skinning verdict: rigid, but its bind pose places the mesh away from its object — converts to a plain mesh with
35
+ /// that fixed offset baked in, one mesh asset shared by every copy with the same offset (so they still instance).
36
+ /// </summary>
37
+ private const string SkinRigidOffset = "rigid — needs no skinning (offset baked)";
38
+
39
+ /// <summary>Offset matrices are compared at this precision when copies share one baked mesh.</summary>
40
+ private const int OffsetKeyDecimals = 4;
41
+
42
+ /// <summary>Skinning verdict: rigid, but converting would change it (its bone moves on its own, or the bind pose differs).</summary>
43
+ private const string SkinRigidByHand = "rigid — convert by hand";
44
+
45
+ /// <summary>Skinning verdict: several weighted bones that nothing animates — the pose never changes.</summary>
46
+ private const string SkinFrozenPose = "frozen pose — bake to a static mesh";
47
+
48
+ /// <summary>Skinning verdict: really deforms (animated bones, blend shapes or cloth).</summary>
49
+ private const string SkinDeforms = "deforms — really skinned";
50
+
24
51
  // ------------------------------------------------------------------------------------------------------------
25
52
  // Survey
26
53
  // ------------------------------------------------------------------------------------------------------------
@@ -43,6 +70,8 @@ public static class BtOptimize
43
70
 
44
71
  SurveyLights(context, md, json);
45
72
  SurveyRenderers(context, md, json);
73
+ SurveySkinning(context, md, json);
74
+ SurveyRepeats(context, md, json);
46
75
  SurveyPostProcessing(context, md, json);
47
76
  SurveyPipeline(md, json);
48
77
  SurveyExporter(context, md, json);
@@ -147,6 +176,106 @@ public static class BtOptimize
147
176
  { "mirroredGroups", GroupsToJson(mirroredGroups) } };
148
177
  }
149
178
 
179
+ /// <summary>
180
+ /// Every skinned renderer and whether it really needs skinning. A skinned mesh in BabylonJS is skinned every frame,
181
+ /// and copies of one that animate separately can never share an instanced draw: each copy is its own draw in every
182
+ /// pass. DAE / FBX imports often make rigid props (coins, item boxes, trees, signs) one-bone skinned meshes that
183
+ /// bought nothing — those convert to MeshFilter + MeshRenderer (Tune `unskinRigid`).
184
+ /// </summary>
185
+ private static void SurveySkinning(Context context, StringBuilder md, Dictionary<string, object> json)
186
+ {
187
+ var rows = new List<object>();
188
+ var verdictCounts = new Dictionary<string, int>();
189
+ md.AppendLine("## Skinned meshes — which ones need skinning");
190
+ md.AppendLine();
191
+ var skinnedRenderers = context.Renderers.OfType<SkinnedMeshRenderer>().ToList();
192
+ if (skinnedRenderers.Count == 0) { md.AppendLine("None."); md.AppendLine(); json["skinning"] = rows; return; }
193
+ md.AppendLine("| Mesh | Copies | Verdict | Why | Next step | Example |");
194
+ md.AppendLine("|---|---|---|---|---|---|");
195
+ var groups = skinnedRenderers.Select(renderer => new { renderer, verdict = ClassifySkinning(renderer, context) })
196
+ .GroupBy(entry => (entry.renderer.sharedMesh != null ? entry.renderer.sharedMesh.name : "none") + "|" + entry.verdict.Kind)
197
+ .OrderByDescending(group => group.Count());
198
+ foreach (var group in groups)
199
+ {
200
+ var first = group.First();
201
+ int copies = group.Count();
202
+ string nextStep = NextStepForSkinning(first.verdict.Kind, copies);
203
+ verdictCounts[first.verdict.Kind] = verdictCounts.TryGetValue(first.verdict.Kind, out var count) ? count + copies : copies;
204
+ string meshName = first.renderer.sharedMesh != null ? first.renderer.sharedMesh.name : "none";
205
+ md.AppendLine("| " + meshName + " | " + copies + " | " + first.verdict.Kind + " | " + first.verdict.Why + " | " + nextStep + " | " + PathOf(first.renderer.transform) + " |");
206
+ rows.Add(new Dictionary<string, object> { { "mesh", meshName }, { "copies", copies }, { "verdict", first.verdict.Kind }, { "why", first.verdict.Why },
207
+ { "nextStep", nextStep }, { "example", PathOf(first.renderer.transform) } });
208
+ }
209
+ md.AppendLine();
210
+ md.AppendLine("Skinned renderers: **" + skinnedRenderers.Count + "** — " + string.Join(", ", verdictCounts.Select(pair => pair.Key + " " + pair.Value)) + ".");
211
+ md.AppendLine();
212
+ context.Summary.AppendLine("skinned=" + skinnedRenderers.Count + " " + string.Join(" ", verdictCounts.Select(pair => "[" + pair.Key + "]=" + pair.Value)));
213
+ json["skinning"] = rows;
214
+ }
215
+
216
+ /// <summary>What to do about a group of skinned renderers with the given verdict.</summary>
217
+ private static string NextStepForSkinning(string verdictKind, int copies)
218
+ {
219
+ if (verdictKind == SkinRigid) return "Tune converts it (unskinRigid)";
220
+ if (verdictKind == SkinRigidOffset) return "Tune converts it to a shared baked mesh (unskinRigid)";
221
+ if (verdictKind == SkinRigidByHand) return "convert by hand (see Why), then re-survey";
222
+ if (verdictKind == SkinFrozenPose) return "bake each copy to a static mesh by hand (SkinnedMeshRenderer.BakeMesh), then re-survey";
223
+ return copies > 1 ? "repeated deforming mesh: candidate for the toolkit AnimatorControlRig VAT (crowd) mode — instanced, one draw" : "keep";
224
+ }
225
+
226
+ /// <summary>
227
+ /// Every mesh drawn more than once with the same materials, and whether its copies can share one instanced draw in
228
+ /// BabylonJS. The exporter writes repeated meshes as glTF instances (ExportMeshInstances), but never skinned or
229
+ /// lightmapped copies, and a material splits into copies per reflection probe. Repeated props are usually the
230
+ /// largest group of draws in a level after the level geometry itself.
231
+ /// </summary>
232
+ private static void SurveyRepeats(Context context, StringBuilder md, Dictionary<string, object> json)
233
+ {
234
+ var rows = new List<object>();
235
+ md.AppendLine("## Repeated meshes — do the copies share one draw?");
236
+ md.AppendLine();
237
+ md.AppendLine("| Mesh | Copies | Draws now (est.) | Draws if instanced | What stops sharing | Example |");
238
+ md.AppendLine("|---|---|---|---|---|---|");
239
+ int drawsNow = 0, drawsInstanced = 0;
240
+ var repeated = context.Renderers.GroupBy(RepeatKey).Where(group => group.Count() > 1).OrderByDescending(group => group.Count() * SubMeshCount(group.First()));
241
+ foreach (var group in repeated)
242
+ {
243
+ var renderers = group.ToList();
244
+ int subMeshes = SubMeshCount(renderers[0]);
245
+ var blockers = InstancingBlockers(renderers, context);
246
+ int probeZones = renderers.Select(DominantReflectionProbe).Distinct().Count();
247
+ int groupDrawsNow = blockers.Count == 0 ? subMeshes * probeZones : subMeshes * renderers.Count;
248
+ drawsNow += groupDrawsNow;
249
+ drawsInstanced += subMeshes * probeZones;
250
+ string meshName = MeshOf(renderers[0]) != null ? MeshOf(renderers[0]).name : renderers[0].name;
251
+ string blockerText = blockers.Count == 0 ? (probeZones > 1 ? "shares (one draw per reflection probe zone: " + probeZones + ")" : "shares one draw") : string.Join("; ", blockers);
252
+ md.AppendLine("| " + meshName + " | " + renderers.Count + " | " + groupDrawsNow + " | " + subMeshes * probeZones + " | " + blockerText + " | " + PathOf(renderers[0].transform) + " |");
253
+ rows.Add(new Dictionary<string, object> { { "mesh", meshName }, { "copies", renderers.Count }, { "drawsNow", groupDrawsNow }, { "drawsIfInstanced", subMeshes * probeZones },
254
+ { "blockers", blockers.Cast<object>().ToList() }, { "example", PathOf(renderers[0].transform) } });
255
+ }
256
+ md.AppendLine();
257
+ md.AppendLine("Repeated-mesh draws (one pass, all copies in view): **" + drawsNow + "** now, **" + drawsInstanced + "** if every group shared its draw.");
258
+ md.AppendLine();
259
+ context.Summary.AppendLine("repeatedDraws now=" + drawsNow + " instanced=" + drawsInstanced);
260
+ json["repeats"] = new Dictionary<string, object> { { "drawsNow", drawsNow }, { "drawsIfInstanced", drawsInstanced }, { "groups", rows } };
261
+ }
262
+
263
+ /// <summary>Why copies of one mesh cannot share an instanced draw in BabylonJS (empty when they can).</summary>
264
+ private static List<string> InstancingBlockers(List<Renderer> renderers, Context context)
265
+ {
266
+ var blockers = new List<string>();
267
+ var skinned = renderers.OfType<SkinnedMeshRenderer>().ToList();
268
+ if (skinned.Count > 0)
269
+ {
270
+ string verdict = ClassifySkinning(skinned[0], context).Kind;
271
+ blockers.Add("skinned ×" + skinned.Count + " (" + verdict + ")");
272
+ }
273
+ int lightmapped = renderers.OfType<MeshRenderer>().Count(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
274
+ && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
275
+ if (lightmapped > 0) blockers.Add("lightmapped ×" + lightmapped + " (each lightmapped copy is exported as its own mesh)");
276
+ return blockers;
277
+ }
278
+
150
279
  /// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
151
280
  private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
152
281
  {
@@ -299,6 +428,18 @@ public static class BtOptimize
299
428
  public string[] keepLights = new string[0];
300
429
  /// <summary>Turn realtime shadows off on point / spot lights that stay runtime (each is a full scene pass per frame, six for a point light).</summary>
301
430
  public bool pointSpotShadowsOff = true;
431
+ /// <summary>
432
+ /// Replace SkinnedMeshRenderers that need no skinning (one weighted bone moving with the object, no blend shapes
433
+ /// or cloth, rest pose equal to the mesh) with MeshFilter + MeshRenderer on the same mesh and materials. Animators
434
+ /// stay: transform, child and collider curves keep working. Runs first, so the other steps see the new renderers.
435
+ /// </summary>
436
+ public bool unskinRigid = true;
437
+ /// <summary>
438
+ /// A mesh drawn this many times or more (same mesh and materials) stays light-probe lit instead of being
439
+ /// lightmapped, so the exporter can share one instanced draw across the copies (lightmapped copies never share).
440
+ /// 0 turns the rule off.
441
+ /// </summary>
442
+ public int instanceRepeatsFrom = 4;
302
443
  /// <summary>Mark renderers static when nothing in the browser can move them.</summary>
303
444
  public bool markStatic = true;
304
445
  /// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
@@ -332,6 +473,12 @@ public static class BtOptimize
332
473
  var changes = new List<Change>();
333
474
  var kept = new List<Change>();
334
475
 
476
+ if (options.unskinRigid)
477
+ {
478
+ int converted = UnskinRigid(context, options, changes, kept);
479
+ // The converted objects now have MeshRenderers: gather the scene again so the static and lightmap steps see them.
480
+ if (converted > 0 && !options.dryRun) context = new Context(scene);
481
+ }
335
482
  if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
336
483
  if (options.markStatic) MarkStatic(context, options, changes, kept);
337
484
  if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
@@ -370,6 +517,92 @@ public static class BtOptimize
370
517
  return summary.ToString();
371
518
  }
372
519
 
520
+ /// <summary>
521
+ /// Replaces every skinned renderer that needs no skinning with a MeshFilter + MeshRenderer on the same mesh. An
522
+ /// Animator on the object is not a reason to skip it: Animators that move, scale or toggle the object (spawn pops,
523
+ /// spins, bobs) keep working on a plain mesh. Only real deformation, a bone that moves on its own, a bind pose that
524
+ /// differs from the mesh, or a curve / script aimed at the SkinnedMeshRenderer itself keeps a renderer skinned.
525
+ /// </summary>
526
+ /// <returns>How many renderers were converted (or would be, in a dry run).</returns>
527
+ private static int UnskinRigid(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
528
+ {
529
+ int converted = 0;
530
+ var bakedMeshes = new Dictionary<string, Mesh>();
531
+ string bakedFolder = UnskinnedMeshFolder(context.Scene);
532
+ foreach (var renderer in context.Renderers.OfType<SkinnedMeshRenderer>().ToList())
533
+ {
534
+ string path = PathOf(renderer.transform);
535
+ if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "skinned", Path = path, Why = "--exclude" }); continue; }
536
+ var verdict = ClassifySkinning(renderer, context);
537
+ int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
538
+ string copiesNote = copies > 1 ? " — " + copies + " copies" : "";
539
+ bool offsetBaked = verdict.Kind == SkinRigidOffset;
540
+ if (verdict.Kind != SkinRigid && !offsetBaked)
541
+ {
542
+ kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
543
+ continue;
544
+ }
545
+ // An offset bind pose is handled by moving a plain leaf object onto the mesh (the mesh stays shared by every
546
+ // copy); only when that is impossible is the offset baked into a mesh asset.
547
+ bool reseat = offsetBaked && CanReseatObject(renderer, context);
548
+ var mesh = renderer.sharedMesh;
549
+ string howPlaced = "same mesh";
550
+ if (offsetBaked && !options.dryRun)
551
+ {
552
+ if (reseat) reseat = TryReseatObject(renderer.transform, mesh, verdict.MeshToWorld, RestPoseTolerance(renderer));
553
+ if (!reseat) mesh = BakeOffsetMesh(mesh, verdict.MeshToObject, bakedFolder, bakedMeshes);
554
+ }
555
+ if (offsetBaked) howPlaced = reseat ? "same mesh, object moved onto the bind pose" : "baked mesh in " + bakedFolder;
556
+ changes.Add(new Change { Kind = "Unskinned (rigid)", Path = path, Before = "SkinnedMeshRenderer, " + verdict.Why,
557
+ After = "MeshFilter + MeshRenderer, " + howPlaced + ", same materials",
558
+ Why = "skinning bought nothing: BabylonJS skins it every frame, and skinned copies can never share an instanced draw" + copiesNote });
559
+ converted++;
560
+ if (!options.dryRun) ReplaceWithMeshRenderer(renderer, mesh);
561
+ }
562
+ if (bakedMeshes.Count > 0) AssetDatabase.SaveAssets();
563
+ return converted;
564
+ }
565
+
566
+ /// <summary>
567
+ /// Swaps a SkinnedMeshRenderer for a MeshFilter + MeshRenderer on the same GameObject drawing `mesh` (the skinned
568
+ /// mesh itself, or its offset-baked copy), with the same materials and renderer settings. Bones, colliders,
569
+ /// Animators and static flags stay as they are.
570
+ /// </summary>
571
+ private static void ReplaceWithMeshRenderer(SkinnedMeshRenderer skinned, Mesh mesh)
572
+ {
573
+ var gameObject = skinned.gameObject;
574
+ var materials = skinned.sharedMaterials;
575
+ var shadowCasting = skinned.shadowCastingMode;
576
+ bool receiveShadows = skinned.receiveShadows, wasEnabled = skinned.enabled, allowOcclusion = skinned.allowOcclusionWhenDynamic;
577
+ var probeUsage = skinned.lightProbeUsage;
578
+ var reflectionUsage = skinned.reflectionProbeUsage;
579
+ var probeAnchor = skinned.probeAnchor;
580
+ var motionVectors = skinned.motionVectorGenerationMode;
581
+ uint renderingLayers = skinned.renderingLayerMask;
582
+ int sortingLayer = skinned.sortingLayerID, sortingOrder = skinned.sortingOrder;
583
+ // Unity allows one Renderer per GameObject: the skinned one must go before the MeshRenderer can be added.
584
+ UnityEngine.Object.DestroyImmediate(skinned);
585
+ // Unity's missing-component result is a fake null that `??` does not see, so compare explicitly.
586
+ var filter = gameObject.GetComponent<MeshFilter>();
587
+ if (filter == null) filter = gameObject.AddComponent<MeshFilter>();
588
+ filter.sharedMesh = mesh;
589
+ var meshRenderer = gameObject.AddComponent<MeshRenderer>();
590
+ meshRenderer.sharedMaterials = materials;
591
+ meshRenderer.shadowCastingMode = shadowCasting;
592
+ meshRenderer.receiveShadows = receiveShadows;
593
+ meshRenderer.lightProbeUsage = probeUsage;
594
+ meshRenderer.reflectionProbeUsage = reflectionUsage;
595
+ meshRenderer.probeAnchor = probeAnchor;
596
+ meshRenderer.motionVectorGenerationMode = motionVectors;
597
+ meshRenderer.allowOcclusionWhenDynamic = allowOcclusion;
598
+ meshRenderer.renderingLayerMask = renderingLayers;
599
+ meshRenderer.sortingLayerID = sortingLayer;
600
+ meshRenderer.sortingOrder = sortingOrder;
601
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
602
+ meshRenderer.enabled = wasEnabled;
603
+ EditorUtility.SetDirty(gameObject);
604
+ }
605
+
373
606
  /// <summary>
374
607
  /// Runtime point / spot lights that nothing in the browser drives become Baked: their direct light and shadows move
375
608
  /// into the lightmaps (static objects) and light probes (dynamic objects), and they cost nothing per frame. A light a
@@ -461,10 +694,13 @@ public static class BtOptimize
461
694
  var lod = renderer.GetComponentInParent<LODGroup>();
462
695
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
463
696
  bool lightmappable = level <= 0 && HasUV2(renderer) && VertexAnimationOf(renderer) == null && !IsTransparent(renderer);
697
+ bool keepInstanceable = IsRepeatedForInstancing(renderer, context, options);
464
698
  var newFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.ReflectionProbeStatic;
465
699
  if (lightmappable) newFlags |= StaticEditorFlags.ContributeGI;
466
700
  var receive = renderer.receiveGI;
467
- var newReceive = lightmappable || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)) ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
701
+ // A repeated prop still contributes bounce light, but stays probe-lit so its copies share one instanced draw.
702
+ bool receivesLightmaps = !keepInstanceable && (lightmappable || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)));
703
+ var newReceive = receivesLightmaps ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
468
704
  if (!options.dryRun)
469
705
  {
470
706
  GameObjectUtility.SetStaticEditorFlags(gameObject, newFlags);
@@ -472,7 +708,8 @@ public static class BtOptimize
472
708
  EditorUtility.SetDirty(renderer);
473
709
  }
474
710
  changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (lightmappable ? "static + ContributeGI, " : "static, ") + newReceive,
475
- Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "") });
711
+ Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "")
712
+ + (keepInstanceable ? "; stays probe-lit — " + context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw" : "") });
476
713
  }
477
714
  }
478
715
 
@@ -495,6 +732,8 @@ public static class BtOptimize
495
732
  string path = PathOf(renderer.transform);
496
733
  if (IsExcluded(renderer.transform, options.exclude)) continue;
497
734
  string reason = NotAVisibleSurface(renderer) ?? (!HasUV2(renderer) ? "no lightmap UVs (UV2)" : VertexAnimationOf(renderer) ?? (IsTransparent(renderer) ? "transparent" : null));
735
+ if (reason == null && IsRepeatedForInstancing(renderer, context, options))
736
+ reason = context.RepeatCounts[RepeatKey(renderer)] + " copies: stays probe-lit so they share one instanced draw (lightmapped copies are exported as separate meshes)";
498
737
  if (reason != null) { kept.Add(new Change { Kind = "probe-lit", Path = path, Why = reason }); continue; }
499
738
  string before = (flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI, " : "no ContributeGI, ") + renderer.receiveGI;
500
739
  if (!options.dryRun)
@@ -725,6 +964,224 @@ public static class BtOptimize
725
964
  return false;
726
965
  }
727
966
 
967
+ // ------------------------------------------------------------------------------------------------------------
968
+ // Skinning and repeats
969
+ // ------------------------------------------------------------------------------------------------------------
970
+
971
+ /// <summary>
972
+ /// What a skinned renderer really needs: one of the Skin* verdicts and the evidence. For a rigid mesh, also the
973
+ /// fixed matrix that takes its mesh vertices to where the skinning draws them, in the object's local space.
974
+ /// </summary>
975
+ private sealed class SkinningVerdict
976
+ {
977
+ public string Kind, Why;
978
+ public Matrix4x4 MeshToObject = Matrix4x4.identity;
979
+ /// <summary>Where the skinning draws the mesh: bone × bind pose (mesh space to world space).</summary>
980
+ public Matrix4x4 MeshToWorld = Matrix4x4.identity;
981
+ public SkinningVerdict(string kind, string why) { Kind = kind; Why = why; }
982
+ }
983
+
984
+ /// <summary>
985
+ /// Decides whether a SkinnedMeshRenderer needs skinning, from what actually deforms it: its weighted bones, blend
986
+ /// shapes and cloth, and which transforms animation clips, Timeline or browser scripts move. An Animator alone
987
+ /// decides nothing — most props' Animators only move, scale or toggle the object as a whole.
988
+ /// </summary>
989
+ private static SkinningVerdict ClassifySkinning(SkinnedMeshRenderer renderer, Context context)
990
+ {
991
+ var mesh = renderer.sharedMesh;
992
+ if (mesh == null) return new SkinningVerdict(SkinDeforms, "no mesh");
993
+ if (mesh.blendShapeCount > 0) return new SkinningVerdict(SkinDeforms, mesh.blendShapeCount + " blend shapes");
994
+ if (renderer.GetComponent<Cloth>() != null) return new SkinningVerdict(SkinDeforms, "Cloth");
995
+ var bones = renderer.bones;
996
+ var weightedBoneIndices = WeightedBoneIndices(renderer);
997
+ if (weightedBoneIndices.Count > 1)
998
+ {
999
+ string movedBone = weightedBoneIndices.Select(index => SeparateMotionBetween(bones[index], renderer.transform, context)).FirstOrDefault(motion => motion != null);
1000
+ return movedBone != null
1001
+ ? new SkinningVerdict(SkinDeforms, weightedBoneIndices.Count + " weighted bones; " + movedBone)
1002
+ : new SkinningVerdict(SkinFrozenPose, weightedBoneIndices.Count + " weighted bones, none moved by a clip, Timeline or script");
1003
+ }
1004
+ if (weightedBoneIndices.Count == 0 || mesh.bindposes.Length <= weightedBoneIndices[0]) return new SkinningVerdict(SkinRigidByHand, "no usable bone weights or bind poses");
1005
+ int boneIndex = weightedBoneIndices[0];
1006
+ var bone = bones[boneIndex];
1007
+ string separateMotion = SeparateMotionBetween(bone, renderer.transform, context);
1008
+ if (separateMotion != null) return new SkinningVerdict(SkinRigidByHand, "one bone, but it may move apart from the object (" + separateMotion + "): parent a plain mesh under '" + bone.name + "'");
1009
+ if (context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve)) return new SkinningVerdict(SkinRigidByHand, "a clip animates the SkinnedMeshRenderer itself (" + curve + "): retarget the curve to MeshRenderer");
1010
+ if (context.ReferencedComponents.Contains(renderer)) return new SkinningVerdict(SkinRigidByHand, "a component references the SkinnedMeshRenderer itself");
1011
+ // A one-bone vertex is drawn at bone × bindpose × vertex; a MeshFilter draws it at object × vertex. The fixed
1012
+ // difference between the two, in the object's space, is all the skinning does.
1013
+ var meshToWorld = bone.localToWorldMatrix * mesh.bindposes[boneIndex];
1014
+ var meshToObject = renderer.transform.worldToLocalMatrix * meshToWorld;
1015
+ float offset = LargestVertexOffset(mesh, meshToObject, renderer.transform.lossyScale);
1016
+ string evidence = "one bone ('" + bone.name + "') moving with the object, no blend shapes or cloth";
1017
+ if (offset <= RestPoseTolerance(renderer)) return new SkinningVerdict(SkinRigid, evidence + ", bind pose within " + offset.ToString("0.####") + " units");
1018
+ return new SkinningVerdict(SkinRigidOffset, evidence + "; the bind pose offsets the mesh by up to " + offset.ToString("0.###") + " units")
1019
+ { MeshToObject = meshToObject, MeshToWorld = meshToWorld };
1020
+ }
1021
+
1022
+ /// <summary>How far, in world units, a converted vertex may land from where the skinning drew it.</summary>
1023
+ private static float RestPoseTolerance(Renderer renderer)
1024
+ {
1025
+ return Mathf.Max(RestPoseToleranceUnits, renderer.bounds.size.magnitude * RestPoseRelativeTolerance);
1026
+ }
1027
+
1028
+ /// <summary>
1029
+ /// True when the renderer's object can simply be moved to where the skinning draws the mesh: a leaf with nothing on
1030
+ /// it but its Transform and renderer, that no clip animates and nothing references. Moving it keeps the original
1031
+ /// mesh, so every copy still shares one mesh (and one instanced draw).
1032
+ /// </summary>
1033
+ private static bool CanReseatObject(SkinnedMeshRenderer renderer, Context context)
1034
+ {
1035
+ var transform = renderer.transform;
1036
+ if (transform.childCount > 0 || context.AnimatedTransforms.ContainsKey(transform) || context.Referencers.ContainsKey(renderer.gameObject)) return false;
1037
+ return renderer.GetComponents<Component>().All(component => component is Transform || component is SkinnedMeshRenderer);
1038
+ }
1039
+
1040
+ /// <summary>
1041
+ /// Moves the object so its transform equals `meshToWorld`, then checks every vertex lands where the skinning drew
1042
+ /// it. Restores the old pose and returns false when it cannot (shear, a parent's non-uniform scale under rotation).
1043
+ /// </summary>
1044
+ private static bool TryReseatObject(Transform transform, Mesh mesh, Matrix4x4 meshToWorld, float tolerance)
1045
+ {
1046
+ Vector3 oldPosition = transform.localPosition, oldScale = transform.localScale;
1047
+ Quaternion oldRotation = transform.localRotation;
1048
+ var parentScale = transform.parent != null ? transform.parent.lossyScale : Vector3.one;
1049
+ var targetScale = meshToWorld.lossyScale;
1050
+ transform.SetPositionAndRotation(meshToWorld.GetPosition(), meshToWorld.rotation);
1051
+ transform.localScale = new Vector3(targetScale.x / parentScale.x, targetScale.y / parentScale.y, targetScale.z / parentScale.z);
1052
+ var placed = transform.localToWorldMatrix;
1053
+ bool matches = mesh.vertices.All(vertex => Vector3.Distance(placed.MultiplyPoint3x4(vertex), meshToWorld.MultiplyPoint3x4(vertex)) <= tolerance);
1054
+ if (matches) return true;
1055
+ transform.localPosition = oldPosition;
1056
+ transform.localRotation = oldRotation;
1057
+ transform.localScale = oldScale;
1058
+ return false;
1059
+ }
1060
+
1061
+ /// <summary>The indices of the bones that carry any vertex weight.</summary>
1062
+ private static List<int> WeightedBoneIndices(SkinnedMeshRenderer renderer)
1063
+ {
1064
+ var bones = renderer.bones;
1065
+ var weightedIndices = new HashSet<int>();
1066
+ foreach (var weight in renderer.sharedMesh.GetAllBoneWeights())
1067
+ if (weight.weight > 0f) weightedIndices.Add(weight.boneIndex);
1068
+ return weightedIndices.Where(index => index >= 0 && index < bones.Length && bones[index] != null).OrderBy(index => index).ToList();
1069
+ }
1070
+
1071
+ /// <summary>The largest distance, in world units, that the matrix moves any vertex of the mesh.</summary>
1072
+ private static float LargestVertexOffset(Mesh mesh, Matrix4x4 meshToObject, Vector3 objectScale)
1073
+ {
1074
+ float largest = 0f;
1075
+ foreach (var vertex in mesh.vertices)
1076
+ largest = Mathf.Max(largest, Vector3.Scale(meshToObject.MultiplyPoint3x4(vertex) - vertex, objectScale).magnitude);
1077
+ return largest;
1078
+ }
1079
+
1080
+ /// <summary>
1081
+ /// A plain copy of a rigid skinned mesh with its fixed bind-pose offset applied to positions, normals and
1082
+ /// tangents (winding flipped when the offset mirrors), saved once per mesh and offset so every copy shares it.
1083
+ /// </summary>
1084
+ private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
1085
+ {
1086
+ string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], OffsetKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1087
+ string cacheKey = source.GetHashCode() + "|" + offsetKey;
1088
+ if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
1089
+ var baked = UnityEngine.Object.Instantiate(source);
1090
+ baked.name = source.name + "_Unskinned_" + bakedMeshes.Count;
1091
+ var normalMatrix = meshToObject.inverse.transpose;
1092
+ float handedness = meshToObject.determinant < 0f ? -1f : 1f;
1093
+ baked.vertices = source.vertices.Select(vertex => meshToObject.MultiplyPoint3x4(vertex)).ToArray();
1094
+ if (source.normals.Length > 0) baked.normals = source.normals.Select(normal => normalMatrix.MultiplyVector(normal).normalized).ToArray();
1095
+ if (source.tangents.Length > 0)
1096
+ baked.tangents = source.tangents.Select(tangent =>
1097
+ {
1098
+ var direction = meshToObject.MultiplyVector(new Vector3(tangent.x, tangent.y, tangent.z)).normalized;
1099
+ return new Vector4(direction.x, direction.y, direction.z, tangent.w * handedness);
1100
+ }).ToArray();
1101
+ if (handedness < 0f)
1102
+ for (int subMesh = 0; subMesh < baked.subMeshCount; subMesh++)
1103
+ baked.SetTriangles(baked.GetTriangles(subMesh).Reverse().ToArray(), subMesh);
1104
+ baked.boneWeights = new BoneWeight[0];
1105
+ baked.bindposes = new Matrix4x4[0];
1106
+ baked.RecalculateBounds();
1107
+ if (!AssetDatabase.IsValidFolder(folder)) AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), Path.GetFileName(folder));
1108
+ AssetDatabase.CreateAsset(baked, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + baked.name + ".asset"));
1109
+ bakedMeshes[cacheKey] = baked;
1110
+ return baked;
1111
+ }
1112
+
1113
+ /// <summary>
1114
+ /// Folder for meshes baked from offset rigid skinned meshes: &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1115
+ /// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
1116
+ /// </summary>
1117
+ private static string UnskinnedMeshFolder(Scene scene)
1118
+ {
1119
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_UnskinnedMeshes";
1120
+ }
1121
+
1122
+ /// <summary>
1123
+ /// What moves the bone relative to the renderer's object, or null when the two always move together. Only the
1124
+ /// transforms between each of them and their nearest common ancestor count: whatever moves that ancestor (an
1125
+ /// Animator popping the whole prop in, a script spinning it) moves bone and mesh alike.
1126
+ /// </summary>
1127
+ private static string SeparateMotionBetween(Transform bone, Transform rendererTransform, Context context)
1128
+ {
1129
+ var rendererAncestors = new HashSet<Transform>();
1130
+ for (var node = rendererTransform; node != null; node = node.parent) rendererAncestors.Add(node);
1131
+ var commonAncestor = bone;
1132
+ while (commonAncestor != null && !rendererAncestors.Contains(commonAncestor)) commonAncestor = commonAncestor.parent;
1133
+ foreach (var start in new[] { bone, rendererTransform })
1134
+ for (var node = start; node != null && node != commonAncestor; node = node.parent)
1135
+ {
1136
+ if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return "'" + node.name + "' is animated by " + animator;
1137
+ foreach (var component in node.GetComponents<Component>())
1138
+ if (component is EditorScriptComponent || component is Rigidbody || component is UnityEngine.Animations.IConstraint)
1139
+ return "'" + node.name + "' has " + component.GetType().Name;
1140
+ }
1141
+ return null;
1142
+ }
1143
+
1144
+ /// <summary>True when the renderer's mesh and materials repeat often enough that its copies should share an instanced draw.</summary>
1145
+ private static bool IsRepeatedForInstancing(Renderer renderer, Context context, TuneOptions options)
1146
+ {
1147
+ return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) && copies >= options.instanceRepeatsFrom;
1148
+ }
1149
+
1150
+ /// <summary>
1151
+ /// Identifies renderers that draw the same mesh with the same materials (the copies an instanced draw can share).
1152
+ /// Unity objects hash by identity, which works on every Editor version (GetInstanceID is obsolete in Unity 6.5).
1153
+ /// </summary>
1154
+ private static string RepeatKey(Renderer renderer)
1155
+ {
1156
+ var mesh = MeshOf(renderer);
1157
+ string meshKey = mesh != null ? mesh.GetHashCode().ToString() : "none";
1158
+ return meshKey + "|" + string.Join(",", renderer.sharedMaterials.Select(material => material != null ? material.GetHashCode() : 0));
1159
+ }
1160
+
1161
+ /// <summary>The mesh a Mesh or SkinnedMeshRenderer draws.</summary>
1162
+ private static Mesh MeshOf(Renderer renderer)
1163
+ {
1164
+ if (renderer is SkinnedMeshRenderer skinned) return skinned.sharedMesh;
1165
+ var filter = renderer.GetComponent<MeshFilter>();
1166
+ return filter != null ? filter.sharedMesh : null;
1167
+ }
1168
+
1169
+ /// <summary>Draw calls one copy costs per pass: one per submesh.</summary>
1170
+ private static int SubMeshCount(Renderer renderer)
1171
+ {
1172
+ var mesh = MeshOf(renderer);
1173
+ return mesh != null ? Mathf.Max(1, mesh.subMeshCount) : 1;
1174
+ }
1175
+
1176
+ /// <summary>The reflection probe that lights the renderer most (the exporter splits a material per probe), or "".</summary>
1177
+ private static string DominantReflectionProbe(Renderer renderer)
1178
+ {
1179
+ var probes = new List<ReflectionProbeBlendInfo>();
1180
+ renderer.GetClosestReflectionProbes(probes);
1181
+ var dominant = probes.OrderByDescending(probe => probe.weight).FirstOrDefault();
1182
+ return dominant.probe != null ? dominant.probe.name : "";
1183
+ }
1184
+
728
1185
  // ------------------------------------------------------------------------------------------------------------
729
1186
  // Helpers
730
1187
  // ------------------------------------------------------------------------------------------------------------
@@ -740,6 +1197,14 @@ public static class BtOptimize
740
1197
  public readonly HashSet<GameObject> TimelineBound;
741
1198
  /// <summary>Objects that toolkit script components (which run in the browser) point at.</summary>
742
1199
  public readonly Dictionary<GameObject, List<string>> WebReferencers;
1200
+ /// <summary>Transforms an animation clip (Animator / Animation) or a Timeline moves, with what moves them.</summary>
1201
+ public readonly Dictionary<Transform, string> AnimatedTransforms;
1202
+ /// <summary>Objects whose Renderer / SkinnedMeshRenderer a clip animates directly, with the curve.</summary>
1203
+ public readonly Dictionary<Transform, string> RendererCurveTargets;
1204
+ /// <summary>Components (not just GameObjects) a serialized field points at.</summary>
1205
+ public readonly HashSet<Component> ReferencedComponents;
1206
+ /// <summary>How many active renderers draw each mesh + materials combination (see RepeatKey).</summary>
1207
+ public readonly Dictionary<string, int> RepeatCounts;
743
1208
  public readonly StringBuilder Summary = new StringBuilder();
744
1209
 
745
1210
  public Context(Scene scene)
@@ -751,6 +1216,11 @@ public static class BtOptimize
751
1216
  Referencers = CollectReferencers(Roots, false);
752
1217
  WebReferencers = CollectReferencers(Roots, true);
753
1218
  TimelineBound = CollectTimelineBindings(Roots);
1219
+ AnimatedTransforms = new Dictionary<Transform, string>();
1220
+ RendererCurveTargets = new Dictionary<Transform, string>();
1221
+ CollectAnimationTargets(this);
1222
+ ReferencedComponents = CollectReferencedComponents(Roots);
1223
+ RepeatCounts = Renderers.GroupBy(RepeatKey).ToDictionary(group => group.Key, group => group.Count());
754
1224
  }
755
1225
 
756
1226
  /// <summary>Every component of type T in the scene, including inactive objects.</summary>
@@ -881,6 +1351,57 @@ public static class BtOptimize
881
1351
  return result;
882
1352
  }
883
1353
 
1354
+ /// <summary>
1355
+ /// Fills the context's AnimatedTransforms (every transform a clip of an Animator or legacy Animation moves, plus
1356
+ /// every Timeline-bound object and its children) and RendererCurveTargets (objects whose renderer component a clip
1357
+ /// animates — converting that renderer would break the curve).
1358
+ /// </summary>
1359
+ private static void CollectAnimationTargets(Context context)
1360
+ {
1361
+ foreach (var root in context.Roots)
1362
+ {
1363
+ foreach (var animator in root.GetComponentsInChildren<Animator>(true))
1364
+ {
1365
+ var clips = animator.runtimeAnimatorController != null ? animator.runtimeAnimatorController.animationClips : new AnimationClip[0];
1366
+ AddClipTargets(context, animator.transform, clips, "Animator on " + animator.name);
1367
+ }
1368
+ foreach (var animation in root.GetComponentsInChildren<Animation>(true))
1369
+ AddClipTargets(context, animation.transform, AnimationUtility.GetAnimationClips(animation.gameObject), "Animation on " + animation.name);
1370
+ }
1371
+ foreach (var bound in context.TimelineBound)
1372
+ foreach (var node in bound.GetComponentsInChildren<Transform>(true))
1373
+ context.AnimatedTransforms[node] = "a Timeline track";
1374
+ }
1375
+
1376
+ /// <summary>Records what each clip's curves move, resolving curve paths from the animating object.</summary>
1377
+ private static void AddClipTargets(Context context, Transform animatedRoot, IEnumerable<AnimationClip> clips, string source)
1378
+ {
1379
+ foreach (var clip in clips.Where(clip => clip != null).Distinct())
1380
+ foreach (var binding in AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip)))
1381
+ {
1382
+ var target = binding.path == "" ? animatedRoot : animatedRoot.Find(binding.path);
1383
+ if (target == null) continue;
1384
+ if (binding.type == typeof(Transform)) context.AnimatedTransforms[target] = source + " (clip '" + clip.name + "')";
1385
+ else if (typeof(Renderer).IsAssignableFrom(binding.type)) context.RendererCurveTargets[target] = binding.type.Name + "." + binding.propertyName + " in '" + clip.name + "'";
1386
+ }
1387
+ }
1388
+
1389
+ /// <summary>Every component a serialized field in the scene points at directly (a GameObject reference does not count).</summary>
1390
+ private static HashSet<Component> CollectReferencedComponents(List<GameObject> roots)
1391
+ {
1392
+ var referenced = new HashSet<Component>();
1393
+ foreach (var root in roots)
1394
+ foreach (var component in root.GetComponentsInChildren<Component>(true))
1395
+ {
1396
+ if (component == null || component is Transform || component is MeshFilter || component is Renderer || component is LODGroup) continue;
1397
+ var property = new SerializedObject(component).GetIterator();
1398
+ while (property.Next(true))
1399
+ if (property.propertyType == SerializedPropertyType.ObjectReference && property.objectReferenceValue is Component target && target != component)
1400
+ referenced.Add(target);
1401
+ }
1402
+ return referenced;
1403
+ }
1404
+
884
1405
  /// <summary>Every GameObject bound to a track of a PlayableDirector in the scene.</summary>
885
1406
  private static HashSet<GameObject> CollectTimelineBindings(List<GameObject> roots)
886
1407
  {
@@ -30,6 +30,47 @@ function change(before, after, digits = 0) {
30
30
  return `${before.toFixed(digits)} → **${after.toFixed(digits)}** (${percent >= 0 ? "+" : ""}${percent}%)`;
31
31
  }
32
32
 
33
+ /** How many owners and repeated shapes each pin's accounting tables list. */
34
+ const DRAW_OWNER_ROWS = 12;
35
+
36
+ /**
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.
40
+ * @param {string[]} lines - the report lines to append to
41
+ * @param {object[]} runs - the parsed profile runs, in label order
42
+ * @param {(index: number) => string} name - the label of run `index`
43
+ */
44
+ function appendDrawOwners(lines, runs, name) {
45
+ const last = runs[runs.length - 1];
46
+ for (const pin of last.pins) {
47
+ const accountings = runs.map((run) => (run.pins || []).find((candidate) => candidate.atSeconds === pin.atSeconds)?.drawOwners ?? null);
48
+ const lastAccounting = accountings[accountings.length - 1];
49
+ 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
+ lines.push(`**Main-pass draws by owner — ${pin.atSeconds} s view**`);
52
+ lines.push("");
53
+ 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
+ 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 : "—"));
57
+ 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 : "—"} |`);
60
+ }
61
+ lines.push(`| **All main-pass draws** | ${accountings.map((accounting) => (accounting ? `**${accounting.mainDraws}**` : "—")).join(" | ")} | | |`);
62
+ lines.push("");
63
+ const costly = lastAccounting.repeats.filter((repeat) => repeat.blocker != null).slice(0, DRAW_OWNER_ROWS);
64
+ if (costly.length === 0) continue;
65
+ lines.push(`Repeated shapes still drawn once per copy (${name(runs.length - 1)}):`);
66
+ lines.push("");
67
+ lines.push("| Shape | Owner | Copies | Draws | Why the copies do not share one draw |");
68
+ lines.push("|---|---|---|---|---|");
69
+ for (const repeat of costly) lines.push(`| ${repeat.shape} | ${repeat.owner} | ${repeat.copies} | ${repeat.draws} | ${repeat.blocker} |`);
70
+ lines.push("");
71
+ }
72
+ }
73
+
33
74
  /** Entry point. */
34
75
  function main() {
35
76
  const { flags, files } = parseArguments(process.argv.slice(2));
@@ -59,6 +100,7 @@ function main() {
59
100
  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
101
  }
61
102
  lines.push("");
103
+ appendDrawOwners(lines, runs, name);
62
104
  }
63
105
  if (first.samples && last.samples) {
64
106
  lines.push(`| Timeline | FPS | p95 frame ms | Worst frame ms | Draws / frame |`);
@@ -315,6 +315,9 @@ function installProbe() {
315
315
  /**
316
316
  * For every active mesh: the lights Babylon actually binds (mesh.lightSources, capped by the material's
317
317
  * maxSimultaneousLights) and how many of those cannot reach the mesh at all (point / spot beyond their range).
318
+ * Babylon's Light.canAffectMesh has no range test, so tighter mesh bounds never lower the bindings. The reach test
319
+ * clamps each light into the mesh's world box, so a mesh with scene-sized bounds (a skinned mesh, a track-wide
320
+ * mesh) always counts as in range: a low share on such a scene understates the waste.
318
321
  */
319
322
  state.lightAudit = () => {
320
323
  const scene = state.scene();
@@ -342,6 +345,75 @@ function installProbe() {
342
345
  shadowedBoundPerMesh: +(shadowed / Math.max(1, meshes)).toFixed(2), mostBound: Object.entries(names).sort((a, b) => b[1] - a[1]).slice(0, 6) };
343
346
  };
344
347
 
348
+ /**
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
354
+ */
355
+ state.drawOwners = () => {
356
+ const scene = state.scene();
357
+ 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
+ const subMeshDraws = (mesh) => (mesh.subMeshes ? mesh.subMeshes.length : 1);
364
+ const owners = new Map();
365
+ const repeats = new Map();
366
+ const drawnSources = new Set();
367
+ let mainDraws = 0;
368
+ for (const mesh of activeMeshes) {
369
+ 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);
372
+ 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);
377
+ owner.meshes++;
378
+ owner.draws += draws;
379
+ if (source.skeleton) owner.skinned++;
380
+ if (mesh.isAnInstance) owner.instances++;
381
+ if (mesh.material && mesh.material.lightmapTexture) owner.lightmapped++;
382
+ if (source.geometry) owner.geometries.add(source.geometry.uniqueId);
383
+ if (owner.examples.length < 3) owner.examples.push(mesh.name);
384
+ if (!source.geometry) continue;
385
+ const repeatKey = source.geometry.uniqueId + "|" + (mesh.material ? mesh.material.uniqueId : "none");
386
+ if (!repeats.has(repeatKey)) repeats.set(repeatKey, { shape: source.name, owner: ownerName, copies: 0, draws: 0, skinned: 0, instances: 0, lightmapped: 0 });
387
+ const repeat = repeats.get(repeatKey);
388
+ repeat.copies++;
389
+ repeat.draws += draws;
390
+ if (source.skeleton) repeat.skinned++;
391
+ if (mesh.isAnInstance) repeat.instances++;
392
+ if (mesh.material && mesh.material.lightmapTexture) repeat.lightmapped++;
393
+ }
394
+ const shadowCasters = new Map();
395
+ for (const light of scene.lights) {
396
+ const generator = light.getShadowGenerator && light.getShadowGenerator();
397
+ const renderList = generator && generator.getShadowMap() ? generator.getShadowMap().renderList || [] : [];
398
+ for (const caster of renderList) shadowCasters.set(ownerOf(caster), (shadowCasters.get(ownerOf(caster)) || 0) + 1);
399
+ }
400
+ const blockerOf = (repeat) => {
401
+ if (repeat.skinned > 0) return "skinned: every copy is its own draw (Babylon cannot instance separately animated skinned meshes)";
402
+ if (repeat.lightmapped > 0) return "lightmapped: the exporter gives every lightmapped copy its own mesh";
403
+ 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
+ return null;
405
+ };
406
+ 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
+ })),
412
+ repeats: [...repeats.values()].filter((repeat) => repeat.copies > 1).sort((first, second) => second.draws - first.draws).slice(0, 25)
413
+ .map((repeat) => ({ ...repeat, blocker: blockerOf(repeat) })),
414
+ };
415
+ };
416
+
345
417
  /**
346
418
  * Switches one runtime cost off (on = false) or back on (on = true).
347
419
  * Keys: dpr, taa, motionblur, bloom, post (every camera post-process), shadows, lights (every point / spot light).
@@ -518,6 +590,7 @@ async function main() {
518
590
  process.stderr.write(`WARNING pin ${seconds}s drifted: target ${JSON.stringify(pinned)} actual ${JSON.stringify(poseBefore)} -> ${JSON.stringify(poseAfter)}\n`);
519
591
  const cpu = flags.cpuprofile === "true" ? await cpuProfile(page, windowSeconds) : null;
520
592
  const lightAudit = await page.evaluate(() => window.__btProfile.lightAudit());
593
+ const drawOwners = await page.evaluate(() => window.__btProfile.drawOwners());
521
594
  const steps = [];
522
595
  for (const key of toggles) {
523
596
  const change = await page.evaluate((k) => window.__btProfile.toggle(k, false), key);
@@ -528,7 +601,7 @@ async function main() {
528
601
  steps.push({ off: key, change, fps: off.fps, p50Ms: off.p50Ms, drawCalls: off.drawCalls, passes: off.passes, cpuRenderMs: off.cpuRenderMs, cpuFrameMs: off.cpuFrameMs });
529
602
  }
530
603
  const after = await measure(page, windowSeconds);
531
- report.pins.push({ atSeconds: seconds, readyMs, pinned, actual: { before: poseBefore, after: poseAfter }, baseline, lightAudit, cpu, steps, baselineAgain: { fps: after.fps, p50Ms: after.p50Ms } });
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 } });
532
605
  await page.close();
533
606
  }
534
607
  }