@babylonjs-toolkit/agent 1.2.10 → 1.2.11

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.
@@ -36,18 +36,40 @@ public static class BtOptimize
36
36
  /// </summary>
37
37
  private const string SkinRigidOffset = "rigid — needs no skinning (offset baked)";
38
38
 
39
- /// <summary>Offset matrices are compared at this precision when copies share one baked mesh.</summary>
40
- private const int OffsetKeyDecimals = 4;
39
+ /// <summary>Offset matrices and baked pose vertices are compared at this precision when copies share one baked mesh.</summary>
40
+ private const int SharedMeshKeyDecimals = 4;
41
41
 
42
- /// <summary>Skinning verdict: rigid, but converting would change it (its bone moves on its own, or the bind pose differs).</summary>
42
+ /// <summary>
43
+ /// Skinning verdict: one bone, and the only thing that seemed to move it apart from the object is a toolkit script
44
+ /// on the renderer's own object — converts to a plain mesh baked as it is drawn now (the script stays).
45
+ /// </summary>
46
+ private const string SkinRigidScriptHost = "rigid — a script sits on the object; Tune bakes it in place";
47
+
48
+ /// <summary>
49
+ /// Skinning verdict: rigid, but a clip animates the SkinnedMeshRenderer itself — converts like a rigid mesh, and the
50
+ /// clip is copied with those curves aimed at MeshRenderer, on a copy of the Animator's controller.
51
+ /// </summary>
52
+ private const string SkinRigidRendererCurves = "rigid — Tune retargets its renderer curves";
53
+
54
+ /// <summary>
55
+ /// Skinning verdict: rigid, but converting would change it — its bone moves apart from the object (a clip, Timeline,
56
+ /// constraint or physics body), a component references the SkinnedMeshRenderer, or a clip Tune cannot retarget (a
57
+ /// legacy Animation, an override controller) animates it.
58
+ /// </summary>
43
59
  private const string SkinRigidByHand = "rigid — convert by hand";
44
60
 
45
- /// <summary>Skinning verdict: several weighted bones that nothing animates — the pose never changes.</summary>
61
+ /// <summary>
62
+ /// Skinning verdict: several weighted bones that nothing moves apart from the object — the pose never changes. Tune
63
+ /// bakes the pose to a static mesh, copies with the same pose sharing one mesh asset.
64
+ /// </summary>
46
65
  private const string SkinFrozenPose = "frozen pose — bake to a static mesh";
47
66
 
48
67
  /// <summary>Skinning verdict: really deforms (animated bones, blend shapes or cloth).</summary>
49
68
  private const string SkinDeforms = "deforms — really skinned";
50
69
 
70
+ /// <summary>Why --keep-gi leaves an object out of the bake (see TuneOptions.keepSourceGI).</summary>
71
+ private const string KeepGIReason = "keep-gi: not a GI contributor in the source";
72
+
51
73
  // ------------------------------------------------------------------------------------------------------------
52
74
  // Survey
53
75
  // ------------------------------------------------------------------------------------------------------------
@@ -218,8 +240,10 @@ public static class BtOptimize
218
240
  {
219
241
  if (verdictKind == SkinRigid) return "Tune converts it (unskinRigid)";
220
242
  if (verdictKind == SkinRigidOffset) return "Tune converts it to a shared baked mesh (unskinRigid)";
243
+ if (verdictKind == SkinRigidScriptHost) return "Tune bakes it to a plain mesh in place (unskinRigid)";
244
+ if (verdictKind == SkinRigidRendererCurves) return "Tune converts it and retargets the clip to MeshRenderer (unskinRigid)";
221
245
  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";
246
+ if (verdictKind == SkinFrozenPose) return "Tune bakes it to a static mesh";
223
247
  return copies > 1 ? "repeated deforming mesh: candidate for the toolkit AnimatorControlRig VAT (crowd) mode — instanced, one draw" : "keep";
224
248
  }
225
249
 
@@ -435,11 +459,17 @@ public static class BtOptimize
435
459
  /// </summary>
436
460
  public bool unskinRigid = true;
437
461
  /// <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.
462
+ /// A mesh drawn this many times or more (same mesh and materials) is not lightmapped (lightmapped copies never
463
+ /// share), and its copies get Light Probe Usage Off so they share one instanced draw: the toolkit loads every
464
+ /// probe-lit node as its own mesh (SceneManager.DeinstanceProbeLitNodes). 0 turns the rule off.
441
465
  /// </summary>
442
466
  public int instanceRepeatsFrom = 4;
467
+ /// <summary>
468
+ /// Keep Contribute GI exactly as the source scene has it (the source named in working-copy.txt): no step adds
469
+ /// Contribute GI to an object that did not contribute in the source, so the re-bake keeps the source's indirect
470
+ /// light. Off by default, because merging needs the newly lightmapped props.
471
+ /// </summary>
472
+ public bool keepSourceGI = false;
443
473
  /// <summary>Mark renderers static when nothing in the browser can move them.</summary>
444
474
  public bool markStatic = true;
445
475
  /// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
@@ -469,7 +499,8 @@ public static class BtOptimize
469
499
  string folder = ReportFolder(scene);
470
500
  if (!options.dryRun && !File.Exists(Path.Combine(folder, "working-copy.txt")))
471
501
  throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; Tune never edits a source scene.");
472
- var context = new Context(scene);
502
+ var sourceGIContributors = SourceGIContributorsOf(scene, folder);
503
+ var context = new Context(scene, sourceGIContributors);
473
504
  var changes = new List<Change>();
474
505
  var kept = new List<Change>();
475
506
 
@@ -477,12 +508,17 @@ public static class BtOptimize
477
508
  {
478
509
  int converted = UnskinRigid(context, options, changes, kept);
479
510
  // 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);
511
+ if (converted > 0 && !options.dryRun) context = new Context(scene, sourceGIContributors);
481
512
  }
482
513
  if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
483
514
  if (options.markStatic) MarkStatic(context, options, changes, kept);
484
515
  if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
516
+ if (options.instanceRepeatsFrom > 0) InstanceRepeats(context, options, changes, kept);
485
517
  if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
518
+ // A dry run changed no flags, so its copy count is the one the planned changes would leave.
519
+ int copyGIContributors = options.dryRun ? context.PlannedGIContributors.Count : GIContributorPaths(scene.GetRootGameObjects()).Count;
520
+ string giContributorsLine = "GI contributors: source " + sourceGIContributors.Count + " → copy " + copyGIContributors
521
+ + (options.keepSourceGI ? " (--keep-gi)" : "");
486
522
 
487
523
  if (!options.dryRun)
488
524
  {
@@ -492,6 +528,7 @@ public static class BtOptimize
492
528
  }
493
529
 
494
530
  var md = new StringBuilder("# bt-optimize tune" + (options.dryRun ? " plan (dry run — nothing changed)" : "") + " — " + scene.path + "\n\n");
531
+ md.AppendLine(giContributorsLine + "\n");
495
532
  foreach (var kind in changes.Select(change => change.Kind).Distinct())
