@babylonjs-toolkit/agent 1.2.11 → 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.
- package/README.md +2 -2
- package/package.json +1 -1
- package/skills/bt-optimize/SKILL.md +81 -45
- package/skills/bt-optimize/planning.md +104 -0
- package/skills/bt-optimize/scripts/BtCombine.cs +18 -2
- package/skills/bt-optimize/scripts/BtOptimize.cs +739 -15
- package/skills/bt-optimize/scripts/qa/profile-browser.mjs +50 -1
- package/skills/bt-plan/SKILL.md +4 -1
- package/skills/bt-spec/SKILL.md +1 -1
|
@@ -94,6 +94,7 @@ public static class BtOptimize
|
|
|
94
94
|
SurveyRenderers(context, md, json);
|
|
95
95
|
SurveySkinning(context, md, json);
|
|
96
96
|
SurveyRepeats(context, md, json);
|
|
97
|
+
SurveyShadowCasters(context, md, json);
|
|
97
98
|
SurveyPostProcessing(context, md, json);
|
|
98
99
|
SurveyPipeline(md, json);
|
|
99
100
|
SurveyExporter(context, md, json);
|
|
@@ -297,9 +298,100 @@ public static class BtOptimize
|
|
|
297
298
|
int lightmapped = renderers.OfType<MeshRenderer>().Count(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
|
|
298
299
|
&& GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
|
|
299
300
|
if (lightmapped > 0) blockers.Add("lightmapped ×" + lightmapped + " (each lightmapped copy is exported as its own mesh)");
|
|
301
|
+
int probeLit = renderers.OfType<MeshRenderer>().Count(renderer => renderer.lightProbeUsage != LightProbeUsage.Off && !(renderer.receiveGI == ReceiveGI.Lightmaps
|
|
302
|
+
&& GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI)));
|
|
303
|
+
if (probeLit > 0) blockers.Add("probe-lit ×" + probeLit + " (the toolkit loads each light-probe-lit node as its own mesh — SceneManager.DeinstanceProbeLitNodes; Tune turns probes off on repeats)");
|
|
300
304
|
return blockers;
|
|
301
305
|
}
|
|
302
306
|
|
|
307
|
+
/// <summary>Share of a renderer's surface area that faces up or down within this cosine (about 37°) to count as horizontal.</summary>
|
|
308
|
+
private const float HorizontalNormalCosine = 0.8f;
|
|
309
|
+
|
|
310
|
+
/// <summary>A shadow caster whose surface is at least this share horizontal is listed as a prune candidate.</summary>
|
|
311
|
+
private const float FlatCasterShare = 0.9f;
|
|
312
|
+
|
|
313
|
+
/// <summary>How many prune candidates the survey lists.</summary>
|
|
314
|
+
private const int MaxCasterCandidates = 40;
|
|
315
|
+
|
|
316
|
+
/// <summary>
|
|
317
|
+
/// Shadow casters that are probably pure cost: unique (not repeated), shadow-casting renderers whose surface is almost
|
|
318
|
+
/// all horizontal — roads, ground, markings, water and grass planes, undersides. A flat surface's shadow falls only
|
|
319
|
+
/// on what lies right under it, yet a directional light draws it again in every cascade it touches. These are
|
|
320
|
+
/// candidates only: an overhanging lip or a deck above other geometry does cast a visible shadow, so each one is
|
|
321
|
+
/// pruned (PruneShadowCasters) only when Unity captures at the pinned poses show no change. The browser's
|
|
322
|
+
/// per-cascade dump (`profile-browser.mjs --casters true`) adds far backdrops and gives each caster's draws.
|
|
323
|
+
/// </summary>
|
|
324
|
+
private static void SurveyShadowCasters(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
325
|
+
{
|
|
326
|
+
var rows = new List<object>();
|
|
327
|
+
md.AppendLine("## Shadow casters — flat surfaces to prune (verify each by capture)");
|
|
328
|
+
md.AppendLine();
|
|
329
|
+
// Skinned meshes Tune converts to plain meshes (often whole DAE / FBX levels) are ground too; really skinned ones are characters.
|
|
330
|
+
var casters = context.Renderers
|
|
331
|
+
.Where(renderer => renderer is MeshRenderer || (renderer is SkinnedMeshRenderer skinned && TuneConverts(ClassifySkinning(skinned, context).Kind)))
|
|
332
|
+
.Where(renderer => renderer.shadowCastingMode == ShadowCastingMode.On || renderer.shadowCastingMode == ShadowCastingMode.TwoSided)
|
|
333
|
+
.Where(renderer => !context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var copies) || copies == 1)
|
|
334
|
+
.Select(renderer => new { renderer, surface = HorizontalSurface(renderer) })
|
|
335
|
+
.Where(entry => entry.surface.TotalArea > 0f && entry.surface.HorizontalArea / entry.surface.TotalArea >= FlatCasterShare)
|
|
336
|
+
.OrderByDescending(entry => entry.surface.TotalArea)
|
|
337
|
+
.Take(MaxCasterCandidates)
|
|
338
|
+
.ToList();
|
|
339
|
+
int shadowCasting = context.Renderers.Count(renderer => renderer.shadowCastingMode != ShadowCastingMode.Off);
|
|
340
|
+
md.AppendLine("Shadow-casting renderers: **" + shadowCasting + "**. Flat candidates (≥ " + (FlatCasterShare * 100f).ToString("0") + "% of the surface horizontal): **" + casters.Count + "**.");
|
|
341
|
+
md.AppendLine();
|
|
342
|
+
if (casters.Count == 0) { md.AppendLine("None."); md.AppendLine(); json["shadowCasterCandidates"] = rows; return; }
|
|
343
|
+
md.AppendLine("| Renderer | Area (m²) | Horizontal | Static |");
|
|
344
|
+
md.AppendLine("|---|---|---|---|");
|
|
345
|
+
foreach (var entry in casters)
|
|
346
|
+
{
|
|
347
|
+
string path = PathOf(entry.renderer.transform);
|
|
348
|
+
float share = entry.surface.HorizontalArea / entry.surface.TotalArea;
|
|
349
|
+
bool isStatic = GameObjectUtility.GetStaticEditorFlags(entry.renderer.gameObject) != 0;
|
|
350
|
+
md.AppendLine("| " + path + " | " + entry.surface.TotalArea.ToString("0") + " | " + (share * 100f).ToString("0") + "% | " + (isStatic ? "yes" : "no") + " |");
|
|
351
|
+
rows.Add(new Dictionary<string, object> { { "path", path }, { "area", entry.surface.TotalArea }, { "horizontalShare", share }, { "static", isStatic } });
|
|
352
|
+
}
|
|
353
|
+
md.AppendLine();
|
|
354
|
+
context.Summary.AppendLine("shadowCasters=" + shadowCasting + " flatCandidates=" + casters.Count);
|
|
355
|
+
json["shadowCasterCandidates"] = rows;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/// <summary>A renderer's world-space surface area, and how much of it faces up or down (see HorizontalNormalCosine).</summary>
|
|
359
|
+
private struct SurfaceArea
|
|
360
|
+
{
|
|
361
|
+
public float TotalArea, HorizontalArea;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/// <summary>Measures the renderer's triangles in world space (a skinned mesh as its bones draw it now).</summary>
|
|
365
|
+
private static SurfaceArea HorizontalSurface(Renderer renderer)
|
|
366
|
+
{
|
|
367
|
+
var area = new SurfaceArea();
|
|
368
|
+
// Editor scripts read a mesh's vertices whatever its Read/Write import setting (the unskin step relies on it too).
|
|
369
|
+
var mesh = MeshOf(renderer);
|
|
370
|
+
if (mesh == null) return area;
|
|
371
|
+
Vector3[] localVertices;
|
|
372
|
+
if (renderer is SkinnedMeshRenderer skinned)
|
|
373
|
+
{
|
|
374
|
+
// BakeMesh writes the skinned shape in the renderer's space, without its scale (useScale false).
|
|
375
|
+
var posed = new Mesh();
|
|
376
|
+
skinned.BakeMesh(posed, false);
|
|
377
|
+
localVertices = posed.vertices;
|
|
378
|
+
UnityEngine.Object.DestroyImmediate(posed);
|
|
379
|
+
}
|
|
380
|
+
else localVertices = mesh.vertices;
|
|
381
|
+
var toWorld = renderer is SkinnedMeshRenderer ? Matrix4x4.TRS(renderer.transform.position, renderer.transform.rotation, Vector3.one) : renderer.transform.localToWorldMatrix;
|
|
382
|
+
var vertices = localVertices.Select(vertex => toWorld.MultiplyPoint3x4(vertex)).ToArray();
|
|
383
|
+
var triangles = mesh.triangles;
|
|
384
|
+
for (int i = 0; i + 2 < triangles.Length; i += 3)
|
|
385
|
+
{
|
|
386
|
+
var cross = Vector3.Cross(vertices[triangles[i + 1]] - vertices[triangles[i]], vertices[triangles[i + 2]] - vertices[triangles[i]]);
|
|
387
|
+
float triangleArea = cross.magnitude * 0.5f;
|
|
388
|
+
if (triangleArea <= 0f) continue;
|
|
389
|
+
area.TotalArea += triangleArea;
|
|
390
|
+
if (Mathf.Abs(cross.normalized.y) >= HorizontalNormalCosine) area.HorizontalArea += triangleArea;
|
|
391
|
+
}
|
|
392
|
+
return area;
|
|
393
|
+
}
|
|
394
|
+
|
|
303
395
|
/// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
|
|
304
396
|
private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
305
397
|
{
|
|
@@ -344,6 +436,10 @@ public static class BtOptimize
|
|
|
344
436
|
+ " HDR=" + camera.allowHDR + " MSAA=" + camera.allowMSAA + " far=" + camera.farClipPlane);
|
|
345
437
|
cameras.Add(new Dictionary<string, object> { { "path", PathOf(camera.transform) }, { "enabled", camera.isActiveAndEnabled }, { "antialiasing", aa }, { "antialiasingQuality", aaQuality }, { "postProcessing", post }, { "far", camera.farClipPlane } });
|
|
346
438
|
}
|
|
439
|
+
int postCameras = cameras.Cast<Dictionary<string, object>>().Count(camera => (bool)camera["enabled"] && (string)camera["postProcessing"] == "True");
|
|
440
|
+
md.AppendLine();
|
|
441
|
+
md.AppendLine("Enabled cameras with post-processing: **" + postCameras + "**" + (postCameras > 1
|
|
442
|
+
? " — each builds its own post chain in the browser; check the profile census's post passes, and turn post off on a camera that is not the one the player sees" : "") + ".");
|
|
347
443
|
md.AppendLine();
|
|
348
444
|
json["volumes"] = volumes;
|
|
349
445
|
json["cameras"] = cameras;
|
|
@@ -445,7 +541,7 @@ public static class BtOptimize
|
|
|
445
541
|
/// <summary>
|
|
446
542
|
/// Also bake lights that cast realtime shadows. Off by default: a shadowed key light reaches past geometry its
|
|
447
543
|
/// shadow map ignores (single-sided back faces, the near plane around its fixture) and the lightmapper does not —
|
|
448
|
-
/// baked,
|
|
544
|
+
/// baked, a measured scene's room lights stayed trapped and the rooms went dark. Kept lights lose only their realtime shadows.
|
|
449
545
|
/// </summary>
|
|
450
546
|
public bool bakeShadowedLights = false;
|
|
451
547
|
/// <summary>Light names (or prefixes ending in *) that stay as they are.</summary>
|
|
@@ -470,12 +566,27 @@ public static class BtOptimize
|
|
|
470
566
|
/// light. Off by default, because merging needs the newly lightmapped props.
|
|
471
567
|
/// </summary>
|
|
472
568
|
public bool keepSourceGI = false;
|
|
569
|
+
/// <summary>
|
|
570
|
+
/// Clear every static flag on objects that move in the browser although they are marked static: a clip or a
|
|
571
|
+
/// Timeline moves them (or an ancestor), or a physics body or navigation agent does. The exporter freezes a static
|
|
572
|
+
/// object's world matrix, so a static spinning prop would stand still (and a lightmap baked in one place is wrong
|
|
573
|
+
/// once it moves); they become probe-lit.
|
|
574
|
+
/// </summary>
|
|
575
|
+
public bool unfreezeAnimated = true;
|
|
473
576
|
/// <summary>Mark renderers static when nothing in the browser can move them.</summary>
|
|
474
577
|
public bool markStatic = true;
|
|
475
578
|
/// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
|
|
476
579
|
public bool lightmapProbeLit = true;
|
|
477
580
|
/// <summary>Deactivate motion blur overrides whose intensity is 0 in the profiles this scene uses (a no-op in Unity).</summary>
|
|
478
581
|
public bool fixZeroMotionBlur = true;
|
|
582
|
+
/// <summary>
|
|
583
|
+
/// A character that really deforms (bones a clip moves) and appears this many times or more (Animators whose
|
|
584
|
+
/// skinned renderers draw the same meshes) becomes a vertex-animation (VAT) crowd: the toolkit's
|
|
585
|
+
/// AnimatorControlRig in UseVertexAnimations mode, its materials copied onto the toolkit's vertex-animation shader,
|
|
586
|
+
/// its renderers at world scale 1 with Light Probes Off. The exporter bakes the clips to vertex animation textures
|
|
587
|
+
/// and the browser draws the copies instanced, each keeping its own Animator state. 0 turns the rule off.
|
|
588
|
+
/// </summary>
|
|
589
|
+
public int vatCrowdsFrom = 4;
|
|
479
590
|
/// <summary>Object names (or prefixes ending in *) whose subtrees Tune never touches.</summary>
|
|
480
591
|
public string[] exclude = new string[0];
|
|
481
592
|
/// <summary>Plan only: report every change without making it (works on any scene, including the source).</summary>
|
|
@@ -510,10 +621,12 @@ public static class BtOptimize
|
|
|
510
621
|
// The converted objects now have MeshRenderers: gather the scene again so the static and lightmap steps see them.
|
|
511
622
|
if (converted > 0 && !options.dryRun) context = new Context(scene, sourceGIContributors);
|
|
512
623
|
}
|
|
624
|
+
if (options.unfreezeAnimated) UnfreezeAnimated(context, options, changes, kept);
|
|
513
625
|
if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
|
|
514
626
|
if (options.markStatic) MarkStatic(context, options, changes, kept);
|
|
515
627
|
if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
|
|
516
628
|
if (options.instanceRepeatsFrom > 0) InstanceRepeats(context, options, changes, kept);
|
|
629
|
+
if (options.vatCrowdsFrom > 0) VatCrowds(context, options, changes, kept);
|
|
517
630
|
if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
|
|
518
631
|
// A dry run changed no flags, so its copy count is the one the planned changes would leave.
|
|
519
632
|
int copyGIContributors = options.dryRun ? context.PlannedGIContributors.Count : GIContributorPaths(scene.GetRootGameObjects()).Count;
|
|
@@ -578,13 +691,15 @@ public static class BtOptimize
|
|
|
578
691
|
if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "skinned", Path = path, Why = "--exclude" }); continue; }
|
|
579
692
|
var verdict = ClassifySkinning(renderer, context);
|
|
580
693
|
int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
|
|
581
|
-
|
|
694
|
+
// A baked pose is shared only by copies with the same shape, so the source mesh's copy count says nothing about it.
|
|
695
|
+
bool bakesShape = verdict.Kind == SkinRigidScriptHost || verdict.Kind == SkinFrozenPose;
|
|
696
|
+
string copiesNote = copies > 1 && !bakesShape ? " — " + copies + " copies" : "";
|
|
582
697
|
if (!TuneConverts(verdict.Kind))
|
|
583
698
|
{
|
|
584
699
|
kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
|
|
585
700
|
continue;
|
|
586
701
|
}
|
|
587
|
-
bool bakesPose =
|
|
702
|
+
bool bakesPose = bakesShape;
|
|
588
703
|
string howPlaced;
|
|
589
704
|
var mesh = bakesPose
|
|
590
705
|
? BakedPoseMesh(renderer, bakedFolder, bakedMeshes, !options.dryRun, out howPlaced)
|
|
@@ -600,6 +715,7 @@ public static class BtOptimize
|
|
|
600
715
|
if (options.dryRun)
|
|
601
716
|
{
|
|
602
717
|
context.PlannedUnskinned.Add(renderer);
|
|
718
|
+
context.PlannedMeshKeys[renderer] = PlannedMeshKey(renderer, mesh, verdict, bakesPose, context);
|
|
603
719
|
continue;
|
|
604
720
|
}
|
|
605
721
|
var gameObject = renderer.gameObject;
|
|
@@ -608,6 +724,7 @@ public static class BtOptimize
|
|
|
608
724
|
}
|
|
609
725
|
if (options.dryRun)
|
|
610
726
|
{
|
|
727
|
+
RecountPlannedRepeats(context);
|
|
611
728
|
DiscardUnsavedMeshes(bakedMeshes.Values);
|
|
612
729
|
return converted;
|
|
613
730
|
}
|
|
@@ -616,6 +733,24 @@ public static class BtOptimize
|
|
|
616
733
|
return converted;
|
|
617
734
|
}
|
|
618
735
|
|
|
736
|
+
/// <summary>
|
|
737
|
+
/// Which mesh a renderer a dry run plans to convert will draw: its baked pose (copies with the same shape share one
|
|
738
|
+
/// mesh), its own mesh (one-bone props, or an object moved onto its bind pose), or one offset-baked mesh per distinct
|
|
739
|
+
/// bind-pose offset. Copies only share an instanced draw when this key matches, so the dry run counts them by it.
|
|
740
|
+
/// </summary>
|
|
741
|
+
private static string PlannedMeshKey(SkinnedMeshRenderer renderer, Mesh plannedMesh, SkinningVerdict verdict, bool bakesPose, Context context)
|
|
742
|
+
{
|
|
743
|
+
if (bakesPose || !verdict.OffsetBaked || CanReseatObject(renderer, context)) return plannedMesh.GetHashCode().ToString();
|
|
744
|
+
return renderer.sharedMesh.GetHashCode() + "|" + OffsetKey(verdict.MeshToObject);
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/// <summary>A dry run's repeat counts once the planned conversions draw their planned meshes (see PlannedMeshKey).</summary>
|
|
748
|
+
private static void RecountPlannedRepeats(Context context)
|
|
749
|
+
{
|
|
750
|
+
context.RepeatCounts.Clear();
|
|
751
|
+
foreach (var group in context.Renderers.GroupBy(renderer => RepeatKeyOf(renderer, context))) context.RepeatCounts[group.Key] = group.Count();
|
|
752
|
+
}
|
|
753
|
+
|
|
619
754
|
/// <summary>True for the skinning verdicts UnskinRigid converts to a plain mesh.</summary>
|
|
620
755
|
private static bool TuneConverts(string verdictKind)
|
|
621
756
|
{
|
|
@@ -766,7 +901,7 @@ public static class BtOptimize
|
|
|
766
901
|
/// <summary>
|
|
767
902
|
/// A light inside its own fixture (a lantern shell around the bulb) is lit fine in real time — the shadow map's near
|
|
768
903
|
/// plane clips the shell — but the lightmapper traces from the bulb with no near plane, so a shadow-casting shell
|
|
769
|
-
/// traps a baked light (
|
|
904
|
+
/// traps a baked light (lit floor under each lantern, dark walls and ceiling). The fixture's own renderers
|
|
770
905
|
/// whose bounds hold the light stop casting shadows.
|
|
771
906
|
/// </summary>
|
|
772
907
|
private static void FreeFromFixture(Light light, TuneOptions options, List<Change> changes)
|
|
@@ -850,6 +985,7 @@ public static class BtOptimize
|
|
|
850
985
|
{
|
|
851
986
|
var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);
|
|
852
987
|
if (!flags.HasFlag(StaticEditorFlags.BatchingStatic) && !flags.HasFlag(StaticEditorFlags.ContributeGI)) continue;
|
|
988
|
+
if (context.PlannedNonStatic.Contains(renderer.gameObject)) continue;
|
|
853
989
|
var lod = renderer.GetComponentInParent<LODGroup>();
|
|
854
990
|
int level = lod != null ? LodLevelOf(lod, renderer) : -1;
|
|
855
991
|
if (level > 0) continue;
|
|
@@ -922,7 +1058,7 @@ public static class BtOptimize
|
|
|
922
1058
|
changes.Add(new Change { Kind = "Light probes off (instancing)", Path = path,
|
|
923
1059
|
Before = "Light Probes " + renderer.lightProbeUsage + ", Receive GI " + receive + (meshRenderer == null ? " (once unskinned)" : ""),
|
|
924
1060
|
After = "Light Probes Off, Receive GI LightProbes, Reflection Probes " + renderer.reflectionProbeUsage,
|
|
925
|
-
Why = context.RepeatCounts[
|
|
1061
|
+
Why = context.RepeatCounts[RepeatKeyOf(renderer, context)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
|
|
926
1062
|
+ " (SceneManager.DeinstanceProbeLitNodes); the copies light from the scene's ambient instead of the nearest probe" });
|
|
927
1063
|
if (options.dryRun || meshRenderer == null) continue;
|
|
928
1064
|
meshRenderer.lightProbeUsage = LightProbeUsage.Off;
|
|
@@ -931,6 +1067,274 @@ public static class BtOptimize
|
|
|
931
1067
|
}
|
|
932
1068
|
}
|
|
933
1069
|
|
|
1070
|
+
/// <summary>
|
|
1071
|
+
/// Clears every static flag on an object that is marked static but moves in the browser: a clip or Timeline moves it
|
|
1072
|
+
/// or an ancestor, or a physics body or navigation agent does (see BrowserMoverOf). The exporter freezes a static
|
|
1073
|
+
/// object's world matrix, so a static spinning, bobbing or popping prop would stand still; and a lightmap baked in one
|
|
1074
|
+
/// place is wrong once the object moves, so its renderer becomes probe-lit. Runs before the static and lightmap
|
|
1075
|
+
/// steps, which then leave these objects alone.
|
|
1076
|
+
/// </summary>
|
|
1077
|
+
private static void UnfreezeAnimated(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
|
|
1078
|
+
{
|
|
1079
|
+
foreach (var transform in context.Roots.SelectMany(root => root.GetComponentsInChildren<Transform>(true)))
|
|
1080
|
+
{
|
|
1081
|
+
var gameObject = transform.gameObject;
|
|
1082
|
+
var flags = GameObjectUtility.GetStaticEditorFlags(gameObject);
|
|
1083
|
+
if (flags == 0) continue;
|
|
1084
|
+
string mover = BrowserMoverOf(transform, context);
|
|
1085
|
+
if (mover == null) continue;
|
|
1086
|
+
string path = PathOf(transform);
|
|
1087
|
+
if (IsExcluded(transform, options.exclude)) { kept.Add(new Change { Kind = "static, but moves", Path = path, Why = "--exclude; " + mover }); continue; }
|
|
1088
|
+
var meshRenderer = gameObject.GetComponent<MeshRenderer>();
|
|
1089
|
+
bool wasLightmapped = meshRenderer != null && meshRenderer.receiveGI == ReceiveGI.Lightmaps;
|
|
1090
|
+
context.PlannedNonStatic.Add(gameObject);
|
|
1091
|
+
context.PlannedGIContributors.Remove(path);
|
|
1092
|
+
changes.Add(new Change { Kind = "Static cleared (moves in the browser)", Path = path, Before = "static (" + flags + ")" + (wasLightmapped ? ", Lightmaps" : ""),
|
|
1093
|
+
After = "not static" + (meshRenderer != null ? ", LightProbes" : ""),
|
|
1094
|
+
Why = mover + ": the exporter freezes a static object's world matrix, so it would stand still in the browser"
|
|
1095
|
+
+ (wasLightmapped ? "; a lightmap baked in one place is wrong once it moves" : "") });
|
|
1096
|
+
if (options.dryRun) continue;
|
|
1097
|
+
GameObjectUtility.SetStaticEditorFlags(gameObject, 0);
|
|
1098
|
+
if (meshRenderer != null)
|
|
1099
|
+
{
|
|
1100
|
+
meshRenderer.receiveGI = ReceiveGI.LightProbes;
|
|
1101
|
+
EditorUtility.SetDirty(meshRenderer);
|
|
1102
|
+
}
|
|
1103
|
+
EditorUtility.SetDirty(gameObject);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
/// <summary>
|
|
1108
|
+
/// What moves the object in the browser — a clip or Timeline on it or an ancestor (Context.AnimatedTransforms), or a
|
|
1109
|
+
/// Rigidbody, CharacterController or NavMeshAgent on it or an ancestor — or null. Narrower than WebDriverOf on
|
|
1110
|
+
/// purpose: an Animator on a level root that only animates one light does not move the rest of the level.
|
|
1111
|
+
/// </summary>
|
|
1112
|
+
private static string BrowserMoverOf(Transform transform, Context context)
|
|
1113
|
+
{
|
|
1114
|
+
for (var node = transform; node != null; node = node.parent)
|
|
1115
|
+
{
|
|
1116
|
+
string where = node == transform ? "" : "'" + node.name + "' above it: ";
|
|
1117
|
+
if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return where + "moved by " + animator;
|
|
1118
|
+
foreach (var component in node.GetComponents<Component>())
|
|
1119
|
+
if (component is Rigidbody || component is CharacterController || component is UnityEngine.AI.NavMeshAgent)
|
|
1120
|
+
return where + "moved by its " + component.GetType().Name;
|
|
1121
|
+
}
|
|
1122
|
+
return null;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/// <summary>The toolkit component that switches a rig to vertex animation textures (CanvasTools.dll).</summary>
|
|
1126
|
+
private const string AnimatorControlRigTypeName = "AnimatorControlRig";
|
|
1127
|
+
|
|
1128
|
+
/// <summary>The AnimatorControlRig.animationMode value that exports baked vertex animation textures.</summary>
|
|
1129
|
+
private const string VertexAnimationModeName = "UseVertexAnimations";
|
|
1130
|
+
|
|
1131
|
+
/// <summary>The toolkit shader a vertex-animated renderer's materials must use (AnimatorControlRigEditor.VAT_SHADER_NAME).</summary>
|
|
1132
|
+
private const string VertexAnimationShaderName = "Babylon/Custom/Vertex Animation Shader";
|
|
1133
|
+
|
|
1134
|
+
/// <summary>Colour properties a VAT material copy takes its tint from, in order of preference (URP / HDRP, then Built-in).</summary>
|
|
1135
|
+
private static readonly string[] VatColorSources = { "_BaseColor", "_Color" };
|
|
1136
|
+
|
|
1137
|
+
/// <summary>Texture properties copied onto a VAT material: source names in order of preference, and the VAT shader's name.</summary>
|
|
1138
|
+
private static readonly (string[] Sources, string Target)[] VatTextureProperties = {
|
|
1139
|
+
(new[] { "_BaseMap", "_BaseColorMap", "_MainTex" }, "_MainTex"), (new[] { "_BumpMap", "_NormalMap" }, "_BumpMap") };
|
|
1140
|
+
|
|
1141
|
+
/// <summary>Float properties copied onto a VAT material: source names in order of preference, and the VAT shader's name.</summary>
|
|
1142
|
+
private static readonly (string[] Sources, string Target)[] VatFloatProperties = {
|
|
1143
|
+
(new[] { "_Smoothness", "_Glossiness" }, "_Glossiness"), (new[] { "_Metallic" }, "_Metallic"), (new[] { "_BumpScale", "_NormalScale" }, "_BumpScale") };
|
|
1144
|
+
|
|
1145
|
+
/// <summary>World scale counts as 1 within this tolerance.</summary>
|
|
1146
|
+
private const float UnitScaleTolerance = 0.0001f;
|
|
1147
|
+
|
|
1148
|
+
/// <summary>One animated character: an Animator and the skinned renderers it drives (not those under a nested Animator).</summary>
|
|
1149
|
+
private sealed class Character
|
|
1150
|
+
{
|
|
1151
|
+
public readonly Animator Animator;
|
|
1152
|
+
public readonly SkinnedMeshRenderer[] Renderers;
|
|
1153
|
+
/// <summary>The meshes the character draws, as one key: characters with equal keys are copies of one character.</summary>
|
|
1154
|
+
public readonly string MeshKey;
|
|
1155
|
+
|
|
1156
|
+
public Character(Animator animator, SkinnedMeshRenderer[] renderers)
|
|
1157
|
+
{
|
|
1158
|
+
Animator = animator;
|
|
1159
|
+
Renderers = renderers;
|
|
1160
|
+
MeshKey = string.Join(",", renderers.Select(renderer => renderer.sharedMesh != null ? renderer.sharedMesh.GetHashCode() : 0).OrderBy(hash => hash));
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/// <summary>
|
|
1165
|
+
/// Makes every crowd of a really deforming character (vatCrowdsFrom copies or more: Animators whose skinned renderers
|
|
1166
|
+
/// draw the same meshes) a vertex-animation crowd. Skinned copies can never share an instanced draw, and each is
|
|
1167
|
+
/// skinned every frame; with the toolkit's AnimatorControlRig in UseVertexAnimations mode the exporter bakes each
|
|
1168
|
+
/// controller's clips to vertex animation textures and the browser draws the copies as instances — one draw per
|
|
1169
|
+
/// material in view — each keeping its own Animator state. Its materials are copied onto the toolkit's
|
|
1170
|
+
/// vertex-animation shader (one copy per source material, shared by every copy), its renderers get world scale 1
|
|
1171
|
+
/// (the baker writes world-size positions and the browser applies the renderer node's scale again; Unity draws a
|
|
1172
|
+
/// skinned mesh from its bones, so it looks the same) and Light Probes Off (the toolkit de-instances probe-lit nodes).
|
|
1173
|
+
/// Runs after the renderer steps; characters with blend shapes, cloth, transparent materials or a renderer that is
|
|
1174
|
+
/// also a bone or parent are reported, not converted.
|
|
1175
|
+
/// </summary>
|
|
1176
|
+
private static void VatCrowds(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
|
|
1177
|
+
{
|
|
1178
|
+
var drawn = new HashSet<Renderer>(context.Renderers);
|
|
1179
|
+
var plannedUnskinned = new HashSet<SkinnedMeshRenderer>(context.PlannedUnskinned);
|
|
1180
|
+
var characters = context.All<Animator>()
|
|
1181
|
+
.Where(animator => animator.isActiveAndEnabled && animator.runtimeAnimatorController != null)
|
|
1182
|
+
.Select(animator => new Character(animator, animator.GetComponentsInChildren<SkinnedMeshRenderer>(true)
|
|
1183
|
+
.Where(skinned => drawn.Contains(skinned) && !plannedUnskinned.Contains(skinned) && skinned.GetComponentInParent<Animator>() == animator)
|
|
1184
|
+
.ToArray()))
|
|
1185
|
+
.Where(character => character.Renderers.Length > 0)
|
|
1186
|
+
.ToList();
|
|
1187
|
+
var rigType = AnimatorControlRigType();
|
|
1188
|
+
var vatShader = Shader.Find(VertexAnimationShaderName);
|
|
1189
|
+
string folder = VatCrowdFolder(context.Scene);
|
|
1190
|
+
var vatMaterials = new Dictionary<Material, Material>();
|
|
1191
|
+
foreach (var crowd in characters.GroupBy(character => character.MeshKey).Where(group => group.Count() >= options.vatCrowdsFrom))
|
|
1192
|
+
{
|
|
1193
|
+
var members = new List<Character>();
|
|
1194
|
+
foreach (var character in crowd)
|
|
1195
|
+
{
|
|
1196
|
+
if (IsExcluded(character.Animator.transform, options.exclude)) kept.Add(new Change { Kind = "deforming crowd", Path = PathOf(character.Animator.transform), Why = "--exclude" });
|
|
1197
|
+
else if (!IsVertexAnimated(character.Animator, rigType)) members.Add(character);
|
|
1198
|
+
}
|
|
1199
|
+
if (members.Count == 0) continue;
|
|
1200
|
+
string blocker = rigType == null ? "this toolkit build has no " + AnimatorControlRigTypeName + " (update CanvasTools.dll)"
|
|
1201
|
+
: vatShader == null ? "shader '" + VertexAnimationShaderName + "' not found (update the toolkit editor package)"
|
|
1202
|
+
: members.Select(VatBlocker).FirstOrDefault(reason => reason != null);
|
|
1203
|
+
string copies = crowd.Count() + " copies of one deforming character";
|
|
1204
|
+
if (blocker != null)
|
|
1205
|
+
{
|
|
1206
|
+
foreach (var member in members) kept.Add(new Change { Kind = "deforming crowd", Path = PathOf(member.Animator.transform), Why = copies + "; not made a VAT crowd: " + blocker });
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
foreach (var member in members)
|
|
1210
|
+
{
|
|
1211
|
+
changes.Add(new Change { Kind = "VAT crowd", Path = PathOf(member.Animator.transform),
|
|
1212
|
+
Before = member.Renderers.Length + " SkinnedMeshRenderer (skinned every frame, one draw per copy per pass)",
|
|
1213
|
+
After = AnimatorControlRigTypeName + " " + VertexAnimationModeName + ", VAT materials in " + folder + ", renderer world scale 1, Light Probes Off",
|
|
1214
|
+
Why = copies + " (controller " + member.Animator.runtimeAnimatorController.name + "): skinned copies never instance; baked to vertex animation"
|
|
1215
|
+
+ " textures they draw instanced, one draw per material in view, each keeping its own Animator state. The Editor draws the VAT shader"
|
|
1216
|
+
+ " magenta in URP / HDRP: judge the crowd in the browser" });
|
|
1217
|
+
if (options.dryRun) continue;
|
|
1218
|
+
ConfigureVertexAnimationRig(member.Animator, rigType, member.Renderers);
|
|
1219
|
+
foreach (var skinned in member.Renderers)
|
|
1220
|
+
{
|
|
1221
|
+
skinned.sharedMaterials = skinned.sharedMaterials.Select(material => VatMaterial(material, vatShader, folder, vatMaterials)).ToArray();
|
|
1222
|
+
SetUnitWorldScale(skinned.transform);
|
|
1223
|
+
skinned.lightProbeUsage = LightProbeUsage.Off;
|
|
1224
|
+
EditorUtility.SetDirty(skinned);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
if (!options.dryRun && vatMaterials.Count > 0) AssetDatabase.SaveAssets();
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
/// <summary>Why a character cannot become a VAT crowd member automatically, or null.</summary>
|
|
1232
|
+
private static string VatBlocker(Character character)
|
|
1233
|
+
{
|
|
1234
|
+
foreach (var skinned in character.Renderers)
|
|
1235
|
+
{
|
|
1236
|
+
string name = "'" + skinned.name + "'";
|
|
1237
|
+
if (skinned.sharedMesh == null) return name + " has no mesh";
|
|
1238
|
+
if (skinned.sharedMesh.blendShapeCount > 0) return name + " has blend shapes (vertex animation textures bake bones only)";
|
|
1239
|
+
if (skinned.GetComponent<Cloth>() != null) return name + " has Cloth";
|
|
1240
|
+
if (IsTransparent(skinned)) return name + " is transparent (the VAT shader is opaque)";
|
|
1241
|
+
if (skinned.transform.childCount > 0 || character.Renderers.Any(other => other.bones.Contains(skinned.transform)))
|
|
1242
|
+
return name + " is also a bone or a parent: setting its world scale to 1 would move what hangs under it — set up the AnimatorControlRig by hand";
|
|
1243
|
+
var parentScale = skinned.transform.parent != null ? skinned.transform.parent.lossyScale : Vector3.one;
|
|
1244
|
+
if (Mathf.Abs(parentScale.x - parentScale.y) > UnitScaleTolerance * parentScale.x || Mathf.Abs(parentScale.x - parentScale.z) > UnitScaleTolerance * parentScale.x)
|
|
1245
|
+
return name + " sits under a non-uniform scale: its world scale cannot be set to 1 — set up the AnimatorControlRig by hand";
|
|
1246
|
+
if (skinned.sharedMaterials.Any(material => material != null && material.shader.name != VertexAnimationShaderName && !VatTextureProperties[0].Sources.Any(material.HasProperty)))
|
|
1247
|
+
return name + " uses a material with no base colour texture property Tune knows (" + string.Join(", ", VatTextureProperties[0].Sources) + ")";
|
|
1248
|
+
}
|
|
1249
|
+
return null;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/// <summary>The toolkit's AnimatorControlRig type, found by name in the loaded assemblies, or null when this toolkit build has none.</summary>
|
|
1253
|
+
private static Type AnimatorControlRigType()
|
|
1254
|
+
{
|
|
1255
|
+
return AppDomain.CurrentDomain.GetAssemblies()
|
|
1256
|
+
.Select(assembly => assembly.GetType(AnimatorControlRigTypeName, false))
|
|
1257
|
+
.FirstOrDefault(type => type != null && type.GetField("animationMode") != null && type.GetField("meshRenderers") != null);
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/// <summary>True when the animator already has an AnimatorControlRig in vertex-animation mode.</summary>
|
|
1261
|
+
private static bool IsVertexAnimated(Animator animator, Type rigType)
|
|
1262
|
+
{
|
|
1263
|
+
var rig = rigType != null ? animator.GetComponent(rigType) : null;
|
|
1264
|
+
return rig != null && rigType.GetField("animationMode").GetValue(rig).ToString() == VertexAnimationModeName;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
/// <summary>Adds (or reuses) the animator's AnimatorControlRig and sets it to vertex animations over the renderers.</summary>
|
|
1268
|
+
private static void ConfigureVertexAnimationRig(Animator animator, Type rigType, SkinnedMeshRenderer[] skinnedRenderers)
|
|
1269
|
+
{
|
|
1270
|
+
var rig = animator.GetComponent(rigType);
|
|
1271
|
+
if (rig == null) rig = animator.gameObject.AddComponent(rigType);
|
|
1272
|
+
var modeField = rigType.GetField("animationMode");
|
|
1273
|
+
modeField.SetValue(rig, Enum.Parse(modeField.FieldType, VertexAnimationModeName));
|
|
1274
|
+
rigType.GetField("meshRenderers").SetValue(rig, skinnedRenderers);
|
|
1275
|
+
EditorUtility.SetDirty(rig);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/// <summary>
|
|
1279
|
+
/// The vertex-animation copy of a material (tint, base colour and normal maps with their tiling, smoothness, metallic,
|
|
1280
|
+
/// normal strength), saved in the folder as <material>_VAT.mat and updated in place on a re-run so its GUID stays
|
|
1281
|
+
/// stable. Every copy of the character shares it. A material already on the vertex-animation shader is returned as it is.
|
|
1282
|
+
/// </summary>
|
|
1283
|
+
private static Material VatMaterial(Material source, Shader vatShader, string folder, Dictionary<Material, Material> vatMaterials)
|
|
1284
|
+
{
|
|
1285
|
+
if (source == null || source.shader == vatShader) return source;
|
|
1286
|
+
if (vatMaterials.TryGetValue(source, out var existing)) return existing;
|
|
1287
|
+
var vat = new Material(vatShader) { name = source.name + "_VAT", enableInstancing = true };
|
|
1288
|
+
string colorSource = VatColorSources.FirstOrDefault(source.HasProperty);
|
|
1289
|
+
if (colorSource != null && vat.HasProperty("_Color")) vat.SetColor("_Color", source.GetColor(colorSource));
|
|
1290
|
+
foreach (var (sources, target) in VatTextureProperties)
|
|
1291
|
+
{
|
|
1292
|
+
string from = sources.FirstOrDefault(source.HasProperty);
|
|
1293
|
+
if (from == null || !vat.HasProperty(target)) continue;
|
|
1294
|
+
vat.SetTexture(target, source.GetTexture(from));
|
|
1295
|
+
vat.SetTextureScale(target, source.GetTextureScale(from));
|
|
1296
|
+
vat.SetTextureOffset(target, source.GetTextureOffset(from));
|
|
1297
|
+
}
|
|
1298
|
+
foreach (var (sources, target) in VatFloatProperties)
|
|
1299
|
+
{
|
|
1300
|
+
string from = sources.FirstOrDefault(source.HasProperty);
|
|
1301
|
+
if (from != null && vat.HasProperty(target)) vat.SetFloat(target, source.GetFloat(from));
|
|
1302
|
+
}
|
|
1303
|
+
if (vat.HasProperty("_BumpMap") && vat.GetTexture("_BumpMap") != null) vat.EnableKeyword("_NORMALMAP");
|
|
1304
|
+
EnsureFolder(folder);
|
|
1305
|
+
string assetPath = folder + "/" + vat.name + ".mat";
|
|
1306
|
+
var previous = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
|
|
1307
|
+
if (previous == null) AssetDatabase.CreateAsset(vat, assetPath);
|
|
1308
|
+
else
|
|
1309
|
+
{
|
|
1310
|
+
EditorUtility.CopySerialized(vat, previous);
|
|
1311
|
+
UnityEngine.Object.DestroyImmediate(vat);
|
|
1312
|
+
vat = previous;
|
|
1313
|
+
}
|
|
1314
|
+
vatMaterials[source] = vat;
|
|
1315
|
+
return vat;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/// <summary>Sets the object's local scale so its world scale is 1 (its parents are scaled uniformly; see VatBlocker).</summary>
|
|
1319
|
+
private static void SetUnitWorldScale(Transform transform)
|
|
1320
|
+
{
|
|
1321
|
+
float parentScale = transform.parent != null ? transform.parent.lossyScale.x : 1f;
|
|
1322
|
+
transform.localScale = Vector3.one / parentScale;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
/// <summary>True when the object's world scale is 1 on every axis, within UnitScaleTolerance.</summary>
|
|
1326
|
+
private static bool HasUnitWorldScale(Transform transform)
|
|
1327
|
+
{
|
|
1328
|
+
var scale = transform.lossyScale;
|
|
1329
|
+
return Mathf.Abs(scale.x - 1f) < UnitScaleTolerance && Mathf.Abs(scale.y - 1f) < UnitScaleTolerance && Mathf.Abs(scale.z - 1f) < UnitScaleTolerance;
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/// <summary>Folder for the VAT material copies: <scene folder>/<scene>_VatCrowd (BtCombine.PrepareCopy reset and RemoveCopy delete it).</summary>
|
|
1333
|
+
private static string VatCrowdFolder(Scene scene)
|
|
1334
|
+
{
|
|
1335
|
+
return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_VatCrowd";
|
|
1336
|
+
}
|
|
1337
|
+
|
|
934
1338
|
/// <summary>
|
|
935
1339
|
/// True when --keep-gi forbids Contribute GI on the object at this hierarchy path: it did not contribute GI in the
|
|
936
1340
|
/// source scene, and adding it would pull the object into the re-bake (darkening the source's indirect light).
|
|
@@ -1002,11 +1406,309 @@ public static class BtOptimize
|
|
|
1002
1406
|
}
|
|
1003
1407
|
}
|
|
1004
1408
|
|
|
1409
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
1410
|
+
// Shadow casters — pruned per object, from the browser's per-cascade caster dump, proven by capture
|
|
1411
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
1412
|
+
|
|
1413
|
+
/// <summary>The file PruneShadowCasters keeps in the working copy's report folder: what it pruned and each renderer's original mode.</summary>
|
|
1414
|
+
private const string PrunedCastersFileName = "pruned-casters.json";
|
|
1415
|
+
|
|
1416
|
+
/// <summary>Settings for PruneShadowCasters.</summary>
|
|
1417
|
+
[Serializable]
|
|
1418
|
+
public class CasterOptions
|
|
1419
|
+
{
|
|
1420
|
+
/// <summary>
|
|
1421
|
+
/// The complete prune list: renderers (object names or hierarchy paths) that stop casting shadows. A renderer an
|
|
1422
|
+
/// earlier run pruned that this list no longer names gets its original Cast Shadows mode back.
|
|
1423
|
+
/// </summary>
|
|
1424
|
+
public string[] paths = new string[0];
|
|
1425
|
+
/// <summary>Report what would change without changing it.</summary>
|
|
1426
|
+
public bool dryRun = false;
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/// <summary>What PruneShadowCasters last pruned: hierarchy paths and, at the same index, each one's original Cast Shadows mode.</summary>
|
|
1430
|
+
[Serializable]
|
|
1431
|
+
private class PrunedCasterRecord
|
|
1432
|
+
{
|
|
1433
|
+
public string[] paths = new string[0];
|
|
1434
|
+
public string[] modes = new string[0];
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
/// <summary>
|
|
1438
|
+
/// Sets Cast Shadows Off on every renderer in the prune list (Receive Shadows stays as it is) and gives every renderer
|
|
1439
|
+
/// an earlier run pruned that the list no longer names its original mode back, so the list can be edited and re-run
|
|
1440
|
+
/// at any time. The list comes from the browser's per-cascade caster dump (`profile-browser.mjs --casters true`) and
|
|
1441
|
+
/// survey.md's flat-surface candidates, and each entry stays only if the Unity captures at the pinned poses show no
|
|
1442
|
+
/// visible shadow change. Cast Shadows also drives the lightmapper's occlusion, so bake after pruning. Works only on a
|
|
1443
|
+
/// bt-optimize working copy; saves the scene and writes pruned-casters.json.
|
|
1444
|
+
/// </summary>
|
|
1445
|
+
/// <param name="optionsJson">A CasterOptions object as JSON, e.g. {"paths":["Level/Road","Ground*"]}.</param>
|
|
1446
|
+
/// <returns>A summary: renderers pruned, renderers restored, names that matched nothing.</returns>
|
|
1447
|
+
public static string PruneShadowCasters(string optionsJson)
|
|
1448
|
+
{
|
|
1449
|
+
var options = string.IsNullOrWhiteSpace(optionsJson) ? new CasterOptions() : JsonUtility.FromJson<CasterOptions>(optionsJson);
|
|
1450
|
+
var scene = SceneManager.GetActiveScene();
|
|
1451
|
+
string folder = ReportFolder(scene);
|
|
1452
|
+
if (!File.Exists(Path.Combine(folder, "working-copy.txt")))
|
|
1453
|
+
throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; PruneShadowCasters never edits a source scene.");
|
|
1454
|
+
var renderers = new Context(scene).Renderers;
|
|
1455
|
+
string recordPath = Path.Combine(folder, PrunedCastersFileName);
|
|
1456
|
+
var previous = ReadPrunedCasters(recordPath);
|
|
1457
|
+
var originalModes = new Dictionary<string, string>();
|
|
1458
|
+
for (int i = 0; i < previous.paths.Length && i < previous.modes.Length; i++) originalModes[previous.paths[i]] = previous.modes[i];
|
|
1459
|
+
|
|
1460
|
+
var pruned = new Dictionary<string, string>();
|
|
1461
|
+
var unmatched = new List<string>();
|
|
1462
|
+
int changed = 0;
|
|
1463
|
+
foreach (string nameOrPath in options.paths)
|
|
1464
|
+
{
|
|
1465
|
+
var matches = renderers.Where(renderer => MatchesName(renderer.name, new[] { nameOrPath }) || PathOf(renderer.transform) == nameOrPath).ToList();
|
|
1466
|
+
if (matches.Count == 0) { unmatched.Add(nameOrPath); continue; }
|
|
1467
|
+
foreach (var renderer in matches)
|
|
1468
|
+
{
|
|
1469
|
+
string path = PathOf(renderer.transform);
|
|
1470
|
+
pruned[path] = originalModes.TryGetValue(path, out var original) ? original : renderer.shadowCastingMode.ToString();
|
|
1471
|
+
if (renderer.shadowCastingMode == ShadowCastingMode.Off) continue;
|
|
1472
|
+
changed++;
|
|
1473
|
+
if (options.dryRun) continue;
|
|
1474
|
+
renderer.shadowCastingMode = ShadowCastingMode.Off;
|
|
1475
|
+
EditorUtility.SetDirty(renderer);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
int restored = 0;
|
|
1479
|
+
foreach (var entry in originalModes.Where(entry => !pruned.ContainsKey(entry.Key)))
|
|
1480
|
+
foreach (var renderer in renderers.Where(renderer => PathOf(renderer.transform) == entry.Key && renderer.shadowCastingMode == ShadowCastingMode.Off))
|
|
1481
|
+
{
|
|
1482
|
+
restored++;
|
|
1483
|
+
if (options.dryRun) continue;
|
|
1484
|
+
renderer.shadowCastingMode = (ShadowCastingMode)Enum.Parse(typeof(ShadowCastingMode), entry.Value);
|
|
1485
|
+
EditorUtility.SetDirty(renderer);
|
|
1486
|
+
}
|
|
1487
|
+
if (!options.dryRun)
|
|
1488
|
+
{
|
|
1489
|
+
File.WriteAllText(recordPath, JsonUtility.ToJson(new PrunedCasterRecord { paths = pruned.Keys.ToArray(), modes = pruned.Values.ToArray() }, true));
|
|
1490
|
+
EditorSceneManager.MarkSceneDirty(scene);
|
|
1491
|
+
EditorSceneManager.SaveScene(scene);
|
|
1492
|
+
}
|
|
1493
|
+
return (options.dryRun ? "dry run — nothing changed\n" : "") + "pruned=" + pruned.Count + " (newly off " + changed + ") restored=" + restored
|
|
1494
|
+
+ "\nunmatched=" + string.Join(", ", unmatched) + "\nneedsBake=" + (changed + restored > 0);
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/// <summary>
|
|
1498
|
+
/// Reads the prune record. A plain JSON array of paths (written by a hand-made prune step before this one existed) is
|
|
1499
|
+
/// read as renderers that cast On in the source.
|
|
1500
|
+
/// </summary>
|
|
1501
|
+
private static PrunedCasterRecord ReadPrunedCasters(string recordPath)
|
|
1502
|
+
{
|
|
1503
|
+
if (!File.Exists(recordPath)) return new PrunedCasterRecord();
|
|
1504
|
+
string text = File.ReadAllText(recordPath).Trim();
|
|
1505
|
+
if (!text.StartsWith("[", StringComparison.Ordinal)) return JsonUtility.FromJson<PrunedCasterRecord>(text);
|
|
1506
|
+
var paths = System.Text.RegularExpressions.Regex.Matches(text, "\"((?:[^\"\\\\]|\\\\.)*)\"")
|
|
1507
|
+
.Cast<System.Text.RegularExpressions.Match>().Select(match => System.Text.RegularExpressions.Regex.Unescape(match.Groups[1].Value)).ToArray();
|
|
1508
|
+
return new PrunedCasterRecord { paths = paths, modes = paths.Select(path => ShadowCastingMode.On.ToString()).ToArray() };
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1511
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
1512
|
+
// Verify — the working copy against its source and the Tune rules
|
|
1513
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
1514
|
+
|
|
1515
|
+
/// <summary>
|
|
1516
|
+
/// Checks the active working copy against its source (the scene named in working-copy.txt) and the Tune rules, and
|
|
1517
|
+
/// writes verify.md / verify.json. Problems: unsaved changes; a pose camera left in the scene; a camera whose enabled
|
|
1518
|
+
/// state differs from the source (a capture step that disabled the main camera and was saved ships a game with no
|
|
1519
|
+
/// post-processing); lighting settings that differ from the source; rigid skinned meshes Tune converts that are
|
|
1520
|
+
/// still skinned; repeated meshes (instanceRepeatsFrom copies or more) that are lightmapped or probe-lit; static
|
|
1521
|
+
/// objects that move in the browser; VAT crowd members missing their materials, unit scale or probes-off; pruned
|
|
1522
|
+
/// shadow casters casting again; with keepSourceGI, GI contributors the source does not have. Changes nothing.
|
|
1523
|
+
/// </summary>
|
|
1524
|
+
/// <param name="optionsJson">The TuneOptions the copy was tuned with (thresholds and exclusions), or empty for the defaults.</param>
|
|
1525
|
+
/// <returns>"problems=N" and one line per problem.</returns>
|
|
1526
|
+
public static string Verify(string optionsJson)
|
|
1527
|
+
{
|
|
1528
|
+
var options = string.IsNullOrWhiteSpace(optionsJson) ? new TuneOptions() : JsonUtility.FromJson<TuneOptions>(optionsJson);
|
|
1529
|
+
var scene = SceneManager.GetActiveScene();
|
|
1530
|
+
string folder = ReportFolder(scene);
|
|
1531
|
+
string recordPath = Path.Combine(folder, "working-copy.txt");
|
|
1532
|
+
if (!File.Exists(recordPath)) throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy (no " + recordPath + ").");
|
|
1533
|
+
string sourcePath = File.ReadAllText(recordPath).Trim();
|
|
1534
|
+
var context = new Context(scene);
|
|
1535
|
+
var problems = new List<string>();
|
|
1536
|
+
var checks = new Dictionary<string, object>();
|
|
1537
|
+
|
|
1538
|
+
if (scene.isDirty) problems.Add("the scene has unsaved changes — save it before exporting");
|
|
1539
|
+
if (scene.GetRootGameObjects().Any(root => root.name == PoseCameraName)) problems.Add(PoseCameraName + " is in the scene — reopen the scene before exporting (it would export as a camera)");
|
|
1540
|
+
|
|
1541
|
+
var copyCameras = CameraStates(scene);
|
|
1542
|
+
var copyLighting = ReadLighting(scene);
|
|
1543
|
+
var source = ReadFromScene(sourcePath, scene, sourceScene => new { cameras = CameraStates(sourceScene), lighting = ReadLighting(sourceScene), contributors = GIContributorPaths(sourceScene.GetRootGameObjects()) });
|
|
1544
|
+
foreach (var camera in source.cameras)
|
|
1545
|
+
{
|
|
1546
|
+
if (!copyCameras.TryGetValue(camera.Key, out bool enabled)) problems.Add("camera " + camera.Key + " is missing from the copy");
|
|
1547
|
+
else if (enabled != camera.Value) problems.Add("camera " + camera.Key + " is " + (enabled ? "enabled" : "disabled") + " in the copy but " + (camera.Value ? "enabled" : "disabled") + " in the source");
|
|
1548
|
+
}
|
|
1549
|
+
foreach (var setting in source.lighting.Where(setting => !copyLighting.TryGetValue(setting.Key, out var value) || value != setting.Value))
|
|
1550
|
+
problems.Add("lighting " + setting.Key + ": copy " + (copyLighting.TryGetValue(setting.Key, out var copyValue) ? copyValue : "missing") + ", source " + setting.Value);
|
|
1551
|
+
checks["lighting"] = copyLighting.ToDictionary(pair => pair.Key, pair => (object)pair.Value);
|
|
1552
|
+
|
|
1553
|
+
var rigidLeft = context.Renderers.OfType<SkinnedMeshRenderer>().Where(renderer => !IsExcluded(renderer.transform, options.exclude))
|
|
1554
|
+
.Where(renderer => options.unskinRigid && TuneConverts(ClassifySkinning(renderer, context).Kind)).Select(renderer => PathOf(renderer.transform)).ToList();
|
|
1555
|
+
problems.AddRange(rigidLeft.Select(path => "still skinned although it needs no skinning: " + path));
|
|
1556
|
+
checks["rigidSkinnedLeft"] = rigidLeft.Count;
|
|
1557
|
+
checks["skinnedLeft"] = context.Renderers.OfType<SkinnedMeshRenderer>().Count();
|
|
1558
|
+
|
|
1559
|
+
var repeats = options.instanceRepeatsFrom <= 0 ? new List<Renderer>() : context.Renderers.OfType<MeshRenderer>().Cast<Renderer>()
|
|
1560
|
+
.Where(renderer => !IsExcluded(renderer.transform, options.exclude) && IsRepeatedForInstancing(renderer, context, options)).ToList();
|
|
1561
|
+
var lightmappedRepeats = repeats.Where(renderer => ((MeshRenderer)renderer).receiveGI == ReceiveGI.Lightmaps
|
|
1562
|
+
&& GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI)).Select(renderer => PathOf(renderer.transform)).ToList();
|
|
1563
|
+
var probeLitRepeats = repeats.Where(renderer => renderer.lightProbeUsage != LightProbeUsage.Off).Select(renderer => PathOf(renderer.transform)).Except(lightmappedRepeats).ToList();
|
|
1564
|
+
problems.AddRange(lightmappedRepeats.Select(path => "repeated mesh is lightmapped (its copies cannot instance): " + path));
|
|
1565
|
+
problems.AddRange(probeLitRepeats.Select(path => "repeated mesh is probe-lit (the toolkit de-instances it): " + path));
|
|
1566
|
+
checks["repeatRenderers"] = repeats.Count;
|
|
1567
|
+
|
|
1568
|
+
if (options.unfreezeAnimated)
|
|
1569
|
+
{
|
|
1570
|
+
var staticMovers = context.Roots.SelectMany(root => root.GetComponentsInChildren<Transform>(true))
|
|
1571
|
+
.Where(transform => GameObjectUtility.GetStaticEditorFlags(transform.gameObject) != 0 && !IsExcluded(transform, options.exclude))
|
|
1572
|
+
.Select(transform => new { transform, mover = BrowserMoverOf(transform, context) }).Where(entry => entry.mover != null)
|
|
1573
|
+
.Select(entry => PathOf(entry.transform) + " (" + entry.mover + ")").ToList();
|
|
1574
|
+
problems.AddRange(staticMovers.Select(entry => "static but moves in the browser: " + entry));
|
|
1575
|
+
checks["staticMovers"] = staticMovers.Count;
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
var rigType = AnimatorControlRigType();
|
|
1579
|
+
var vatAnimators = rigType == null ? new List<Animator>() : context.All<Animator>().Where(animator => IsVertexAnimated(animator, rigType)).ToList();
|
|
1580
|
+
foreach (var animator in vatAnimators)
|
|
1581
|
+
foreach (var skinned in animator.GetComponentsInChildren<SkinnedMeshRenderer>(true).Where(skinned => skinned.GetComponentInParent<Animator>() == animator))
|
|
1582
|
+
{
|
|
1583
|
+
string path = PathOf(skinned.transform);
|
|
1584
|
+
if (skinned.sharedMaterials.Any(material => material == null || material.shader.name != VertexAnimationShaderName)) problems.Add("VAT crowd member has a material not on " + VertexAnimationShaderName + ": " + path);
|
|
1585
|
+
if (!HasUnitWorldScale(skinned.transform)) problems.Add("VAT crowd member's renderer is not at world scale 1 (it would draw at the wrong size): " + path);
|
|
1586
|
+
if (skinned.lightProbeUsage != LightProbeUsage.Off) problems.Add("VAT crowd member is probe-lit (its copies would not instance): " + path);
|
|
1587
|
+
}
|
|
1588
|
+
checks["vatCrowdMembers"] = vatAnimators.Count;
|
|
1589
|
+
|
|
1590
|
+
string prunedPath = Path.Combine(folder, PrunedCastersFileName);
|
|
1591
|
+
if (File.Exists(prunedPath))
|
|
1592
|
+
{
|
|
1593
|
+
var record = ReadPrunedCasters(prunedPath);
|
|
1594
|
+
foreach (string path in record.paths)
|
|
1595
|
+
{
|
|
1596
|
+
var renderer = context.Renderers.FirstOrDefault(candidate => PathOf(candidate.transform) == path);
|
|
1597
|
+
if (renderer == null) problems.Add("pruned shadow caster is missing: " + path);
|
|
1598
|
+
else if (renderer.shadowCastingMode != ShadowCastingMode.Off) problems.Add("pruned shadow caster casts again: " + path);
|
|
1599
|
+
}
|
|
1600
|
+
checks["prunedCasters"] = record.paths.Length;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
var copyContributors = GIContributorPaths(scene.GetRootGameObjects());
|
|
1604
|
+
var newContributors = copyContributors.Except(source.contributors).ToList();
|
|
1605
|
+
if (options.keepSourceGI) problems.AddRange(newContributors.Select(path => "--keep-gi: contributes GI but did not in the source: " + path));
|
|
1606
|
+
checks["giContributors"] = new Dictionary<string, object> { { "source", source.contributors.Count }, { "copy", copyContributors.Count }, { "new", newContributors.Count } };
|
|
1607
|
+
|
|
1608
|
+
var md = new StringBuilder("# bt-optimize verify — " + scene.path + "\n\nSource: `" + sourcePath + "`\n\n**Problems: " + problems.Count + "**\n\n");
|
|
1609
|
+
foreach (var problem in problems) md.AppendLine("- " + problem);
|
|
1610
|
+
md.AppendLine("\n## Checks\n");
|
|
1611
|
+
foreach (var check in checks) md.AppendLine("- " + check.Key + ": " + FormatValue(check.Value is Dictionary<string, object> dictionary ? string.Join(", ", dictionary.Select(pair => pair.Key + "=" + pair.Value)) : check.Value));
|
|
1612
|
+
File.WriteAllText(Path.Combine(folder, "verify.md"), md.ToString());
|
|
1613
|
+
File.WriteAllText(Path.Combine(folder, "verify.json"), ToJson(new Dictionary<string, object> { { "scene", scene.path }, { "source", sourcePath },
|
|
1614
|
+
{ "problems", problems.Cast<object>().ToList() }, { "checks", checks } }, 0));
|
|
1615
|
+
return "problems=" + problems.Count + "\n" + string.Join("\n", problems.Take(40)) + (problems.Count > 40 ? "\n… (all in verify.md)" : "");
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
/// <summary>
|
|
1619
|
+
/// Reads something from another scene: an open one is read as it is; otherwise it is opened additively, made the
|
|
1620
|
+
/// active scene while it is read (RenderSettings and lighting settings belong to the active scene), and closed unsaved.
|
|
1621
|
+
/// </summary>
|
|
1622
|
+
private static T ReadFromScene<T>(string scenePath, Scene returnTo, Func<Scene, T> read)
|
|
1623
|
+
{
|
|
1624
|
+
var open = SceneManager.GetSceneByPath(scenePath);
|
|
1625
|
+
bool opened = !open.isLoaded;
|
|
1626
|
+
var scene = opened ? EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive) : open;
|
|
1627
|
+
try
|
|
1628
|
+
{
|
|
1629
|
+
SceneManager.SetActiveScene(scene);
|
|
1630
|
+
return read(scene);
|
|
1631
|
+
}
|
|
1632
|
+
finally
|
|
1633
|
+
{
|
|
1634
|
+
SceneManager.SetActiveScene(returnTo);
|
|
1635
|
+
if (opened) EditorSceneManager.CloseScene(scene, true);
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
/// <summary>Every camera's hierarchy path and whether it renders (enabled on an active object).</summary>
|
|
1640
|
+
private static Dictionary<string, bool> CameraStates(Scene scene)
|
|
1641
|
+
{
|
|
1642
|
+
var states = new Dictionary<string, bool>();
|
|
1643
|
+
foreach (var camera in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(camera => camera.name != PoseCameraName))
|
|
1644
|
+
states[PathOf(camera.transform)] = camera.enabled && camera.gameObject.activeInHierarchy;
|
|
1645
|
+
return states;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
/// <summary>
|
|
1649
|
+
/// The scene's lighting setup as text, for comparing a copy with its source: the Lighting Settings (mixed mode,
|
|
1650
|
+
/// indirect intensity, albedo boost, lightmapper, resolution), ambient and reflection settings, skybox, fog, and the
|
|
1651
|
+
/// main directional light's mode and shadows. The scene must be the active scene.
|
|
1652
|
+
/// </summary>
|
|
1653
|
+
private static Dictionary<string, string> ReadLighting(Scene scene)
|
|
1654
|
+
{
|
|
1655
|
+
var culture = System.Globalization.CultureInfo.InvariantCulture;
|
|
1656
|
+
var values = new Dictionary<string, string>();
|
|
1657
|
+
LightingSettings settings = null;
|
|
1658
|
+
try { settings = Lightmapping.lightingSettings; } catch (Exception) { /* the scene has no Lighting Settings asset */ }
|
|
1659
|
+
if (settings != null)
|
|
1660
|
+
{
|
|
1661
|
+
values["mixedBakeMode"] = settings.mixedBakeMode.ToString();
|
|
1662
|
+
values["indirectScale"] = settings.indirectScale.ToString("0.###", culture);
|
|
1663
|
+
values["albedoBoost"] = settings.albedoBoost.ToString("0.###", culture);
|
|
1664
|
+
values["lightmapper"] = settings.lightmapper.ToString();
|
|
1665
|
+
values["lightmapResolution"] = settings.lightmapResolution.ToString("0.###", culture);
|
|
1666
|
+
}
|
|
1667
|
+
values["ambientMode"] = RenderSettings.ambientMode.ToString();
|
|
1668
|
+
values["ambientColor"] = RenderSettings.ambientLight.ToString("F3");
|
|
1669
|
+
values["ambientIntensity"] = RenderSettings.ambientIntensity.ToString("0.###", culture);
|
|
1670
|
+
values["reflectionIntensity"] = RenderSettings.reflectionIntensity.ToString("0.###", culture);
|
|
1671
|
+
values["skybox"] = RenderSettings.skybox != null ? RenderSettings.skybox.name : "none";
|
|
1672
|
+
values["fog"] = RenderSettings.fog + " " + RenderSettings.fogMode + " " + RenderSettings.fogColor.ToString("F3");
|
|
1673
|
+
var sun = RenderSettings.sun != null && RenderSettings.sun.gameObject.scene == scene ? RenderSettings.sun
|
|
1674
|
+
: scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Light>(true))
|
|
1675
|
+
.Where(light => light.isActiveAndEnabled && light.type == LightType.Directional).OrderByDescending(light => light.intensity).FirstOrDefault();
|
|
1676
|
+
values["sun"] = sun != null ? sun.name + " " + sun.lightmapBakeType + " shadows " + sun.shadows + " intensity " + sun.intensity.ToString("0.###", culture) : "none";
|
|
1677
|
+
return values;
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
/// <summary>A bake that has not written its LightingData this many seconds after it was started, and is not running, has stopped.</summary>
|
|
1681
|
+
private const long BakeStartGraceSeconds = 120;
|
|
1682
|
+
|
|
1683
|
+
/// <summary>
|
|
1684
|
+
/// Where a bake started at the given time stands, for `wait.mjs cmd` to poll: "baking" while the lightmapper runs,
|
|
1685
|
+
/// "done" once it has stopped and the active scene's LightingData asset was written at or after the start, "stopped"
|
|
1686
|
+
/// when it is not running and wrote nothing more than BakeStartGraceSeconds after the start, "waiting" otherwise.
|
|
1687
|
+
/// `lighting_bake_status` alone can report "completed" before the bake has started.
|
|
1688
|
+
/// </summary>
|
|
1689
|
+
/// <param name="startedUnixSeconds">When bake_lighting was called, in Unix seconds (`date +%s`).</param>
|
|
1690
|
+
public static string BakeState(string startedUnixSeconds)
|
|
1691
|
+
{
|
|
1692
|
+
long started = long.Parse(startedUnixSeconds, System.Globalization.CultureInfo.InvariantCulture);
|
|
1693
|
+
if (Lightmapping.isRunning) return "baking";
|
|
1694
|
+
var data = Lightmapping.lightingDataAsset;
|
|
1695
|
+
string path = data != null ? AssetDatabase.GetAssetPath(data) : "";
|
|
1696
|
+
long written = path.Length > 0 && File.Exists(path) ? new DateTimeOffset(File.GetLastWriteTimeUtc(path)).ToUnixTimeSeconds() : 0;
|
|
1697
|
+
if (written >= started) return "done";
|
|
1698
|
+
return DateTimeOffset.UtcNow.ToUnixTimeSeconds() - started > BakeStartGraceSeconds ? "stopped" : "waiting";
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
/// <summary>The name of the capture camera PoseView places.</summary>
|
|
1702
|
+
private const string PoseCameraName = "BtOptimizePoseCamera";
|
|
1703
|
+
|
|
1005
1704
|
/// <summary>
|
|
1006
1705
|
/// Opens the scene (discarding nothing: refuses when the open scene has unsaved changes) and places a capture camera
|
|
1007
1706
|
/// named "BtOptimizePoseCamera" at a pose recorded by the browser profiler (toolkit scenes keep Unity's coordinates),
|
|
1008
1707
|
/// copying the main camera's settings and URP data so post-processing matches. Capture it with
|
|
1009
|
-
/// `capture_game_view --camera BtOptimizePoseCamera`.
|
|
1708
|
+
/// `capture_game_view --camera BtOptimizePoseCamera`. It never touches the scene's own cameras (a disabled main camera
|
|
1709
|
+
/// that got saved once shipped a game with no post-processing): the pose camera renders above them by depth and is
|
|
1710
|
+
/// flagged DontSaveInEditor, so it is never written to the scene. Reopen the scene before exporting — the exporter
|
|
1711
|
+
/// would otherwise see it as one more camera.
|
|
1010
1712
|
/// </summary>
|
|
1011
1713
|
public static string PoseView(string scenePath, float px, float py, float pz, float qx, float qy, float qz, float qw, float verticalFovRadians)
|
|
1012
1714
|
{
|
|
@@ -1014,15 +1716,15 @@ public static class BtOptimize
|
|
|
1014
1716
|
if (active.path != scenePath)
|
|
1015
1717
|
{
|
|
1016
1718
|
// The only unsaved change PoseView allows itself to discard is its own pose camera.
|
|
1017
|
-
bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name ==
|
|
1719
|
+
bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == PoseCameraName);
|
|
1018
1720
|
if (active.isDirty && !onlyPoseCamera) throw new InvalidOperationException("'" + active.path + "' has unsaved changes; save or discard them first.");
|
|
1019
1721
|
EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
|
|
1020
1722
|
}
|
|
1021
1723
|
var scene = SceneManager.GetActiveScene();
|
|
1022
|
-
var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name ==
|
|
1724
|
+
var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == PoseCameraName);
|
|
1023
1725
|
if (existing != null) UnityEngine.Object.DestroyImmediate(existing);
|
|
1024
1726
|
var main = Camera.main;
|
|
1025
|
-
var go = new GameObject(
|
|
1727
|
+
var go = new GameObject(PoseCameraName) { hideFlags = HideFlags.DontSaveInEditor };
|
|
1026
1728
|
var camera = go.AddComponent<Camera>();
|
|
1027
1729
|
if (main != null)
|
|
1028
1730
|
{
|
|
@@ -1033,8 +1735,11 @@ public static class BtOptimize
|
|
|
1033
1735
|
var data = go.GetComponent(mainData.GetType()) ?? go.AddComponent(mainData.GetType());
|
|
1034
1736
|
EditorUtility.CopySerialized(mainData, data);
|
|
1035
1737
|
}
|
|
1036
|
-
main.enabled = false;
|
|
1037
1738
|
}
|
|
1739
|
+
// Render above every scene camera instead of disabling any of them: the scene's cameras are never changed.
|
|
1740
|
+
var sceneCameras = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Camera>(true)).Where(other => other != camera).ToList();
|
|
1741
|
+
camera.depth = sceneCameras.Count > 0 ? sceneCameras.Max(other => other.depth) + 1f : camera.depth;
|
|
1742
|
+
foreach (var component in go.GetComponents<Component>()) component.hideFlags = HideFlags.DontSaveInEditor;
|
|
1038
1743
|
go.transform.SetPositionAndRotation(new Vector3(px, py, pz), new Quaternion(qx, qy, qz, qw));
|
|
1039
1744
|
camera.fieldOfView = verticalFovRadians * Mathf.Rad2Deg;
|
|
1040
1745
|
camera.enabled = true;
|
|
@@ -1126,8 +1831,8 @@ public static class BtOptimize
|
|
|
1126
1831
|
/// <summary>
|
|
1127
1832
|
/// Why the renderer is not a visible, lightmappable surface, or null. Only shaders with a lightmapper Meta pass
|
|
1128
1833
|
/// (URP Lit / Simple Lit / Unlit, Built-in Standard, Shader Graph Lit / Unlit…) describe a surface to the bake.
|
|
1129
|
-
/// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI,
|
|
1130
|
-
///
|
|
1834
|
+
/// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, an invisible stencil mesh
|
|
1835
|
+
/// (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
|
|
1131
1836
|
/// room went dark.
|
|
1132
1837
|
/// </summary>
|
|
1133
1838
|
private static string NotAVisibleSurface(Renderer renderer)
|
|
@@ -1355,8 +2060,7 @@ public static class BtOptimize
|
|
|
1355
2060
|
/// </summary>
|
|
1356
2061
|
private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
|
|
1357
2062
|
{
|
|
1358
|
-
string
|
|
1359
|
-
string cacheKey = source.GetHashCode() + "|" + offsetKey;
|
|
2063
|
+
string cacheKey = source.GetHashCode() + "|" + OffsetKey(meshToObject);
|
|
1360
2064
|
if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
|
|
1361
2065
|
var baked = UnityEngine.Object.Instantiate(source);
|
|
1362
2066
|
baked.name = source.name + "_Unskinned_" + bakedMeshes.Count;
|
|
@@ -1381,6 +2085,12 @@ public static class BtOptimize
|
|
|
1381
2085
|
return baked;
|
|
1382
2086
|
}
|
|
1383
2087
|
|
|
2088
|
+
/// <summary>A bind-pose offset matrix as text, rounded to SharedMeshKeyDecimals: copies with equal keys share one baked mesh.</summary>
|
|
2089
|
+
private static string OffsetKey(Matrix4x4 meshToObject)
|
|
2090
|
+
{
|
|
2091
|
+
return string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
|
|
2092
|
+
}
|
|
2093
|
+
|
|
1384
2094
|
/// <summary>
|
|
1385
2095
|
/// Folder for meshes baked from skinned meshes (offset rigid meshes and baked poses): <scene folder>/<scene>_UnskinnedMeshes.
|
|
1386
2096
|
/// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
|
|
@@ -1704,7 +2414,17 @@ public static class BtOptimize
|
|
|
1704
2414
|
/// <summary>True when the renderer's mesh and materials repeat often enough that its copies should share an instanced draw.</summary>
|
|
1705
2415
|
private static bool IsRepeatedForInstancing(Renderer renderer, Context context, TuneOptions options)
|
|
1706
2416
|
{
|
|
1707
|
-
return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(
|
|
2417
|
+
return options.instanceRepeatsFrom > 0 && context.RepeatCounts.TryGetValue(RepeatKeyOf(renderer, context), out var copies) && copies >= options.instanceRepeatsFrom;
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
/// <summary>
|
|
2421
|
+
/// RepeatKey, except that a skinned renderer a dry run plans to convert is keyed by the mesh it will draw
|
|
2422
|
+
/// (see PlannedMeshKey) rather than the skinned mesh it draws now.
|
|
2423
|
+
/// </summary>
|
|
2424
|
+
private static string RepeatKeyOf(Renderer renderer, Context context)
|
|
2425
|
+
{
|
|
2426
|
+
if (!(renderer is SkinnedMeshRenderer skinned) || !context.PlannedMeshKeys.TryGetValue(skinned, out var plannedMesh)) return RepeatKey(renderer);
|
|
2427
|
+
return "planned " + plannedMesh + "|" + string.Join(",", renderer.sharedMaterials.Select(material => material != null ? material.GetHashCode() : 0));
|
|
1708
2428
|
}
|
|
1709
2429
|
|
|
1710
2430
|
/// <summary>
|
|
@@ -1774,6 +2494,10 @@ public static class BtOptimize
|
|
|
1774
2494
|
public readonly HashSet<string> PlannedGIContributors;
|
|
1775
2495
|
/// <summary>Skinned renderers a dry run plans to convert: later steps treat them as the MeshRenderers they become.</summary>
|
|
1776
2496
|
public readonly List<SkinnedMeshRenderer> PlannedUnskinned = new List<SkinnedMeshRenderer>();
|
|
2497
|
+
/// <summary>For each renderer a dry run plans to convert, the identity of the mesh it will draw (see PlannedMeshKey).</summary>
|
|
2498
|
+
public readonly Dictionary<SkinnedMeshRenderer, string> PlannedMeshKeys = new Dictionary<SkinnedMeshRenderer, string>();
|
|
2499
|
+
/// <summary>Objects whose static flags Tune clears (UnfreezeAnimated); a dry run's later steps treat them as non-static.</summary>
|
|
2500
|
+
public readonly HashSet<GameObject> PlannedNonStatic = new HashSet<GameObject>();
|
|
1777
2501
|
public readonly StringBuilder Summary = new StringBuilder();
|
|
1778
2502
|
|
|
1779
2503
|
/// <param name="scene">The scene to gather.</param>
|