using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Unity.Profiling;
using Unity.Profiling.LowLevel.Unsafe;
using UnityEngine;
namespace GrassCutter
{
public partial class DemoBot
{
///
/// -demoperf N: load save slot N, stand at the base and record where the main thread's time goes for a while:
/// every profiler marker (a development build has one per script Update), the slow frames and what was busy in them.
/// Writes perf.txt beside the shots. Needs a development build for the per-script markers.
///
IEnumerator Phase(StringBuilder outp, List<(string name, ProfilerRecorder rec)> recs, ProfilerRecorder loop, string label, float seconds, System.Action begin, System.Action each)
{
var total = new Dictionary();
var spikes = new List<(int frame, float at, double ms, string top)>();
var frames = new List();
begin();
float t0 = Time.realtimeSinceStartup, until = t0 + seconds;
int f = 0;
while (Time.realtimeSinceStartup < until)
{
yield return null;
f++;
each(f);
double frameMs = loop.Valid ? loop.LastValue / 1e6 : Time.unscaledDeltaTime * 1000.0;
frames.Add(frameMs);
var busy = new List<(string, double)>();
foreach (var (name, rec) in recs)
{
if (!rec.Valid) continue;
double ms = rec.LastValue / 1e6;
if (ms <= 0 || ms > 1000) continue;
total[name] = (total.TryGetValue(name, out var t) ? t : 0) + ms;
if (frameMs > 20 && ms > 1 && name != "PlayerLoop") busy.Add((name, ms));
}
if (frameMs > 20)
spikes.Add((f, Time.realtimeSinceStartup - t0, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(14).Select(b => $"{b.Item1} {b.Item2:0.0}"))));
}
frames.Sort();
double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)];
outp.AppendLine();
outp.AppendLine($"=== {label}: {f} frames, mean {frames.Average():0.0} ms, median {Pct(0.5):0.0}, p95 {Pct(0.95):0.0}, p99 {Pct(0.99):0.0}, max {frames.LastOrDefault():0.0}; {spikes.Count} over 20 ms, {spikes.Count(s => s.ms > 50)} over 50 ms");
foreach (var kv in total.Where(kv => kv.Key.StartsWith("GC:") || kv.Key.StartsWith("GC.") || kv.Key.StartsWith("Physics") || kv.Key.StartsWith("Gfx.") || kv.Key.StartsWith("Loading") || kv.Key.Contains("Upload")).OrderByDescending(kv => kv.Value).Take(40))
outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}");
outp.AppendLine("— slow frames —");
foreach (var s in spikes.OrderByDescending(s => s.ms).Take(20))
outp.AppendLine($"#{s.frame} t{s.at:0.0} {s.ms:0.0} ms: {s.top}");
}
IEnumerator Perf(int slot)
{
SaveSlots.Current = slot - 1;
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(6f);
var outp = new StringBuilder();
outp.AppendLine($"loaded: {BuildPiece.All.Count} pieces, {Cargo.All.Count} cargo, {Mowbot.All.Count} bots, {Vehicle.All.Count} vehicles, planet r {Planet.Radius:0} m, sectors started {MowMap.Started}, finished {MowMap.Finished}");
int bodies = 0, awake = 0;
foreach (var rb in FindObjectsByType(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; }
outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType(FindObjectsSortMode.None).Length}");
if (CommandLine.Has("-tune"))
{
foreach (var r in FindObjectsByType(FindObjectsSortMode.None)) r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
if (UnityEngine.Rendering.GraphicsSettings.currentRenderPipeline is UnityEngine.Rendering.Universal.UniversalRenderPipelineAsset ua) ua.gpuResidentDrawerMode = UnityEngine.Rendering.GPUResidentDrawerMode.Disabled;
outp.AppendLine("tuned: light probes off, resident drawer off");
}
var home = Planet.FromBase(0f, -12f);
Me.Teleport(Planet.OnSurface(home) + home * 0.2f);
yield return new WaitForSeconds(1f);
Me.LookAt(Planet.OnSurface(Planet.FromBase(0f, 0f)));
yield return new WaitForSeconds(1f);
// every marker there is, recorded at once
var handles = new List();
ProfilerRecorderHandle.GetAvailable(handles);
var recs = new List<(string name, ProfilerRecorder rec)>();
foreach (var h in handles)
{
var d = ProfilerRecorderHandle.GetDescription(h);
if (d.UnitType != ProfilerMarkerDataUnit.TimeNanoseconds) continue;
recs.Add((d.Name, ProfilerRecorder.StartNew(d.Category, d.Name, 1)));
}
var loop = recs.FirstOrDefault(r => r.name == "PlayerLoop").rec;
outp.AppendLine($"recording {recs.Count} markers, PlayerLoop {(loop.Valid ? "ok" : "MISSING")}");
// three things a player does: walk about the base, drive a mower across fresh meadow, run through the meadow
yield return Phase(outp, recs, loop, "walk at the base", 25f, () => Ctl.BotMove = new Vector2(0.3f, 1f), f => { if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y); });
Ctl.BotMove = Vector2.zero;
var ride = Vehicle.All.Where(v => v && v.Def.width > 0f).OrderByDescending(v => v.Def.width).FirstOrDefault();
if (ride)
{
var far = Planet.FromBase(90f, 160f);
var up = far;
ride.ServerPut(Planet.OnSurface(far) + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, up), up));
yield return new WaitForSeconds(1f);
Me.Teleport(ride.transform.position + ride.transform.right * 3f);
yield return new WaitForSeconds(0.5f);
ride.Interact();
yield return new WaitForSeconds(1.5f);
ride.Tank.Value = 0f;
yield return Phase(outp, recs, loop, $"drive the {ride.kind} through the meadow", 40f, () => Ctl.BotMove = new Vector2(0.15f, 1f), f => { });
Ctl.BotMove = Vector2.zero;
ride.RequestExit();
yield return new WaitForSeconds(1.5f);
}
else outp.AppendLine("no mower to drive");
var run = Planet.FromBase(-150f, 120f);
Me.Teleport(Planet.OnSurface(run) + run * 0.3f);
yield return new WaitForSeconds(1f);
yield return Phase(outp, recs, loop, "run through the meadow", 25f, () => { Ctl.BotMove = new Vector2(0f, 1f); Ctl.BotSprint = true; }, f => { if (f % 200 == 0) Ctl.BotMove = new Vector2(Ctl.BotMove.x > 0 ? -0.4f : 0.4f, 1f); });
Ctl.BotMove = Vector2.zero;
Ctl.BotSprint = false;
foreach (var (_, rec) in recs) rec.Dispose();
float render = 0f;
yield return BotCapture.FrameCost(40, v => render = v);
outp.AppendLine($"render (camera at the base, GPU waited for): {render:0.0} ms");
File.WriteAllText(Path.Combine(folder, "perf.txt"), outp.ToString());
Log("perf done");
Application.Quit();
}
}
}