496
533
  {
497
534
  var list = changes.Where(change => change.Kind == kind).ToList();
@@ -507,21 +544,25 @@ public static class BtOptimize
507
544
  File.WriteAllText(Path.Combine(folder, stem + ".md"), md.ToString());
508
545
  File.WriteAllText(Path.Combine(folder, stem + ".json"), ToJson(new Dictionary<string, object> {
509
546
  { "scene", scene.path },
547
+ { "giContributors", new Dictionary<string, object> { { "source", sourceGIContributors.Count }, { "copy", copyGIContributors }, { "keepSourceGI", options.keepSourceGI } } },
510
548
  { "changes", changes.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "before", change.Before }, { "after", change.After }, { "why", change.Why } }).ToList() },
511
549
  { "kept", kept.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "why", change.Why } }).ToList() } }, 0));
512
550
 
513
551
  var summary = new StringBuilder("tuned=" + scene.path + "\n");
514
552
  foreach (var group in changes.GroupBy(change => change.Kind)) summary.AppendLine(" " + group.Key + ": " + group.Count());
515
553
  foreach (var group in kept.GroupBy(change => change.Kind)) summary.AppendLine(" kept " + group.Key + ": " + group.Count());
554
+ summary.AppendLine(giContributorsLine);
516
555
  summary.AppendLine("needsBake=" + changes.Any(change => change.Kind != "Volume profile"));
517
556
  return summary.ToString();
518
557
  }
519
558
 
520
559
  /// <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.
560
+ /// Replaces every skinned renderer that needs no skinning with a MeshFilter + MeshRenderer. An Animator on the object
561
+ /// is not a reason to skip it: Animators that move, scale or toggle the object (spawn pops, spins, bobs) keep working
562
+ /// on a plain mesh. One-bone props keep their mesh (or a shared offset-baked copy); a script host and a frozen pose
563
+ /// are baked as they are drawn now, copies with the same shape sharing one mesh asset; a clip that animates the
564
+ /// SkinnedMeshRenderer itself is copied with its curves aimed at MeshRenderer, on a copy of its controller. Only real
565
+ /// deformation and the still-manual cases (see SkinRigidByHand) keep a renderer skinned.
525
566
  /// </summary>
526
567
  /// <returns>How many renderers were converted (or would be, in a dry run).</returns>
527
568
  private static int UnskinRigid(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
@@ -529,6 +570,8 @@ public static class BtOptimize
529
570
  int converted = 0;
530
571
  var bakedMeshes = new Dictionary<string, Mesh>();
531
572
  string bakedFolder = UnskinnedMeshFolder(context.Scene);
573
+ string clipFolder = RetargetedClipFolder(context.Scene);
574
+ var curveAnimators = new List<Animator>();
532
575
  foreach (var renderer in context.Renderers.OfType<SkinnedMeshRenderer>().ToList())
533
576
  {
534
577
  string path = PathOf(renderer.transform);
@@ -536,37 +579,113 @@ public static class BtOptimize
536
579
  var verdict = ClassifySkinning(renderer, context);
537
580
  int copies = context.RepeatCounts.TryGetValue(RepeatKey(renderer), out var count) ? count : 1;
538
581
  string copiesNote = copies > 1 ? " — " + copies + " copies" : "";
539
- bool offsetBaked = verdict.Kind == SkinRigidOffset;
540
- if (verdict.Kind != SkinRigid && !offsetBaked)
582
+ if (!TuneConverts(verdict.Kind))
541
583
  {
542
584
  kept.Add(new Change { Kind = "skinned", Path = path, Why = verdict.Kind + ": " + verdict.Why + copiesNote + "; next: " + NextStepForSkinning(verdict.Kind, copies) });
543
585
  continue;
544
586
  }
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,
587
+ bool bakesPose = verdict.Kind == SkinRigidScriptHost || verdict.Kind == SkinFrozenPose;
588
+ string howPlaced;
589
+ var mesh = bakesPose
590
+ ? BakedPoseMesh(renderer, bakedFolder, bakedMeshes, !options.dryRun, out howPlaced)
591
+ : PlacedRigidMesh(renderer, verdict, context, options.dryRun, bakedFolder, bakedMeshes, out howPlaced);
592
+ var animators = AnimatorsWithRendererCurves(renderer);
593
+ curveAnimators.AddRange(animators);
594
+ string retargetNote = animators.Count > 0 ? "; " + RetargetPlan(animators, renderer.transform, clipFolder) : "";
595
+ bool clearsContributeGI = WithheldContributeGI(renderer.gameObject, path, context, options);
596
+ changes.Add(new Change { Kind = UnskinnedChangeKind(verdict.Kind), Path = path, Before = "SkinnedMeshRenderer, " + verdict.Why,
557
597
  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 });
598
+ Why = UnskinnedReason(verdict.Kind) + copiesNote + retargetNote + (clearsContributeGI ? "; Contribute GI cleared — " + KeepGIReason : "") });
559
599
  converted++;
560
- if (!options.dryRun) ReplaceWithMeshRenderer(renderer, mesh);
600
+ if (options.dryRun)
601
+ {
602
+ context.PlannedUnskinned.Add(renderer);
603
+ continue;
604
+ }
605
+ var gameObject = renderer.gameObject;
606
+ ReplaceWithMeshRenderer(renderer, mesh);
607
+ if (clearsContributeGI) GameObjectUtility.SetStaticEditorFlags(gameObject, GameObjectUtility.GetStaticEditorFlags(gameObject) & ~StaticEditorFlags.ContributeGI);
561
608
  }
562
- if (bakedMeshes.Count > 0) AssetDatabase.SaveAssets();
609
+ if (options.dryRun)
610
+ {
611
+ DiscardUnsavedMeshes(bakedMeshes.Values);
612
+ return converted;
613
+ }
614
+ RetargetAnimators(curveAnimators.Distinct().ToList(), clipFolder);
615
+ if (bakedMeshes.Count > 0 || curveAnimators.Count > 0) AssetDatabase.SaveAssets();
563
616
  return converted;
564
617
  }
565
618
 
