@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,969 @@
|
|
|
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 UnityEditor;
|
|
8
|
+
using UnityEditor.SceneManagement;
|
|
9
|
+
using UnityEngine;
|
|
10
|
+
using UnityEngine.Rendering;
|
|
11
|
+
using UnityEngine.SceneManagement;
|
|
12
|
+
|
|
13
|
+
/// <summary>
|
|
14
|
+
/// bt-optimize engine. Surveys the active scene for everything that costs frame time once it is exported to
|
|
15
|
+
/// BabylonJS (runtime lights, realtime shadows, post-processing, render resolution, probe-lit and non-static
|
|
16
|
+
/// geometry, mirrored transforms, materials and textures), and applies the fixes the skill decides on.
|
|
17
|
+
/// Run every entry point with `unity command run_script --file <this file> --entry BtOptimize.<Method>`.
|
|
18
|
+
/// </summary>
|
|
19
|
+
public static class BtOptimize
|
|
20
|
+
{
|
|
21
|
+
/// <summary>Render queues from here up are transparent.</summary>
|
|
22
|
+
private const int FirstTransparentQueue = 2500;
|
|
23
|
+
|
|
24
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
25
|
+
// Survey
|
|
26
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
/// <summary>
|
|
29
|
+
/// Writes .agents/optimize/<Scene>/survey.md and survey.json for the active scene and returns a short summary.
|
|
30
|
+
/// Read-only: nothing in the scene or project changes.
|
|
31
|
+
/// </summary>
|
|
32
|
+
public static string Survey()
|
|
33
|
+
{
|
|
34
|
+
var scene = SceneManager.GetActiveScene();
|
|
35
|
+
var context = new Context(scene);
|
|
36
|
+
var md = new StringBuilder();
|
|
37
|
+
var json = new Dictionary<string, object>();
|
|
38
|
+
md.AppendLine("# bt-optimize survey — " + scene.name);
|
|
39
|
+
md.AppendLine();
|
|
40
|
+
md.AppendLine("Scene: `" + scene.path + "` ");
|
|
41
|
+
md.AppendLine("Generated: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
|
|
42
|
+
md.AppendLine();
|
|
43
|
+
|
|
44
|
+
SurveyLights(context, md, json);
|
|
45
|
+
SurveyRenderers(context, md, json);
|
|
46
|
+
SurveyPostProcessing(context, md, json);
|
|
47
|
+
SurveyPipeline(md, json);
|
|
48
|
+
SurveyExporter(context, md, json);
|
|
49
|
+
SurveyProbes(context, md, json);
|
|
50
|
+
SurveyMaterials(context, md, json);
|
|
51
|
+
|
|
52
|
+
string folder = ReportFolder(scene);
|
|
53
|
+
File.WriteAllText(Path.Combine(folder, "survey.md"), md.ToString());
|
|
54
|
+
File.WriteAllText(Path.Combine(folder, "survey.json"), ToJson(json, 0));
|
|
55
|
+
return "survey written to " + folder + "\n" + context.Summary.ToString();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// <summary>Every light, how it reaches BabylonJS, and whether anything at runtime drives it.</summary>
|
|
59
|
+
private static void SurveyLights(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
60
|
+
{
|
|
61
|
+
var rows = new List<object>();
|
|
62
|
+
md.AppendLine("## Lights");
|
|
63
|
+
md.AppendLine();
|
|
64
|
+
md.AppendLine("| Light | Type | Mode | Shadows | Range | Intensity | Renderers reached | Driven by |");
|
|
65
|
+
md.AppendLine("|---|---|---|---|---|---|---|---|");
|
|
66
|
+
int realtime = 0, shadowed = 0, baked = 0;
|
|
67
|
+
foreach (var light in context.Lights)
|
|
68
|
+
{
|
|
69
|
+
string mode = light.lightmapBakeType.ToString();
|
|
70
|
+
bool runtime = light.lightmapBakeType != LightmapBakeType.Baked && light.type != LightType.Rectangle && light.type != LightType.Disc;
|
|
71
|
+
if (runtime) realtime++; else baked++;
|
|
72
|
+
if (runtime && light.shadows != LightShadows.None) shadowed++;
|
|
73
|
+
int reached = runtime ? context.Renderers.Count(renderer => Reaches(light, renderer)) : 0;
|
|
74
|
+
string driver = DriverOf(light.gameObject, context);
|
|
75
|
+
md.AppendLine("| " + PathOf(light.transform) + " | " + light.type + " | " + mode + " | " + light.shadows + " | " + light.range.ToString("0.#")
|
|
76
|
+
+ " | " + light.intensity.ToString("0.##") + " | " + reached + " | " + (driver ?? "—") + " |");
|
|
77
|
+
rows.Add(new Dictionary<string, object> {
|
|
78
|
+
{ "path", PathOf(light.transform) }, { "type", light.type.ToString() }, { "mode", mode }, { "runtime", runtime },
|
|
79
|
+
{ "shadows", light.shadows.ToString() }, { "range", light.range }, { "intensity", light.intensity },
|
|
80
|
+
{ "renderersReached", reached }, { "driver", driver ?? "" } });
|
|
81
|
+
}
|
|
82
|
+
md.AppendLine();
|
|
83
|
+
md.AppendLine("Runtime lights (Realtime + Mixed): **" + realtime + "**, casting shadows: **" + shadowed + "**, Baked: " + baked + ".");
|
|
84
|
+
md.AppendLine();
|
|
85
|
+
// Inactive lights are skipped by Tune, but a browser-side script may activate their object (they then cost like any runtime light).
|
|
86
|
+
var inactive = context.All<Light>().Where(light => !light.gameObject.activeInHierarchy && light.lightmapBakeType != LightmapBakeType.Baked).ToList();
|
|
87
|
+
if (inactive.Count > 0)
|
|
88
|
+
{
|
|
89
|
+
md.AppendLine("Inactive runtime lights (a script may switch them on in the browser; check the profile's census): " + inactive.Count);
|
|
90
|
+
foreach (var light in inactive.Take(12)) md.AppendLine("- " + PathOf(light.transform) + " (" + light.type + " " + light.lightmapBakeType + ", range " + light.range.ToString("0.#") + ", driven by " + (WebDriverOf(light.gameObject, context) ?? DriverOf(light.gameObject, context) ?? "—") + ")");
|
|
91
|
+
md.AppendLine();
|
|
92
|
+
}
|
|
93
|
+
context.Summary.AppendLine("lights runtime=" + realtime + " shadowed=" + shadowed + " baked=" + baked);
|
|
94
|
+
json["lights"] = rows;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// <summary>Static flags, GI mode, mirrored transforms and why non-static renderers are not static.</summary>
|
|
98
|
+
private static void SurveyRenderers(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
99
|
+
{
|
|
100
|
+
var renderers = context.Renderers;
|
|
101
|
+
int lightmapped = 0, probeLit = 0, notStatic = 0, mirrored = 0, transparent = 0;
|
|
102
|
+
var probeLitGroups = new Dictionary<string, Group>();
|
|
103
|
+
var nonStaticGroups = new Dictionary<string, Group>();
|
|
104
|
+
var mirroredGroups = new Dictionary<string, Group>();
|
|
105
|
+
foreach (var renderer in renderers)
|
|
106
|
+
{
|
|
107
|
+
var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);
|
|
108
|
+
bool isStatic = flags.HasFlag(StaticEditorFlags.ContributeGI) || flags.HasFlag(StaticEditorFlags.BatchingStatic);
|
|
109
|
+
var lod = renderer.GetComponentInParent<LODGroup>();
|
|
110
|
+
int level = lod != null ? LodLevelOf(lod, renderer) : -1;
|
|
111
|
+
bool receivesLightmaps = renderer is MeshRenderer meshRenderer && meshRenderer.receiveGI == ReceiveGI.Lightmaps;
|
|
112
|
+
// A lower LOD level that receives lightmaps without contributing GI borrows LOD0's lightmap region.
|
|
113
|
+
bool isLightmapped = receivesLightmaps && (flags.HasFlag(StaticEditorFlags.ContributeGI) || level > 0);
|
|
114
|
+
if (renderer.sharedMaterials.Any(material => material != null && material.renderQueue >= FirstTransparentQueue)) transparent++;
|
|
115
|
+
string key = GroupKey(renderer);
|
|
116
|
+
if (isLightmapped) lightmapped++;
|
|
117
|
+
else if (renderer.lightProbeUsage != LightProbeUsage.Off)
|
|
118
|
+
{
|
|
119
|
+
probeLit++;
|
|
120
|
+
if (level <= 0) Add(probeLitGroups, key, renderer, ProbeLitNote(renderer, flags, level));
|
|
121
|
+
}
|
|
122
|
+
if (!isStatic)
|
|
123
|
+
{
|
|
124
|
+
notStatic++;
|
|
125
|
+
Add(nonStaticGroups, key, renderer, DriverOf(renderer.gameObject, context) ?? "nothing found that moves it");
|
|
126
|
+
}
|
|
127
|
+
if (renderer.transform.localToWorldMatrix.determinant < 0f)
|
|
128
|
+
{
|
|
129
|
+
mirrored++;
|
|
130
|
+
var scale = renderer.transform.lossyScale;
|
|
131
|
+
Add(mirroredGroups, key, renderer, "scale " + scale.x.ToString("0.##") + "," + scale.y.ToString("0.##") + "," + scale.z.ToString("0.##"));
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
md.AppendLine("## Renderers");
|
|
135
|
+
md.AppendLine();
|
|
136
|
+
md.AppendLine("Total **" + renderers.Count + "**: lightmapped " + lightmapped + ", probe-lit " + probeLit + ", not static " + notStatic
|
|
137
|
+
+ ", mirrored " + mirrored + ", transparent " + transparent + ".");
|
|
138
|
+
md.AppendLine();
|
|
139
|
+
WriteGroups(md, "Probe-lit (LOD0 / non-LOD) — could be lightmapped", probeLitGroups);
|
|
140
|
+
WriteGroups(md, "Not static — and what moves them", nonStaticGroups);
|
|
141
|
+
WriteGroups(md, "Mirrored (negative scale)", mirroredGroups);
|
|
142
|
+
context.Summary.AppendLine("renderers=" + renderers.Count + " lightmapped=" + lightmapped + " probeLit=" + probeLit + " notStatic=" + notStatic + " mirrored=" + mirrored);
|
|
143
|
+
json["renderers"] = new Dictionary<string, object> {
|
|
144
|
+
{ "total", renderers.Count }, { "lightmapped", lightmapped }, { "probeLit", probeLit }, { "notStatic", notStatic },
|
|
145
|
+
{ "mirrored", mirrored }, { "transparent", transparent },
|
|
146
|
+
{ "probeLitGroups", GroupsToJson(probeLitGroups) }, { "nonStaticGroups", GroupsToJson(nonStaticGroups) },
|
|
147
|
+
{ "mirroredGroups", GroupsToJson(mirroredGroups) } };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/// <summary>Every Volume and its active overrides, plus every camera's anti-aliasing and post-processing flags.</summary>
|
|
151
|
+
private static void SurveyPostProcessing(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
152
|
+
{
|
|
153
|
+
md.AppendLine("## Post-processing and cameras");
|
|
154
|
+
md.AppendLine();
|
|
155
|
+
var volumes = new List<object>();
|
|
156
|
+
foreach (var volume in context.All<Volume>())
|
|
157
|
+
{
|
|
158
|
+
var profile = volume.sharedProfile;
|
|
159
|
+
var overrides = new List<object>();
|
|
160
|
+
md.AppendLine("- Volume `" + PathOf(volume.transform) + "` (" + (volume.isGlobal ? "global" : "local") + ", weight " + volume.weight.ToString("0.##")
|
|
161
|
+
+ ", priority " + volume.priority + ") profile `" + (profile != null ? profile.name : "none") + "`");
|
|
162
|
+
if (profile != null)
|
|
163
|
+
foreach (var component in profile.components)
|
|
164
|
+
{
|
|
165
|
+
if (component == null) continue;
|
|
166
|
+
var parameters = new List<string>();
|
|
167
|
+
foreach (var field in component.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
|
|
168
|
+
{
|
|
169
|
+
if (!(field.GetValue(component) is VolumeParameter parameter) || !parameter.overrideState) continue;
|
|
170
|
+
object value = parameter.GetType().GetProperty("value")?.GetValue(parameter);
|
|
171
|
+
parameters.Add(field.Name + "=" + FormatValue(value));
|
|
172
|
+
}
|
|
173
|
+
md.AppendLine(" - " + component.GetType().Name + (component.active ? "" : " (inactive)") + ": " + string.Join(", ", parameters));
|
|
174
|
+
overrides.Add(new Dictionary<string, object> { { "type", component.GetType().Name }, { "active", component.active }, { "parameters", parameters } });
|
|
175
|
+
}
|
|
176
|
+
volumes.Add(new Dictionary<string, object> { { "path", PathOf(volume.transform) }, { "global", volume.isGlobal }, { "profile", profile != null ? AssetDatabase.GetAssetPath(profile) : "" }, { "overrides", overrides } });
|
|
177
|
+
}
|
|
178
|
+
var cameras = new List<object>();
|
|
179
|
+
foreach (var camera in context.All<Camera>())
|
|
180
|
+
{
|
|
181
|
+
var data = camera.GetComponents<Component>().FirstOrDefault(component => component != null && component.GetType().Name == "UniversalAdditionalCameraData");
|
|
182
|
+
string aa = "", aaQuality = "", post = "";
|
|
183
|
+
if (data != null)
|
|
184
|
+
{
|
|
185
|
+
var serialized = new SerializedObject(data);
|
|
186
|
+
aa = EnumName(serialized.FindProperty("m_Antialiasing"));
|
|
187
|
+
aaQuality = EnumName(serialized.FindProperty("m_AntialiasingQuality"));
|
|
188
|
+
post = serialized.FindProperty("m_RenderPostProcessing")?.boolValue.ToString() ?? "";
|
|
189
|
+
}
|
|
190
|
+
md.AppendLine("- Camera `" + PathOf(camera.transform) + "` enabled=" + camera.isActiveAndEnabled + " AA=" + aa + " (" + aaQuality + ") post=" + post
|
|
191
|
+
+ " HDR=" + camera.allowHDR + " MSAA=" + camera.allowMSAA + " far=" + camera.farClipPlane);
|
|
192
|
+
cameras.Add(new Dictionary<string, object> { { "path", PathOf(camera.transform) }, { "enabled", camera.isActiveAndEnabled }, { "antialiasing", aa }, { "antialiasingQuality", aaQuality }, { "postProcessing", post }, { "far", camera.farClipPlane } });
|
|
193
|
+
}
|
|
194
|
+
md.AppendLine();
|
|
195
|
+
json["volumes"] = volumes;
|
|
196
|
+
json["cameras"] = cameras;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// <summary>The render pipeline asset's resolution, MSAA and shadow settings (read through serialized names).</summary>
|
|
200
|
+
private static void SurveyPipeline(StringBuilder md, Dictionary<string, object> json)
|
|
201
|
+
{
|
|
202
|
+
var pipeline = QualitySettings.renderPipeline != null ? QualitySettings.renderPipeline : GraphicsSettings.defaultRenderPipeline;
|
|
203
|
+
var values = new Dictionary<string, object>();
|
|
204
|
+
md.AppendLine("## Render pipeline asset");
|
|
205
|
+
md.AppendLine();
|
|
206
|
+
if (pipeline == null) { md.AppendLine("Built-in render pipeline."); md.AppendLine(); json["pipeline"] = values; return; }
|
|
207
|
+
values["asset"] = AssetDatabase.GetAssetPath(pipeline);
|
|
208
|
+
var serialized = new SerializedObject(pipeline);
|
|
209
|
+
foreach (var name in new[] { "m_RenderScale", "m_MSAA", "m_MainLightShadowsSupported", "m_MainLightShadowmapResolution", "m_AdditionalLightsRenderingMode",
|
|
210
|
+
"m_AdditionalLightsPerObjectLimit", "m_AdditionalLightShadowsSupported", "m_AdditionalLightsShadowmapResolution", "m_ShadowDistance",
|
|
211
|
+
"m_ShadowCascadeCount", "m_SoftShadowsSupported", "m_SupportsHDR", "m_ReflectionProbeBlending", "m_ReflectionProbeBoxProjection" })
|
|
212
|
+
{
|
|
213
|
+
var property = serialized.FindProperty(name);
|
|
214
|
+
if (property == null) continue;
|
|
215
|
+
values[name] = PropertyValue(property);
|
|
216
|
+
}
|
|
217
|
+
md.AppendLine("`" + values["asset"] + "`: " + string.Join(", ", values.Where(pair => pair.Key != "asset").Select(pair => pair.Key.Substring(2) + "=" + pair.Value)));
|
|
218
|
+
md.AppendLine();
|
|
219
|
+
json["pipeline"] = values;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/// <summary>The toolkit exporter settings that shape runtime cost, and the scene controller's light budget.</summary>
|
|
223
|
+
private static void SurveyExporter(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
224
|
+
{
|
|
225
|
+
var values = new Dictionary<string, object>();
|
|
226
|
+
var info = CanvasToolsInfo.Instance;
|
|
227
|
+
foreach (var name in new[] { "AdaptToDeviceRatio", "GpuRenderingMode", "PerformanceMode", "EnableAntiAliasing", "PreserveDrawBuffer", "EnableStencilBuffer",
|
|
228
|
+
"FreezeStaticMeshes", "ExportMeshInstances", "TextureImageFormat", "TextureImageQuality", "SuperCompressKtx2Lightmaps", "SuperCompressWebpLightmaps",
|
|
229
|
+
"ReflectionProbePower", "ExportFileFormat", "MeshExportSystem" })
|
|
230
|
+
{
|
|
231
|
+
var property = typeof(CanvasToolsInfo).GetProperty(name);
|
|
232
|
+
if (property != null) values[name] = property.GetValue(info);
|
|
233
|
+
}
|
|
234
|
+
try { values["maximumLights"] = UnityTools.GetMaxSimultaneousLights(UnityTools.GetDefaultSceneController()); } catch (Exception) { values["maximumLights"] = 4; }
|
|
235
|
+
md.AppendLine("## Exporter settings (runtime cost)");
|
|
236
|
+
md.AppendLine();
|
|
237
|
+
md.AppendLine(string.Join(", ", values.Select(pair => pair.Key + "=" + pair.Value)));
|
|
238
|
+
md.AppendLine();
|
|
239
|
+
md.AppendLine("AdaptToDeviceRatio 0 = render at device pixels on desktop (4× pixels on a 2× screen); GpuRenderingMode 1/2 = WebGPU snapshot rendering standard/fast.");
|
|
240
|
+
md.AppendLine();
|
|
241
|
+
json["exporter"] = values;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/// <summary>Reflection probes and light probes.</summary>
|
|
245
|
+
private static void SurveyProbes(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
246
|
+
{
|
|
247
|
+
var probes = context.All<ReflectionProbe>().ToList();
|
|
248
|
+
int lightProbes = context.All<LightProbeGroup>().Sum(group => group.probePositions.Length);
|
|
249
|
+
md.AppendLine("## Probes");
|
|
250
|
+
md.AppendLine();
|
|
251
|
+
md.AppendLine("Reflection probes: " + probes.Count + " (" + string.Join(", ", probes.GroupBy(probe => probe.mode + "@" + probe.resolution).Select(group => group.Count() + "× " + group.Key))
|
|
252
|
+
+ "). Light probes: " + lightProbes + ".");
|
|
253
|
+
md.AppendLine();
|
|
254
|
+
json["probes"] = new Dictionary<string, object> { { "reflection", probes.Count }, { "realtimeReflection", probes.Count(probe => probe.mode == ReflectionProbeMode.Realtime) }, { "lightProbes", lightProbes } };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/// <summary>Unique materials and textures the renderers use, and the biggest textures.</summary>
|
|
258
|
+
private static void SurveyMaterials(Context context, StringBuilder md, Dictionary<string, object> json)
|
|
259
|
+
{
|
|
260
|
+
var materials = new HashSet<Material>(context.Renderers.SelectMany(renderer => renderer.sharedMaterials).Where(material => material != null));
|
|
261
|
+
var textures = new HashSet<Texture>();
|
|
262
|
+
foreach (var material in materials)
|
|
263
|
+
foreach (var name in material.GetTexturePropertyNames())
|
|
264
|
+
{
|
|
265
|
+
var texture = material.GetTexture(name);
|
|
266
|
+
if (texture != null) textures.Add(texture);
|
|
267
|
+
}
|
|
268
|
+
long pixels = textures.Sum(texture => (long)texture.width * texture.height);
|
|
269
|
+
var biggest = textures.OrderByDescending(texture => (long)texture.width * texture.height).Take(15).ToList();
|
|
270
|
+
md.AppendLine("## Materials and textures");
|
|
271
|
+
md.AppendLine();
|
|
272
|
+
md.AppendLine("Unique materials: " + materials.Count + " (" + string.Join(", ", materials.GroupBy(material => material.shader != null ? material.shader.name : "none").OrderByDescending(group => group.Count()).Take(8).Select(group => group.Count() + "× " + group.Key))
|
|
273
|
+
+ "). Unique textures: " + textures.Count + ", " + (pixels / 1000000.0).ToString("0") + " Mpx (≈" + (pixels * 4 * 1.33 / 1048576).ToString("0") + " MB uncompressed RGBA).");
|
|
274
|
+
md.AppendLine();
|
|
275
|
+
foreach (var texture in biggest) md.AppendLine("- " + texture.width + "×" + texture.height + " `" + AssetDatabase.GetAssetPath(texture) + "`");
|
|
276
|
+
md.AppendLine();
|
|
277
|
+
context.Summary.AppendLine("materials=" + materials.Count + " textures=" + textures.Count + " texMpx=" + (pixels / 1000000));
|
|
278
|
+
json["materials"] = new Dictionary<string, object> { { "unique", materials.Count }, { "textures", textures.Count }, { "megapixels", pixels / 1000000.0 },
|
|
279
|
+
{ "biggest", biggest.Select(texture => (object)(texture.width + "x" + texture.height + " " + AssetDatabase.GetAssetPath(texture))).ToList() } };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
283
|
+
// Tune — the scene-side fixes, applied to the working copy only
|
|
284
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
285
|
+
|
|
286
|
+
/// <summary>Settings for Tune. Every field has a safe default; the skill passes overrides as JSON.</summary>
|
|
287
|
+
[Serializable]
|
|
288
|
+
public class TuneOptions
|
|
289
|
+
{
|
|
290
|
+
/// <summary>Turn runtime point / spot lights that nothing in the browser drives into Baked lights.</summary>
|
|
291
|
+
public bool bakeLights = true;
|
|
292
|
+
/// <summary>
|
|
293
|
+
/// Also bake lights that cast realtime shadows. Off by default: a shadowed key light reaches past geometry its
|
|
294
|
+
/// shadow map ignores (single-sided back faces, the near plane around its fixture) and the lightmapper does not —
|
|
295
|
+
/// baked, Garden's room lights stayed trapped and the rooms went dark. Kept lights lose only their realtime shadows.
|
|
296
|
+
/// </summary>
|
|
297
|
+
public bool bakeShadowedLights = false;
|
|
298
|
+
/// <summary>Light names (or prefixes ending in *) that stay as they are.</summary>
|
|
299
|
+
public string[] keepLights = new string[0];
|
|
300
|
+
/// <summary>Turn realtime shadows off on point / spot lights that stay runtime (each is a full scene pass per frame, six for a point light).</summary>
|
|
301
|
+
public bool pointSpotShadowsOff = true;
|
|
302
|
+
/// <summary>Mark renderers static when nothing in the browser can move them.</summary>
|
|
303
|
+
public bool markStatic = true;
|
|
304
|
+
/// <summary>Switch static, probe-lit renderers that have lightmap UVs (and no vertex animation) to lightmaps.</summary>
|
|
305
|
+
public bool lightmapProbeLit = true;
|
|
306
|
+
/// <summary>Deactivate motion blur overrides whose intensity is 0 in the profiles this scene uses (a no-op in Unity).</summary>
|
|
307
|
+
public bool fixZeroMotionBlur = true;
|
|
308
|
+
/// <summary>Object names (or prefixes ending in *) whose subtrees Tune never touches.</summary>
|
|
309
|
+
public string[] exclude = new string[0];
|
|
310
|
+
/// <summary>Plan only: report every change without making it (works on any scene, including the source).</summary>
|
|
311
|
+
public bool dryRun = false;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/// <summary>One change Tune made, for the report and for undo.</summary>
|
|
315
|
+
private sealed class Change
|
|
316
|
+
{
|
|
317
|
+
public string Kind, Path, Before, After, Why;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/// <summary>
|
|
321
|
+
/// Applies the scene-side fixes to the active scene, which must be a bt-optimize working copy, saves it and writes
|
|
322
|
+
/// tune.md / tune.json. Lighting must be re-baked afterwards when lights or GI flags changed.
|
|
323
|
+
/// </summary>
|
|
324
|
+
public static string Tune(string optionsJson)
|
|
325
|
+
{
|
|
326
|
+
var options = string.IsNullOrWhiteSpace(optionsJson) ? new TuneOptions() : JsonUtility.FromJson<TuneOptions>(optionsJson);
|
|
327
|
+
var scene = SceneManager.GetActiveScene();
|
|
328
|
+
string folder = ReportFolder(scene);
|
|
329
|
+
if (!options.dryRun && !File.Exists(Path.Combine(folder, "working-copy.txt")))
|
|
330
|
+
throw new InvalidOperationException(scene.path + " is not a bt-optimize working copy. Run BtCombine.PrepareCopy first; Tune never edits a source scene.");
|
|
331
|
+
var context = new Context(scene);
|
|
332
|
+
var changes = new List<Change>();
|
|
333
|
+
var kept = new List<Change>();
|
|
334
|
+
|
|
335
|
+
if (options.bakeLights || options.pointSpotShadowsOff) TuneLights(context, options, changes, kept);
|
|
336
|
+
if (options.markStatic) MarkStatic(context, options, changes, kept);
|
|
337
|
+
if (options.lightmapProbeLit) LightmapProbeLit(context, options, changes, kept);
|
|
338
|
+
if (options.fixZeroMotionBlur) FixZeroMotionBlur(context, changes, options.dryRun);
|
|
339
|
+
|
|
340
|
+
if (!options.dryRun)
|
|
341
|
+
{
|
|
342
|
+
EditorSceneManager.MarkSceneDirty(scene);
|
|
343
|
+
EditorSceneManager.SaveScene(scene);
|
|
344
|
+
AssetDatabase.SaveAssets();
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
var md = new StringBuilder("# bt-optimize tune" + (options.dryRun ? " plan (dry run — nothing changed)" : "") + " — " + scene.path + "\n\n");
|
|
348
|
+
foreach (var kind in changes.Select(change => change.Kind).Distinct())
|
|
349
|
+
{
|
|
350
|
+
var list = changes.Where(change => change.Kind == kind).ToList();
|
|
351
|
+
md.AppendLine("## " + kind + " — " + list.Count + "\n");
|
|
352
|
+
md.AppendLine("| Object | Before | After | Why |\n|---|---|---|---|");
|
|
353
|
+
foreach (var change in list) md.AppendLine("| " + change.Path + " | " + change.Before + " | " + change.After + " | " + change.Why + " |");
|
|
354
|
+
md.AppendLine();
|
|
355
|
+
}
|
|
356
|
+
md.AppendLine("## Left alone — " + kept.Count + "\n");
|
|
357
|
+
md.AppendLine("| Object | Kind | Why |\n|---|---|---|");
|
|
358
|
+
foreach (var change in kept) md.AppendLine("| " + change.Path + " | " + change.Kind + " | " + change.Why + " |");
|
|
359
|
+
string stem = options.dryRun ? "tune-plan" : "tune";
|
|
360
|
+
File.WriteAllText(Path.Combine(folder, stem + ".md"), md.ToString());
|
|
361
|
+
File.WriteAllText(Path.Combine(folder, stem + ".json"), ToJson(new Dictionary<string, object> {
|
|
362
|
+
{ "scene", scene.path },
|
|
363
|
+
{ "changes", changes.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "before", change.Before }, { "after", change.After }, { "why", change.Why } }).ToList() },
|
|
364
|
+
{ "kept", kept.Select(change => (object)new Dictionary<string, object> { { "kind", change.Kind }, { "path", change.Path }, { "why", change.Why } }).ToList() } }, 0));
|
|
365
|
+
|
|
366
|
+
var summary = new StringBuilder("tuned=" + scene.path + "\n");
|
|
367
|
+
foreach (var group in changes.GroupBy(change => change.Kind)) summary.AppendLine(" " + group.Key + ": " + group.Count());
|
|
368
|
+
foreach (var group in kept.GroupBy(change => change.Kind)) summary.AppendLine(" kept " + group.Key + ": " + group.Count());
|
|
369
|
+
summary.AppendLine("needsBake=" + changes.Any(change => change.Kind != "Volume profile"));
|
|
370
|
+
return summary.ToString();
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/// <summary>
|
|
374
|
+
/// Runtime point / spot lights that nothing in the browser drives become Baked: their direct light and shadows move
|
|
375
|
+
/// into the lightmaps (static objects) and light probes (dynamic objects), and they cost nothing per frame. A light a
|
|
376
|
+
/// web-side driver animates stays runtime, with its realtime shadows turned off.
|
|
377
|
+
/// </summary>
|
|
378
|
+
private static void TuneLights(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
|
|
379
|
+
{
|
|
380
|
+
foreach (var light in context.Lights)
|
|
381
|
+
{
|
|
382
|
+
if (light.type != LightType.Point && light.type != LightType.Spot) continue;
|
|
383
|
+
if (light.lightmapBakeType == LightmapBakeType.Baked) continue;
|
|
384
|
+
string path = PathOf(light.transform);
|
|
385
|
+
if (IsExcluded(light.transform, options.exclude) || MatchesName(light.name, options.keepLights)) { kept.Add(new Change { Kind = "light", Path = path, Why = "--keep-lights / --exclude" }); continue; }
|
|
386
|
+
string webDriver = WebDriverOf(light.gameObject, context);
|
|
387
|
+
bool shadowedKeyLight = light.shadows != LightShadows.None && !options.bakeShadowedLights;
|
|
388
|
+
if (options.bakeLights && webDriver == null && !shadowedKeyLight)
|
|
389
|
+
{
|
|
390
|
+
string unityOnly = DriverOf(light.gameObject, context);
|
|
391
|
+
if (!options.dryRun)
|
|
392
|
+
{
|
|
393
|
+
var serialized = new SerializedObject(light);
|
|
394
|
+
serialized.FindProperty("m_Lightmapping").intValue = (int)LightmapBakeType.Baked;
|
|
395
|
+
serialized.ApplyModifiedPropertiesWithoutUndo();
|
|
396
|
+
}
|
|
397
|
+
changes.Add(new Change { Kind = "Light → Baked", Path = path, Before = light.type + " " + light.lightmapBakeType + ", shadows " + light.shadows, After = "Baked",
|
|
398
|
+
Why = "nothing in the browser animates it" + (unityOnly != null ? " (Unity-only: " + unityOnly + ")" : "") });
|
|
399
|
+
FreeFromFixture(light, options, changes);
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
if (options.pointSpotShadowsOff && light.shadows != LightShadows.None)
|
|
403
|
+
{
|
|
404
|
+
changes.Add(new Change { Kind = "Realtime shadows off", Path = path, Before = light.lightmapBakeType + ", shadows " + light.shadows, After = light.lightmapBakeType + ", shadows None",
|
|
405
|
+
Why = (webDriver != null ? "stays runtime (" + webDriver + ")" : "shadowed key light stays runtime so it lights what it lit in Unity (baking it changes occlusion; --bake-shadowed-lights to bake)")
|
|
406
|
+
+ "; each shadowed light re-draws the scene every frame" });
|
|
407
|
+
if (!options.dryRun) { light.shadows = LightShadows.None; EditorUtility.SetDirty(light); }
|
|
408
|
+
continue;
|
|
409
|
+
}
|
|
410
|
+
kept.Add(new Change { Kind = "light", Path = path, Why = "runtime: " + (webDriver ?? "bakeLights off") });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/// <summary>
|
|
415
|
+
/// A light inside its own fixture (a lantern shell around the bulb) is lit fine in real time — the shadow map's near
|
|
416
|
+
/// plane clips the shell — but the lightmapper traces from the bulb with no near plane, so a shadow-casting shell
|
|
417
|
+
/// traps a baked light (Garden: lit floor under each lantern, dark walls and ceiling). The fixture's own renderers
|
|
418
|
+
/// whose bounds hold the light stop casting shadows.
|
|
419
|
+
/// </summary>
|
|
420
|
+
private static void FreeFromFixture(Light light, TuneOptions options, List<Change> changes)
|
|
421
|
+
{
|
|
422
|
+
var fixture = PrefabUtility.GetOutermostPrefabInstanceRoot(light.gameObject);
|
|
423
|
+
var root = fixture != null ? fixture.transform : light.transform.parent;
|
|
424
|
+
if (root == null) return;
|
|
425
|
+
var position = light.transform.position;
|
|
426
|
+
foreach (var renderer in root.GetComponentsInChildren<MeshRenderer>(true))
|
|
427
|
+
{
|
|
428
|
+
if (renderer.shadowCastingMode == ShadowCastingMode.Off || renderer.shadowCastingMode == ShadowCastingMode.ShadowsOnly) continue;
|
|
429
|
+
var bounds = renderer.bounds;
|
|
430
|
+
bounds.Expand(2f * Mathf.Max(0.05f, light.shadowNearPlane));
|
|
431
|
+
if (!bounds.Contains(position)) continue;
|
|
432
|
+
changes.Add(new Change { Kind = "Fixture shadows off", Path = PathOf(renderer.transform), Before = "Cast Shadows " + renderer.shadowCastingMode, After = "Off",
|
|
433
|
+
Why = "holds the baked light " + light.name + "; a shadow-casting shell traps a baked light (realtime shadows clipped it at the near plane)" });
|
|
434
|
+
if (options.dryRun) continue;
|
|
435
|
+
renderer.shadowCastingMode = ShadowCastingMode.Off;
|
|
436
|
+
EditorUtility.SetDirty(renderer);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/// <summary>
|
|
441
|
+
/// Renderers that are not static, but that nothing in the browser can move or toggle, get static flags so the
|
|
442
|
+
/// exporter freezes their world matrices and they can be lightmapped and merged. Objects a script points at directly
|
|
443
|
+
/// stay as they are (the script may move or toggle them in Unity).
|
|
444
|
+
/// </summary>
|
|
445
|
+
private static void MarkStatic(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
|
|
446
|
+
{
|
|
447
|
+
foreach (var renderer in context.Renderers.OfType<MeshRenderer>())
|
|
448
|
+
{
|
|
449
|
+
var gameObject = renderer.gameObject;
|
|
450
|
+
var flags = GameObjectUtility.GetStaticEditorFlags(gameObject);
|
|
451
|
+
if (flags.HasFlag(StaticEditorFlags.ContributeGI) || flags.HasFlag(StaticEditorFlags.BatchingStatic)) continue;
|
|
452
|
+
string path = PathOf(renderer.transform);
|
|
453
|
+
if (IsExcluded(renderer.transform, options.exclude)) { kept.Add(new Change { Kind = "not static", Path = path, Why = "--exclude" }); continue; }
|
|
454
|
+
string webDriver = WebDriverOf(gameObject, context);
|
|
455
|
+
if (webDriver != null) { kept.Add(new Change { Kind = "not static", Path = path, Why = "moves in the browser: " + webDriver }); continue; }
|
|
456
|
+
if (context.Referencers.TryGetValue(gameObject, out var referencers)) { kept.Add(new Change { Kind = "not static", Path = path, Why = "a script points at it: " + string.Join("/", referencers.Distinct().Take(3)) }); continue; }
|
|
457
|
+
if (renderer.GetComponentInParent<ParticleSystem>() != null) { kept.Add(new Change { Kind = "not static", Path = path, Why = "part of a particle system" }); continue; }
|
|
458
|
+
string notSurface = NotAVisibleSurface(renderer);
|
|
459
|
+
if (notSurface != null) { kept.Add(new Change { Kind = "not static", Path = path, Why = notSurface }); continue; }
|
|
460
|
+
|
|
461
|
+
var lod = renderer.GetComponentInParent<LODGroup>();
|
|
462
|
+
int level = lod != null ? LodLevelOf(lod, renderer) : -1;
|
|
463
|
+
bool lightmappable = level <= 0 && HasUV2(renderer) && VertexAnimationOf(renderer) == null && !IsTransparent(renderer);
|
|
464
|
+
var newFlags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.ReflectionProbeStatic;
|
|
465
|
+
if (lightmappable) newFlags |= StaticEditorFlags.ContributeGI;
|
|
466
|
+
var receive = renderer.receiveGI;
|
|
467
|
+
var newReceive = lightmappable || (level > 0 && HasUV2(renderer) && LodZeroIsLightmapped(lod)) ? ReceiveGI.Lightmaps : ReceiveGI.LightProbes;
|
|
468
|
+
if (!options.dryRun)
|
|
469
|
+
{
|
|
470
|
+
GameObjectUtility.SetStaticEditorFlags(gameObject, newFlags);
|
|
471
|
+
renderer.receiveGI = newReceive;
|
|
472
|
+
EditorUtility.SetDirty(renderer);
|
|
473
|
+
}
|
|
474
|
+
changes.Add(new Change { Kind = "Marked static", Path = path, Before = "not static, " + receive, After = (lightmappable ? "static + ContributeGI, " : "static, ") + newReceive,
|
|
475
|
+
Why = "nothing in the browser moves it" + (DriverOf(gameObject, context) is string unityOnly ? " (Unity-only: " + unityOnly + ")" : "") });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/// <summary>
|
|
480
|
+
/// Static renderers that are light-probe lit although they have lightmap UVs and no vertex animation switch to
|
|
481
|
+
/// lightmaps (LOD0 contributes GI; lower levels borrow LOD0's lightmap). Lightmapped renderers can be merged; a
|
|
482
|
+
/// merged probe-lit mesh would get one probe sample for its whole area.
|
|
483
|
+
/// </summary>
|
|
484
|
+
private static void LightmapProbeLit(Context context, TuneOptions options, List<Change> changes, List<Change> kept)
|
|
485
|
+
{
|
|
486
|
+
foreach (var renderer in context.Renderers.OfType<MeshRenderer>())
|
|
487
|
+
{
|
|
488
|
+
var flags = GameObjectUtility.GetStaticEditorFlags(renderer.gameObject);
|
|
489
|
+
if (!flags.HasFlag(StaticEditorFlags.BatchingStatic) && !flags.HasFlag(StaticEditorFlags.ContributeGI)) continue;
|
|
490
|
+
var lod = renderer.GetComponentInParent<LODGroup>();
|
|
491
|
+
int level = lod != null ? LodLevelOf(lod, renderer) : -1;
|
|
492
|
+
if (level > 0) continue;
|
|
493
|
+
bool lightmapped = renderer.receiveGI == ReceiveGI.Lightmaps && flags.HasFlag(StaticEditorFlags.ContributeGI);
|
|
494
|
+
if (lightmapped || renderer.lightProbeUsage == LightProbeUsage.Off) continue;
|
|
495
|
+
string path = PathOf(renderer.transform);
|
|
496
|
+
if (IsExcluded(renderer.transform, options.exclude)) continue;
|
|
497
|
+
string reason = NotAVisibleSurface(renderer) ?? (!HasUV2(renderer) ? "no lightmap UVs (UV2)" : VertexAnimationOf(renderer) ?? (IsTransparent(renderer) ? "transparent" : null));
|
|
498
|
+
if (reason != null) { kept.Add(new Change { Kind = "probe-lit", Path = path, Why = reason }); continue; }
|
|
499
|
+
string before = (flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI, " : "no ContributeGI, ") + renderer.receiveGI;
|
|
500
|
+
if (!options.dryRun)
|
|
501
|
+
{
|
|
502
|
+
GameObjectUtility.SetStaticEditorFlags(renderer.gameObject, flags | StaticEditorFlags.ContributeGI);
|
|
503
|
+
renderer.receiveGI = ReceiveGI.Lightmaps;
|
|
504
|
+
EditorUtility.SetDirty(renderer);
|
|
505
|
+
}
|
|
506
|
+
int lowerLevels = 0;
|
|
507
|
+
if (lod != null)
|
|
508
|
+
{
|
|
509
|
+
var lods = lod.GetLODs();
|
|
510
|
+
for (int i = 1; i < lods.Length; i++)
|
|
511
|
+
foreach (var lower in lods[i].renderers.OfType<MeshRenderer>())
|
|
512
|
+
{
|
|
513
|
+
if (!HasUV2(lower)) continue;
|
|
514
|
+
lowerLevels++;
|
|
515
|
+
if (options.dryRun) continue;
|
|
516
|
+
GameObjectUtility.SetStaticEditorFlags(lower.gameObject, GameObjectUtility.GetStaticEditorFlags(lower.gameObject) & ~StaticEditorFlags.ContributeGI | StaticEditorFlags.BatchingStatic);
|
|
517
|
+
lower.receiveGI = ReceiveGI.Lightmaps;
|
|
518
|
+
EditorUtility.SetDirty(lower);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
changes.Add(new Change { Kind = "Probe-lit → lightmapped", Path = path, Before = before, After = "ContributeGI, Lightmaps" + (lowerLevels > 0 ? " (+" + lowerLevels + " lower LOD renderers share LOD0's lightmap)" : ""),
|
|
522
|
+
Why = "static with lightmap UVs; lightmapped meshes can merge" });
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/// <summary>
|
|
527
|
+
/// A motion blur override with intensity 0 does nothing in Unity (MotionBlur.IsActive() is false), but older
|
|
528
|
+
/// toolkit runtimes still build a motion blur post-process and the buffers it needs. Deactivating the override
|
|
529
|
+
/// changes nothing in Unity. The profile is a project asset: the change is recorded for undo.
|
|
530
|
+
/// </summary>
|
|
531
|
+
private static void FixZeroMotionBlur(Context context, List<Change> changes, bool dryRun)
|
|
532
|
+
{
|
|
533
|
+
var profiles = new HashSet<VolumeProfile>(context.All<Volume>().Select(volume => volume.sharedProfile).Where(profile => profile != null));
|
|
534
|
+
var manager = VolumeManager.instance;
|
|
535
|
+
foreach (var name in new[] { "globalDefaultProfile", "qualityDefaultProfile" })
|
|
536
|
+
if (typeof(VolumeManager).GetProperty(name)?.GetValue(manager) is VolumeProfile profile) profiles.Add(profile);
|
|
537
|
+
foreach (var profile in profiles)
|
|
538
|
+
foreach (var component in profile.components)
|
|
539
|
+
{
|
|
540
|
+
if (component == null || !component.active || component.GetType().Name != "MotionBlur") continue;
|
|
541
|
+
var field = component.GetType().GetField("intensity");
|
|
542
|
+
if (!(field?.GetValue(component) is VolumeParameter parameter)) continue;
|
|
543
|
+
float intensity = Convert.ToSingle(parameter.GetType().GetProperty("value").GetValue(parameter));
|
|
544
|
+
if (intensity > 0f) continue;
|
|
545
|
+
if (!dryRun)
|
|
546
|
+
{
|
|
547
|
+
component.active = false;
|
|
548
|
+
EditorUtility.SetDirty(component);
|
|
549
|
+
EditorUtility.SetDirty(profile);
|
|
550
|
+
}
|
|
551
|
+
changes.Add(new Change { Kind = "Volume profile", Path = AssetDatabase.GetAssetPath(profile) + " MotionBlur", Before = "active, intensity 0", After = "inactive",
|
|
552
|
+
Why = "intensity 0 is off in Unity; the browser still built the effect (project asset — undo: re-tick the override)" });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/// <summary>
|
|
557
|
+
/// Opens the scene (discarding nothing: refuses when the open scene has unsaved changes) and places a capture camera
|
|
558
|
+
/// named "BtOptimizePoseCamera" at a pose recorded by the browser profiler (toolkit scenes keep Unity's coordinates),
|
|
559
|
+
/// copying the main camera's settings and URP data so post-processing matches. Capture it with
|
|
560
|
+
/// `capture_game_view --camera BtOptimizePoseCamera`. The camera is never saved: reopening the scene removes it.
|
|
561
|
+
/// </summary>
|
|
562
|
+
public static string PoseView(string scenePath, float px, float py, float pz, float qx, float qy, float qz, float qw, float verticalFovRadians)
|
|
563
|
+
{
|
|
564
|
+
var active = SceneManager.GetActiveScene();
|
|
565
|
+
if (active.path != scenePath)
|
|
566
|
+
{
|
|
567
|
+
// The only unsaved change PoseView allows itself to discard is its own pose camera.
|
|
568
|
+
bool onlyPoseCamera = active.GetRootGameObjects().Any(root => root.name == "BtOptimizePoseCamera");
|
|
569
|
+
if (active.isDirty && !onlyPoseCamera) throw new InvalidOperationException("'" + active.path + "' has unsaved changes; save or discard them first.");
|
|
570
|
+
EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
|
|
571
|
+
}
|
|
572
|
+
var scene = SceneManager.GetActiveScene();
|
|
573
|
+
var existing = scene.GetRootGameObjects().FirstOrDefault(root => root.name == "BtOptimizePoseCamera");
|
|
574
|
+
if (existing != null) UnityEngine.Object.DestroyImmediate(existing);
|
|
575
|
+
var main = Camera.main;
|
|
576
|
+
var go = new GameObject("BtOptimizePoseCamera");
|
|
577
|
+
var camera = go.AddComponent<Camera>();
|
|
578
|
+
if (main != null)
|
|
579
|
+
{
|
|
580
|
+
camera.CopyFrom(main);
|
|
581
|
+
var mainData = main.GetComponents<Component>().FirstOrDefault(c => c != null && c.GetType().Name == "UniversalAdditionalCameraData");
|
|
582
|
+
if (mainData != null)
|
|
583
|
+
{
|
|
584
|
+
var data = go.GetComponent(mainData.GetType()) ?? go.AddComponent(mainData.GetType());
|
|
585
|
+
EditorUtility.CopySerialized(mainData, data);
|
|
586
|
+
}
|
|
587
|
+
main.enabled = false;
|
|
588
|
+
}
|
|
589
|
+
go.transform.SetPositionAndRotation(new Vector3(px, py, pz), new Quaternion(qx, qy, qz, qw));
|
|
590
|
+
camera.fieldOfView = verticalFovRadians * Mathf.Rad2Deg;
|
|
591
|
+
camera.enabled = true;
|
|
592
|
+
return "pose camera at " + go.transform.position.ToString("F2") + " fov " + camera.fieldOfView.ToString("F1") + " in " + scene.path;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/// <summary>
|
|
596
|
+
/// Opt-in, project-wide exporter settings (they change every scene's export). `textures`: "ktx2" (KTX2 / UASTC:
|
|
597
|
+
/// ~4-8x less GPU memory, slower export) or "keep"; `resolution`: "css" (render at CSS pixels on desktop - a quarter
|
|
598
|
+
/// of the pixels on a 2x screen; helps only a GPU-bound scene) or "keep". Previous values are appended to
|
|
599
|
+
/// .agents/optimize/exporter-settings-undo.txt.
|
|
600
|
+
/// </summary>
|
|
601
|
+
public static string ExporterSettings(string textures, string resolution)
|
|
602
|
+
{
|
|
603
|
+
var info = CanvasToolsInfo.Instance;
|
|
604
|
+
var log = new StringBuilder();
|
|
605
|
+
if (textures == "ktx2" && info.TextureImageFormat != 3)
|
|
606
|
+
{
|
|
607
|
+
log.AppendLine("TextureImageFormat " + info.TextureImageFormat + " -> 3 (KTX2)");
|
|
608
|
+
info.TextureImageFormat = 3;
|
|
609
|
+
}
|
|
610
|
+
if (resolution == "css" && info.AdaptToDeviceRatio != -1)
|
|
611
|
+
{
|
|
612
|
+
log.AppendLine("AdaptToDeviceRatio " + info.AdaptToDeviceRatio + " -> -1 (CSS pixels)");
|
|
613
|
+
info.AdaptToDeviceRatio = -1;
|
|
614
|
+
}
|
|
615
|
+
if (log.Length == 0) return "exporter settings unchanged";
|
|
616
|
+
CanvasToolsInfo.SaveSettings();
|
|
617
|
+
string folder = Path.Combine(Path.GetDirectoryName(Application.dataPath), ".agents", "optimize");
|
|
618
|
+
Directory.CreateDirectory(folder);
|
|
619
|
+
File.AppendAllText(Path.Combine(folder, "exporter-settings-undo.txt"), DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "\n" + log);
|
|
620
|
+
return log.ToString();
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/// <summary>
|
|
624
|
+
/// Names what can move, toggle or animate the object in the browser: toolkit script components (EditorScriptComponent),
|
|
625
|
+
/// Animator / Animation, Timeline bindings, physics bodies, navigation agents and constraints — on the object or an
|
|
626
|
+
/// ancestor — and toolkit script components that point at it. Unity-only MonoBehaviours do not run in the browser.
|
|
627
|
+
/// </summary>
|
|
628
|
+
private static string WebDriverOf(GameObject gameObject, Context context)
|
|
629
|
+
{
|
|
630
|
+
for (var node = gameObject.transform; node != null; node = node.parent)
|
|
631
|
+
{
|
|
632
|
+
string where = node == gameObject.transform ? "" : " on " + node.name;
|
|
633
|
+
foreach (var component in node.GetComponents<Component>())
|
|
634
|
+
{
|
|
635
|
+
if (component == null) continue;
|
|
636
|
+
if (component is EditorScriptComponent) return "script " + component.GetType().Name + where;
|
|
637
|
+
if (component is Animator || component is Animation || component is Rigidbody || component is CharacterController
|
|
638
|
+
|| component is UnityEngine.AI.NavMeshAgent || component is UnityEngine.Animations.IConstraint)
|
|
639
|
+
return component.GetType().Name + where;
|
|
640
|
+
}
|
|
641
|
+
if (context.TimelineBound.Contains(node.gameObject)) return "Timeline binding" + where;
|
|
642
|
+
if (context.WebReferencers.TryGetValue(node.gameObject, out var scripts)) return "referenced by " + string.Join("/", scripts.Distinct().Take(2)) + where;
|
|
643
|
+
}
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/// <summary>Why the renderer's shaders move vertices (wind, vertex animation), or null.</summary>
|
|
648
|
+
private static string VertexAnimationOf(Renderer renderer)
|
|
649
|
+
{
|
|
650
|
+
foreach (var material in renderer.sharedMaterials)
|
|
651
|
+
{
|
|
652
|
+
if (material == null || material.shader == null) continue;
|
|
653
|
+
string path = AssetDatabase.GetAssetPath(material.shader);
|
|
654
|
+
if (!path.EndsWith(".shadergraph")) continue;
|
|
655
|
+
if (!s_VertexAnimation.TryGetValue(path, out var verdict))
|
|
656
|
+
s_VertexAnimation[path] = verdict = GraphMovesVertices(File.ReadAllText(path)) ? "Shader Graph moves vertices (" + material.shader.name + ")" : null;
|
|
657
|
+
if (verdict != null) return verdict;
|
|
658
|
+
}
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
private static readonly Dictionary<string, string> s_VertexAnimation = new Dictionary<string, string>();
|
|
663
|
+
|
|
664
|
+
/// <summary>True when something is wired into the graph's vertex Position block (same scan as the merge stage).</summary>
|
|
665
|
+
private static bool GraphMovesVertices(string graphText)
|
|
666
|
+
{
|
|
667
|
+
var objectId = new System.Text.RegularExpressions.Regex("\"m_ObjectId\":\\s*\"([0-9a-f]+)\"");
|
|
668
|
+
foreach (var chunk in graphText.Split(new[] { "\n}\n" }, StringSplitOptions.None))
|
|
669
|
+
{
|
|
670
|
+
if (!chunk.Contains("\"m_SerializedDescriptor\": \"VertexDescription.Position\"")) continue;
|
|
671
|
+
var blockId = objectId.Match(chunk);
|
|
672
|
+
if (blockId.Success && System.Text.RegularExpressions.Regex.IsMatch(graphText, "\"m_InputSlot\":\\s*\\{\\s*\"m_Node\":\\s*\\{\\s*\"m_Id\":\\s*\"" + blockId.Groups[1].Value + "\"")) return true;
|
|
673
|
+
}
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/// <summary>
|
|
678
|
+
/// Why the renderer is not a visible, lightmappable surface, or null. Only shaders with a lightmapper Meta pass
|
|
679
|
+
/// (URP Lit / Simple Lit / Unlit, Built-in Standard, Shader Graph Lit / Unlit…) describe a surface to the bake.
|
|
680
|
+
/// Stencil masks, depth-only and other utility shaders have none — marked Contribute GI, Garden's invisible
|
|
681
|
+
/// `Room1Screens` stencil mesh (Custom/StencilOnly, wrapping a whole room) became a solid box in the bake and the
|
|
682
|
+
/// room went dark.
|
|
683
|
+
/// </summary>
|
|
684
|
+
private static string NotAVisibleSurface(Renderer renderer)
|
|
685
|
+
{
|
|
686
|
+
foreach (var material in renderer.sharedMaterials)
|
|
687
|
+
{
|
|
688
|
+
if (material == null || material.shader == null) return "missing material or shader";
|
|
689
|
+
var shader = material.shader;
|
|
690
|
+
// URP / Shader Graph tag the pass LightMode "META"; compare case-insensitively, and accept a pass named Meta.
|
|
691
|
+
bool hasMeta = material.FindPass("Meta") >= 0;
|
|
692
|
+
for (int pass = 0; pass < shader.passCount && !hasMeta; pass++)
|
|
693
|
+
hasMeta = string.Equals(shader.FindPassTagValue(pass, new ShaderTagId("LightMode")).name, "Meta", StringComparison.OrdinalIgnoreCase);
|
|
694
|
+
if (!hasMeta) return "not a visible surface for the lightmapper (" + shader.name + " has no Meta pass: stencil / depth / utility shader)";
|
|
695
|
+
}
|
|
696
|
+
return null;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private static bool HasUV2(Renderer renderer)
|
|
700
|
+
{
|
|
701
|
+
var filter = renderer.GetComponent<MeshFilter>();
|
|
702
|
+
return filter != null && filter.sharedMesh != null && filter.sharedMesh.HasVertexAttribute(VertexAttribute.TexCoord1);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
private static bool IsTransparent(Renderer renderer)
|
|
706
|
+
{
|
|
707
|
+
return renderer.sharedMaterials.Any(material => material != null && material.renderQueue >= FirstTransparentQueue);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
private static bool LodZeroIsLightmapped(LODGroup lod)
|
|
711
|
+
{
|
|
712
|
+
var lods = lod.GetLODs();
|
|
713
|
+
return lods.Length > 0 && lods[0].renderers.OfType<MeshRenderer>().Any(renderer => renderer.receiveGI == ReceiveGI.Lightmaps
|
|
714
|
+
&& GameObjectUtility.GetStaticEditorFlags(renderer.gameObject).HasFlag(StaticEditorFlags.ContributeGI));
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
private static bool MatchesName(string name, string[] patterns)
|
|
718
|
+
{
|
|
719
|
+
return patterns != null && patterns.Any(pattern => pattern.EndsWith("*") ? name.StartsWith(pattern.TrimEnd('*')) : name == pattern);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
private static bool IsExcluded(Transform transform, string[] patterns)
|
|
723
|
+
{
|
|
724
|
+
for (var node = transform; node != null; node = node.parent) if (MatchesName(node.name, patterns)) return true;
|
|
725
|
+
return false;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
729
|
+
// Helpers
|
|
730
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
731
|
+
|
|
732
|
+
/// <summary>Everything the survey needs about the scene, gathered once.</summary>
|
|
733
|
+
private sealed class Context
|
|
734
|
+
{
|
|
735
|
+
public readonly Scene Scene;
|
|
736
|
+
public readonly List<GameObject> Roots;
|
|
737
|
+
public readonly List<Light> Lights;
|
|
738
|
+
public readonly List<Renderer> Renderers;
|
|
739
|
+
public readonly Dictionary<GameObject, List<string>> Referencers;
|
|
740
|
+
public readonly HashSet<GameObject> TimelineBound;
|
|
741
|
+
/// <summary>Objects that toolkit script components (which run in the browser) point at.</summary>
|
|
742
|
+
public readonly Dictionary<GameObject, List<string>> WebReferencers;
|
|
743
|
+
public readonly StringBuilder Summary = new StringBuilder();
|
|
744
|
+
|
|
745
|
+
public Context(Scene scene)
|
|
746
|
+
{
|
|
747
|
+
Scene = scene;
|
|
748
|
+
Roots = scene.GetRootGameObjects().ToList();
|
|
749
|
+
Lights = All<Light>().Where(light => light.isActiveAndEnabled).ToList();
|
|
750
|
+
Renderers = All<Renderer>().Where(renderer => renderer.enabled && renderer.gameObject.activeInHierarchy && (renderer is MeshRenderer || renderer is SkinnedMeshRenderer)).ToList();
|
|
751
|
+
Referencers = CollectReferencers(Roots, false);
|
|
752
|
+
WebReferencers = CollectReferencers(Roots, true);
|
|
753
|
+
TimelineBound = CollectTimelineBindings(Roots);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/// <summary>Every component of type T in the scene, including inactive objects.</summary>
|
|
757
|
+
public IEnumerable<T> All<T>() where T : Component
|
|
758
|
+
{
|
|
759
|
+
return Roots.SelectMany(root => root.GetComponentsInChildren<T>(true));
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/// <summary>A set of renderers that share a prefab / mesh key, with one example note.</summary>
|
|
764
|
+
private sealed class Group
|
|
765
|
+
{
|
|
766
|
+
public int Count;
|
|
767
|
+
public readonly List<string> Paths = new List<string>();
|
|
768
|
+
public readonly Dictionary<string, int> Notes = new Dictionary<string, int>();
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
private static void Add(Dictionary<string, Group> groups, string key, Renderer renderer, string note)
|
|
772
|
+
{
|
|
773
|
+
if (!groups.TryGetValue(key, out var group)) groups[key] = group = new Group();
|
|
774
|
+
group.Count++;
|
|
775
|
+
if (group.Paths.Count < 3) group.Paths.Add(PathOf(renderer.transform));
|
|
776
|
+
group.Notes[note] = group.Notes.TryGetValue(note, out var count) ? count + 1 : 1;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
private static void WriteGroups(StringBuilder md, string title, Dictionary<string, Group> groups)
|
|
780
|
+
{
|
|
781
|
+
md.AppendLine("### " + title + " — " + groups.Values.Sum(group => group.Count) + " renderers in " + groups.Count + " groups");
|
|
782
|
+
md.AppendLine();
|
|
783
|
+
if (groups.Count == 0) { md.AppendLine("None."); md.AppendLine(); return; }
|
|
784
|
+
md.AppendLine("| Group | Count | Why / notes | Example |");
|
|
785
|
+
md.AppendLine("|---|---|---|---|");
|
|
786
|
+
foreach (var pair in groups.OrderByDescending(pair => pair.Value.Count))
|
|
787
|
+
md.AppendLine("| " + pair.Key + " | " + pair.Value.Count + " | " + string.Join("; ", pair.Value.Notes.OrderByDescending(note => note.Value).Select(note => note.Key + " ×" + note.Value)) + " | " + pair.Value.Paths.First() + " |");
|
|
788
|
+
md.AppendLine();
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
private static List<object> GroupsToJson(Dictionary<string, Group> groups)
|
|
792
|
+
{
|
|
793
|
+
return groups.OrderByDescending(pair => pair.Value.Count).Select(pair => (object)new Dictionary<string, object> {
|
|
794
|
+
{ "key", pair.Key }, { "count", pair.Value.Count }, { "notes", pair.Value.Notes.Select(note => (object)(note.Key + " x" + note.Value)).ToList() },
|
|
795
|
+
{ "examples", pair.Value.Paths.Cast<object>().ToList() } }).ToList();
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
/// <summary>Groups renderers by their nearest prefab instance root name, or by mesh name.</summary>
|
|
799
|
+
private static string GroupKey(Renderer renderer)
|
|
800
|
+
{
|
|
801
|
+
var root = PrefabUtility.GetOutermostPrefabInstanceRoot(renderer.gameObject);
|
|
802
|
+
if (root != null) return StripCopySuffix(root.name);
|
|
803
|
+
var filter = renderer.GetComponent<MeshFilter>();
|
|
804
|
+
return filter != null && filter.sharedMesh != null ? "mesh " + filter.sharedMesh.name : StripCopySuffix(renderer.name);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
private static string StripCopySuffix(string name)
|
|
808
|
+
{
|
|
809
|
+
int index = name.IndexOf(" (", StringComparison.Ordinal);
|
|
810
|
+
return index > 0 ? name.Substring(0, index) : name;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/// <summary>What a probe-lit renderer would need to become lightmapped.</summary>
|
|
814
|
+
private static string ProbeLitNote(Renderer renderer, StaticEditorFlags flags, int lodLevel)
|
|
815
|
+
{
|
|
816
|
+
var filter = renderer.GetComponent<MeshFilter>();
|
|
817
|
+
bool uv2 = filter != null && filter.sharedMesh != null && filter.sharedMesh.HasVertexAttribute(VertexAttribute.TexCoord1);
|
|
818
|
+
string gi = flags.HasFlag(StaticEditorFlags.ContributeGI) ? "ContributeGI" : "no ContributeGI";
|
|
819
|
+
string receive = renderer is MeshRenderer meshRenderer ? "receive " + meshRenderer.receiveGI : "skinned";
|
|
820
|
+
return gi + ", " + receive + ", " + (uv2 ? "has UV2" : "NO UV2") + (lodLevel == 0 ? ", LOD0" : "");
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
private static int LodLevelOf(LODGroup lodGroup, Renderer renderer)
|
|
824
|
+
{
|
|
825
|
+
var lods = lodGroup.GetLODs();
|
|
826
|
+
for (int i = 0; i < lods.Length; i++) if (lods[i].renderers.Contains(renderer)) return i;
|
|
827
|
+
return -1;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/// <summary>
|
|
831
|
+
/// Names what can move, toggle or animate the object at runtime: scripts, Animator / Animation, Rigidbody,
|
|
832
|
+
/// timeline bindings and serialized references (on the object or any ancestor). Null when nothing does.
|
|
833
|
+
/// </summary>
|
|
834
|
+
private static string DriverOf(GameObject gameObject, Context context)
|
|
835
|
+
{
|
|
836
|
+
var reasons = new List<string>();
|
|
837
|
+
for (var node = gameObject.transform; node != null; node = node.parent)
|
|
838
|
+
{
|
|
839
|
+
string where = node == gameObject.transform ? "" : " on " + node.name;
|
|
840
|
+
foreach (var behaviour in node.GetComponents<MonoBehaviour>())
|
|
841
|
+
if (behaviour != null && !IsPassiveComponent(behaviour)) reasons.Add("script " + behaviour.GetType().Name + where);
|
|
842
|
+
if (node.GetComponent<Animator>() != null) reasons.Add("Animator" + where);
|
|
843
|
+
if (node.GetComponent<Animation>() != null) reasons.Add("Animation" + where);
|
|
844
|
+
if (node.GetComponent<Rigidbody>() != null) reasons.Add("Rigidbody" + where);
|
|
845
|
+
if (context.TimelineBound.Contains(node.gameObject)) reasons.Add("Timeline binding" + where);
|
|
846
|
+
if (context.Referencers.TryGetValue(node.gameObject, out var referencers)) reasons.Add("referenced by " + string.Join("/", referencers.Distinct().Take(3)) + where);
|
|
847
|
+
if (reasons.Count >= 3) break;
|
|
848
|
+
}
|
|
849
|
+
return reasons.Count > 0 ? string.Join(", ", reasons.Distinct().Take(3)) : null;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/// <summary>Components that never move or toggle their object (data-only toolkit or Unity helpers).</summary>
|
|
853
|
+
private static bool IsPassiveComponent(MonoBehaviour behaviour)
|
|
854
|
+
{
|
|
855
|
+
string name = behaviour.GetType().Name;
|
|
856
|
+
return name == "UniversalAdditionalLightData" || name == "UniversalAdditionalCameraData" || name == "MeshCombinerSettings"
|
|
857
|
+
|| name == "LightSettings" || name == "AdditionalTags";
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/// <summary>For every GameObject a serialized field points at: the types of the components pointing at it.</summary>
|
|
861
|
+
private static Dictionary<GameObject, List<string>> CollectReferencers(List<GameObject> roots, bool webScriptsOnly)
|
|
862
|
+
{
|
|
863
|
+
var result = new Dictionary<GameObject, List<string>>();
|
|
864
|
+
foreach (var root in roots)
|
|
865
|
+
foreach (var component in root.GetComponentsInChildren<Component>(true))
|
|
866
|
+
{
|
|
867
|
+
if (component == null || component is Transform || component is MeshFilter || component is Renderer || component is LODGroup) continue;
|
|
868
|
+
if (component is MonoBehaviour behaviour && IsPassiveComponent(behaviour)) continue;
|
|
869
|
+
if (webScriptsOnly && !(component is EditorScriptComponent)) continue;
|
|
870
|
+
var property = new SerializedObject(component).GetIterator();
|
|
871
|
+
while (property.Next(true))
|
|
872
|
+
{
|
|
873
|
+
if (property.propertyType != SerializedPropertyType.ObjectReference) continue;
|
|
874
|
+
var value = property.objectReferenceValue;
|
|
875
|
+
var target = value as GameObject ?? (value as Component)?.gameObject;
|
|
876
|
+
if (target == null || target == component.gameObject || !target.scene.IsValid()) continue;
|
|
877
|
+
if (!result.TryGetValue(target, out var list)) result[target] = list = new List<string>();
|
|
878
|
+
list.Add(component.GetType().Name);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return result;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/// <summary>Every GameObject bound to a track of a PlayableDirector in the scene.</summary>
|
|
885
|
+
private static HashSet<GameObject> CollectTimelineBindings(List<GameObject> roots)
|
|
886
|
+
{
|
|
887
|
+
var bound = new HashSet<GameObject>();
|
|
888
|
+
foreach (var root in roots)
|
|
889
|
+
foreach (var director in root.GetComponentsInChildren<UnityEngine.Playables.PlayableDirector>(true))
|
|
890
|
+
{
|
|
891
|
+
if (director.playableAsset == null) continue;
|
|
892
|
+
foreach (var output in director.playableAsset.outputs)
|
|
893
|
+
{
|
|
894
|
+
var binding = output.sourceObject != null ? director.GetGenericBinding(output.sourceObject) : null;
|
|
895
|
+
var target = binding as GameObject ?? (binding as Component)?.gameObject;
|
|
896
|
+
if (target != null) bound.Add(target);
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
return bound;
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/// <summary>True when the light's range reaches the renderer's bounds (directional lights reach everything).</summary>
|
|
903
|
+
private static bool Reaches(Light light, Renderer renderer)
|
|
904
|
+
{
|
|
905
|
+
return light.type == LightType.Directional || renderer.bounds.SqrDistance(light.transform.position) <= light.range * light.range;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
private static string EnumName(SerializedProperty property)
|
|
909
|
+
{
|
|
910
|
+
if (property == null) return "";
|
|
911
|
+
return property.propertyType == SerializedPropertyType.Enum && property.enumValueIndex >= 0 && property.enumValueIndex < property.enumNames.Length
|
|
912
|
+
? property.enumNames[property.enumValueIndex] : property.intValue.ToString();
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
private static object PropertyValue(SerializedProperty property)
|
|
916
|
+
{
|
|
917
|
+
switch (property.propertyType)
|
|
918
|
+
{
|
|
919
|
+
case SerializedPropertyType.Boolean: return property.boolValue;
|
|
920
|
+
case SerializedPropertyType.Float: return property.floatValue;
|
|
921
|
+
case SerializedPropertyType.Integer: return property.intValue;
|
|
922
|
+
case SerializedPropertyType.Enum: return EnumName(property);
|
|
923
|
+
default: return property.propertyType.ToString();
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
private static string FormatValue(object value)
|
|
928
|
+
{
|
|
929
|
+
if (value == null) return "null";
|
|
930
|
+
if (value is float number) return number.ToString("0.###");
|
|
931
|
+
if (value is UnityEngine.Object asset) return asset.name;
|
|
932
|
+
return value.ToString();
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
private static string PathOf(Transform transform)
|
|
936
|
+
{
|
|
937
|
+
var parts = new List<string>();
|
|
938
|
+
for (var node = transform; node != null; node = node.parent) parts.Insert(0, node.name);
|
|
939
|
+
return string.Join("/", parts);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
private static string ReportFolder(Scene scene)
|
|
943
|
+
{
|
|
944
|
+
string folder = Path.Combine(Path.GetDirectoryName(Application.dataPath), ".agents", "optimize", scene.name);
|
|
945
|
+
Directory.CreateDirectory(folder);
|
|
946
|
+
return folder;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/// <summary>Minimal JSON writer for dictionaries, lists, strings, numbers and booleans.</summary>
|
|
950
|
+
private static string ToJson(object value, int depth)
|
|
951
|
+
{
|
|
952
|
+
string indent = new string(' ', depth * 2), inner = new string(' ', (depth + 1) * 2);
|
|
953
|
+
switch (value)
|
|
954
|
+
{
|
|
955
|
+
case null: return "null";
|
|
956
|
+
case string text: return "\"" + text.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\"";
|
|
957
|
+
case bool flag: return flag ? "true" : "false";
|
|
958
|
+
case float number: return number.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
959
|
+
case double number: return number.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
960
|
+
case int or long: return Convert.ToString(value, System.Globalization.CultureInfo.InvariantCulture);
|
|
961
|
+
case Dictionary<string, object> map:
|
|
962
|
+
return "{\n" + string.Join(",\n", map.Select(pair => inner + ToJson(pair.Key, 0) + ": " + ToJson(pair.Value, depth + 1))) + "\n" + indent + "}";
|
|
963
|
+
case System.Collections.IEnumerable list:
|
|
964
|
+
var items = list.Cast<object>().Select(item => inner + ToJson(item, depth + 1)).ToList();
|
|
965
|
+
return items.Count == 0 ? "[]" : "[\n" + string.Join(",\n", items) + "\n" + indent + "]";
|
|
966
|
+
default: return ToJson(value.ToString(), depth);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|