@babylonjs-toolkit/agent 1.1.52 → 1.1.55
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 +18 -17
- package/package.json +1 -1
- package/skills/bt-gauntlet/SKILL.md +19 -19
- package/skills/bt-gauntlet/references/loop-templates.md +12 -12
- package/skills/bt-gauntlet/references/spec-composition.md +6 -6
- package/skills/bt-gauntlet/references/target-images.md +6 -6
- package/skills/bt-gauntlet/references/unity-pipeline.md +3 -3
- package/skills/bt-gauntlet/references/workspace.md +5 -5
- package/skills/bt-hero/SKILL.md +2 -2
- package/skills/bt-optimize/SKILL.md +338 -0
- package/skills/bt-optimize/scripts/BtCombine.cs +1625 -0
- package/skills/bt-optimize/scripts/BtOptimize.cs +969 -0
- package/skills/bt-optimize/scripts/qa/compare-browser.mjs +164 -0
- package/skills/bt-optimize/scripts/qa/compare-profiles.mjs +80 -0
- package/skills/bt-optimize/scripts/qa/gltf-stats.mjs +57 -0
- package/skills/bt-optimize/scripts/qa/package.json +9 -0
- package/skills/bt-optimize/scripts/qa/profile-browser.mjs +547 -0
- package/skills/bt-plan/SKILL.md +9 -9
- package/skills/bt-prototype/SKILL.md +4 -4
- package/skills/bt-recon/SKILL.md +14 -14
- package/skills/bt-spec/SKILL.md +5 -5
|
@@ -0,0 +1,1625 @@
|
|
|
1
|
+
using System;
|
|
2
|
+
using System.Collections.Generic;
|
|
3
|
+
using System.IO;
|
|
4
|
+
using System.Linq;
|
|
5
|
+
using System.Reflection;
|
|
6
|
+
using System.Text;
|
|
7
|
+
using System.Text.RegularExpressions;
|
|
8
|
+
using UnityEditor;
|
|
9
|
+
using UnityEditor.SceneManagement;
|
|
10
|
+
using UnityEngine;
|
|
11
|
+
using UnityEngine.Rendering;
|
|
12
|
+
using UnityEngine.SceneManagement;
|
|
13
|
+
|
|
14
|
+
/// <summary>
|
|
15
|
+
/// bt-optimize merge stage. Decides which static meshes and LOD groups of the active scene can be merged without changing
|
|
16
|
+
/// how the scene looks in Unity or in BabylonJS, writes the reasoning to .agents/optimize/<scene>/, and merges them with the
|
|
17
|
+
/// Babylon Toolkit's MeshCombiner (Pack Source Lightmap UVs mode, so no vertex is split).
|
|
18
|
+
/// Run every entry point with `unity command run_script --file <this file> --entry BtCombine.<Method>`.
|
|
19
|
+
/// </summary>
|
|
20
|
+
public static class BtCombine
|
|
21
|
+
{
|
|
22
|
+
/// <summary>Name prefix of merged static meshes; the planner never merges these again.</summary>
|
|
23
|
+
private const string StaticPrefix = "Combined_";
|
|
24
|
+
|
|
25
|
+
/// <summary>Name prefix of merged LOD clusters.</summary>
|
|
26
|
+
private const string LodPrefix = "CombinedLOD_";
|
|
27
|
+
|
|
28
|
+
/// <summary>First of the toolkit's reserved export layers (Hidden, No Instance, Ignore Export, Prefab).</summary>
|
|
29
|
+
private const int FirstReservedLayer = 28;
|
|
30
|
+
|
|
31
|
+
/// <summary>Render queues from here up are transparent: they are sorted per mesh, so merging changes draw order.</summary>
|
|
32
|
+
private const int FirstTransparentQueue = 2500;
|
|
33
|
+
|
|
34
|
+
/// <summary>Largest vertex count one merged mesh may reach; bigger meshes cull badly and upload slowly.</summary>
|
|
35
|
+
private const int MaxVerticesPerMesh = 200000;
|
|
36
|
+
|
|
37
|
+
/// <summary>A merged mesh may grow at most this much over the sum of its sources before the run is flagged as bloated.</summary>
|
|
38
|
+
private const float VertexBloatTolerance = 1.02f;
|
|
39
|
+
|
|
40
|
+
/// <summary>Largest share of the LOD0 → LOD1 switch distance a cluster member may sit from the cluster centre.</summary>
|
|
41
|
+
private const float MaxLodSwitchError = 0.2f;
|
|
42
|
+
|
|
43
|
+
/// <summary>A rescaled LOD0 transition height must stay below this, or the cluster is too big to switch like its members.</summary>
|
|
44
|
+
private const float MaxRescaledTransition = 0.95f;
|
|
45
|
+
|
|
46
|
+
/// <summary>Built-in shaders whose look does not depend on the object's pivot or object space.</summary>
|
|
47
|
+
private static readonly string[] SafeShaders =
|
|
48
|
+
{
|
|
49
|
+
"Universal Render Pipeline/Lit", "Universal Render Pipeline/Simple Lit", "Universal Render Pipeline/Complex Lit",
|
|
50
|
+
"Universal Render Pipeline/Baked Lit", "Universal Render Pipeline/Unlit",
|
|
51
|
+
"Standard", "Standard (Specular setup)", "Autodesk Interactive", "HDRP/Lit", "HDRP/Unlit",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/// <summary>Settings for a run. Every field has a safe default; the skill passes overrides as JSON.</summary>
|
|
55
|
+
[Serializable]
|
|
56
|
+
public class Options
|
|
57
|
+
{
|
|
58
|
+
/// <summary>Edge of the square area cell ("patch"), in meters, that keeps merged meshes local.</summary>
|
|
59
|
+
public float cellSize = 15f;
|
|
60
|
+
/// <summary>How far, in meters, a merged group's footprint may extend past its largest piece.</summary>
|
|
61
|
+
public float maxSpread = 3f;
|
|
62
|
+
/// <summary>Largest share of one lightmap atlas a merged lightmapped mesh may fill.</summary>
|
|
63
|
+
public float maxAtlasShare = 0.45f;
|
|
64
|
+
/// <summary>Also merge Shader Graph materials that pass the object-space / vertex-animation scan.</summary>
|
|
65
|
+
public bool includeShaderGraphs = false;
|
|
66
|
+
/// <summary>Merge LOD groups into LOD clusters.</summary>
|
|
67
|
+
public bool combineLods = true;
|
|
68
|
+
/// <summary>Names (or name prefixes ending in *) of objects whose subtrees are never merged.</summary>
|
|
69
|
+
public string[] exclude = new string[0];
|
|
70
|
+
/// <summary>When set, only renderers under these hierarchy paths are considered.</summary>
|
|
71
|
+
public string[] only = new string[0];
|
|
72
|
+
/// <summary>Extra shader names to treat as safe.</summary>
|
|
73
|
+
public string[] extraShaders = new string[0];
|
|
74
|
+
/// <summary>Proceed on a toolkit without Pack Source Lightmap UVs (re-unwraps and bloats vertices).</summary>
|
|
75
|
+
public bool allowUnityUnwrap = false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// <summary>One planned (Analyze) or performed (Apply) merge.</summary>
|
|
79
|
+
public class GroupRecord
|
|
80
|
+
{
|
|
81
|
+
public string name;
|
|
82
|
+
public string kind;
|
|
83
|
+
public string container;
|
|
84
|
+
public string probe;
|
|
85
|
+
public bool lightmapped;
|
|
86
|
+
public int lodLevels;
|
|
87
|
+
public int vertices;
|
|
88
|
+
public int drawsBefore;
|
|
89
|
+
public int drawsAfter;
|
|
90
|
+
public int lights;
|
|
91
|
+
public float atlasShare;
|
|
92
|
+
public float densityBefore;
|
|
93
|
+
public float spreadMeters;
|
|
94
|
+
public float sizeRatio;
|
|
95
|
+
public string[] sources = new string[0];
|
|
96
|
+
public string combinedPath = "";
|
|
97
|
+
public string[] meshAssets = new string[0];
|
|
98
|
+
public int combinedVertices;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// <summary>The whole analysis or manifest.</summary>
|
|
102
|
+
public class RunRecord
|
|
103
|
+
{
|
|
104
|
+
public string scene;
|
|
105
|
+
public string mode;
|
|
106
|
+
public int renderersBefore;
|
|
107
|
+
public int drawsBefore;
|
|
108
|
+
public int renderersAfter;
|
|
109
|
+
public int drawsAfter;
|
|
110
|
+
public List<GroupRecord> groups = new List<GroupRecord>();
|
|
111
|
+
public List<string> advisories = new List<string>();
|
|
112
|
+
public List<string> warnings = new List<string>();
|
|
113
|
+
|
|
114
|
+
/// <summary>Writes the record as JSON (flat arrays: JsonUtility drops lists of custom classes from run_script assemblies).</summary>
|
|
115
|
+
public string ToJson()
|
|
116
|
+
{
|
|
117
|
+
var file = new RunFile
|
|
118
|
+
{
|
|
119
|
+
scene = scene, mode = mode, renderersBefore = renderersBefore, drawsBefore = drawsBefore,
|
|
120
|
+
renderersAfter = renderersAfter, drawsAfter = drawsAfter, advisories = advisories.ToArray(), warnings = warnings.ToArray(),
|
|
121
|
+
names = groups.Select(g => g.name).ToArray(), kinds = groups.Select(g => g.kind).ToArray(),
|
|
122
|
+
containers = groups.Select(g => g.container).ToArray(), probes = groups.Select(g => g.probe).ToArray(),
|
|
123
|
+
lightmapped = groups.Select(g => g.lightmapped).ToArray(), lodLevels = groups.Select(g => g.lodLevels).ToArray(),
|
|
124
|
+
vertices = groups.Select(g => g.vertices).ToArray(), groupDrawsBefore = groups.Select(g => g.drawsBefore).ToArray(),
|
|
125
|
+
groupDrawsAfter = groups.Select(g => g.drawsAfter).ToArray(), lights = groups.Select(g => g.lights).ToArray(),
|
|
126
|
+
atlasShare = groups.Select(g => g.atlasShare).ToArray(), densityBefore = groups.Select(g => g.densityBefore).ToArray(),
|
|
127
|
+
spreadMeters = groups.Select(g => g.spreadMeters).ToArray(), sizeRatio = groups.Select(g => g.sizeRatio).ToArray(),
|
|
128
|
+
sources = groups.Select(g => string.Join(SourceSeparator, g.sources)).ToArray(), combinedPaths = groups.Select(g => g.combinedPath).ToArray(),
|
|
129
|
+
meshAssets = groups.Select(g => string.Join(SourceSeparator, g.meshAssets)).ToArray(), combinedVertices = groups.Select(g => g.combinedVertices).ToArray(),
|
|
130
|
+
};
|
|
131
|
+
return JsonUtility.ToJson(file, true);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// <summary>Reads a record written by ToJson.</summary>
|
|
135
|
+
public static RunRecord FromJson(string json)
|
|
136
|
+
{
|
|
137
|
+
var file = JsonUtility.FromJson<RunFile>(json);
|
|
138
|
+
var record = new RunRecord
|
|
139
|
+
{
|
|
140
|
+
scene = file.scene, mode = file.mode, renderersBefore = file.renderersBefore, drawsBefore = file.drawsBefore,
|
|
141
|
+
renderersAfter = file.renderersAfter, drawsAfter = file.drawsAfter,
|
|
142
|
+
advisories = file.advisories.ToList(), warnings = file.warnings.ToList(),
|
|
143
|
+
};
|
|
144
|
+
for (int i = 0; i < file.names.Length; i++)
|
|
145
|
+
{
|
|
146
|
+
record.groups.Add(new GroupRecord
|
|
147
|
+
{
|
|
148
|
+
name = file.names[i], kind = file.kinds[i], container = file.containers[i], probe = file.probes[i], lightmapped = file.lightmapped[i],
|
|
149
|
+
lodLevels = file.lodLevels[i], vertices = file.vertices[i], drawsBefore = file.groupDrawsBefore[i], drawsAfter = file.groupDrawsAfter[i],
|
|
150
|
+
lights = file.lights[i], atlasShare = file.atlasShare[i], densityBefore = file.densityBefore[i], spreadMeters = file.spreadMeters[i],
|
|
151
|
+
sizeRatio = file.sizeRatio[i], sources = file.sources[i].Split(new[] { SourceSeparator }, StringSplitOptions.RemoveEmptyEntries),
|
|
152
|
+
combinedPath = file.combinedPaths[i], meshAssets = file.meshAssets[i].Split(new[] { SourceSeparator }, StringSplitOptions.RemoveEmptyEntries),
|
|
153
|
+
combinedVertices = file.combinedVertices[i],
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
return record;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/// <summary>Separator for lists stored inside one JSON string.</summary>
|
|
161
|
+
private const string SourceSeparator = " ;; ";
|
|
162
|
+
|
|
163
|
+
/// <summary>On-disk form of a RunRecord: one array per group field (index i across arrays = group i).</summary>
|
|
164
|
+
[Serializable]
|
|
165
|
+
public class RunFile
|
|
166
|
+
{
|
|
167
|
+
public string scene;
|
|
168
|
+
public string mode;
|
|
169
|
+
public int renderersBefore;
|
|
170
|
+
public int drawsBefore;
|
|
171
|
+
public int renderersAfter;
|
|
172
|
+
public int drawsAfter;
|
|
173
|
+
public string[] advisories = new string[0];
|
|
174
|
+
public string[] warnings = new string[0];
|
|
175
|
+
public string[] names = new string[0];
|
|
176
|
+
public string[] kinds = new string[0];
|
|
177
|
+
public string[] containers = new string[0];
|
|
178
|
+
public string[] probes = new string[0];
|
|
179
|
+
public bool[] lightmapped = new bool[0];
|
|
180
|
+
public int[] lodLevels = new int[0];
|
|
181
|
+
public int[] vertices = new int[0];
|
|
182
|
+
public int[] groupDrawsBefore = new int[0];
|
|
183
|
+
public int[] groupDrawsAfter = new int[0];
|
|
184
|
+
public int[] lights = new int[0];
|
|
185
|
+
public float[] atlasShare = new float[0];
|
|
186
|
+
public float[] densityBefore = new float[0];
|
|
187
|
+
public float[] spreadMeters = new float[0];
|
|
188
|
+
public float[] sizeRatio = new float[0];
|
|
189
|
+
public string[] sources = new string[0];
|
|
190
|
+
public string[] combinedPaths = new string[0];
|
|
191
|
+
public string[] meshAssets = new string[0];
|
|
192
|
+
public int[] combinedVertices = new int[0];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ------------------------------------------------------------------------------------------------ entry points
|
|
196
|
+
|
|
197
|
+
/// <summary>
|
|
198
|
+
/// Read-only readiness check: Editor state, toolkit packing support, scene save state and lighting state.
|
|
199
|
+
/// </summary>
|
|
200
|
+
public static string Preflight(string sourceScene)
|
|
201
|
+
{
|
|
202
|
+
var report = new StringBuilder();
|
|
203
|
+
report.AppendLine("unity=" + Application.unityVersion);
|
|
204
|
+
report.AppendLine("playMode=" + EditorApplication.isPlayingOrWillChangePlaymode);
|
|
205
|
+
report.AppendLine("packSourceLightmapUVs=" + ToolkitPacksSourceUVs());
|
|
206
|
+
report.AppendLine("mergesMirrored=" + ToolkitHandlesMirrors());
|
|
207
|
+
report.AppendLine("sourceExists=" + File.Exists(sourceScene));
|
|
208
|
+
var active = SceneManager.GetActiveScene();
|
|
209
|
+
report.AppendLine("activeScene=" + active.path + " dirty=" + active.isDirty);
|
|
210
|
+
report.AppendLine("maxLightsPerMesh=" + MaxLightsPerMesh());
|
|
211
|
+
return report.ToString();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/// <summary>
|
|
215
|
+
/// Makes (or with reset, re-makes) the working copy of the source scene and opens it. The source is never edited.
|
|
216
|
+
/// A reset copies the file over the existing copy so its GUID survives, and deletes the previous merged meshes.
|
|
217
|
+
/// </summary>
|
|
218
|
+
public static string PrepareCopy(string sourceScene, string outputScene, bool reset)
|
|
219
|
+
{
|
|
220
|
+
ThrowIfAnySceneDirty();
|
|
221
|
+
if (sourceScene == outputScene) throw new InvalidOperationException("The output scene must differ from the source (use --in-place handling in the skill).");
|
|
222
|
+
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
|
|
223
|
+
bool existed = File.Exists(outputScene);
|
|
224
|
+
if (!existed)
|
|
225
|
+
{
|
|
226
|
+
if (!AssetDatabase.CopyAsset(sourceScene, outputScene)) throw new InvalidOperationException("Could not copy " + sourceScene + " to " + outputScene);
|
|
227
|
+
}
|
|
228
|
+
else if (reset)
|
|
229
|
+
{
|
|
230
|
+
File.Copy(sourceScene, outputScene, true);
|
|
231
|
+
AssetDatabase.ImportAsset(outputScene, ImportAssetOptions.ForceUpdate);
|
|
232
|
+
string meshFolder = MeshFolderFor(outputScene);
|
|
233
|
+
if (AssetDatabase.IsValidFolder(meshFolder)) AssetDatabase.DeleteAsset(meshFolder);
|
|
234
|
+
string manifest = Path.Combine(ReportFolderFor(outputScene), "combine-manifest.json");
|
|
235
|
+
if (File.Exists(manifest)) File.Delete(manifest);
|
|
236
|
+
}
|
|
237
|
+
var scene = EditorSceneManager.OpenScene(outputScene, OpenSceneMode.Single);
|
|
238
|
+
Directory.CreateDirectory(ReportFolderFor(outputScene));
|
|
239
|
+
File.WriteAllText(WorkingCopyMarker(outputScene), sourceScene);
|
|
240
|
+
return "opened=" + scene.path + " created=" + !existed + " reset=" + (existed && reset);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/// <summary>Deletes a working copy, its merged meshes, its baked lighting folder and its report folder.</summary>
|
|
244
|
+
public static string RemoveCopy(string outputScene, string reopenScene)
|
|
245
|
+
{
|
|
246
|
+
if (!File.Exists(WorkingCopyMarker(outputScene))) throw new InvalidOperationException(outputScene + " is not a bt-optimize working copy; refusing to delete it.");
|
|
247
|
+
ThrowIfAnySceneDirty();
|
|
248
|
+
EditorSceneManager.OpenScene(reopenScene, OpenSceneMode.Single);
|
|
249
|
+
bool sceneDeleted = AssetDatabase.DeleteAsset(outputScene);
|
|
250
|
+
bool meshesDeleted = AssetDatabase.DeleteAsset(MeshFolderFor(outputScene));
|
|
251
|
+
bool lightingDeleted = AssetDatabase.DeleteAsset(Path.ChangeExtension(outputScene, null).Replace('\\', '/'));
|
|
252
|
+
string reportFolder = ReportFolderFor(outputScene);
|
|
253
|
+
if (Directory.Exists(reportFolder)) Directory.Delete(reportFolder, true);
|
|
254
|
+
return "sceneDeleted=" + sceneDeleted + " meshesDeleted=" + meshesDeleted + " lightingDeleted=" + lightingDeleted;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/// <summary>
|
|
258
|
+
/// Plans the merges for the active scene without changing it, and writes analysis.md + analysis.json to
|
|
259
|
+
/// .agents/optimize/<scene>/ (combine-plan.md / .json). Returns the Markdown report.
|
|
260
|
+
/// </summary>
|
|
261
|
+
public static string Analyze(string optionsJson)
|
|
262
|
+
{
|
|
263
|
+
var options = ParseOptions(optionsJson);
|
|
264
|
+
var scene = SceneManager.GetActiveScene();
|
|
265
|
+
var plan = BuildPlan(scene, options);
|
|
266
|
+
var record = plan.ToRecord("analysis");
|
|
267
|
+
string markdown = plan.ToMarkdown(record, options);
|
|
268
|
+
string folder = ReportFolderFor(scene.path);
|
|
269
|
+
Directory.CreateDirectory(folder);
|
|
270
|
+
File.WriteAllText(Path.Combine(folder, "combine-plan.md"), markdown);
|
|
271
|
+
File.WriteAllText(Path.Combine(folder, "combine-plan.json"), record.ToJson());
|
|
272
|
+
return markdown;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/// <summary>
|
|
276
|
+
/// Plans and performs the merges on the active scene (which must be a bt-optimize working copy), saves it, and
|
|
277
|
+
/// writes manifest.json. Lighting must be re-baked afterwards when any lightmapped mesh was merged.
|
|
278
|
+
/// </summary>
|
|
279
|
+
public static string Apply(string optionsJson)
|
|
280
|
+
{
|
|
281
|
+
var options = ParseOptions(optionsJson);
|
|
282
|
+
if (!ToolkitPacksSourceUVs() && !options.allowUnityUnwrap)
|
|
283
|
+
{
|
|
284
|
+
throw new InvalidOperationException("This Babylon Toolkit build has no Pack Source Lightmap UVs mode: its combiner re-unwraps merged meshes "
|
|
285
|
+
+ "and splits vertices (often +50%). Update CanvasTools.dll, or pass allowUnityUnwrap to accept the bloat.");
|
|
286
|
+
}
|
|
287
|
+
var scene = SceneManager.GetActiveScene();
|
|
288
|
+
if (!File.Exists(WorkingCopyMarker(scene.path)))
|
|
289
|
+
{
|
|
290
|
+
throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run PrepareCopy first; Apply never edits a source scene.");
|
|
291
|
+
}
|
|
292
|
+
string manifestPath = Path.Combine(ReportFolderFor(scene.path), "combine-manifest.json");
|
|
293
|
+
if (File.Exists(manifestPath) || HasCombinedObjects(scene))
|
|
294
|
+
{
|
|
295
|
+
throw new InvalidOperationException("This scene was already combined. Run with reset to start again from the source scene.");
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
var plan = BuildPlan(scene, options);
|
|
299
|
+
var record = plan.ToRecord("manifest");
|
|
300
|
+
string meshFolder = MeshFolderFor(scene.path);
|
|
301
|
+
EnsureFolder(meshFolder);
|
|
302
|
+
var usedNames = new HashSet<string>();
|
|
303
|
+
foreach (var groupRecord in record.groups)
|
|
304
|
+
{
|
|
305
|
+
groupRecord.name = UniqueName(groupRecord.name, usedNames);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
for (int i = 0; i < plan.StaticGroups.Count; i++)
|
|
309
|
+
{
|
|
310
|
+
CombineStaticGroup(plan.StaticGroups[i], record.groups[i], meshFolder, plan.Context, record);
|
|
311
|
+
}
|
|
312
|
+
for (int i = 0; i < plan.LodClusters.Count; i++)
|
|
313
|
+
{
|
|
314
|
+
CombineLodCluster(plan.LodClusters[i], record.groups[plan.StaticGroups.Count + i], meshFolder, plan.Context, record);
|
|
315
|
+
}
|
|
316
|
+
UnityMeshSimplifier.MeshCombiner.ClearUv2Cache();
|
|
317
|
+
|
|
318
|
+
EditorSceneManager.MarkSceneDirty(scene);
|
|
319
|
+
EditorSceneManager.SaveScene(scene);
|
|
320
|
+
AssetDatabase.SaveAssets();
|
|
321
|
+
CountScene(scene, out record.renderersAfter, out record.drawsAfter);
|
|
322
|
+
Directory.CreateDirectory(ReportFolderFor(scene.path));
|
|
323
|
+
File.WriteAllText(manifestPath, record.ToJson());
|
|
324
|
+
|
|
325
|
+
var summary = new StringBuilder();
|
|
326
|
+
summary.AppendLine("applied=" + scene.path + " groups=" + record.groups.Count + " renderers " + record.renderersBefore + " -> " + record.renderersAfter
|
|
327
|
+
+ " draws " + record.drawsBefore + " -> " + record.drawsAfter);
|
|
328
|
+
summary.AppendLine("needsBake=" + record.groups.Any(g => g.lightmapped));
|
|
329
|
+
foreach (var group in record.groups)
|
|
330
|
+
{
|
|
331
|
+
summary.AppendLine(" " + group.kind + " " + group.name + " sources=" + group.sources.Length + " verts " + group.vertices + " -> " + group.combinedVertices);
|
|
332
|
+
}
|
|
333
|
+
foreach (var warning in record.warnings) summary.AppendLine(" WARNING " + warning);
|
|
334
|
+
return summary.ToString();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/// <summary>
|
|
338
|
+
/// Post-bake checks on the active (combined) scene: every merged lightmapped mesh got a lightmap slot, its UV2 is
|
|
339
|
+
/// inside 0..1, its texel density is close to its sources', LOD clusters are well formed, and the scene uses its
|
|
340
|
+
/// own LightingData. Writes verify.md and returns it.
|
|
341
|
+
/// </summary>
|
|
342
|
+
public static string Verify()
|
|
343
|
+
{
|
|
344
|
+
var scene = SceneManager.GetActiveScene();
|
|
345
|
+
string manifestPath = Path.Combine(ReportFolderFor(scene.path), "combine-manifest.json");
|
|
346
|
+
if (!File.Exists(manifestPath)) throw new InvalidOperationException("No manifest.json for " + scene.path + ". Run Apply first.");
|
|
347
|
+
var manifest = RunRecord.FromJson(File.ReadAllText(manifestPath));
|
|
348
|
+
var report = new StringBuilder("# bt-optimize merge verify — " + scene.path + "\n\n");
|
|
349
|
+
int problems = 0;
|
|
350
|
+
|
|
351
|
+
string lightingData = Lightmapping.lightingDataAsset != null ? AssetDatabase.GetAssetPath(Lightmapping.lightingDataAsset) : "";
|
|
352
|
+
string expectedLightingFolder = Path.ChangeExtension(scene.path, null).Replace('\\', '/') + "/";
|
|
353
|
+
bool ownLighting = lightingData.StartsWith(expectedLightingFolder);
|
|
354
|
+
bool anyLightmapped = manifest.groups.Any(g => g.lightmapped);
|
|
355
|
+
report.AppendLine("- LightingData: `" + (lightingData == "" ? "none" : lightingData) + "` " + (ownLighting ? "(this scene's own bake)" : anyLightmapped ? "**NOT this scene's bake — re-bake**" : ""));
|
|
356
|
+
if (anyLightmapped && !ownLighting) problems++;
|
|
357
|
+
report.AppendLine("\n| Merged object | Check | Result |\n|---|---|---|");
|
|
358
|
+
|
|
359
|
+
foreach (var group in manifest.groups)
|
|
360
|
+
{
|
|
361
|
+
var root = FindByPath(scene, group.combinedPath);
|
|
362
|
+
if (root == null) { report.AppendLine("| " + group.name + " | exists | **missing** |"); problems++; continue; }
|
|
363
|
+
var renderers = root.GetComponentsInChildren<MeshRenderer>();
|
|
364
|
+
foreach (var renderer in renderers)
|
|
365
|
+
{
|
|
366
|
+
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
|
|
367
|
+
bool wantsLightmap = IsLightmapped(renderer);
|
|
368
|
+
if (wantsLightmap)
|
|
369
|
+
{
|
|
370
|
+
bool hasSlot = renderer.lightmapIndex >= 0 && renderer.lightmapIndex < 65534;
|
|
371
|
+
if (!hasSlot) problems++;
|
|
372
|
+
report.AppendLine("| " + renderer.name + " | lightmap slot | " + (hasSlot ? "index " + renderer.lightmapIndex : "**none — bake again**") + " |");
|
|
373
|
+
var uvs = new List<Vector2>();
|
|
374
|
+
mesh.GetUVs(1, uvs);
|
|
375
|
+
bool inRange = uvs.Count > 0 && uvs.All(uv => uv.x >= -0.0001f && uv.y >= -0.0001f && uv.x <= 1.0001f && uv.y <= 1.0001f);
|
|
376
|
+
if (!inRange) problems++;
|
|
377
|
+
report.AppendLine("| " + renderer.name + " | UV2 inside 0..1 | " + (inRange ? "yes" : "**no**") + " |");
|
|
378
|
+
if (hasSlot && group.densityBefore > 0f && renderer == renderers[0])
|
|
379
|
+
{
|
|
380
|
+
float density = TexelDensity(renderer);
|
|
381
|
+
bool close = density >= group.densityBefore * 0.8f;
|
|
382
|
+
if (!close) problems++;
|
|
383
|
+
report.AppendLine("| " + renderer.name + " | texels/m (sources " + group.densityBefore.ToString("0.0") + ") | " + density.ToString("0.0") + (close ? "" : " **too low**") + " |");
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
var lodGroup = root.GetComponent<LODGroup>();
|
|
388
|
+
if (lodGroup != null)
|
|
389
|
+
{
|
|
390
|
+
var lods = lodGroup.GetLODs();
|
|
391
|
+
bool monotonic = true;
|
|
392
|
+
for (int i = 1; i < lods.Length; i++) monotonic &= lods[i].screenRelativeTransitionHeight < lods[i - 1].screenRelativeTransitionHeight;
|
|
393
|
+
bool onePerLevel = lods.All(lod => lod.renderers.Length == 1 && lod.renderers[0] != null);
|
|
394
|
+
if (!monotonic || !onePerLevel) problems++;
|
|
395
|
+
report.AppendLine("| " + root.name + " | LOD levels | " + lods.Length + " levels, transitions " + string.Join(" / ", lods.Select(l => l.screenRelativeTransitionHeight.ToString("0.###")))
|
|
396
|
+
+ (monotonic && onePerLevel ? "" : " **malformed**") + " |");
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
report.AppendLine("\nproblems=" + problems);
|
|
400
|
+
File.WriteAllText(Path.Combine(ReportFolderFor(scene.path), "combine-verify.md"), report.ToString());
|
|
401
|
+
return report.ToString();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/// <summary>
|
|
405
|
+
/// QA: lists the world positions of the largest merges in the active (combined) scene — LOD clusters first — as
|
|
406
|
+
/// "name|x|y|z|size" lines, so the skill can point the camera at them in both scenes.
|
|
407
|
+
/// </summary>
|
|
408
|
+
public static string QaPoints(int count)
|
|
409
|
+
{
|
|
410
|
+
var scene = SceneManager.GetActiveScene();
|
|
411
|
+
var manifest = RunRecord.FromJson(File.ReadAllText(Path.Combine(ReportFolderFor(scene.path), "combine-manifest.json")));
|
|
412
|
+
var lines = new StringBuilder();
|
|
413
|
+
foreach (var group in manifest.groups.OrderByDescending(g => g.kind == "lod").ThenByDescending(g => g.sources.Length).Take(count))
|
|
414
|
+
{
|
|
415
|
+
var root = FindByPath(scene, group.combinedPath);
|
|
416
|
+
if (root == null) continue;
|
|
417
|
+
var bounds = MergedBounds(root.GetComponentsInChildren<Renderer>().Select(r => r.bounds));
|
|
418
|
+
lines.AppendLine(group.name + "|" + bounds.center.x.ToString("F2") + "|" + bounds.center.y.ToString("F2") + "|" + bounds.center.z.ToString("F2") + "|" + Mathf.Max(bounds.size.x, bounds.size.y, bounds.size.z).ToString("F2"));
|
|
419
|
+
}
|
|
420
|
+
return lines.ToString();
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/// <summary>
|
|
424
|
+
/// QA: opens a scene, aims its main camera at a world point from the given distance (Cinemachine disabled so it
|
|
425
|
+
/// stays put), and forces every LOD group to forceLod (-1 = normal switching). Nothing is saved; capture with
|
|
426
|
+
/// capture_game_view --camera <main camera>, then reopen the working copy.
|
|
427
|
+
/// </summary>
|
|
428
|
+
public static string QaView(string scenePath, float x, float y, float z, float distance, int forceLod)
|
|
429
|
+
{
|
|
430
|
+
ThrowIfAnySceneDirty();
|
|
431
|
+
var scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
|
|
432
|
+
var mainCamera = Camera.main;
|
|
433
|
+
if (mainCamera == null) throw new InvalidOperationException("The scene has no camera tagged MainCamera.");
|
|
434
|
+
var brain = mainCamera.GetComponent("CinemachineBrain") as Behaviour;
|
|
435
|
+
if (brain != null) brain.enabled = false;
|
|
436
|
+
var target = new Vector3(x, y, z);
|
|
437
|
+
AddTemporaryColliders(scene, target, distance * 1.5f);
|
|
438
|
+
var position = ClearViewpoint(target, distance);
|
|
439
|
+
mainCamera.transform.SetPositionAndRotation(position, Quaternion.LookRotation(target - position));
|
|
440
|
+
foreach (var lodGroup in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<LODGroup>())) lodGroup.ForceLOD(forceLod);
|
|
441
|
+
return "camera=" + mainCamera.name + " at " + position + " forceLod=" + forceLod;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/// <summary>
|
|
445
|
+
/// Picks a camera position with a clear line of sight to the target: tries the full distance, then half, then a
|
|
446
|
+
/// quarter (so it fits inside rooms), and at each distance directions slightly above, level, then below (below
|
|
447
|
+
/// finds ceilings from inside). Trigger volumes are ignored. Returns the first spot that is not inside geometry and
|
|
448
|
+
/// sees the target unblocked; otherwise the spot whose view reaches furthest towards the target.
|
|
449
|
+
/// </summary>
|
|
450
|
+
private static Vector3 ClearViewpoint(Vector3 target, float distance)
|
|
451
|
+
{
|
|
452
|
+
float[] distanceScales = { 1f, 0.5f, 0.25f };
|
|
453
|
+
float[] elevations = { 0.35f, 0f, -0.35f };
|
|
454
|
+
var best = target + new Vector3(0.7f, 0.45f, -0.7f) * distance;
|
|
455
|
+
float bestReach = -1f;
|
|
456
|
+
foreach (float distanceScale in distanceScales)
|
|
457
|
+
{
|
|
458
|
+
float tryDistance = Mathf.Max(1.5f, distance * distanceScale);
|
|
459
|
+
foreach (float elevation in elevations)
|
|
460
|
+
{
|
|
461
|
+
for (int step = 0; step < 8; step++)
|
|
462
|
+
{
|
|
463
|
+
float angle = step * Mathf.PI / 4f + Mathf.PI / 4f;
|
|
464
|
+
var direction = new Vector3(Mathf.Cos(angle), elevation, Mathf.Sin(angle)).normalized;
|
|
465
|
+
var position = target + direction * tryDistance;
|
|
466
|
+
if (Physics.CheckSphere(position, 0.25f, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Ignore)) continue;
|
|
467
|
+
float reach = Physics.Raycast(position, -direction, out RaycastHit hit, tryDistance, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Ignore)
|
|
468
|
+
? hit.distance / tryDistance : 1f;
|
|
469
|
+
if (reach >= 0.7f) return position;
|
|
470
|
+
if (reach > bestReach) { bestReach = reach; best = position; }
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return best;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/// <summary>
|
|
478
|
+
/// Gives every renderer near the target a temporary MeshCollider (QaView never saves, so they vanish when the scene
|
|
479
|
+
/// is reopened), so line-of-sight tests also see roofs and walls that have no colliders of their own.
|
|
480
|
+
/// </summary>
|
|
481
|
+
private static void AddTemporaryColliders(Scene scene, Vector3 target, float radius)
|
|
482
|
+
{
|
|
483
|
+
foreach (var renderer in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<MeshRenderer>()))
|
|
484
|
+
{
|
|
485
|
+
if (renderer.GetComponent<Collider>() != null || renderer.bounds.SqrDistance(target) > radius * radius) continue;
|
|
486
|
+
var filter = renderer.GetComponent<MeshFilter>();
|
|
487
|
+
if (filter == null || filter.sharedMesh == null) continue;
|
|
488
|
+
renderer.gameObject.AddComponent<MeshCollider>().sharedMesh = filter.sharedMesh;
|
|
489
|
+
}
|
|
490
|
+
Physics.SyncTransforms();
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/// <summary>
|
|
494
|
+
/// After a bake, raises Scale In Lightmap on every merged lightmapped mesh whose measured texel density fell below
|
|
495
|
+
/// its sources' (Unity sizes a merged mesh slightly smaller than the sum of its parts, more so when it holds many
|
|
496
|
+
/// small pieces). The scale grows by exactly the measured shortfall, capped at MaxDensityCorrection, and the scene is
|
|
497
|
+
/// saved. Returns how many meshes changed; when any did, bake again and run Verify.
|
|
498
|
+
/// </summary>
|
|
499
|
+
public static string CorrectDensity()
|
|
500
|
+
{
|
|
501
|
+
var scene = SceneManager.GetActiveScene();
|
|
502
|
+
if (!File.Exists(WorkingCopyMarker(scene.path))) throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy.");
|
|
503
|
+
string manifestPath = Path.Combine(ReportFolderFor(scene.path), "combine-manifest.json");
|
|
504
|
+
var manifest = RunRecord.FromJson(File.ReadAllText(manifestPath));
|
|
505
|
+
var report = new StringBuilder();
|
|
506
|
+
int corrected = 0;
|
|
507
|
+
foreach (var group in manifest.groups.Where(g => g.lightmapped && g.densityBefore > 0f))
|
|
508
|
+
{
|
|
509
|
+
var root = FindByPath(scene, group.combinedPath);
|
|
510
|
+
if (root == null) continue;
|
|
511
|
+
var renderer = root.GetComponentsInChildren<MeshRenderer>().FirstOrDefault(IsLightmapped);
|
|
512
|
+
if (renderer == null) continue;
|
|
513
|
+
float density = TexelDensity(renderer);
|
|
514
|
+
if (density <= 0f) continue;
|
|
515
|
+
float ratio = density / group.densityBefore;
|
|
516
|
+
if (ratio >= DensityTarget) continue;
|
|
517
|
+
float factor = Mathf.Min(1f / ratio, MaxDensityCorrection);
|
|
518
|
+
var serialized = new SerializedObject(renderer);
|
|
519
|
+
var scale = serialized.FindProperty("m_ScaleInLightmap");
|
|
520
|
+
float before = scale.floatValue;
|
|
521
|
+
scale.floatValue = before * factor;
|
|
522
|
+
serialized.ApplyModifiedPropertiesWithoutUndo();
|
|
523
|
+
corrected++;
|
|
524
|
+
report.AppendLine(" " + group.name + " density " + density.ToString("0.0") + "/" + group.densityBefore.ToString("0.0")
|
|
525
|
+
+ " -> Scale In Lightmap " + before.ToString("0.###") + " x" + factor.ToString("0.00") + " = " + scale.floatValue.ToString("0.###"));
|
|
526
|
+
}
|
|
527
|
+
if (corrected > 0)
|
|
528
|
+
{
|
|
529
|
+
EditorSceneManager.MarkSceneDirty(scene);
|
|
530
|
+
EditorSceneManager.SaveScene(scene);
|
|
531
|
+
}
|
|
532
|
+
return "corrected=" + corrected + (corrected > 0 ? " (bake again, then Verify)" : "") + "\n" + report;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/// <summary>Merged meshes keeping less than this share of their sources' texel density get a Scale In Lightmap correction.</summary>
|
|
536
|
+
private const float DensityTarget = 0.95f;
|
|
537
|
+
|
|
538
|
+
/// <summary>Largest Scale In Lightmap multiplier one correction pass applies.</summary>
|
|
539
|
+
private const float MaxDensityCorrection = 2f;
|
|
540
|
+
|
|
541
|
+
// ------------------------------------------------------------------------------------------------ planning
|
|
542
|
+
|
|
543
|
+
/// <summary>Scene-wide facts the planner reads many times.</summary>
|
|
544
|
+
private sealed class SceneContext
|
|
545
|
+
{
|
|
546
|
+
public Scene Scene;
|
|
547
|
+
public Options Options;
|
|
548
|
+
public HashSet<GameObject> Referenced;
|
|
549
|
+
public List<Light> RuntimeLights;
|
|
550
|
+
public Dictionary<Renderer, HashSet<Light>> LightCache = new Dictionary<Renderer, HashSet<Light>>();
|
|
551
|
+
public Dictionary<Renderer, LODGroup> LodOwner = new Dictionary<Renderer, LODGroup>();
|
|
552
|
+
public Dictionary<UnityEngine.Object, int> Ids = new Dictionary<UnityEngine.Object, int>();
|
|
553
|
+
public Dictionary<Shader, string> ShaderGraphVerdicts = new Dictionary<Shader, string>();
|
|
554
|
+
public bool HasLightProbes;
|
|
555
|
+
public int MaxLights;
|
|
556
|
+
public float TexelsPerUnit;
|
|
557
|
+
public int AtlasSize;
|
|
558
|
+
public float LodBias;
|
|
559
|
+
public float FieldOfView;
|
|
560
|
+
|
|
561
|
+
/// <summary>A stable small id for an object within this run (portable across Unity versions).</summary>
|
|
562
|
+
public int IdOf(UnityEngine.Object target)
|
|
563
|
+
{
|
|
564
|
+
if (target == null) return 0;
|
|
565
|
+
if (!Ids.TryGetValue(target, out int id)) { id = Ids.Count + 1; Ids[target] = id; }
|
|
566
|
+
return id;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/// <summary>A set of plain static renderers that will become one mesh.</summary>
|
|
571
|
+
private sealed class StaticGroup
|
|
572
|
+
{
|
|
573
|
+
public List<MeshRenderer> Renderers;
|
|
574
|
+
public Transform Container;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/// <summary>A set of LOD groups that will become one LOD group with one merged renderer per level.</summary>
|
|
578
|
+
private sealed class LodCluster
|
|
579
|
+
{
|
|
580
|
+
public List<LODGroup> Members;
|
|
581
|
+
public Transform Container;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/// <summary>The planner's result: what merges, what stays, and why.</summary>
|
|
585
|
+
private sealed class Plan
|
|
586
|
+
{
|
|
587
|
+
public SceneContext Context;
|
|
588
|
+
public List<StaticGroup> StaticGroups = new List<StaticGroup>();
|
|
589
|
+
public List<LodCluster> LodClusters = new List<LodCluster>();
|
|
590
|
+
public Dictionary<string, List<string>> Kept = new Dictionary<string, List<string>>();
|
|
591
|
+
public List<string> Singletons = new List<string>();
|
|
592
|
+
public List<string> Advisories = new List<string>();
|
|
593
|
+
public int RenderersBefore;
|
|
594
|
+
public int DrawsBefore;
|
|
595
|
+
public int EligibleStatic;
|
|
596
|
+
public int LodGroupsTotal;
|
|
597
|
+
public int LodGroupsEligible;
|
|
598
|
+
|
|
599
|
+
/// <summary>Records that an object stays as it is, for the given reason.</summary>
|
|
600
|
+
public void Keep(string reason, string path)
|
|
601
|
+
{
|
|
602
|
+
if (!Kept.TryGetValue(reason, out var paths)) { paths = new List<string>(); Kept[reason] = paths; }
|
|
603
|
+
paths.Add(path);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/// <summary>Turns the plan into the serializable record (group names, sizes, savings).</summary>
|
|
607
|
+
public RunRecord ToRecord(string mode)
|
|
608
|
+
{
|
|
609
|
+
var record = new RunRecord { scene = Context.Scene.path, mode = mode, renderersBefore = RenderersBefore, drawsBefore = DrawsBefore };
|
|
610
|
+
foreach (var group in StaticGroups) record.groups.Add(DescribeStatic(group, Context));
|
|
611
|
+
foreach (var cluster in LodClusters) record.groups.Add(DescribeLod(cluster, Context));
|
|
612
|
+
record.renderersAfter = RenderersBefore - record.groups.Sum(g => g.sources.Length) + record.groups.Sum(g => Math.Max(1, g.lodLevels));
|
|
613
|
+
record.drawsAfter = DrawsBefore - record.groups.Sum(g => g.drawsBefore - g.drawsAfter);
|
|
614
|
+
record.advisories.AddRange(Advisories);
|
|
615
|
+
return record;
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/// <summary>Builds the human report.</summary>
|
|
619
|
+
public string ToMarkdown(RunRecord record, Options options)
|
|
620
|
+
{
|
|
621
|
+
var text = new StringBuilder();
|
|
622
|
+
text.AppendLine("# bt-optimize merge plan — " + record.scene + "\n");
|
|
623
|
+
text.AppendLine("| | Before | After (planned) |\n|---|---|---|");
|
|
624
|
+
text.AppendLine("| Mesh renderers | " + record.renderersBefore + " | " + record.renderersAfter + " |");
|
|
625
|
+
text.AppendLine("| Draw calls (est., LOD0) | " + record.drawsBefore + " | " + record.drawsAfter + " |");
|
|
626
|
+
text.AppendLine("| Static groups / LOD clusters | | " + StaticGroups.Count + " / " + LodClusters.Count + " |");
|
|
627
|
+
text.AppendLine("\nSettings: cell " + options.cellSize + " m, spread " + options.maxSpread + " m, atlas share " + options.maxAtlasShare
|
|
628
|
+
+ ", max lights per mesh " + Context.MaxLights + ", Shader Graphs " + (options.includeShaderGraphs ? "scanned" : "excluded") + ", LOD clusters " + (options.combineLods ? "on" : "off") + ".\n");
|
|
629
|
+
text.AppendLine("Eligible static renderers: " + EligibleStatic + ". LOD groups: " + LodGroupsEligible + " eligible of " + LodGroupsTotal + ".\n");
|
|
630
|
+
|
|
631
|
+
if (record.advisories.Count > 0)
|
|
632
|
+
{
|
|
633
|
+
text.AppendLine("## Scene advisories\n");
|
|
634
|
+
foreach (var advisory in record.advisories) text.AppendLine("- " + advisory);
|
|
635
|
+
text.AppendLine();
|
|
636
|
+
}
|
|
637
|
+
text.AppendLine("## Planned merges\n");
|
|
638
|
+
text.AppendLine("| Name | Kind | Pieces | Verts | Draws | Probe | Lights | Atlas | Spread | Container |\n|---|---|---|---|---|---|---|---|---|---|");
|
|
639
|
+
foreach (var group in record.groups)
|
|
640
|
+
{
|
|
641
|
+
text.AppendLine("| " + group.name + " | " + group.kind + (group.lodLevels > 0 ? " (" + group.lodLevels + " levels, size x" + group.sizeRatio.ToString("0.0") + ")" : "")
|
|
642
|
+
+ " | " + group.sources.Length + " | " + group.vertices + " | " + group.drawsBefore + " → " + group.drawsAfter + " | " + group.probe
|
|
643
|
+
+ " | " + group.lights + " | " + (group.lightmapped ? group.atlasShare.ToString("0.00") : "probe/none") + " | " + group.spreadMeters.ToString("0.0") + " m | " + group.container + " |");
|
|
644
|
+
}
|
|
645
|
+
text.AppendLine("\n<details><summary>Pieces in each merge</summary>\n");
|
|
646
|
+
foreach (var group in record.groups) text.AppendLine("- **" + group.name + "**: " + string.Join(", ", group.sources));
|
|
647
|
+
text.AppendLine("\n</details>\n");
|
|
648
|
+
|
|
649
|
+
text.AppendLine("## Kept separate — by reason\n\n| Reason | Count | Examples |\n|---|---|---|");
|
|
650
|
+
foreach (var pair in Kept.OrderByDescending(p => p.Value.Count))
|
|
651
|
+
{
|
|
652
|
+
text.AppendLine("| " + pair.Key + " | " + pair.Value.Count + " | " + string.Join(", ", pair.Value.Take(4).Select(p => "`" + p + "`")) + " |");
|
|
653
|
+
}
|
|
654
|
+
text.AppendLine("\n## Eligible but alone (" + Singletons.Count + ")\n");
|
|
655
|
+
text.AppendLine("Nothing compatible close enough to merge with: " + string.Join(", ", Singletons.Take(25).Select(p => "`" + p + "`")) + (Singletons.Count > 25 ? " …" : ""));
|
|
656
|
+
return text.ToString();
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/// <summary>Plans every merge for the scene: per-renderer and per-LOD-group verdicts, grouping, then splitting.</summary>
|
|
661
|
+
private static Plan BuildPlan(Scene scene, Options options)
|
|
662
|
+
{
|
|
663
|
+
var context = CreateContext(scene, options);
|
|
664
|
+
var plan = new Plan { Context = context };
|
|
665
|
+
CountScene(scene, out plan.RenderersBefore, out plan.DrawsBefore);
|
|
666
|
+
AddSceneAdvisories(plan);
|
|
667
|
+
|
|
668
|
+
var allRenderers = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(false)).Where(r => r.enabled).ToList();
|
|
669
|
+
var staticCandidates = new List<MeshRenderer>();
|
|
670
|
+
foreach (var renderer in allRenderers)
|
|
671
|
+
{
|
|
672
|
+
if (context.LodOwner.ContainsKey(renderer)) continue;
|
|
673
|
+
string reason = RendererVerdict(renderer, context, false, 0);
|
|
674
|
+
if (reason == null) staticCandidates.Add(renderer);
|
|
675
|
+
else plan.Keep(reason, PathOf(renderer.transform));
|
|
676
|
+
}
|
|
677
|
+
plan.EligibleStatic = staticCandidates.Count;
|
|
678
|
+
|
|
679
|
+
foreach (var keyed in staticCandidates.GroupBy(renderer => StaticKey(renderer, context)))
|
|
680
|
+
{
|
|
681
|
+
var split = new List<List<MeshRenderer>>();
|
|
682
|
+
SplitRecursively(keyed.ToList(), r => r.bounds, group => StaticGroupNeedsSplit(group, context), split);
|
|
683
|
+
foreach (var group in split)
|
|
684
|
+
{
|
|
685
|
+
if (group.Count < 2) { plan.Singletons.Add(PathOf(group[0].transform)); continue; }
|
|
686
|
+
plan.StaticGroups.Add(new StaticGroup { Renderers = group, Container = FindContainer(group[0].transform.parent, context) });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
var lodGroups = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<LODGroup>(false)).Where(g => g.enabled).ToList();
|
|
691
|
+
plan.LodGroupsTotal = lodGroups.Count;
|
|
692
|
+
var lodCandidates = new List<LODGroup>();
|
|
693
|
+
foreach (var lodGroup in lodGroups)
|
|
694
|
+
{
|
|
695
|
+
string reason = options.combineLods ? LodGroupVerdict(lodGroup, context) : "LOD clusters turned off";
|
|
696
|
+
if (reason == null) lodCandidates.Add(lodGroup);
|
|
697
|
+
else plan.Keep("LOD group: " + reason, PathOf(lodGroup.transform));
|
|
698
|
+
}
|
|
699
|
+
plan.LodGroupsEligible = lodCandidates.Count;
|
|
700
|
+
foreach (var keyed in lodCandidates.GroupBy(lodGroup => LodKey(lodGroup, context)))
|
|
701
|
+
{
|
|
702
|
+
var split = new List<List<LODGroup>>();
|
|
703
|
+
SplitRecursively(keyed.ToList(), LodWorldBounds, cluster => LodClusterNeedsSplit(cluster, context), split);
|
|
704
|
+
foreach (var cluster in split)
|
|
705
|
+
{
|
|
706
|
+
if (cluster.Count < 2) { plan.Singletons.Add(PathOf(cluster[0].transform) + " (LOD)"); continue; }
|
|
707
|
+
plan.LodClusters.Add(new LodCluster { Members = cluster, Container = FindContainer(cluster[0].transform.parent, context) });
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
return plan;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/// <summary>Collects the scene-wide facts: references, runtime lights, LOD ownership, lightmap settings.</summary>
|
|
714
|
+
private static SceneContext CreateContext(Scene scene, Options options)
|
|
715
|
+
{
|
|
716
|
+
var context = new SceneContext { Scene = scene, Options = options };
|
|
717
|
+
context.Referenced = CollectSerializedReferences(scene);
|
|
718
|
+
context.RuntimeLights = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Light>(false))
|
|
719
|
+
.Where(light => light.enabled && light.lightmapBakeType != LightmapBakeType.Baked
|
|
720
|
+
&& (light.type == LightType.Directional || light.type == LightType.Point || light.type == LightType.Spot)).ToList();
|
|
721
|
+
foreach (var lodGroup in scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<LODGroup>(true)))
|
|
722
|
+
foreach (var lod in lodGroup.GetLODs())
|
|
723
|
+
foreach (var renderer in lod.renderers)
|
|
724
|
+
if (renderer != null && !context.LodOwner.ContainsKey(renderer)) context.LodOwner[renderer] = lodGroup;
|
|
725
|
+
context.HasLightProbes = LightmapSettings.lightProbes != null && LightmapSettings.lightProbes.count > 0;
|
|
726
|
+
context.MaxLights = MaxLightsPerMesh();
|
|
727
|
+
LightingSettings lightingSettings = null;
|
|
728
|
+
try { lightingSettings = Lightmapping.lightingSettings; } catch (Exception) { /* no Lighting Settings asset */ }
|
|
729
|
+
context.TexelsPerUnit = lightingSettings != null ? lightingSettings.lightmapResolution : 10f;
|
|
730
|
+
context.AtlasSize = lightingSettings != null ? lightingSettings.lightmapMaxSize : 1024;
|
|
731
|
+
context.LodBias = QualitySettings.lodBias;
|
|
732
|
+
var mainCamera = Camera.main;
|
|
733
|
+
context.FieldOfView = mainCamera != null ? mainCamera.fieldOfView : 60f;
|
|
734
|
+
return context;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/// <summary>Scene-level notes for the report: lighting state and things the user could change to merge more.</summary>
|
|
738
|
+
private static void AddSceneAdvisories(Plan plan)
|
|
739
|
+
{
|
|
740
|
+
var scene = plan.Context.Scene;
|
|
741
|
+
string lightingData = Lightmapping.lightingDataAsset != null ? AssetDatabase.GetAssetPath(Lightmapping.lightingDataAsset) : "";
|
|
742
|
+
string ownFolder = Path.ChangeExtension(scene.path, null).Replace('\\', '/') + "/";
|
|
743
|
+
if (lightingData == "") plan.Advisories.Add("The scene has no baked lighting yet. Merges are planned from the static flags; bake after applying.");
|
|
744
|
+
else if (!lightingData.StartsWith(ownFolder)) plan.Advisories.Add("The scene uses another scene's LightingData (`" + lightingData + "`), typical of a copied scene. The combined copy gets its own bake.");
|
|
745
|
+
if (!plan.Context.HasLightProbes) plan.Advisories.Add("No baked light probes: probe-lit pieces are judged by locality only.");
|
|
746
|
+
if (!ToolkitPacksSourceUVs()) plan.Advisories.Add("**This toolkit build lacks Pack Source Lightmap UVs — Apply will refuse (vertex bloat).**");
|
|
747
|
+
plan.Advisories.Add("Runtime (Realtime/Mixed) lights: " + plan.Context.RuntimeLights.Count + "; BabylonJS applies at most " + plan.Context.MaxLights + " per mesh, so merges never add lights beyond that.");
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/// <summary>
|
|
751
|
+
/// Returns why a renderer must stay as it is, or null when it can be merged. LOD members skip the LOD check, and
|
|
752
|
+
/// their levels above 0 may be probe-lit (they are only seen from a distance).
|
|
753
|
+
/// </summary>
|
|
754
|
+
private static string RendererVerdict(MeshRenderer renderer, SceneContext context, bool lodMember, int lodLevel)
|
|
755
|
+
{
|
|
756
|
+
var options = context.Options;
|
|
757
|
+
var gameObject = renderer.gameObject;
|
|
758
|
+
if (gameObject.name.StartsWith(StaticPrefix) || gameObject.name.StartsWith(LodPrefix)) return "already a merge result";
|
|
759
|
+
var meshFilter = renderer.GetComponent<MeshFilter>();
|
|
760
|
+
if (meshFilter == null || meshFilter.sharedMesh == null || meshFilter.sharedMesh.vertexCount == 0) return "no mesh";
|
|
761
|
+
if (IsExcludedByName(renderer.transform, options)) return "excluded by --exclude";
|
|
762
|
+
if (options.only.Length > 0 && !options.only.Any(path => PathOf(renderer.transform).StartsWith(path.TrimStart('/')))) return "outside --only";
|
|
763
|
+
var flags = GameObjectUtility.GetStaticEditorFlags(gameObject);
|
|
764
|
+
if (!flags.HasFlag(StaticEditorFlags.ContributeGI) && !flags.HasFlag(StaticEditorFlags.BatchingStatic)) return "not marked static (mark it Static if it never moves)";
|
|
765
|
+
if (gameObject.layer >= FirstReservedLayer) return "on a toolkit reserved layer (28-31)";
|
|
766
|
+
var materials = renderer.sharedMaterials;
|
|
767
|
+
if (materials.Length != meshFilter.sharedMesh.subMeshCount) return "material count differs from submesh count";
|
|
768
|
+
if (materials.Any(material => material == null)) return "missing material";
|
|
769
|
+
if (materials.Any(material => material.renderQueue >= FirstTransparentQueue)) return "transparent (sorted per mesh)";
|
|
770
|
+
foreach (var material in materials)
|
|
771
|
+
{
|
|
772
|
+
string shaderReason = ShaderVerdict(material.shader, context);
|
|
773
|
+
if (shaderReason != null) return shaderReason;
|
|
774
|
+
}
|
|
775
|
+
if (renderer.transform.localToWorldMatrix.determinant < 0f && !ToolkitHandlesMirrors()) return "mirrored (negative scale) transform — update CanvasTools.dll to merge it";
|
|
776
|
+
if (renderer.additionalVertexStreams != null) return "vertex-painted (additional vertex streams)";
|
|
777
|
+
if (renderer.GetComponents<MonoBehaviour>().Length > 0) return "has a script component";
|
|
778
|
+
if (context.Referenced.Contains(gameObject)) return "referenced by a script, timeline or component";
|
|
779
|
+
bool probeLit = !IsLightmapped(renderer) && renderer.lightProbeUsage != LightProbeUsage.Off && context.HasLightProbes;
|
|
780
|
+
if (probeLit && !(lodMember && lodLevel > 0)) return "light-probe lit (a merged mesh gets one probe sample)";
|
|
781
|
+
for (var ancestor = renderer.transform; ancestor != null; ancestor = ancestor.parent)
|
|
782
|
+
{
|
|
783
|
+
if (!lodMember && ancestor.GetComponent<LODGroup>() != null) return "inside a LOD group";
|
|
784
|
+
if (ancestor.GetComponent<Animator>() != null || ancestor.GetComponent<Animation>() != null) return "under an Animator / Animation";
|
|
785
|
+
if (ancestor.GetComponent<ParticleSystem>() != null) return "under a particle system";
|
|
786
|
+
if (ancestor.GetComponent<Rigidbody>() != null) return "under a Rigidbody (moves at runtime)";
|
|
787
|
+
}
|
|
788
|
+
return null;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/// <summary>Returns why a whole LOD group must stay as it is, or null when it can join a LOD cluster.</summary>
|
|
792
|
+
private static string LodGroupVerdict(LODGroup lodGroup, SceneContext context)
|
|
793
|
+
{
|
|
794
|
+
var gameObject = lodGroup.gameObject;
|
|
795
|
+
if (gameObject.name.StartsWith(LodPrefix)) return "already a merge result";
|
|
796
|
+
if (IsExcludedByName(lodGroup.transform, context.Options)) return "excluded by --exclude";
|
|
797
|
+
if (gameObject.GetComponents<MonoBehaviour>().Length > 0) return "has a script component";
|
|
798
|
+
if (context.Referenced.Contains(gameObject)) return "referenced by a script, timeline or component";
|
|
799
|
+
if (lodGroup.transform.localToWorldMatrix.determinant < 0f && !ToolkitHandlesMirrors()) return "mirrored (negative scale) transform — update CanvasTools.dll to merge it";
|
|
800
|
+
var lods = lodGroup.GetLODs();
|
|
801
|
+
if (lods.Length < 2) return "fewer than 2 LOD levels";
|
|
802
|
+
var seen = new HashSet<Renderer>();
|
|
803
|
+
for (int level = 0; level < lods.Length; level++)
|
|
804
|
+
{
|
|
805
|
+
var renderers = lods[level].renderers.Where(r => r != null).ToList();
|
|
806
|
+
if (renderers.Count == 0) return "LOD" + level + " is empty";
|
|
807
|
+
foreach (var renderer in renderers)
|
|
808
|
+
{
|
|
809
|
+
if (!seen.Add(renderer)) return "a renderer is used by more than one LOD level";
|
|
810
|
+
if (!(renderer is MeshRenderer meshRenderer)) return "LOD" + level + " has a non-mesh renderer (billboard / skinned)";
|
|
811
|
+
if (!renderer.transform.IsChildOf(lodGroup.transform)) return "a LOD renderer lives outside the group's hierarchy";
|
|
812
|
+
if (!renderer.enabled || !renderer.gameObject.activeInHierarchy) return "LOD" + level + " has a disabled renderer";
|
|
813
|
+
string reason = RendererVerdict(meshRenderer, context, true, level);
|
|
814
|
+
if (reason != null) return "LOD" + level + ": " + reason;
|
|
815
|
+
}
|
|
816
|
+
string signature = RendererSignature(renderers[0], context);
|
|
817
|
+
if (renderers.Any(r => RendererSignature(r, context) != signature)) return "LOD" + level + " renderers have mixed lighting/shadow settings";
|
|
818
|
+
}
|
|
819
|
+
var sharingLevels = Enumerable.Range(1, lods.Length - 1).Where(level => lods[level].renderers.Any(r => r != null && SharesLodZeroLightmap(r))).ToList();
|
|
820
|
+
if (sharingLevels.Count > 0)
|
|
821
|
+
{
|
|
822
|
+
var lodZero = lods[0].renderers.Where(r => r != null).ToList();
|
|
823
|
+
if (lodZero.Count != 1) return "lower LODs share LOD0's lightmap, but LOD0 has several renderers";
|
|
824
|
+
if (!HasLightmapUVs(lodZero[0])) return "lower LODs share LOD0's lightmap, but LOD0 has no lightmap UVs";
|
|
825
|
+
foreach (int level in sharingLevels)
|
|
826
|
+
{
|
|
827
|
+
if (lods[level].renderers.Where(r => r != null).Any(r => !HasLightmapUVs(r))) return "LOD" + level + " shares LOD0's lightmap but has no lightmap UVs";
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/// <summary>
|
|
834
|
+
/// Decides whether a shader is safe to merge. Built-ins on the safe list are; Shader Graphs only with
|
|
835
|
+
/// includeShaderGraphs and only when the graph reads no object-space data and does not move vertices.
|
|
836
|
+
/// </summary>
|
|
837
|
+
private static string ShaderVerdict(Shader shader, SceneContext context)
|
|
838
|
+
{
|
|
839
|
+
if (shader == null) return "missing shader";
|
|
840
|
+
if (SafeShaders.Contains(shader.name) || context.Options.extraShaders.Contains(shader.name)) return null;
|
|
841
|
+
string path = AssetDatabase.GetAssetPath(shader);
|
|
842
|
+
if (!path.EndsWith(".shadergraph")) return "custom shader (not on the safe list; add it with --shaders)";
|
|
843
|
+
if (!context.Options.includeShaderGraphs) return "Shader Graph (may use the pivot or object space: wind, holograms; opt in with --include-shadergraphs)";
|
|
844
|
+
if (!context.ShaderGraphVerdicts.TryGetValue(shader, out string verdict))
|
|
845
|
+
{
|
|
846
|
+
verdict = ScanShaderGraph(File.ReadAllText(path));
|
|
847
|
+
context.ShaderGraphVerdicts[shader] = verdict;
|
|
848
|
+
}
|
|
849
|
+
return verdict;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/// <summary>
|
|
853
|
+
/// Scans a .shadergraph file for what breaks when many objects share one pivot: the Object node, object-space
|
|
854
|
+
/// position / normal / tangent / view nodes, Transform nodes, and anything wired into the vertex Position block.
|
|
855
|
+
/// </summary>
|
|
856
|
+
private static string ScanShaderGraph(string graphText)
|
|
857
|
+
{
|
|
858
|
+
if (graphText.Contains("UnityEditor.ShaderGraph.ObjectNode")) return "Shader Graph uses the Object node (pivot / scale)";
|
|
859
|
+
if (graphText.Contains("UnityEditor.ShaderGraph.TransformationMatrixNode")) return "Shader Graph uses a Transformation Matrix node (model matrix)";
|
|
860
|
+
// A .shadergraph file is a sequence of JSON objects, each closing with "}" on its own line
|
|
861
|
+
var objectSpaceNode = new Regex("\"m_Type\":\\s*\"UnityEditor\\.ShaderGraph\\.(PositionNode|NormalVectorNode|TangentVectorNode|BitangentVectorNode|ViewDirectionNode|ViewVectorNode)\"[\\s\\S]*?\"m_Space\":\\s*0[,\\s]");
|
|
862
|
+
var objectId = new Regex("\"m_ObjectId\":\\s*\"([0-9a-f]+)\"");
|
|
863
|
+
var objectSpaceConversion = new Regex("\"m_Conversion\":\\s*\\{\\s*\"from\":\\s*0\\b|\"m_Conversion\":\\s*\\{[^}]*\"to\":\\s*0\\b");
|
|
864
|
+
foreach (var chunk in graphText.Split(new[] { "\n}\n" }, StringSplitOptions.None))
|
|
865
|
+
{
|
|
866
|
+
if (objectSpaceNode.IsMatch(chunk)) return "Shader Graph reads object-space position/normal";
|
|
867
|
+
// Transform nodes are fine (usually tangent -> world normals) unless they convert from or to Object space (0)
|
|
868
|
+
if (chunk.Contains("\"UnityEditor.ShaderGraph.TransformNode\"") && objectSpaceConversion.IsMatch(chunk)) return "Shader Graph transforms to/from object space";
|
|
869
|
+
if (!chunk.Contains("\"m_SerializedDescriptor\": \"VertexDescription.Position\"")) continue;
|
|
870
|
+
var blockId = objectId.Match(chunk);
|
|
871
|
+
if (blockId.Success && Regex.IsMatch(graphText, "\"m_InputSlot\":\\s*\\{\\s*\"m_Node\":\\s*\\{\\s*\"m_Id\":\\s*\"" + blockId.Groups[1].Value + "\""))
|
|
872
|
+
{
|
|
873
|
+
return "Shader Graph moves vertices (wind / vertex animation)";
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return null;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/// <summary>Everything two renderers must share to live in one mesh, as a comparable string.</summary>
|
|
880
|
+
private static string RendererSignature(Renderer renderer, SceneContext context)
|
|
881
|
+
{
|
|
882
|
+
var serialized = new SerializedObject(renderer);
|
|
883
|
+
var lightmapParameters = serialized.FindProperty("m_LightmapParameters").objectReferenceValue;
|
|
884
|
+
return string.Join("|", new[]
|
|
885
|
+
{
|
|
886
|
+
renderer.shadowCastingMode.ToString(), renderer.receiveShadows.ToString(), IsLightmapped(renderer).ToString(),
|
|
887
|
+
renderer.lightProbeUsage.ToString(), renderer.reflectionProbeUsage.ToString(), context.IdOf(renderer.probeAnchor).ToString(),
|
|
888
|
+
serialized.FindProperty("m_ScaleInLightmap").floatValue.ToString("0.###"), context.IdOf(lightmapParameters).ToString(),
|
|
889
|
+
renderer.renderingLayerMask.ToString(), renderer.gameObject.layer.ToString(), renderer.gameObject.tag,
|
|
890
|
+
((int)GameObjectUtility.GetStaticEditorFlags(renderer.gameObject)).ToString(), renderer.staticShadowCaster.ToString(),
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/// <summary>Grouping key for plain static renderers: container, area cell, reflection probe and renderer settings.</summary>
|
|
895
|
+
private static string StaticKey(MeshRenderer renderer, SceneContext context)
|
|
896
|
+
{
|
|
897
|
+
var center = renderer.bounds.center;
|
|
898
|
+
return context.IdOf(FindContainer(renderer.transform.parent, context)) + "|" + CellOf(center, context.Options.cellSize) + "|"
|
|
899
|
+
+ context.IdOf(DominantReflectionProbe(renderer)) + "|" + RendererSignature(renderer, context);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/// <summary>
|
|
903
|
+
/// Grouping key for LOD groups: container, area cell, reflection probe, level count, fade settings, the exact
|
|
904
|
+
/// transition heights (instances of one prefab share them) and every level's renderer settings.
|
|
905
|
+
/// </summary>
|
|
906
|
+
private static string LodKey(LODGroup lodGroup, SceneContext context)
|
|
907
|
+
{
|
|
908
|
+
var lods = lodGroup.GetLODs();
|
|
909
|
+
var firstRenderer = lods[0].renderers.First(r => r != null);
|
|
910
|
+
var key = new StringBuilder();
|
|
911
|
+
key.Append(context.IdOf(FindContainer(lodGroup.transform.parent, context))).Append('|').Append(CellOf(LodWorldBounds(lodGroup).center, context.Options.cellSize));
|
|
912
|
+
key.Append('|').Append(context.IdOf(DominantReflectionProbe(firstRenderer))).Append('|').Append(lods.Length);
|
|
913
|
+
key.Append('|').Append(lodGroup.fadeMode).Append('|').Append(lodGroup.animateCrossFading);
|
|
914
|
+
key.Append('|').Append(lodGroup.gameObject.layer).Append('|').Append(lodGroup.gameObject.tag);
|
|
915
|
+
foreach (var lod in lods)
|
|
916
|
+
{
|
|
917
|
+
key.Append('|').Append(lod.screenRelativeTransitionHeight.ToString("0.###")).Append('/').Append(lod.fadeTransitionWidth.ToString("0.###"));
|
|
918
|
+
key.Append('/').Append(RendererSignature(lod.renderers.First(r => r != null), context));
|
|
919
|
+
}
|
|
920
|
+
return key.ToString();
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/// <summary>True when a static group breaks a budget and must be halved.</summary>
|
|
924
|
+
private static bool StaticGroupNeedsSplit(List<MeshRenderer> group, SceneContext context)
|
|
925
|
+
{
|
|
926
|
+
if (group.Count < 2) return false;
|
|
927
|
+
var merged = MergedBounds(group.Select(r => r.bounds));
|
|
928
|
+
var largest = group.OrderByDescending(r => r.bounds.size.x * r.bounds.size.z).First().bounds;
|
|
929
|
+
if (merged.size.x > largest.size.x + context.Options.maxSpread || merged.size.z > largest.size.z + context.Options.maxSpread) return true;
|
|
930
|
+
if (!ProbeContains(DominantReflectionProbe(group[0]), merged.center)) return true;
|
|
931
|
+
if (IsLightmapped(group[0]) && LightmapTexels(group, context) > AtlasBudget(context)) return true;
|
|
932
|
+
if (group.Sum(r => r.GetComponent<MeshFilter>().sharedMesh.vertexCount) > MaxVerticesPerMesh) return true;
|
|
933
|
+
return LightsAdded(group, context);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/// <summary>
|
|
937
|
+
/// True when a LOD cluster breaks a budget: its members would switch level too far from their own distance, the
|
|
938
|
+
/// rescaled LOD0 height would leave the valid range, or it breaks the probe, atlas, vertex or light rules.
|
|
939
|
+
/// </summary>
|
|
940
|
+
private static bool LodClusterNeedsSplit(List<LODGroup> cluster, SceneContext context)
|
|
941
|
+
{
|
|
942
|
+
if (cluster.Count < 2) return false;
|
|
943
|
+
var merged = MergedBounds(cluster.Select(LodWorldBounds));
|
|
944
|
+
float clusterSize = Mathf.Max(merged.size.x, merged.size.y, merged.size.z);
|
|
945
|
+
float memberSize = cluster.Average(WorldLodSize);
|
|
946
|
+
float firstTransition = cluster[0].GetLODs()[0].screenRelativeTransitionHeight;
|
|
947
|
+
if (firstTransition * clusterSize / memberSize >= MaxRescaledTransition) return true;
|
|
948
|
+
float switchDistance = memberSize * context.LodBias / (2f * Mathf.Tan(context.FieldOfView * 0.5f * Mathf.Deg2Rad) * Mathf.Max(firstTransition, 0.0001f));
|
|
949
|
+
if (clusterSize * 0.5f > MaxLodSwitchError * switchDistance) return true;
|
|
950
|
+
var levelZero = cluster.SelectMany(g => g.GetLODs()[0].renderers.OfType<MeshRenderer>()).ToList();
|
|
951
|
+
if (!ProbeContains(DominantReflectionProbe(levelZero[0]), merged.center)) return true;
|
|
952
|
+
if (IsLightmapped(levelZero[0]) && LightmapTexels(levelZero, context) > AtlasBudget(context)) return true;
|
|
953
|
+
if (levelZero.Sum(r => r.GetComponent<MeshFilter>().sharedMesh.vertexCount) > MaxVerticesPerMesh) return true;
|
|
954
|
+
return LightsAdded(levelZero, context);
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
/// <summary>
|
|
958
|
+
/// True when the merged set would be reached by more runtime lights than BabylonJS applies per mesh, beyond what
|
|
959
|
+
/// its most-lit piece already had — merging must never cost a piece one of its lights.
|
|
960
|
+
/// </summary>
|
|
961
|
+
private static bool LightsAdded(List<MeshRenderer> renderers, SceneContext context)
|
|
962
|
+
{
|
|
963
|
+
var union = new HashSet<Light>();
|
|
964
|
+
int mostPerPiece = 0;
|
|
965
|
+
foreach (var renderer in renderers)
|
|
966
|
+
{
|
|
967
|
+
var lights = LightsReaching(renderer, context);
|
|
968
|
+
union.UnionWith(lights);
|
|
969
|
+
mostPerPiece = Math.Max(mostPerPiece, lights.Count);
|
|
970
|
+
}
|
|
971
|
+
return union.Count > Math.Max(context.MaxLights, mostPerPiece);
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/// <summary>Halves a set along its longest axis until no part needs splitting.</summary>
|
|
975
|
+
private static void SplitRecursively<T>(List<T> items, Func<T, Bounds> boundsOf, Func<List<T>, bool> needsSplit, List<List<T>> output)
|
|
976
|
+
{
|
|
977
|
+
if (items.Count < 2 || !needsSplit(items))
|
|
978
|
+
{
|
|
979
|
+
output.Add(items);
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
var bounds = MergedBounds(items.Select(boundsOf));
|
|
983
|
+
int axis = bounds.size.x >= bounds.size.y && bounds.size.x >= bounds.size.z ? 0 : (bounds.size.y >= bounds.size.z ? 1 : 2);
|
|
984
|
+
var sorted = items.OrderBy(item => boundsOf(item).center[axis]).ToList();
|
|
985
|
+
int half = sorted.Count / 2;
|
|
986
|
+
SplitRecursively(sorted.Take(half).ToList(), boundsOf, needsSplit, output);
|
|
987
|
+
SplitRecursively(sorted.Skip(half).ToList(), boundsOf, needsSplit, output);
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// ------------------------------------------------------------------------------------------------ describing
|
|
991
|
+
|
|
992
|
+
/// <summary>Sizes and savings of a planned static merge.</summary>
|
|
993
|
+
private static GroupRecord DescribeStatic(StaticGroup group, SceneContext context)
|
|
994
|
+
{
|
|
995
|
+
var first = group.Renderers[0];
|
|
996
|
+
var materials = group.Renderers.SelectMany(r => r.sharedMaterials).Distinct().ToList();
|
|
997
|
+
var merged = MergedBounds(group.Renderers.Select(r => r.bounds));
|
|
998
|
+
var largest = group.Renderers.OrderByDescending(r => r.bounds.size.x * r.bounds.size.z).First().bounds;
|
|
999
|
+
return new GroupRecord
|
|
1000
|
+
{
|
|
1001
|
+
name = StaticPrefix + SafeName(group.Container != null ? group.Container.name : "Scene") + "_" + SafeName(materials[0].name) + (materials.Count > 1 ? "_plus" + (materials.Count - 1) : ""),
|
|
1002
|
+
kind = "static",
|
|
1003
|
+
container = group.Container != null ? PathOf(group.Container) : "(scene root)",
|
|
1004
|
+
probe = ProbeName(DominantReflectionProbe(first)),
|
|
1005
|
+
lightmapped = IsLightmapped(first),
|
|
1006
|
+
vertices = group.Renderers.Sum(r => r.GetComponent<MeshFilter>().sharedMesh.vertexCount),
|
|
1007
|
+
drawsBefore = group.Renderers.Sum(r => r.sharedMaterials.Length),
|
|
1008
|
+
drawsAfter = materials.Count,
|
|
1009
|
+
lights = group.Renderers.SelectMany(r => LightsReaching(r, context)).Distinct().Count(),
|
|
1010
|
+
atlasShare = IsLightmapped(first) ? (float)(LightmapTexels(group.Renderers, context) / ((double)context.AtlasSize * context.AtlasSize)) : 0f,
|
|
1011
|
+
densityBefore = AreaWeightedDensity(group.Renderers),
|
|
1012
|
+
spreadMeters = Mathf.Max(merged.size.x - largest.size.x, merged.size.z - largest.size.z, 0f),
|
|
1013
|
+
sources = group.Renderers.Select(r => PathOf(r.transform)).ToArray(),
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/// <summary>Sizes and savings of a planned LOD cluster (draw calls counted at LOD0).</summary>
|
|
1018
|
+
private static GroupRecord DescribeLod(LodCluster cluster, SceneContext context)
|
|
1019
|
+
{
|
|
1020
|
+
var levelZero = cluster.Members.SelectMany(g => g.GetLODs()[0].renderers.OfType<MeshRenderer>()).ToList();
|
|
1021
|
+
var merged = MergedBounds(cluster.Members.Select(LodWorldBounds));
|
|
1022
|
+
float clusterSize = Mathf.Max(merged.size.x, merged.size.y, merged.size.z);
|
|
1023
|
+
var largest = cluster.Members.Select(LodWorldBounds).OrderByDescending(b => b.size.x * b.size.z).First();
|
|
1024
|
+
return new GroupRecord
|
|
1025
|
+
{
|
|
1026
|
+
name = LodPrefix + SafeName(cluster.Container != null ? cluster.Container.name : "Scene") + "_" + SafeName(cluster.Members[0].name) + "_x" + cluster.Members.Count,
|
|
1027
|
+
kind = "lod",
|
|
1028
|
+
container = cluster.Container != null ? PathOf(cluster.Container) : "(scene root)",
|
|
1029
|
+
probe = ProbeName(DominantReflectionProbe(levelZero[0])),
|
|
1030
|
+
lightmapped = IsLightmapped(levelZero[0]),
|
|
1031
|
+
lodLevels = cluster.Members[0].GetLODs().Length,
|
|
1032
|
+
vertices = levelZero.Sum(r => r.GetComponent<MeshFilter>().sharedMesh.vertexCount),
|
|
1033
|
+
drawsBefore = levelZero.Sum(r => r.sharedMaterials.Length),
|
|
1034
|
+
drawsAfter = levelZero.SelectMany(r => r.sharedMaterials).Distinct().Count(),
|
|
1035
|
+
lights = levelZero.SelectMany(r => LightsReaching(r, context)).Distinct().Count(),
|
|
1036
|
+
atlasShare = IsLightmapped(levelZero[0]) ? (float)(LightmapTexels(levelZero, context) / ((double)context.AtlasSize * context.AtlasSize)) : 0f,
|
|
1037
|
+
densityBefore = AreaWeightedDensity(levelZero),
|
|
1038
|
+
spreadMeters = Mathf.Max(merged.size.x - largest.size.x, merged.size.z - largest.size.z, 0f),
|
|
1039
|
+
sizeRatio = clusterSize / cluster.Members.Average(WorldLodSize),
|
|
1040
|
+
sources = cluster.Members.Select(g => PathOf(g.transform)).ToArray(),
|
|
1041
|
+
};
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// ------------------------------------------------------------------------------------------------ applying
|
|
1045
|
+
|
|
1046
|
+
/// <summary>Merges one static group under its container and strips the sources' render components.</summary>
|
|
1047
|
+
private static void CombineStaticGroup(StaticGroup group, GroupRecord record, string meshFolder, SceneContext context, RunRecord run)
|
|
1048
|
+
{
|
|
1049
|
+
var first = group.Renderers[0];
|
|
1050
|
+
var combinedObject = CreateChild(record.name, group.Container, first.gameObject);
|
|
1051
|
+
var renderer = CombineInto(combinedObject, group.Renderers, record.name, meshFolder, run);
|
|
1052
|
+
if (renderer == null)
|
|
1053
|
+
{
|
|
1054
|
+
UnityEngine.Object.DestroyImmediate(combinedObject);
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
record.combinedPath = PathOf(combinedObject.transform);
|
|
1058
|
+
record.meshAssets = new[] { AssetDatabase.GetAssetPath(renderer.GetComponent<MeshFilter>().sharedMesh) };
|
|
1059
|
+
record.combinedVertices = renderer.GetComponent<MeshFilter>().sharedMesh.vertexCount;
|
|
1060
|
+
foreach (var source in group.Renderers) StripRenderer(source, context);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/// <summary>
|
|
1064
|
+
/// Merges one LOD cluster: every level's renderers become one mesh, held by a new LOD group whose transition
|
|
1065
|
+
/// heights are rescaled by the size ratio so members keep switching at the distance they did before.
|
|
1066
|
+
/// </summary>
|
|
1067
|
+
private static void CombineLodCluster(LodCluster cluster, GroupRecord record, string meshFolder, SceneContext context, RunRecord run)
|
|
1068
|
+
{
|
|
1069
|
+
var template = cluster.Members[0];
|
|
1070
|
+
var templateLods = template.GetLODs();
|
|
1071
|
+
var clusterObject = CreateChild(record.name, cluster.Container, template.gameObject);
|
|
1072
|
+
var newLods = new LOD[templateLods.Length];
|
|
1073
|
+
UvPlacement[] lodZeroPlacements = null;
|
|
1074
|
+
for (int level = 0; level < templateLods.Length; level++)
|
|
1075
|
+
{
|
|
1076
|
+
int currentLevel = level;
|
|
1077
|
+
var levelRenderers = cluster.Members.SelectMany(g => g.GetLODs()[currentLevel].renderers.OfType<MeshRenderer>()).ToList();
|
|
1078
|
+
var levelObject = CreateChild("LOD" + level, clusterObject.transform, levelRenderers[0].gameObject);
|
|
1079
|
+
// Unity gives lower LODs that receive lightmaps without contributing GI the LOD0 lightmap region, so their
|
|
1080
|
+
// UV2 must land in exactly the rectangle each member's LOD0 UV2 was packed into
|
|
1081
|
+
Action<Mesh> beforeSave = null;
|
|
1082
|
+
if (level > 0 && SharesLodZeroLightmap(levelRenderers[0]))
|
|
1083
|
+
{
|
|
1084
|
+
var placements = lodZeroPlacements;
|
|
1085
|
+
beforeSave = mesh => ApplyMemberPlacements(mesh, cluster, currentLevel, placements, record.name, run);
|
|
1086
|
+
}
|
|
1087
|
+
var renderer = CombineInto(levelObject, levelRenderers, record.name + "_LOD" + level, meshFolder, run, beforeSave);
|
|
1088
|
+
if (renderer == null)
|
|
1089
|
+
{
|
|
1090
|
+
UnityEngine.Object.DestroyImmediate(clusterObject);
|
|
1091
|
+
run.warnings.Add(record.name + ": LOD" + level + " produced no mesh; cluster skipped, sources kept.");
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
newLods[level] = new LOD(templateLods[level].screenRelativeTransitionHeight, new Renderer[] { renderer }) { fadeTransitionWidth = templateLods[level].fadeTransitionWidth };
|
|
1095
|
+
if (level == 0) lodZeroPlacements = MeasureMemberPlacements(renderer.GetComponent<MeshFilter>().sharedMesh, cluster);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
var lodGroup = clusterObject.AddComponent<LODGroup>();
|
|
1099
|
+
lodGroup.fadeMode = template.fadeMode;
|
|
1100
|
+
lodGroup.animateCrossFading = template.animateCrossFading;
|
|
1101
|
+
lodGroup.SetLODs(newLods);
|
|
1102
|
+
lodGroup.RecalculateBounds();
|
|
1103
|
+
float sizeRatio = lodGroup.size * MaxAbsScale(clusterObject.transform) / cluster.Members.Average(WorldLodSize);
|
|
1104
|
+
float previous = 1f;
|
|
1105
|
+
for (int level = 0; level < newLods.Length; level++)
|
|
1106
|
+
{
|
|
1107
|
+
float rescaled = Mathf.Min(newLods[level].screenRelativeTransitionHeight * sizeRatio, previous - 0.001f);
|
|
1108
|
+
newLods[level].screenRelativeTransitionHeight = Mathf.Max(rescaled, 0.0001f);
|
|
1109
|
+
previous = newLods[level].screenRelativeTransitionHeight;
|
|
1110
|
+
}
|
|
1111
|
+
lodGroup.SetLODs(newLods);
|
|
1112
|
+
|
|
1113
|
+
record.sizeRatio = sizeRatio;
|
|
1114
|
+
record.combinedPath = PathOf(clusterObject.transform);
|
|
1115
|
+
record.meshAssets = newLods.Select(l => AssetDatabase.GetAssetPath(l.renderers[0].GetComponent<MeshFilter>().sharedMesh)).ToArray();
|
|
1116
|
+
record.combinedVertices = newLods[0].renderers[0].GetComponent<MeshFilter>().sharedMesh.vertexCount;
|
|
1117
|
+
foreach (var member in cluster.Members)
|
|
1118
|
+
{
|
|
1119
|
+
foreach (var renderer in member.GetLODs().SelectMany(l => l.renderers).OfType<MeshRenderer>().ToList()) StripRenderer(renderer, context);
|
|
1120
|
+
var memberObject = member.gameObject;
|
|
1121
|
+
UnityEngine.Object.DestroyImmediate(member);
|
|
1122
|
+
RemoveIfEmptyLeaf(memberObject, context);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/// <summary>
|
|
1127
|
+
/// Runs the toolkit MeshCombiner over the renderers into a mesh asset on the given object, copies the renderer
|
|
1128
|
+
/// settings, and checks the vertex count did not grow. Returns null when nothing was produced.
|
|
1129
|
+
/// </summary>
|
|
1130
|
+
private static MeshRenderer CombineInto(GameObject target, List<MeshRenderer> sources, string meshName, string meshFolder, RunRecord run, Action<Mesh> beforeSave = null)
|
|
1131
|
+
{
|
|
1132
|
+
bool lightmapped = IsLightmapped(sources[0]);
|
|
1133
|
+
UnityMeshSimplifier.MeshCombiner.AlwaysRegenerateSecondaryUVSet = lightmapped;
|
|
1134
|
+
UnityMeshSimplifier.MeshCombiner.AlwaysRegenerateAnimationUVSet = false;
|
|
1135
|
+
UnityMeshSimplifier.MeshCombiner.LightmapUVMode = UnityMeshSimplifier.MeshCombiner.LightmapUnwrapMode.FastMeshCombiner;
|
|
1136
|
+
UnityMeshSimplifier.MeshCombiner.LightmapUVInit = true;
|
|
1137
|
+
UnwrapParam.SetDefaults(out UnityMeshSimplifier.MeshCombiner.LightmapUVParams);
|
|
1138
|
+
|
|
1139
|
+
var warnings = new List<string>();
|
|
1140
|
+
var mesh = UnityMeshSimplifier.MeshCombiner.CombineMeshes(target.transform, sources.ToArray(), out Material[] materials, (stage, current, total) => false, message => warnings.Add(message));
|
|
1141
|
+
foreach (var warning in warnings) run.warnings.Add(meshName + ": " + warning);
|
|
1142
|
+
if (mesh == null)
|
|
1143
|
+
{
|
|
1144
|
+
run.warnings.Add(meshName + ": the combiner produced no mesh; sources kept.");
|
|
1145
|
+
return null;
|
|
1146
|
+
}
|
|
1147
|
+
int sourceVertices = sources.Sum(r => r.GetComponent<MeshFilter>().sharedMesh.vertexCount);
|
|
1148
|
+
if (mesh.vertexCount > sourceVertices * VertexBloatTolerance)
|
|
1149
|
+
{
|
|
1150
|
+
run.warnings.Add(meshName + ": " + sourceVertices + " source vertices became " + mesh.vertexCount + " (re-unwrapped; check the toolkit build).");
|
|
1151
|
+
}
|
|
1152
|
+
mesh.name = meshName;
|
|
1153
|
+
mesh.RecalculateBounds();
|
|
1154
|
+
beforeSave?.Invoke(mesh);
|
|
1155
|
+
string assetPath = AssetDatabase.GenerateUniqueAssetPath(meshFolder + "/" + SafeName(meshName) + ".asset");
|
|
1156
|
+
AssetDatabase.CreateAsset(mesh, assetPath);
|
|
1157
|
+
target.AddComponent<MeshFilter>().sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>(assetPath);
|
|
1158
|
+
var renderer = target.AddComponent<MeshRenderer>();
|
|
1159
|
+
renderer.sharedMaterials = materials;
|
|
1160
|
+
CopyRendererSettings(sources[0], renderer);
|
|
1161
|
+
return renderer;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/// <summary>Where one member's LOD0 lightmap UVs went in the packed LOD0 mesh: packed = source * Scale + Offset.</summary>
|
|
1165
|
+
private struct UvPlacement
|
|
1166
|
+
{
|
|
1167
|
+
public float Scale;
|
|
1168
|
+
public Vector2 Offset;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/// <summary>True when a LOD level borrows LOD0's lightmap: it receives lightmaps but does not contribute GI.</summary>
|
|
1172
|
+
private static bool SharesLodZeroLightmap(Renderer renderer)
|
|
1173
|
+
{
|
|
1174
|
+
return renderer is MeshRenderer meshRenderer && meshRenderer.receiveGI == ReceiveGI.Lightmaps
|
|
1175
|
+
&& !GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI);
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/// <summary>
|
|
1179
|
+
/// Recovers, per cluster member, the uniform scale and offset the packer applied to its LOD0 lightmap UVs, by
|
|
1180
|
+
/// comparing the member's source UV2 bounds with its slice of the packed LOD0 mesh (members are appended in order).
|
|
1181
|
+
/// </summary>
|
|
1182
|
+
private static UvPlacement[] MeasureMemberPlacements(Mesh packedLodZero, LodCluster cluster)
|
|
1183
|
+
{
|
|
1184
|
+
var packed = new List<Vector2>();
|
|
1185
|
+
packedLodZero.GetUVs(1, packed);
|
|
1186
|
+
var placements = new UvPlacement[cluster.Members.Count];
|
|
1187
|
+
int vertexOffset = 0;
|
|
1188
|
+
for (int member = 0; member < cluster.Members.Count; member++)
|
|
1189
|
+
{
|
|
1190
|
+
var sourceMesh = cluster.Members[member].GetLODs()[0].renderers.OfType<MeshRenderer>().First().GetComponent<MeshFilter>().sharedMesh;
|
|
1191
|
+
var source = new List<Vector2>();
|
|
1192
|
+
sourceMesh.GetUVs(1, source);
|
|
1193
|
+
var sourceBounds = UvBounds(source, 0, source.Count);
|
|
1194
|
+
var packedBounds = UvBounds(packed, vertexOffset, source.Count);
|
|
1195
|
+
bool useX = sourceBounds.size.x >= sourceBounds.size.y;
|
|
1196
|
+
float sourceSpan = useX ? sourceBounds.size.x : sourceBounds.size.y;
|
|
1197
|
+
float packedSpan = useX ? packedBounds.size.x : packedBounds.size.y;
|
|
1198
|
+
float scale = sourceSpan > 1e-8f ? packedSpan / sourceSpan : 1f;
|
|
1199
|
+
placements[member] = new UvPlacement { Scale = scale, Offset = packedBounds.min - sourceBounds.min * scale };
|
|
1200
|
+
vertexOffset += source.Count;
|
|
1201
|
+
}
|
|
1202
|
+
return placements;
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/// <summary>
|
|
1206
|
+
/// Moves each member's lower-LOD lightmap UVs (still in the member's own LOD0 lightmap space) into the rectangle
|
|
1207
|
+
/// its LOD0 was packed into, so the merged lower level samples the merged LOD0's lightmap region correctly.
|
|
1208
|
+
/// </summary>
|
|
1209
|
+
private static void ApplyMemberPlacements(Mesh mesh, LodCluster cluster, int level, UvPlacement[] placements, string name, RunRecord run)
|
|
1210
|
+
{
|
|
1211
|
+
var uvs = new List<Vector2>();
|
|
1212
|
+
mesh.GetUVs(1, uvs);
|
|
1213
|
+
int vertexOffset = 0;
|
|
1214
|
+
for (int member = 0; member < cluster.Members.Count; member++)
|
|
1215
|
+
{
|
|
1216
|
+
foreach (var renderer in cluster.Members[member].GetLODs()[level].renderers.OfType<MeshRenderer>())
|
|
1217
|
+
{
|
|
1218
|
+
int count = renderer.GetComponent<MeshFilter>().sharedMesh.vertexCount;
|
|
1219
|
+
for (int vertex = vertexOffset; vertex < vertexOffset + count && vertex < uvs.Count; vertex++)
|
|
1220
|
+
{
|
|
1221
|
+
uvs[vertex] = uvs[vertex] * placements[member].Scale + placements[member].Offset;
|
|
1222
|
+
}
|
|
1223
|
+
vertexOffset += count;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
if (vertexOffset != uvs.Count) run.warnings.Add(name + " LOD" + level + ": shared-lightmap UV remap covered " + vertexOffset + " of " + uvs.Count + " vertices.");
|
|
1227
|
+
mesh.SetUVs(1, uvs);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/// <summary>Bounds of a slice of UVs.</summary>
|
|
1231
|
+
private static Rect UvBounds(List<Vector2> uvs, int start, int count)
|
|
1232
|
+
{
|
|
1233
|
+
var min = new Vector2(float.MaxValue, float.MaxValue);
|
|
1234
|
+
var max = new Vector2(float.MinValue, float.MinValue);
|
|
1235
|
+
for (int i = start; i < start + count && i < uvs.Count; i++)
|
|
1236
|
+
{
|
|
1237
|
+
min = Vector2.Min(min, uvs[i]);
|
|
1238
|
+
max = Vector2.Max(max, uvs[i]);
|
|
1239
|
+
}
|
|
1240
|
+
return Rect.MinMaxRect(min.x, min.y, max.x, max.y);
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/// <summary>Creates a child at the container's origin carrying the template's layer, tag and static flags.</summary>
|
|
1244
|
+
private static GameObject CreateChild(string name, Transform parent, GameObject template)
|
|
1245
|
+
{
|
|
1246
|
+
var child = new GameObject(name);
|
|
1247
|
+
child.transform.SetParent(parent, false);
|
|
1248
|
+
child.layer = template.layer;
|
|
1249
|
+
child.tag = template.tag;
|
|
1250
|
+
GameObjectUtility.SetStaticEditorFlags(child, GameObjectUtility.GetStaticEditorFlags(template));
|
|
1251
|
+
return child;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/// <summary>Copies lighting, shadow, probe and lightmap settings from a source renderer to the merged one.</summary>
|
|
1255
|
+
private static void CopyRendererSettings(MeshRenderer source, MeshRenderer target)
|
|
1256
|
+
{
|
|
1257
|
+
target.shadowCastingMode = source.shadowCastingMode;
|
|
1258
|
+
target.receiveShadows = source.receiveShadows;
|
|
1259
|
+
target.receiveGI = source.receiveGI;
|
|
1260
|
+
target.lightProbeUsage = source.lightProbeUsage;
|
|
1261
|
+
target.reflectionProbeUsage = source.reflectionProbeUsage;
|
|
1262
|
+
target.probeAnchor = source.probeAnchor;
|
|
1263
|
+
target.renderingLayerMask = source.renderingLayerMask;
|
|
1264
|
+
target.motionVectorGenerationMode = source.motionVectorGenerationMode;
|
|
1265
|
+
target.allowOcclusionWhenDynamic = source.allowOcclusionWhenDynamic;
|
|
1266
|
+
target.staticShadowCaster = source.staticShadowCaster;
|
|
1267
|
+
var sourceSettings = new SerializedObject(source);
|
|
1268
|
+
var targetSettings = new SerializedObject(target);
|
|
1269
|
+
targetSettings.FindProperty("m_ScaleInLightmap").floatValue = sourceSettings.FindProperty("m_ScaleInLightmap").floatValue;
|
|
1270
|
+
var stitch = targetSettings.FindProperty("m_StitchLightmapSeams");
|
|
1271
|
+
if (stitch != null) stitch.boolValue = sourceSettings.FindProperty("m_StitchLightmapSeams").boolValue;
|
|
1272
|
+
targetSettings.FindProperty("m_LightmapParameters").objectReferenceValue = sourceSettings.FindProperty("m_LightmapParameters").objectReferenceValue;
|
|
1273
|
+
targetSettings.ApplyModifiedPropertiesWithoutUndo();
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/// <summary>Removes a source's MeshRenderer and MeshFilter (colliders and everything else stay), then tidies empty leaves.</summary>
|
|
1277
|
+
private static void StripRenderer(MeshRenderer source, SceneContext context)
|
|
1278
|
+
{
|
|
1279
|
+
var sourceObject = source.gameObject;
|
|
1280
|
+
var filter = sourceObject.GetComponent<MeshFilter>();
|
|
1281
|
+
UnityEngine.Object.DestroyImmediate(source);
|
|
1282
|
+
if (filter != null) UnityEngine.Object.DestroyImmediate(filter);
|
|
1283
|
+
RemoveIfEmptyLeaf(sourceObject, context);
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
/// <summary>Deletes a GameObject left with only its Transform and no children, unless a prefab or script owns it.</summary>
|
|
1287
|
+
private static void RemoveIfEmptyLeaf(GameObject gameObject, SceneContext context)
|
|
1288
|
+
{
|
|
1289
|
+
if (gameObject == null || gameObject.transform.childCount > 0 || gameObject.GetComponents<Component>().Length > 1) return;
|
|
1290
|
+
if (PrefabUtility.IsPartOfPrefabInstance(gameObject) || context.Referenced.Contains(gameObject)) return;
|
|
1291
|
+
UnityEngine.Object.DestroyImmediate(gameObject);
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
// ------------------------------------------------------------------------------------------------ helpers
|
|
1295
|
+
|
|
1296
|
+
/// <summary>True when the installed toolkit can pack source lightmap UVs (no vertex bloat).</summary>
|
|
1297
|
+
private static bool ToolkitPacksSourceUVs()
|
|
1298
|
+
{
|
|
1299
|
+
return typeof(UnityMeshSimplifier.MeshCombiner).GetMethod("PackSourceLightmapUVs", BindingFlags.NonPublic | BindingFlags.Static) != null;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/// <summary>True when the toolkit's MeshCombiner reverses winding and fixes normals / tangents for mirrored sources.</summary>
|
|
1303
|
+
private static bool ToolkitHandlesMirrors()
|
|
1304
|
+
{
|
|
1305
|
+
return typeof(UnityMeshSimplifier.MeshCombiner).GetProperty("HandlesMirroredTransforms", BindingFlags.Public | BindingFlags.Static) != null;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/// <summary>The scene's maximum lights per material (SceneController.lightingOptions.maximumLights, default 4).</summary>
|
|
1309
|
+
private static int MaxLightsPerMesh()
|
|
1310
|
+
{
|
|
1311
|
+
try { return UnityTools.GetMaxSimultaneousLights(UnityTools.GetDefaultSceneController()); }
|
|
1312
|
+
catch (Exception) { return 4; }
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/// <summary>True when the renderer's mesh has a lightmap UV set (UV2).</summary>
|
|
1316
|
+
private static bool HasLightmapUVs(Renderer renderer)
|
|
1317
|
+
{
|
|
1318
|
+
var filter = renderer.GetComponent<MeshFilter>();
|
|
1319
|
+
return filter != null && filter.sharedMesh != null && filter.sharedMesh.HasVertexAttribute(VertexAttribute.TexCoord1);
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/// <summary>True when the renderer gets its indirect light from lightmaps.</summary>
|
|
1323
|
+
private static bool IsLightmapped(Renderer renderer)
|
|
1324
|
+
{
|
|
1325
|
+
return renderer is MeshRenderer meshRenderer && meshRenderer.receiveGI == ReceiveGI.Lightmaps
|
|
1326
|
+
&& GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI);
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/// <summary>
|
|
1330
|
+
/// The highest ancestor, starting at the given parent, reachable through "inert" transforms (no scripts, no
|
|
1331
|
+
/// animation, not referenced). A merged mesh lives there, so toggling or moving anything above it still applies.
|
|
1332
|
+
/// </summary>
|
|
1333
|
+
private static Transform FindContainer(Transform start, SceneContext context)
|
|
1334
|
+
{
|
|
1335
|
+
if (start == null || !IsInert(start, context)) return start;
|
|
1336
|
+
var container = start;
|
|
1337
|
+
while (container.parent != null && IsInert(container.parent, context)) container = container.parent;
|
|
1338
|
+
return container;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/// <summary>True when nothing at runtime can move, toggle or animate this transform on its own.</summary>
|
|
1342
|
+
private static bool IsInert(Transform node, SceneContext context)
|
|
1343
|
+
{
|
|
1344
|
+
return node.gameObject.activeSelf && !context.Referenced.Contains(node.gameObject)
|
|
1345
|
+
&& node.GetComponents<MonoBehaviour>().Length == 0 && node.GetComponent<Animator>() == null && node.GetComponent<Animation>() == null
|
|
1346
|
+
&& node.GetComponent<UnityEngine.Playables.PlayableDirector>() == null && node.GetComponent<Rigidbody>() == null
|
|
1347
|
+
&& node.GetComponent<LODGroup>() == null && node.GetComponent<ParticleSystem>() == null;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/// <summary>
|
|
1351
|
+
/// Every GameObject that a component in the scene points at through a serialized field (scripts, timeline
|
|
1352
|
+
/// bindings, cameras, constraints…), so nothing a script drives is merged away.
|
|
1353
|
+
/// </summary>
|
|
1354
|
+
private static HashSet<GameObject> CollectSerializedReferences(Scene scene)
|
|
1355
|
+
{
|
|
1356
|
+
var referenced = new HashSet<GameObject>();
|
|
1357
|
+
foreach (var root in scene.GetRootGameObjects())
|
|
1358
|
+
foreach (var component in root.GetComponentsInChildren<Component>(true))
|
|
1359
|
+
{
|
|
1360
|
+
if (component == null || component is Transform || component is MeshFilter || component is Renderer || component is LODGroup) continue;
|
|
1361
|
+
var property = new SerializedObject(component).GetIterator();
|
|
1362
|
+
while (property.Next(true))
|
|
1363
|
+
{
|
|
1364
|
+
if (property.propertyType != SerializedPropertyType.ObjectReference) continue;
|
|
1365
|
+
var value = property.objectReferenceValue;
|
|
1366
|
+
if (value == null || value == component) continue;
|
|
1367
|
+
var target = value as GameObject ?? (value as Component)?.gameObject;
|
|
1368
|
+
if (target != null && target != component.gameObject) referenced.Add(target);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
return referenced;
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/// <summary>The runtime lights whose range reaches the renderer (directional lights reach everything).</summary>
|
|
1375
|
+
private static HashSet<Light> LightsReaching(Renderer renderer, SceneContext context)
|
|
1376
|
+
{
|
|
1377
|
+
if (context.LightCache.TryGetValue(renderer, out var cached)) return cached;
|
|
1378
|
+
var bounds = renderer.bounds;
|
|
1379
|
+
var lights = new HashSet<Light>(context.RuntimeLights.Where(light => light.type == LightType.Directional
|
|
1380
|
+
|| bounds.SqrDistance(light.transform.position) <= light.range * light.range));
|
|
1381
|
+
context.LightCache[renderer] = lights;
|
|
1382
|
+
return lights;
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/// <summary>The reflection probe that contributes most to the renderer, or null when only the skybox does.</summary>
|
|
1386
|
+
private static ReflectionProbe DominantReflectionProbe(Renderer renderer)
|
|
1387
|
+
{
|
|
1388
|
+
var blend = new List<ReflectionProbeBlendInfo>();
|
|
1389
|
+
renderer.GetClosestReflectionProbes(blend);
|
|
1390
|
+
return blend.Count > 0 ? blend.OrderByDescending(info => info.weight).First().probe : null;
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
/// <summary>True when the probe's box holds the point (always true for the skybox).</summary>
|
|
1394
|
+
private static bool ProbeContains(ReflectionProbe probe, Vector3 point)
|
|
1395
|
+
{
|
|
1396
|
+
return probe == null || probe.bounds.Contains(point);
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
/// <summary>The probe's name for reports, or "sky".</summary>
|
|
1400
|
+
private static string ProbeName(ReflectionProbe probe)
|
|
1401
|
+
{
|
|
1402
|
+
return probe != null ? probe.name : "sky";
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
/// <summary>The atlas texels one merged lightmapped mesh may use.</summary>
|
|
1406
|
+
private static double AtlasBudget(SceneContext context)
|
|
1407
|
+
{
|
|
1408
|
+
return (double)context.AtlasSize * context.AtlasSize * context.Options.maxAtlasShare;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/// <summary>Estimated lightmap texels: world area x Scale In Lightmap x resolution squared.</summary>
|
|
1412
|
+
private static double LightmapTexels(IEnumerable<MeshRenderer> renderers, SceneContext context)
|
|
1413
|
+
{
|
|
1414
|
+
double texels = 0;
|
|
1415
|
+
foreach (var renderer in renderers)
|
|
1416
|
+
{
|
|
1417
|
+
float scale = new SerializedObject(renderer).FindProperty("m_ScaleInLightmap").floatValue;
|
|
1418
|
+
texels += WorldSurfaceArea(renderer) * scale * context.TexelsPerUnit * context.TexelsPerUnit;
|
|
1419
|
+
}
|
|
1420
|
+
return texels;
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/// <summary>World-space triangle area of a renderer's mesh, in square meters.</summary>
|
|
1424
|
+
private static double WorldSurfaceArea(Renderer renderer)
|
|
1425
|
+
{
|
|
1426
|
+
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
|
|
1427
|
+
var localToWorld = renderer.transform.localToWorldMatrix;
|
|
1428
|
+
var vertices = mesh.vertices;
|
|
1429
|
+
var triangles = mesh.triangles;
|
|
1430
|
+
double area = 0;
|
|
1431
|
+
for (int i = 0; i + 2 < triangles.Length; i += 3)
|
|
1432
|
+
{
|
|
1433
|
+
var a = localToWorld.MultiplyPoint3x4(vertices[triangles[i]]);
|
|
1434
|
+
var b = localToWorld.MultiplyPoint3x4(vertices[triangles[i + 1]]);
|
|
1435
|
+
var c = localToWorld.MultiplyPoint3x4(vertices[triangles[i + 2]]);
|
|
1436
|
+
area += Vector3.Cross(b - a, c - a).magnitude * 0.5;
|
|
1437
|
+
}
|
|
1438
|
+
return area;
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
/// <summary>Baked lightmap texels per meter of a renderer (0 when it has no lightmap slot yet).</summary>
|
|
1442
|
+
private static float TexelDensity(MeshRenderer renderer)
|
|
1443
|
+
{
|
|
1444
|
+
if (renderer.lightmapIndex < 0 || renderer.lightmapIndex >= LightmapSettings.lightmaps.Length) return 0f;
|
|
1445
|
+
var lightmap = LightmapSettings.lightmaps[renderer.lightmapIndex].lightmapColor;
|
|
1446
|
+
if (lightmap == null) return 0f;
|
|
1447
|
+
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
|
|
1448
|
+
var uvs = new List<Vector2>();
|
|
1449
|
+
mesh.GetUVs(1, uvs);
|
|
1450
|
+
if (uvs.Count == 0) return 0f;
|
|
1451
|
+
var triangles = mesh.triangles;
|
|
1452
|
+
double uvArea = 0;
|
|
1453
|
+
for (int i = 0; i + 2 < triangles.Length; i += 3)
|
|
1454
|
+
{
|
|
1455
|
+
var edgeA = uvs[triangles[i + 1]] - uvs[triangles[i]];
|
|
1456
|
+
var edgeB = uvs[triangles[i + 2]] - uvs[triangles[i]];
|
|
1457
|
+
uvArea += Math.Abs(edgeA.x * edgeB.y - edgeA.y * edgeB.x) * 0.5;
|
|
1458
|
+
}
|
|
1459
|
+
var scaleOffset = renderer.lightmapScaleOffset;
|
|
1460
|
+
double texelArea = uvArea * scaleOffset.x * lightmap.width * scaleOffset.y * lightmap.height;
|
|
1461
|
+
double worldArea = WorldSurfaceArea(renderer);
|
|
1462
|
+
return worldArea > 0 ? (float)Math.Sqrt(texelArea / worldArea) : 0f;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
/// <summary>Area-weighted lightmap density of the sources, recorded before merging for the post-bake check.</summary>
|
|
1466
|
+
private static float AreaWeightedDensity(List<MeshRenderer> renderers)
|
|
1467
|
+
{
|
|
1468
|
+
double weighted = 0, total = 0;
|
|
1469
|
+
foreach (var renderer in renderers)
|
|
1470
|
+
{
|
|
1471
|
+
float density = TexelDensity(renderer);
|
|
1472
|
+
if (density <= 0f) continue;
|
|
1473
|
+
double area = WorldSurfaceArea(renderer);
|
|
1474
|
+
weighted += density * area;
|
|
1475
|
+
total += area;
|
|
1476
|
+
}
|
|
1477
|
+
return total > 0 ? (float)(weighted / total) : 0f;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
/// <summary>The LOD group's world-space bounds (from all its renderers).</summary>
|
|
1481
|
+
private static Bounds LodWorldBounds(LODGroup lodGroup)
|
|
1482
|
+
{
|
|
1483
|
+
return MergedBounds(lodGroup.GetLODs().SelectMany(l => l.renderers).Where(r => r != null).Select(r => r.bounds));
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
/// <summary>The LOD group's size in world units (what Unity's switch rule uses).</summary>
|
|
1487
|
+
private static float WorldLodSize(LODGroup lodGroup)
|
|
1488
|
+
{
|
|
1489
|
+
return Mathf.Max(lodGroup.size * MaxAbsScale(lodGroup.transform), 0.0001f);
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
/// <summary>Largest absolute axis of the transform's world scale.</summary>
|
|
1493
|
+
private static float MaxAbsScale(Transform transform)
|
|
1494
|
+
{
|
|
1495
|
+
var scale = transform.lossyScale;
|
|
1496
|
+
return Mathf.Max(Mathf.Abs(scale.x), Mathf.Abs(scale.y), Mathf.Abs(scale.z));
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
/// <summary>Bounds enclosing all the given bounds.</summary>
|
|
1500
|
+
private static Bounds MergedBounds(IEnumerable<Bounds> all)
|
|
1501
|
+
{
|
|
1502
|
+
bool first = true;
|
|
1503
|
+
var merged = new Bounds();
|
|
1504
|
+
foreach (var bounds in all)
|
|
1505
|
+
{
|
|
1506
|
+
if (first) { merged = bounds; first = false; }
|
|
1507
|
+
else merged.Encapsulate(bounds);
|
|
1508
|
+
}
|
|
1509
|
+
return merged;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/// <summary>The area cell ("patch") a point falls in.</summary>
|
|
1513
|
+
private static string CellOf(Vector3 point, float cellSize)
|
|
1514
|
+
{
|
|
1515
|
+
return Mathf.FloorToInt(point.x / cellSize) + "," + Mathf.FloorToInt(point.z / cellSize);
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
/// <summary>Counts enabled mesh renderers and their submeshes (draw calls, LOD levels above 0 not counted).</summary>
|
|
1519
|
+
private static void CountScene(Scene scene, out int renderers, out int draws)
|
|
1520
|
+
{
|
|
1521
|
+
var hiddenLods = new HashSet<Renderer>(scene.GetRootGameObjects().SelectMany(r => r.GetComponentsInChildren<LODGroup>(false))
|
|
1522
|
+
.SelectMany(g => g.GetLODs().Skip(1)).SelectMany(l => l.renderers).Where(r => r != null));
|
|
1523
|
+
var all = scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<MeshRenderer>(false)).Where(r => r.enabled).ToList();
|
|
1524
|
+
renderers = all.Count;
|
|
1525
|
+
draws = all.Where(r => !hiddenLods.Contains(r)).Sum(r => r.sharedMaterials.Length);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
/// <summary>True when the scene already holds merge results.</summary>
|
|
1529
|
+
private static bool HasCombinedObjects(Scene scene)
|
|
1530
|
+
{
|
|
1531
|
+
return scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Transform>(true))
|
|
1532
|
+
.Any(t => t.name.StartsWith(StaticPrefix) || t.name.StartsWith(LodPrefix));
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
/// <summary>True when the object or an ancestor matches an --exclude entry (exact name, or prefix ending in *).</summary>
|
|
1536
|
+
private static bool IsExcludedByName(Transform transform, Options options)
|
|
1537
|
+
{
|
|
1538
|
+
if (options.exclude.Length == 0) return false;
|
|
1539
|
+
for (var node = transform; node != null; node = node.parent)
|
|
1540
|
+
foreach (string pattern in options.exclude)
|
|
1541
|
+
{
|
|
1542
|
+
if (pattern.EndsWith("*") ? node.name.StartsWith(pattern.TrimEnd('*')) : node.name == pattern) return true;
|
|
1543
|
+
}
|
|
1544
|
+
return false;
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/// <summary>Finds a GameObject in the scene by its slash-separated hierarchy path.</summary>
|
|
1548
|
+
private static GameObject FindByPath(Scene scene, string path)
|
|
1549
|
+
{
|
|
1550
|
+
if (string.IsNullOrEmpty(path)) return null;
|
|
1551
|
+
return scene.GetRootGameObjects().SelectMany(root => root.GetComponentsInChildren<Transform>(true)).FirstOrDefault(t => PathOf(t) == path)?.gameObject;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/// <summary>The slash-separated hierarchy path of a transform.</summary>
|
|
1555
|
+
private static string PathOf(Transform transform)
|
|
1556
|
+
{
|
|
1557
|
+
var parts = new List<string>();
|
|
1558
|
+
for (var node = transform; node != null; node = node.parent) parts.Insert(0, node.name);
|
|
1559
|
+
return string.Join("/", parts);
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
/// <summary>A name safe for asset files and GameObjects.</summary>
|
|
1563
|
+
private static string SafeName(string name)
|
|
1564
|
+
{
|
|
1565
|
+
return Regex.Replace(name, "[^A-Za-z0-9_\\-]", "");
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
/// <summary>Returns the name, numbered if it was already used.</summary>
|
|
1569
|
+
private static string UniqueName(string name, HashSet<string> used)
|
|
1570
|
+
{
|
|
1571
|
+
string candidate = name;
|
|
1572
|
+
for (int suffix = 2; !used.Add(candidate); suffix++) candidate = name + "_" + suffix;
|
|
1573
|
+
return candidate;
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/// <summary>
|
|
1577
|
+
/// Refuses to continue while any open scene has unsaved changes: switching scenes from a script discards them
|
|
1578
|
+
/// without asking, and they may be the user's work.
|
|
1579
|
+
/// </summary>
|
|
1580
|
+
private static void ThrowIfAnySceneDirty()
|
|
1581
|
+
{
|
|
1582
|
+
for (int i = 0; i < SceneManager.sceneCount; i++)
|
|
1583
|
+
{
|
|
1584
|
+
var openScene = SceneManager.GetSceneAt(i);
|
|
1585
|
+
if (openScene.isDirty)
|
|
1586
|
+
{
|
|
1587
|
+
throw new InvalidOperationException("'" + (openScene.path == "" ? openScene.name : openScene.path) + "' has unsaved changes. "
|
|
1588
|
+
+ "Ask the user to save or discard them; bt-optimize never switches scenes over unsaved work.");
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
/// <summary>Marker file written by PrepareCopy; holds the source scene path and proves the scene is a working copy.</summary>
|
|
1594
|
+
private static string WorkingCopyMarker(string scenePath)
|
|
1595
|
+
{
|
|
1596
|
+
return Path.Combine(ReportFolderFor(scenePath), "working-copy.txt");
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
/// <summary>Reads options JSON (empty means defaults).</summary>
|
|
1600
|
+
private static Options ParseOptions(string json)
|
|
1601
|
+
{
|
|
1602
|
+
return string.IsNullOrWhiteSpace(json) ? new Options() : JsonUtility.FromJson<Options>(json);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
/// <summary>Folder for a scene's merged mesh assets: <scene folder>/<scene>_CombinedMeshes.</summary>
|
|
1606
|
+
private static string MeshFolderFor(string scenePath)
|
|
1607
|
+
{
|
|
1608
|
+
return Path.GetDirectoryName(scenePath).Replace('\\', '/') + "/" + Path.GetFileNameWithoutExtension(scenePath) + "_CombinedMeshes";
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
/// <summary>Folder for a scene's reports: <project>/.agents/optimize/<scene>.</summary>
|
|
1612
|
+
private static string ReportFolderFor(string scenePath)
|
|
1613
|
+
{
|
|
1614
|
+
return Path.Combine(Directory.GetParent(Application.dataPath).FullName, ".agents", "optimize", Path.GetFileNameWithoutExtension(scenePath));
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/// <summary>Creates an asset folder and its parents if missing.</summary>
|
|
1618
|
+
private static void EnsureFolder(string folder)
|
|
1619
|
+
{
|
|
1620
|
+
if (AssetDatabase.IsValidFolder(folder)) return;
|
|
1621
|
+
string parent = Path.GetDirectoryName(folder).Replace('\\', '/');
|
|
1622
|
+
EnsureFolder(parent);
|
|
1623
|
+
AssetDatabase.CreateFolder(parent, Path.GetFileName(folder));
|
|
1624
|
+
}
|
|
1625
|
+
}
|