619
+ /// <summary>True for the skinning verdicts UnskinRigid converts to a plain mesh.</summary>
620
+ private static bool TuneConverts(string verdictKind)
621
+ {
622
+ return verdictKind == SkinRigid || verdictKind == SkinRigidOffset || verdictKind == SkinRigidScriptHost
623
+ || verdictKind == SkinRigidRendererCurves || verdictKind == SkinFrozenPose;
624
+ }
625
+
626
+ /// <summary>The tune.md change kind for a converted verdict.</summary>
627
+ private static string UnskinnedChangeKind(string verdictKind)
628
+ {
629
+ if (verdictKind == SkinRigidScriptHost) return "Unskinned (script host)";
630
+ if (verdictKind == SkinRigidRendererCurves) return "Unskinned (renderer curves)";
631
+ if (verdictKind == SkinFrozenPose) return "Unskinned (frozen pose)";
632
+ return "Unskinned (rigid)";
633
+ }
634
+
635
+ /// <summary>Why converting a renderer with this verdict is safe and what it buys.</summary>
636
+ private static string UnskinnedReason(string verdictKind)
637
+ {
638
+ const string buys = "BabylonJS skins it every frame, and skinned copies can never share an instanced draw";
639
+ if (verdictKind == SkinRigidScriptHost) return "the script on its own object stays and moves nothing apart from the mesh; baked as it is drawn now — " + buys;
640
+ if (verdictKind == SkinFrozenPose) return "its pose never changes; baked once, and copies with the same pose share the mesh asset — " + buys;
641
+ return "skinning bought nothing: " + buys;
642
+ }
643
+
644
+ /// <summary>
645
+ /// The mesh a one-bone renderer draws once converted. Its own mesh when the bind pose matches; otherwise the leaf
646
+ /// object is moved onto the bind pose (the mesh stays shared by every copy), and only when that is impossible is
647
+ /// the offset baked into a mesh asset. A dry run changes nothing and returns the skinned mesh.
648
+ /// </summary>
649
+ private static Mesh PlacedRigidMesh(SkinnedMeshRenderer renderer, SkinningVerdict verdict, Context context, bool dryRun, string bakedFolder,
650
+ Dictionary<string, Mesh> bakedMeshes, out string howPlaced)
651
+ {
652
+ var mesh = renderer.sharedMesh;
653
+ howPlaced = "same mesh";
654
+ if (!verdict.OffsetBaked) return mesh;
655
+ bool reseat = CanReseatObject(renderer, context);
656
+ if (!dryRun)
657
+ {
658
+ if (reseat) reseat = TryReseatObject(renderer.transform, mesh, verdict.MeshToWorld, RestPoseTolerance(renderer));
659
+ if (!reseat) mesh = BakeOffsetMesh(mesh, verdict.MeshToObject, bakedFolder, bakedMeshes);
660
+ }
661
+ howPlaced = reseat ? "same mesh, object moved onto the bind pose" : "baked mesh in " + bakedFolder;
662
+ return mesh;
663
+ }
664
+
665
+ /// <summary>
666
+ /// True when --keep-gi must clear Contribute GI on a converted object: it carries the flag (a SkinnedMeshRenderer
667
+ /// never takes part in the bake, the MeshRenderer that replaces it would) and did not contribute in the source.
668
+ /// Keeps the context's planned contributor set in step.
669
+ /// </summary>
670
+ private static bool WithheldContributeGI(GameObject gameObject, string path, Context context, TuneOptions options)
671
+ {
672
+ if (!GameObjectUtility.GetStaticEditorFlags(gameObject).HasFlag(StaticEditorFlags.ContributeGI)) return false;
673
+ if (WithheldFromBake(path, context, options)) return true;
674
+ context.PlannedGIContributors.Add(path);
675
+ return false;
676
+ }
677
+
678
+ /// <summary>Destroys the in-memory meshes a dry run baked to compare shapes (none of them was saved).</summary>
679
+ private static void DiscardUnsavedMeshes(IEnumerable<Mesh> meshes)
680
+ {
681
+ foreach (var mesh in meshes.Where(mesh => !EditorUtility.IsPersistent(mesh)).ToList()) UnityEngine.Object.DestroyImmediate(mesh);
682
+ }
683
+
566
684
  /// <summary>
567
685
  /// 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.
686
+ /// mesh itself, its offset-baked copy or its baked pose), with the same materials and renderer settings: shadow
687
+ /// casting and receiving, occlusion, both probe usages, the probe anchor, motion vectors, rendering layers and
688
+ /// sorting. Bones, colliders, Animators and static flags stay as they are.
570
689
  /// </summary>
571
690
  private static void ReplaceWithMeshRenderer(SkinnedMeshRenderer skinned, Mesh mesh)
572
691
  {
@@ -694,12 +813,18 @@ public static class BtOptimize
694
813
  var lod = renderer.GetComponentInParent<LODGroup>();
695
814
  int level = lod != null ? LodLevelOf(lod, renderer) : -1;
696
815
  bool lightmappable = level <= 0 && HasUV2(renderer) && VertexAnimationOf(renderer) == null && !IsTransparent(renderer);
816
+ bool keptOutOfBake = lightmappable && WithheldFromBake(path, context, options);
817
+ bool contributesGI = lightmappable && !keptOutOfBake;
697
818
  bool keepInstanceable = IsRepeatedForInstancing(renderer, context, options);
698
819
  var newFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.ReflectionProbeStatic;
699
- if (lightmappable) newFlags |= StaticEditorFlags.ContributeGI;
820
+ if (contributesGI)
821
+ {
822
+ newFlags |= StaticEditorFlags.ContributeGI;
823
+ context.PlannedGIContributors.Add(path);
824
+ }
700
825
  var receive = renderer.receiveGI;
701
826
  // 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)));
827
+ bool receivesLightmaps = !keepInstanceable && (contributesGI || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)));
703
828
  var newReceive = receivesLightmaps ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
704
829
  if (!options.dryRun)
705
830
  {
@@ -707,9 +832,10 @@ public static class BtOptimize
707
832
  renderer.receiveGI = newReceive;
708
833
  EditorUtility.SetDirty(renderer);
709
834
  }
710
- changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (lightmappable ? "static + ContributeGI, " : "static, ") + newReceive,
835
+ changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (contributesGI ? "static + ContributeGI, " : "static, ") + newReceive,
711
836
  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" : "") });
837
+ + (keepInstanceable ? "; stays probe-lit — " + context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw" : "")
838
+ + (keptOutOfBake ? "; " + KeepGIReason : "") });
713
839
  }
714
840
  }
715
841
 
@@ -734,8 +860,11 @@ public static class BtOptimize
734
860
  string reason = NotAVisibleSurface(renderer) ?? (!HasUV2(renderer) ? "no lightmap UVs (UV2)" : VertexAnimationOf(renderer) ?? (IsTransparent(renderer) ? "transparent" : null));
735
861
  if (reason == null && IsRepeatedForInstancing(renderer, context, options))
736
862
  reason = context.RepeatCounts[RepeatKey(renderer)] + " copies: stays probe-lit so they share one instanced draw (lightmapped copies are exported as separate meshes)";
863
+ bool addsContributeGI = !flags.HasFlag(StaticEditorFlags.ContributeGI);
864
+ if (reason == null && addsContributeGI && WithheldFromBake(path, context, options)) reason = KeepGIReason;
737
865
  if (reason != null) { kept.Add(new Change { Kind = "probe-lit", Path = path, Why = reason }); continue; }
738
- string before = (flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI, " : "no ContributeGI, ") + renderer.receiveGI;
866
+ string before = (addsContributeGI ? "no ContributeGI, " : "ContributeGI, ") + renderer.receiveGI;
867
+ context.PlannedGIContributors.Add(path);
739
868
  if (!options.dryRun)
740
869
  {
741
870
  GameObjectUtility.SetStaticEditorFlags(renderer.gameObject, flags | StaticEditorFlags.ContributeGI);
@@ -751,8 +880,15 @@ public static class BtOptimize
751
880
  {
752
881
  if (!HasUV2(lower)) continue;
753
882
  lowerLevels++;
883
+ // --keep-gi keeps a lower level's own Contribute GI too: the copy's contributor set stays the source's.
884
+ var lowerFlags = GameObjectUtility.GetStaticEditorFlags(lower.gameObject) | StaticEditorFlags.BatchingStatic;
885
+ if (!options.keepSourceGI)
886
+ {
887
+ lowerFlags &= ~StaticEditorFlags.ContributeGI;
888
+ context.PlannedGIContributors.Remove(PathOf(lower.transform));
889
+ }
754
890
  if (options.dryRun) continue;
755
- GameObjectUtility.SetStaticEditorFlags(lower.gameObject, GameObjectUtility.GetStaticEditorFlags(lower.gameObject) & ~StaticEditorFlags.ContributeGI | StaticEditorFlags.BatchingStatic);
891
+ GameObjectUtility.SetStaticEditorFlags(lower.gameObject, lowerFlags);
756
892
  lower.receiveGI = ReceiveGI.Lightmaps;
757
893
  EditorUtility.SetDirty(lower);
758
894
  }
@@ -762,6 +898,80 @@ public static class BtOptimize
762
898
  }
763
899
  }
764
900
 
901
+ /// <summary>
902
+ /// Every unlightmapped copy in a repeat group (instanceRepeatsFrom copies or more of one mesh + materials) gets
903
+ /// Light Probe Usage Off and Receive GI Light Probes, so its copies share one instanced draw: the toolkit loads every
904
+ /// node that carries light probe data as its own mesh (SceneManager.DeinstanceProbeLitNodes). Reflection Probe Usage
905
+ /// and Contribute GI stay as they are. Runs last of the renderer steps, so it sees what Lightmap probe-lit left
906
+ /// unlightmapped; in a dry run it also covers the skinned copies UnskinRigid plans to convert.
907
+ /// </summary>
908
+ private static void InstanceRepeats(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
909
+ {
910
+ var candidates = context.Renderers.OfType<MeshRenderer>().Cast<Renderer>().Concat(context.PlannedUnskinned);
911
+ foreach (var renderer in candidates)
912
+ {
913
+ if (!IsRepeatedForInstancing(renderer, context, options)) continue;
914
+ string path = PathOf(renderer.transform);
915
+ if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "probe-lit repeat", Path = path, Why = "--exclude" }); continue; }
916
+ var meshRenderer = renderer as MeshRenderer;
917
+ // A converted skinned renderer comes out Receive GI Light Probes (see ReplaceWithMeshRenderer).
918
+ var receive = meshRenderer != null ? meshRenderer.receiveGI : ReceiveGI.LightProbes;
919
+ bool lightmapped = receive == ReceiveGI.Lightmaps && GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI);
920
+ if (lightmapped) continue;
921
+ if (renderer.lightProbeUsage == LightProbeUsage.Off && receive == ReceiveGI.LightProbes) continue;
922
+ changes.Add(new Change { Kind = "Light probes off (instancing)", Path = path,
923
+ Before = "Light Probes " + renderer.lightProbeUsage + ", Receive GI " + receive + (meshRenderer == null ? " (once unskinned)" : ""),
924
+ After = "Light Probes Off, Receive GI LightProbes, Reflection Probes " + renderer.reflectionProbeUsage,
925
+ Why = context.RepeatCounts[RepeatKey(renderer)] + " copies share one instanced draw only with light probes off: the toolkit de-instances probe-lit nodes"
926
+ + " (SceneManager.DeinstanceProbeLitNodes); the copies light from the scene's ambient instead of the nearest probe" });
927
+ if (options.dryRun || meshRenderer == null) continue;
928
+ meshRenderer.lightProbeUsage = LightProbeUsage.Off;
929
+ meshRenderer.receiveGI = ReceiveGI.LightProbes;
930
+ EditorUtility.SetDirty(meshRenderer);
931
+ }
932
+ }
933
+
934
+ /// <summary>
935
+ /// True when --keep-gi forbids Contribute GI on the object at this hierarchy path: it did not contribute GI in the
936
+ /// source scene, and adding it would pull the object into the re-bake (darkening the source's indirect light).
937
+ /// </summary>
938
+ private static bool WithheldFromBake(string path, Context context, TuneOptions options)
939
+ {
940
+ return options.keepSourceGI && !context.SourceGIContributors.Contains(path);
941
+ }
942
+
943
+ /// <summary>
944
+ /// The hierarchy paths of the renderers that contribute GI in this scene's source: the scene named in the report
945
+ /// folder's working-copy.txt, opened additively and closed again unsaved (an already open source is only read). A
946
+ /// scene without that record (a dry run on the source itself) is its own source.
947
+ /// </summary>
948
+ private static HashSet<string> SourceGIContributorsOf(Scene scene, string reportFolder)
949
+ {
950
+ string recordPath = Path.Combine(reportFolder, "working-copy.txt");
951
+ string sourcePath = File.Exists(recordPath) ? File.ReadAllText(recordPath).Trim() : scene.path;
952
+ if (sourcePath == scene.path) return GIContributorPaths(scene.GetRootGameObjects());
953
+ var openSource = SceneManager.GetSceneByPath(sourcePath);
954
+ if (openSource.isLoaded) return GIContributorPaths(openSource.GetRootGameObjects());
955
+ var source = EditorSceneManager.OpenScene(sourcePath, OpenSceneMode.Additive);
956
+ try
957
+ {
958
+ return GIContributorPaths(source.GetRootGameObjects());
959
+ }
960
+ finally
961
+ {
962
+ EditorSceneManager.CloseScene(source, true);
963
+ }
964
+ }
965
+
966
+ /// <summary>The hierarchy paths of the active, enabled MeshRenderers under the roots whose objects have Contribute GI.</summary>
967
+ private static HashSet<string> GIContributorPaths(IEnumerable<GameObject> roots)
968
+ {
969
+ return new HashSet<string>(roots.SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(true))
970
+ .Where(renderer => renderer.enabled && renderer.gameObject.activeInHierarchy)
971
+ .Where(renderer => GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI))
972
+ .Select(renderer => PathOf(renderer.transform)));
973
+ }
974
+
765
975
  /// <summary>
766
976
  /// A motion blur override with intensity 0 does nothing in Unity (MotionBlur.IsActive() is false), but older
767
977
  /// toolkit runtimes still build a motion blur post-process and the buffers it needs. Deactivating the override
@@ -975,6 +1185,8 @@ public static class BtOptimize
975
1185
  private sealed class SkinningVerdict
976
1186
  {
977
1187
  public string Kind, Why;
1188
+ /// <summary>True when the bind pose places the mesh farther from its object than the rest-pose tolerance; MeshToObject and MeshToWorld are then set.</summary>
1189
+ public bool OffsetBaked;
978
1190
  public Matrix4x4 MeshToObject = Matrix4x4.identity;
979
1191
  /// <summary>Where the skinning draws the mesh: bone × bind pose (mesh space to world space).</summary>
980
1192
  public Matrix4x4 MeshToWorld = Matrix4x4.identity;
@@ -997,26 +1209,86 @@ public static class BtOptimize
997
1209
  if (weightedBoneIndices.Count > 1)
998
1210
  {
999
1211
  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)
1212
+ if (movedBone != null) return new SkinningVerdict(SkinDeforms, weightedBoneIndices.Count + " weighted bones; " + movedBone);
1213
+ string poseBlocker = ConversionBlocker(renderer, context);
1214
+ return poseBlocker != null
1215
+ ? new SkinningVerdict(SkinRigidByHand, weightedBoneIndices.Count + " weighted bones that never move, but " + poseBlocker)
1002
1216
  : new SkinningVerdict(SkinFrozenPose, weightedBoneIndices.Count + " weighted bones, none moved by a clip, Timeline or script");
1003
1217
  }
1004
1218
  if (weightedBoneIndices.Count == 0 || mesh.bindposes.Length <= weightedBoneIndices[0]) return new SkinningVerdict(SkinRigidByHand, "no usable bone weights or bind poses");
1005
1219
  int boneIndex = weightedBoneIndices[0];
1006
1220
  var bone = bones[boneIndex];
1007
1221
  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");
1222
+ bool scriptHost = separateMotion != null && IsOnlyScriptOnRenderer(renderer, bone, context);
1223
+ if (separateMotion != null && !scriptHost) return new SkinningVerdict(SkinRigidByHand, "one bone, but it may move apart from the object (" + separateMotion + "): parent a plain mesh under '" + bone.name + "'");
1224
+ string blocker = ConversionBlocker(renderer, context);
1225
+ if (blocker != null) return new SkinningVerdict(SkinRigidByHand, "one bone ('" + bone.name + "'), but " + blocker);
1226
+ string curveNote = context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve) ? "; a clip animates the SkinnedMeshRenderer itself (" + curve + ")" : "";
1227
+ if (scriptHost) return new SkinningVerdict(SkinRigidScriptHost, "one bone ('" + bone.name + "'); the only separate motion is " + separateMotion + ", on the renderer's own object" + curveNote);
1011
1228
  // A one-bone vertex is drawn at bone × bindpose × vertex; a MeshFilter draws it at object × vertex. The fixed
1012
1229
  // difference between the two, in the object's space, is all the skinning does.
1013
1230
  var meshToWorld = bone.localToWorldMatrix * mesh.bindposes[boneIndex];
1014
1231
  var meshToObject = renderer.transform.worldToLocalMatrix * meshToWorld;
1015
1232
  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 };
1233
+ bool offsetBaked = offset > RestPoseTolerance(renderer);
1234
+ string evidence = "one bone ('" + bone.name + "') moving with the object, no blend shapes or cloth"
1235
+ + (offsetBaked ? "; the bind pose offsets the mesh by up to " + offset.ToString("0.###") + " units" : ", bind pose within " + offset.ToString("0.####") + " units");
1236
+ string kind = offsetBaked ? SkinRigidOffset : SkinRigid;
1237
+ if (curveNote.Length > 0) kind = SkinRigidRendererCurves;
1238
+ var verdict = new SkinningVerdict(kind, evidence + curveNote) { OffsetBaked = offsetBaked };
1239
+ if (!offsetBaked) return verdict;
1240
+ verdict.MeshToObject = meshToObject;
1241
+ verdict.MeshToWorld = meshToWorld;
1242
+ return verdict;
1243
+ }
1244
+
1245
+ /// <summary>
1246
+ /// Why a skinned renderer whose bones move with it still cannot be converted automatically, or null: a component
1247
+ /// references the SkinnedMeshRenderer itself, or a clip Tune cannot retarget animates it.
1248
+ /// </summary>
1249
+ private static string ConversionBlocker(SkinnedMeshRenderer renderer, Context context)
1250
+ {
1251
+ if (context.ReferencedComponents.Contains(renderer)) return "a component references the SkinnedMeshRenderer itself";
1252
+ return RendererCurveBlocker(renderer, context);
1253
+ }
1254
+
1255
+ /// <summary>
1256
+ /// Why the clips that animate this SkinnedMeshRenderer cannot be retargeted to MeshRenderer, or null (also when no
1257
+ /// clip animates it). Only an Animator playing a plain AnimatorController can be given a retargeted copy.
1258
+ /// </summary>
1259
+ private static string RendererCurveBlocker(SkinnedMeshRenderer renderer, Context context)
1260
+ {
1261
+ if (!context.RendererCurveTargets.TryGetValue(renderer.transform, out var curve)) return null;
1262
+ foreach (var animation in renderer.GetComponentsInParent<Animation>(true))
1263
+ if (AnimationUtility.GetAnimationClips(animation.gameObject).Any(clip => AnimatesRenderer(clip, animation.transform, renderer.transform)))
1264
+ return "a legacy Animation on '" + animation.name + "' animates it (" + curve + "): retarget the curve to MeshRenderer by hand";
1265
+ foreach (var animator in renderer.GetComponentsInParent<Animator>(true))
1266
+ {
1267
+ var controller = animator.runtimeAnimatorController;
1268
+ if (controller == null || controller is UnityEditor.Animations.AnimatorController) continue;
1269
+ if (controller.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, renderer.transform)))
1270
+ return "the Animator on '" + animator.name + "' animates it through a " + controller.GetType().Name + " (" + curve + "): retarget the curve to MeshRenderer by hand";
1271
+ }
1272
+ return null;
1273
+ }
1274
+
1275
+ /// <summary>
1276
+ /// True when the only separate motion between the bone and the renderer's object is a toolkit script on that object
1277
+ /// itself: no clip, Timeline, constraint, Rigidbody or script on either chain up to their common ancestor, and the
1278
+ /// renderer's own object has an EditorScriptComponent but is not animated and has no constraint or Rigidbody.
1279
+ /// </summary>
1280
+ private static bool IsOnlyScriptOnRenderer(SkinnedMeshRenderer renderer, Transform bone, Context context)
1281
+ {
1282
+ var rendererTransform = renderer.transform;
1283
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
1284
+ if (rendererTransform == commonAncestor) return false;
1285
+ var otherLinks = ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform.parent, commonAncestor));
1286
+ if (otherLinks.Any(node => MotionOn(node, context) != null)) return false;
1287
+ if (context.AnimatedTransforms.ContainsKey(rendererTransform)) return false;
1288
+ var components = rendererTransform.GetComponents<Component>();
1289
+ bool hasScript = components.Any(component => component is EditorScriptComponent);
1290
+ bool hasPhysicsOrConstraint = components.Any(component => component is Rigidbody || component is UnityEngine.Animations.IConstraint);
1291
+ return hasScript && !hasPhysicsOrConstraint;
1020
1292
  }
1021
1293
 
1022
1294
  /// <summary>How far, in world units, a converted vertex may land from where the skinning drew it.</summary>
@@ -1083,7 +1355,7 @@ public static class BtOptimize
1083
1355
  /// </summary>
1084
1356
  private static Mesh BakeOffsetMesh(Mesh source, Matrix4x4 meshToObject, string folder, Dictionary<string, Mesh> bakedMeshes)
1085
1357
  {
1086
- string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], OffsetKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1358
+ string offsetKey = string.Join(",", Enumerable.Range(0, 16).Select(index => Math.Round(meshToObject[index], SharedMeshKeyDecimals).ToString(System.Globalization.CultureInfo.InvariantCulture)));
1087
1359
  string cacheKey = source.GetHashCode() + "|" + offsetKey;
1088
1360
  if (bakedMeshes.TryGetValue(cacheKey, out var existing)) return existing;
1089
1361
  var baked = UnityEngine.Object.Instantiate(source);
@@ -1104,14 +1376,13 @@ public static class BtOptimize
1104
1376
  baked.boneWeights = new BoneWeight[0];
1105
1377
  baked.bindposes = new Matrix4x4[0];
1106
1378
  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"));
1379
+ CreateMeshAsset(baked, folder);
1109
1380
  bakedMeshes[cacheKey] = baked;
1110
1381
  return baked;
1111
1382
  }
1112
1383
 
1113
1384
  /// <summary>
1114
- /// Folder for meshes baked from offset rigid skinned meshes: &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1385
+ /// Folder for meshes baked from skinned meshes (offset rigid meshes and baked poses): &lt;scene folder&gt;/&lt;scene&gt;_UnskinnedMeshes.
1115
1386
  /// BtCombine.PrepareCopy (reset) and RemoveCopy delete it with the working copy.
1116
1387
  /// </summary>
1117
1388
  private static string UnskinnedMeshFolder(Scene scene)
@@ -1119,25 +1390,314 @@ public static class BtOptimize
1119
1390
  return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_UnskinnedMeshes";
1120
1391
  }
1121
1392
 
1393
+ /// <summary>Folder for clips and controllers copied with their SkinnedMeshRenderer curves retargeted: &lt;scene folder&gt;/&lt;scene&gt;_RetargetedClips.</summary>
1394
+ private static string RetargetedClipFolder(Scene scene)
1395
+ {
1396
+ return Path.GetDirectoryName(scene.path).Replace('\\', '/') + "/" + scene.name + "_RetargetedClips";
1397
+ }
1398
+
1399
+ /// <summary>Creates the project folder (one level below an existing folder) when it is missing.</summary>
1400
+ private static void EnsureFolder(string folder)
1401
+ {
1402
+ if (!AssetDatabase.IsValidFolder(folder)) AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), Path.GetFileName(folder));
1403
+ }
1404
+
1405
+ /// <summary>Saves the mesh as a new asset named after it in the folder (a unique path when the name is taken).</summary>
1406
+ private static void CreateMeshAsset(Mesh mesh, string folder)
1407
+ {
1408
+ EnsureFolder(folder);
1409
+ AssetDatabase.CreateAsset(mesh, AssetDatabase.GenerateUniqueAssetPath(folder + "/" + mesh.name + ".asset"));
1410
+ }
1411
+
1412
+ /// <summary>
1413
+ /// The renderer's current skinned shape as a plain mesh in its object's space, shared by every renderer with the same
1414
+ /// source mesh and baked vertices (rounded to SharedMeshKeyDecimals) so the copies still instance. Saved in the
1415
+ /// folder unless `save` is false (a dry run, which only compares shapes; see DiscardUnsavedMeshes).
1416
+ /// </summary>
1417
+ private static Mesh BakedPoseMesh(SkinnedMeshRenderer skinned, string folder, Dictionary<string, Mesh> bakedMeshes, bool save, out string howPlaced)
1418
+ {
1419
+ var source = skinned.sharedMesh;
1420
+ var baked = BakePoseToObjectSpace(skinned);
1421
+ string shapeKey = PoseShapeKey(source, baked);
1422
+ if (bakedMeshes.TryGetValue(shapeKey, out var existing))
1423
+ {
1424
+ UnityEngine.Object.DestroyImmediate(baked);
1425
+ baked = existing;
1426
+ }
1427
+ else
1428
+ {
1429
+ string namePrefix = source.name + "_Pose_";
1430
+ baked.name = namePrefix + bakedMeshes.Values.Count(mesh => mesh.name.StartsWith(namePrefix, StringComparison.Ordinal));
1431
+ if (save) CreateMeshAsset(baked, folder);
1432
+ bakedMeshes[shapeKey] = baked;
1433
+ }
1434
+ string assetPath = EditorUtility.IsPersistent(baked) ? AssetDatabase.GetAssetPath(baked) : folder + "/" + baked.name + ".asset";
1435
+ howPlaced = "baked pose, shared mesh asset " + assetPath;
1436
+ return baked;
1437
+ }
1438
+
1439
+ /// <summary>
1440
+ /// A copy of the renderer's mesh with linear-blend skinning applied at the current bone pose, expressed in the
1441
+ /// renderer object's local space (what a MeshFilter on that object must draw), with the skin data removed. A vertex
1442
+ /// with no weights keeps its position.
1443
+ /// </summary>
1444
+ private static Mesh BakePoseToObjectSpace(SkinnedMeshRenderer skinned)
1445
+ {
1446
+ var source = skinned.sharedMesh;
1447
+ var boneToObject = BoneToObjectMatrices(skinned);
1448
+ var normalMatrices = boneToObject.Select(matrix => matrix.inverse.transpose).ToArray();
1449
+ var bonesPerVertex = source.GetBonesPerVertex();
1450
+ var weights = source.GetAllBoneWeights();
1451
+ var vertices = source.vertices;
1452
+ var normals = source.normals;
1453
+ var tangents = source.tangents;
1454
+ int weightIndex = 0;
1455
+ for (int i = 0; i < vertices.Length; i++)
1456
+ {
1457
+ Vector3 position = Vector3.zero, normal = Vector3.zero, tangent = Vector3.zero;
1458
+ int influenceCount = bonesPerVertex[i];
1459
+ for (int j = 0; j < influenceCount; j++, weightIndex++)
1460
+ {
1461
+ var influence = weights[weightIndex];
1462
+ position += influence.weight * boneToObject[influence.boneIndex].MultiplyPoint3x4(vertices[i]);
1463
+ if (normals.Length > 0) normal += influence.weight * normalMatrices[influence.boneIndex].MultiplyVector(normals[i]);
1464
+ if (tangents.Length > 0) tangent += influence.weight * boneToObject[influence.boneIndex].MultiplyVector(tangents[i]);
1465
+ }
1466
+ if (influenceCount == 0) continue;
1467
+ vertices[i] = position;
1468
+ if (normals.Length > 0) normals[i] = normal.normalized;
1469
+ if (tangents.Length > 0)
1470
+ {
1471
+ var direction = tangent.normalized;
1472
+ tangents[i] = new Vector4(direction.x, direction.y, direction.z, tangents[i].w);
1473
+ }
1474
+ }
1475
+ var baked = UnityEngine.Object.Instantiate(source);
1476
+ baked.boneWeights = new BoneWeight[0];
1477
+ baked.bindposes = new Matrix4x4[0];
1478
+ baked.vertices = vertices;
1479
+ if (normals.Length > 0) baked.normals = normals;
1480
+ if (tangents.Length > 0) baked.tangents = tangents;
1481
+ baked.RecalculateBounds();
1482
+ return baked;
1483
+ }
1484
+
1485
+ /// <summary>For each bone: object-from-world × bone-to-world × bind pose (identity for a missing bone or bind pose).</summary>
1486
+ private static Matrix4x4[] BoneToObjectMatrices(SkinnedMeshRenderer skinned)
1487
+ {
1488
+ var bones = skinned.bones;
1489
+ var bindposes = skinned.sharedMesh.bindposes;
1490
+ var worldToObject = skinned.transform.worldToLocalMatrix;
1491
+ var matrices = new Matrix4x4[bones.Length];
1492
+ for (int i = 0; i < bones.Length; i++)
1493
+ matrices[i] = bones[i] != null && i < bindposes.Length ? worldToObject * bones[i].localToWorldMatrix * bindposes[i] : Matrix4x4.identity;
1494
+ return matrices;
1495
+ }
1496
+
1497
+ /// <summary>Identifies a baked shape: the source mesh plus its vertex positions rounded to SharedMeshKeyDecimals.</summary>
1498
+ private static string PoseShapeKey(Mesh source, Mesh baked)
1499
+ {
1500
+ string format = "F" + SharedMeshKeyDecimals;
1501
+ var culture = System.Globalization.CultureInfo.InvariantCulture;
1502
+ var rounded = baked.vertices.Select(vertex => vertex.x.ToString(format, culture) + "," + vertex.y.ToString(format, culture) + "," + vertex.z.ToString(format, culture));
1503
+ return "pose|" + source.GetHashCode() + "|" + string.Join(";", rounded).GetHashCode();
1504
+ }
1505
+
1506
+ // ------------------------------------------------------------------------------------------------------------
1507
+ // Renderer curves — clips that animate a SkinnedMeshRenderer, retargeted to the MeshRenderer that replaces it
1508
+ // ------------------------------------------------------------------------------------------------------------
1509
+
1510
+ /// <summary>The clip's float and object-reference curve bindings that target a SkinnedMeshRenderer.</summary>
1511
+ private static List<EditorCurveBinding> RendererBindings(AnimationClip clip)
1512
+ {
1513
+ return AnimationUtility.GetCurveBindings(clip).Concat(AnimationUtility.GetObjectReferenceCurveBindings(clip))
1514
+ .Where(binding => binding.type == typeof(SkinnedMeshRenderer)).ToList();
1515
+ }
1516
+
1517
+ /// <summary>The transform a curve binding targets, resolved from the animated root, or null.</summary>
1518
+ private static Transform ResolveBinding(Transform animatedRoot, EditorCurveBinding binding)
1519
+ {
1520
+ return binding.path == "" ? animatedRoot : animatedRoot.Find(binding.path);
1521
+ }
1522
+
1523
+ /// <summary>True when the clip, played from the animated root, animates the SkinnedMeshRenderer on the target.</summary>
1524
+ private static bool AnimatesRenderer(AnimationClip clip, Transform animatedRoot, Transform target)
1525
+ {
1526
+ return clip != null && RendererBindings(clip).Any(binding => ResolveBinding(animatedRoot, binding) == target);
1527
+ }
1528
+
1529
+ /// <summary>The Animators on or above the renderer whose controller's clips animate that SkinnedMeshRenderer.</summary>
1530
+ private static List<Animator> AnimatorsWithRendererCurves(SkinnedMeshRenderer skinned)
1531
+ {
1532
+ return skinned.GetComponentsInParent<Animator>(true)
1533
+ .Where(animator => animator.runtimeAnimatorController is UnityEditor.Animations.AnimatorController)
1534
+ .Where(animator => animator.runtimeAnimatorController.animationClips.Any(clip => AnimatesRenderer(clip, animator.transform, skinned.transform)))
1535
+ .ToList();
1536
+ }
1537
+
1538
+ /// <summary>Names, for the report, each clip that will be copied with its curves retargeted and the controller copy that plays it.</summary>
1539
+ private static string RetargetPlan(List<Animator> animators, Transform target, string folder)
1540
+ {
1541
+ var plans = animators.Select(animator =>
1542
+ {
1543
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
1544
+ var clipNames = controller.animationClips.Where(clip => AnimatesRenderer(clip, animator.transform, target)).Select(clip => "'" + clip.name + "'").Distinct();
1545
+ return "clip " + string.Join(", ", clipNames) + " copied with its SkinnedMeshRenderer curves aimed at MeshRenderer, played by controller copy "
1546
+ + RetargetedControllerPath(controller, folder) + " (Animator on " + animator.name + ")";
1547
+ });
1548
+ return string.Join("; ", plans);
1549
+ }
1550
+
1551
+ /// <summary>Where the retargeted copy of a controller is saved.</summary>
1552
+ private static string RetargetedControllerPath(UnityEditor.Animations.AnimatorController controller, string folder)
1553
+ {
1554
+ return folder + "/" + controller.name + "_MeshRenderer.controller";
1555
+ }
1556
+
1557
+ /// <summary>
1558
+ /// Gives each Animator a copy of its controller whose clips aim every SkinnedMeshRenderer curve at a converted object
1559
+ /// (one that now has a MeshRenderer) at MeshRenderer instead, same path and property. Animators sharing a controller
1560
+ /// share its copy. The original clips and controllers are never edited; only the Animators in this scene change.
1561
+ /// </summary>
1562
+ private static void RetargetAnimators(List<Animator> animators, string folder)
1563
+ {
1564
+ var controllerCopies = new Dictionary<UnityEditor.Animations.AnimatorController, UnityEditor.Animations.AnimatorController>();
1565
+ var clipCopies = new Dictionary<AnimationClip, AnimationClip>();
1566
+ foreach (var animator in animators)
1567
+ {
1568
+ var controller = (UnityEditor.Animations.AnimatorController)animator.runtimeAnimatorController;
1569
+ if (!controllerCopies.TryGetValue(controller, out var copy))
1570
+ {
1571
+ copy = RetargetedController(controller, animator.transform, folder, clipCopies);
1572
+ controllerCopies[controller] = copy;
1573
+ }
1574
+ animator.runtimeAnimatorController = copy;
1575
+ EditorUtility.SetDirty(animator);
1576
+ }
1577
+ }
1578
+
1579
+ /// <summary>
1580
+ /// A fresh copy of the controller (replacing a copy an earlier run left) with every clip that has retargeted curves
1581
+ /// swapped for its copy, in every state and blend tree of every layer.
1582
+ /// </summary>
1583
+ private static UnityEditor.Animations.AnimatorController RetargetedController(UnityEditor.Animations.AnimatorController controller, Transform animatedRoot,
1584
+ string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
1585
+ {
1586
+ EnsureFolder(folder);
1587
+ string copyPath = RetargetedControllerPath(controller, folder);
1588
+ AssetDatabase.DeleteAsset(copyPath);
1589
+ if (!AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(controller), copyPath)) throw new InvalidOperationException("Could not copy " + controller.name + " to " + copyPath);
1590
+ var copy = AssetDatabase.LoadAssetAtPath<UnityEditor.Animations.AnimatorController>(copyPath);
1591
+ var replacements = new Dictionary<AnimationClip, AnimationClip>();
1592
+ foreach (var clip in controller.animationClips.Where(clip => clip != null).Distinct())
1593
+ {
1594
+ var retargeted = RetargetedClip(clip, animatedRoot, folder, clipCopies);
1595
+ if (retargeted != null) replacements[clip] = retargeted;
1596
+ }
1597
+ foreach (var layer in copy.layers) ReplaceMotions(layer.stateMachine, replacements);
1598
+ EditorUtility.SetDirty(copy);
1599
+ return copy;
1600
+ }
1601
+
1602
+ /// <summary>
1603
+ /// A copy of the clip with every SkinnedMeshRenderer curve whose target now has a MeshRenderer retargeted to
1604
+ /// MeshRenderer (same path and property), saved in the folder as &lt;clip&gt;_MeshRenderer.anim (an earlier run's copy
1605
+ /// is updated in place). Null when the clip has no such curve. Each clip is copied once per run.
1606
+ /// </summary>
1607
+ private static AnimationClip RetargetedClip(AnimationClip clip, Transform animatedRoot, string folder, Dictionary<AnimationClip, AnimationClip> clipCopies)
1608
+ {
1609
+ if (clipCopies.TryGetValue(clip, out var done)) return done;
1610
+ var bindings = RendererBindings(clip).Where(binding => ResolveBinding(animatedRoot, binding) is Transform target && target.GetComponent<MeshRenderer>() != null).ToList();
1611
+ if (bindings.Count == 0) return null;
1612
+ var retargeted = UnityEngine.Object.Instantiate(clip);
1613
+ retargeted.name = clip.name + "_MeshRenderer";
1614
+ foreach (var binding in bindings) RetargetBinding(clip, retargeted, binding);
1615
+ string clipPath = folder + "/" + retargeted.name + ".anim";
1616
+ var previous = AssetDatabase.LoadAssetAtPath<AnimationClip>(clipPath);
1617
+ if (previous == null)
1618
+ {
1619
+ AssetDatabase.CreateAsset(retargeted, clipPath);
1620
+ }
1621
+ else
1622
+ {
1623
+ EditorUtility.CopySerialized(retargeted, previous);
1624
+ UnityEngine.Object.DestroyImmediate(retargeted);
1625
+ retargeted = previous;
1626
+ }
1627
+ clipCopies[clip] = retargeted;
1628
+ return retargeted;
1629
+ }
1630
+
1631
+ /// <summary>Moves one curve of the copied clip from the SkinnedMeshRenderer binding to the same MeshRenderer binding.</summary>
1632
+ private static void RetargetBinding(AnimationClip source, AnimationClip retargeted, EditorCurveBinding binding)
1633
+ {
1634
+ var meshBinding = binding;
1635
+ meshBinding.type = typeof(MeshRenderer);
1636
+ if (binding.isPPtrCurve)
1637
+ {
1638
+ var keyframes = AnimationUtility.GetObjectReferenceCurve(source, binding);
1639
+ AnimationUtility.SetObjectReferenceCurve(retargeted, binding, null);
1640
+ AnimationUtility.SetObjectReferenceCurve(retargeted, meshBinding, keyframes);
1641
+ return;
1642
+ }
1643
+ var curve = AnimationUtility.GetEditorCurve(source, binding);
1644
+ AnimationUtility.SetEditorCurve(retargeted, binding, null);
1645
+ AnimationUtility.SetEditorCurve(retargeted, meshBinding, curve);
1646
+ }
1647
+
1648
+ /// <summary>Swaps state motions in the state machine (and its sub-state machines) for their replacements.</summary>
1649
+ private static void ReplaceMotions(UnityEditor.Animations.AnimatorStateMachine stateMachine, Dictionary<AnimationClip, AnimationClip> replacements)
1650
+ {
1651
+ foreach (var child in stateMachine.states) child.state.motion = ReplacedMotion(child.state.motion, replacements);
1652
+ foreach (var child in stateMachine.stateMachines) ReplaceMotions(child.stateMachine, replacements);
1653
+ }
1654
+
1655
+ /// <summary>The motion with every replaced clip swapped in: the clip's replacement, or a blend tree with its children swapped.</summary>
1656
+ private static Motion ReplacedMotion(Motion motion, Dictionary<AnimationClip, AnimationClip> replacements)
1657
+ {
1658
+ if (motion is AnimationClip clip) return replacements.TryGetValue(clip, out var replacement) ? replacement : clip;
1659
+ if (!(motion is UnityEditor.Animations.BlendTree blendTree)) return motion;
1660
+ var children = blendTree.children;
1661
+ for (int i = 0; i < children.Length; i++) children[i].motion = ReplacedMotion(children[i].motion, replacements);
1662
+ blendTree.children = children;
1663
+ return blendTree;
1664
+ }
1665
+
1122
1666
  /// <summary>
1123
1667
  /// What moves the bone relative to the renderer's object, or null when the two always move together. Only the
1124
1668
  /// transforms between each of them and their nearest common ancestor count: whatever moves that ancestor (an
1125
1669
  /// Animator popping the whole prop in, a script spinning it) moves bone and mesh alike.
1126
1670
  /// </summary>
1127
1671
  private static string SeparateMotionBetween(Transform bone, Transform rendererTransform, Context context)
1672
+ {
1673
+ var commonAncestor = CommonAncestor(bone, rendererTransform);
1674
+ return ChainBelow(bone, commonAncestor).Concat(ChainBelow(rendererTransform, commonAncestor))
1675
+ .Select(node => MotionOn(node, context)).FirstOrDefault(motion => motion != null);
1676
+ }
1677
+
1678
+ /// <summary>The nearest transform that is the bone or one of its ancestors and also the renderer's object or one of its ancestors (null when none is).</summary>
1679
+ private static Transform CommonAncestor(Transform bone, Transform rendererTransform)
1128
1680
  {
1129
1681
  var rendererAncestors = new HashSet<Transform>();
1130
1682
  for (var node = rendererTransform; node != null; node = node.parent) rendererAncestors.Add(node);
1131
1683
  var commonAncestor = bone;
1132
1684
  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
- }
1685
+ return commonAncestor;
1686
+ }
1687
+
1688
+ /// <summary>The transform and its ancestors up to, but not including, the ancestor (empty when start is null or the ancestor).</summary>
1689
+ private static IEnumerable<Transform> ChainBelow(Transform start, Transform ancestor)
1690
+ {
1691
+ for (var node = start; node != null && node != ancestor; node = node.parent) yield return node;
1692
+ }
1693
+
1694
+ /// <summary>What can move this one transform on its own — a clip or Timeline, a toolkit script, a Rigidbody or a constraint — or null.</summary>
1695
+ private static string MotionOn(Transform node, Context context)
1696
+ {
1697
+ if (context.AnimatedTransforms.TryGetValue(node, out var animator)) return "'" + node.name + "' is animated by " + animator;
1698
+ foreach (var component in node.GetComponents<Component>())
1699
+ if (component is EditorScriptComponent || component is Rigidbody || component is UnityEngine.Animations.IConstraint)
1700
+ return "'" + node.name + "' has " + component.GetType().Name;
1141
1701
  return null;
1142
1702
  }
1143
1703
 
@@ -1205,9 +1765,20 @@ public static class BtOptimize
1205
1765
  public readonly HashSet<Component> ReferencedComponents;
1206
1766
  /// <summary>How many active renderers draw each mesh + materials combination (see RepeatKey).</summary>
1207
1767
  public readonly Dictionary<string, int> RepeatCounts;
1768
+ /// <summary>Hierarchy paths of the renderers that contribute GI in the source scene (Tune only; empty for a survey).</summary>
1769
+ public readonly HashSet<string> SourceGIContributors;
1770
+ /// <summary>
1771
+ /// Hierarchy paths of the renderers that contribute GI once Tune's changes land. Starts as the scene's own set;
1772
+ /// the steps keep it in step with the Contribute GI flags they add or clear, so a dry run can count it too.
1773
+ /// </summary>
1774
+ public readonly HashSet<string> PlannedGIContributors;
1775
+ /// <summary>Skinned renderers a dry run plans to convert: later steps treat them as the MeshRenderers they become.</summary>
1776
+ public readonly List<SkinnedMeshRenderer> PlannedUnskinned = new List<SkinnedMeshRenderer>();
1208
1777
  public readonly StringBuilder Summary = new StringBuilder();
1209
1778
 
1210
- public Context(Scene scene)
1779
+ /// <param name="scene">The scene to gather.</param>
1780
+ /// <param name="sourceGIContributors">Tune's source contributor set (see SourceGIContributorsOf); null for a survey.</param>
1781
+ public Context(Scene scene, HashSet<string> sourceGIContributors = null)
1211
1782
  {
1212
1783
  Scene = scene;
1213
1784
  Roots = scene.GetRootGameObjects().ToList();
@@ -1221,6 +1792,8 @@ public static class BtOptimize
1221
1792
  CollectAnimationTargets(this);
1222
1793
  ReferencedComponents = CollectReferencedComponents(Roots);
1223
1794
  RepeatCounts = Renderers.GroupBy(RepeatKey).ToDictionary(group => group.Key, group => group.Count());
1795
+ SourceGIContributors = sourceGIContributors ?? new HashSet<string>();
1796
+ PlannedGIContributors = GIContributorPaths(Roots);
1224
1797
  }
1225
1798
 
1226
1799
  /// <summary>Every component of type T in the scene, including inactive objects.</summary>