From 80271aea721112f2d7c8458032fdcf5f80e20b66 Mon Sep 17 00:00:00 2001 From: NiemandKG <74151950+NiemandKG@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:04:36 +0600 Subject: [PATCH] Fix Sky Mower tumbling and the hitches on a big farm - Mowbot keeps its heading apart from the drawn pose: a flyer's lean and sway were fed back each frame and rolled it over. - Drone pads looked through every loose bundle, testing every belt end, for each idle drone every frame (43 ms on a 1500-bundle farm): distance first, and a 1.5 s pause after finding nothing. - Saves are written, laid out and compressed off the main thread; backups go in the same queue (an autosave froze the game ~50 ms every 30 s). - Robots tick on staggered frames. - -demoperf N profiles save slot N; -demobots logs the Sky Mower's tilt. On the player's save: frames over 25 ms went from 144 to 0 in 40 s, worst frame 74 ms -> 22 ms. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/Core/DemoBot.Bots.cs | 2 +- Assets/Scripts/Core/DemoBot.Perf.cs | 97 ++++++++++++++++++++++++ Assets/Scripts/Core/DemoBot.Perf.cs.meta | 2 + Assets/Scripts/Core/DemoBot.cs | 5 ++ Assets/Scripts/Core/SaveSlots.cs | 57 ++++++++++++-- Assets/Scripts/Gameplay/DronePad.cs | 10 ++- Assets/Scripts/Gameplay/Mowbot.cs | 20 +++-- Assets/Scripts/Gameplay/TeamState.cs | 2 +- Assets/Scripts/World/MowMap.cs | 93 ++++++++++++++++++----- 9 files changed, 251 insertions(+), 37 deletions(-) create mode 100644 Assets/Scripts/Core/DemoBot.Perf.cs create mode 100644 Assets/Scripts/Core/DemoBot.Perf.cs.meta diff --git a/Assets/Scripts/Core/DemoBot.Bots.cs b/Assets/Scripts/Core/DemoBot.Bots.cs index bb4f00a..b7b787e 100644 --- a/Assets/Scripts/Core/DemoBot.Bots.cs +++ b/Assets/Scripts/Core/DemoBot.Bots.cs @@ -46,7 +46,7 @@ namespace GrassCutter yield return new WaitForSeconds(15f); Log($"t+{k * 15} s at {Mowbot.Haste:0}x: earned {Ts.Money.Value - money:0}, closed {Ts.Closed.Value}"); Log($" robot: {robot.Prompt}"); - Log($" sky: {sky.Prompt} alt {Planet.Altitude(sky.ShownBody.position) - Planet.Altitude(sky.Shown):0.0} m"); + Log($" sky: {sky.Prompt} alt {Planet.Altitude(sky.ShownBody.position) - Planet.Altitude(sky.Shown):0.0} m, tilt {Vector3.Angle(sky.ShownBody.up, Planet.Up(sky.Shown)):0} deg"); Log($" pad: {pad.Prompt}, delivered {pad.Delivered}"); } skyUp = Planet.Up(sky.Shown); diff --git a/Assets/Scripts/Core/DemoBot.Perf.cs b/Assets/Scripts/Core/DemoBot.Perf.cs new file mode 100644 index 0000000..cc081b0 --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Perf.cs @@ -0,0 +1,97 @@ +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 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}"); + + 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")}"); + + var total = new Dictionary(); + var spikes = new List<(int frame, double ms, string top)>(); + var frames = new List(); + float until = Time.realtimeSinceStartup + 40f; + int f = 0; + // walk around a little, as a player would + Ctl.BotMove = new Vector2(0.3f, 1f); + while (Time.realtimeSinceStartup < until) + { + yield return null; + f++; + if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y); + 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 > 25 && ms > 1 && ms < 1000 && (name.StartsWith("GC:") || name.StartsWith("Physics.Simulate") || name.StartsWith("Semaphore") || name.StartsWith("GC.") || name.StartsWith("Gfx."))) busy.Add((name, ms)); + } + if (frameMs > 25) + spikes.Add((f, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(10).Select(b => $"{b.Item1} {b.Item2:0.0}")))); + } + Ctl.BotMove = Vector2.zero; + foreach (var (_, rec) in recs) rec.Dispose(); + + frames.Sort(); + double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)]; + outp.AppendLine($"{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 25 ms"); + outp.AppendLine("— mean ms a frame, top markers —"); + foreach (var kv in total.OrderByDescending(kv => kv.Value).Take(70)) + outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}"); + outp.AppendLine("— slow frames —"); + foreach (var s in spikes.OrderByDescending(s => s.ms).Take(25)) + outp.AppendLine($"#{s.frame} {s.ms:0.0} ms: {s.top}"); + 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(); + } + } +} diff --git a/Assets/Scripts/Core/DemoBot.Perf.cs.meta b/Assets/Scripts/Core/DemoBot.Perf.cs.meta new file mode 100644 index 0000000..5d10108 --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Perf.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 688dd65c0fcdde24ab5d52f06b08ff75 \ No newline at end of file diff --git a/Assets/Scripts/Core/DemoBot.cs b/Assets/Scripts/Core/DemoBot.cs index 7b286d7..2360c87 100644 --- a/Assets/Scripts/Core/DemoBot.cs +++ b/Assets/Scripts/Core/DemoBot.cs @@ -3003,6 +3003,11 @@ namespace GrassCutter yield return Sizes(); yield break; } + if (CommandLine.Get("-demoperf") is string perfSlot) + { + yield return Perf(int.Parse(perfSlot)); + yield break; + } if (CommandLine.Has("-demobots")) { yield return Bots(); diff --git a/Assets/Scripts/Core/SaveSlots.cs b/Assets/Scripts/Core/SaveSlots.cs index fc92eb4..2f18c5f 100644 --- a/Assets/Scripts/Core/SaveSlots.cs +++ b/Assets/Scripts/Core/SaveSlots.cs @@ -99,14 +99,41 @@ namespace GrassCutter // ───────────────────────── writing ───────────────────────── - public static void Write(string json, byte[] map) + // the disk work of a save runs off the main thread, one write after another: a big farm's mow map is over ten + // megabytes, and writing it in the frame froze the game every half minute + static System.Threading.Tasks.Task s_io = System.Threading.Tasks.Task.CompletedTask; + static readonly object s_ioGate = new object(); + + public static void Write(string json, byte[] map) => Write(() => json, () => map); + + /// The save, its text and its map put together off the main thread (JsonUtility works on any thread). + public static void Write(Func json, Func map) { var dir = Folder(Current); - Directory.CreateDirectory(dir); - Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json)); - Put(Path.Combine(dir, MapFile), map); + lock (s_ioGate) + s_io = s_io.ContinueWith(_ => + { + try + { + Directory.CreateDirectory(dir); + Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json())); + Put(Path.Combine(dir, MapFile), map()); + } + catch (Exception e) { Debug.LogWarning("[Save] couldn't write " + dir + ": " + e.Message); } + }); } + /// Waits for a save still being written: before anything reads, copies or deletes the files, and on quitting. + public static void Flush() + { + System.Threading.Tasks.Task t; + lock (s_ioGate) t = s_io; + try { t.Wait(); } catch (AggregateException e) { Debug.LogWarning("[Save] " + e.InnerException?.Message); } + } + + [RuntimeInitializeOnLoadMethod] + static void FlushOnQuit() => Application.quitting += Flush; + /// Written whole or not at all: a crash halfway leaves the last save as it was. static void Put(string path, byte[] data) { @@ -119,18 +146,31 @@ namespace GrassCutter /// The current save goes over the oldest of its backups. public static void Backup() { + // in the same queue as the writes, after the save just asked for: the copy is of that save, and nothing waits var dir = Folder(Current); + var copies = new string[Backups]; + for (int n = 0; n < Backups; n++) copies[n] = Copy(Current, n); + lock (s_ioGate) + s_io = s_io.ContinueWith(_ => + { + try { CopyToBackup(dir, copies); } + catch (Exception e) { Debug.LogWarning("[Save] couldn't back up " + dir + ": " + e.Message); } + }); + } + + static void CopyToBackup(string dir, string[] copies) + { var game = Path.Combine(dir, GameFile); if (!File.Exists(game)) return; int pick = 0; var oldest = DateTime.MaxValue; - for (int n = 0; n < Backups; n++) + for (int n = 0; n < copies.Length; n++) { - var path = Path.Combine(Copy(Current, n), GameFile); + var path = Path.Combine(copies[n], GameFile); var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue; if (when < oldest) { oldest = when; pick = n; } } - var to = Copy(Current, pick); + var to = copies[pick]; Directory.CreateDirectory(to); File.Copy(game, Path.Combine(to, GameFile), true); File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow); @@ -170,6 +210,7 @@ namespace GrassCutter /// The save to load, or null for a new game. A bad one is replaced from its backups first. public static string Read() { + Flush(); Migrate(); var dir = Folder(Current); var json = Text(Path.Combine(dir, GameFile)); @@ -194,6 +235,7 @@ namespace GrassCutter public static SlotInfo Info(int slot) { + Flush(); var path = Path.Combine(Folder(slot), GameFile); var h = Parse(Text(path)); if (h == null) return new SlotInfo { used = File.Exists(path) }; @@ -202,6 +244,7 @@ namespace GrassCutter public static void Delete(int slot) { + Flush(); if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true); } diff --git a/Assets/Scripts/Gameplay/DronePad.cs b/Assets/Scripts/Gameplay/DronePad.cs index db8e55d..a8f52d9 100644 --- a/Assets/Scripts/Gameplay/DronePad.cs +++ b/Assets/Scripts/Gameplay/DronePad.cs @@ -44,6 +44,7 @@ namespace GrassCutter int Count => Mathf.Min(Most, 2 + (Piece ? Piece.Tier.Value : 0)); float Fly => Speed * Mathf.Sqrt(Piece ? Piece.TierMul : 1f); float Reach => Range + RangePerTier * (Piece ? Piece.Tier.Value : 0); + readonly float[] _idleUntil = new float[Most]; float _shipAt; double Now => NetworkManager ? NetworkManager.ServerTime.Time : Time.timeAsDouble; @@ -231,6 +232,8 @@ namespace GrassCutter int out_ = 0; for (int k = 0; k < Most; k++) if (Trip(k).Value.w >= 0f) out_++; if (Silo.Value + (out_ + 1) * GameDefs.BundleKg > Room) return; + // found nothing a moment ago: there are often a thousand bundles on a big farm, don't look through them every frame + if (Time.time < _idleUntil[i]) return; Cargo best = null; float bestD = Reach * Reach; var here = transform.position; @@ -240,13 +243,16 @@ namespace GrassCutter var g = c.Grab; if (!g || g.IsHeld || g.Consumed || !g.Body || g.Body.isKinematic || g.Body.linearVelocity.sqrMagnitude > 0.25f) continue; float d = (c.transform.position - here).sqrMagnitude; + // out of reach or no nearer than the best so far: the cheap test first, the belt ends only for the few left + if (d >= bestD) continue; // right by the pad: just put out of the hatch, or about to be if (d < 3f * 3f) continue; // dropped off the free end of a belt: that's where someone wants it, and it may be this pad's own if (AtBeltEnd(c.transform.position)) continue; - if (d < bestD) { bestD = d; best = c; } + bestD = d; + best = c; } - if (!best) return; + if (!best) { _idleUntil[i] = Time.time + 1.5f; return; } s_claimed.Add(best); _for[i] = best; _holding[i] = false; diff --git a/Assets/Scripts/Gameplay/Mowbot.cs b/Assets/Scripts/Gameplay/Mowbot.cs index 323a691..460cdb0 100644 --- a/Assets/Scripts/Gameplay/Mowbot.cs +++ b/Assets/Scripts/Gameplay/Mowbot.cs @@ -105,6 +105,8 @@ namespace GrassCutter if (IsServer) Seat(Planet.Up(transform.position)); _shown = _from = _to = At.Value; _bobPhase = Random.value * 6.28f; + // each bot thinks on a frame of its own: two dozen robots planning their rows at once was a hitch + _clock = Random.value * Tick; At.OnValueChanged += Heard; _engine = Sfx.Loop(Def.hover > 0f ? "drone_loop" : "robot_mower_loop", Body, 0f); } @@ -197,10 +199,15 @@ namespace GrassCutter _shown = Vector3.Lerp(_from, _to, _leg); // the nose, where the cutter is, goes first float nose = NoseOnBack ? -1f : 1f; - if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(body.forward * nose, up); + // the heading is kept apart from the body: a flyer's lean and sway go on top of it when it is drawn, and must + // never be fed back in, or they pile up frame after frame and it rolls over + if (!_headed) { _heading = body.rotation; _headed = true; } + if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(_heading * Vector3.forward * nose, up); if (flat.sqrMagnitude < 1e-4f) return; - var was = body.rotation; + var was = _heading; var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime)); + _heading = turn; + var pose = turn; // it glides: no shake, no bob, the moving parts do the living bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f; // a flyer hangs over the grass, bobbing a little, and leans into the way it goes @@ -208,9 +215,10 @@ namespace GrassCutter if (Def.hover > 0f) { at += up * (Def.hover + Mathf.Sin(Time.time * 1.9f + _bobPhase) * 0.15f); - turn *= Quaternion.Euler((going ? 8f : 0f) * -nose, 0f, Mathf.Sin(Time.time * 1.3f + _bobPhase) * 2f); + _lean = Mathf.MoveTowards(_lean, going ? 6f : 0f, Time.deltaTime * 12f); + pose = turn * Quaternion.Euler(_lean * -nose, 0f, Mathf.Sin(Time.time * 1.3f + _bobPhase) * 1.5f); } - body.SetPositionAndRotation(at, turn); + body.SetPositionAndRotation(at, pose); Animate(body, Vector3.SignedAngle(was * Vector3.forward, turn * Vector3.forward, up) / Mathf.Max(1e-3f, Time.deltaTime), going); } @@ -226,7 +234,9 @@ namespace GrassCutter float _roll, _level; bool _parts; float _spun, _nextBlink = 2f, _blinkAt = -1f, _swayX, _swayV, _wasGoing, _go; - float _bobPhase; + float _bobPhase, _lean; + Quaternion _heading; + bool _headed; void Animate(Transform body, float turnRate, bool going) { diff --git a/Assets/Scripts/Gameplay/TeamState.cs b/Assets/Scripts/Gameplay/TeamState.cs index 51ae491..c6c7a62 100644 --- a/Assets/Scripts/Gameplay/TeamState.cs +++ b/Assets/Scripts/Gameplay/TeamState.cs @@ -339,7 +339,7 @@ namespace GrassCutter foreach (var c in Cargo.All) if (c && c.IsSpawned && !c.Grab.Consumed && d.cargo.Count < MaxSavedBundles) d.cargo.Add(new CargoSave { kind = (int)c.kind, kg = c.Kg.Value, at = c.transform.position }); - SaveSlots.Write(JsonUtility.ToJson(d), MowMap.Serialize()); + SaveSlots.Write(() => JsonUtility.ToJson(d), MowMap.SerializeLater()); } void Load() diff --git a/Assets/Scripts/World/MowMap.cs b/Assets/Scripts/World/MowMap.cs index 8701ed0..c2bab0d 100644 --- a/Assets/Scripts/World/MowMap.cs +++ b/Assets/Scripts/World/MowMap.cs @@ -215,16 +215,36 @@ namespace GrassCutter } static void Pack(Mask m) + { + m.packed = Deflate(Raw(m)); + m.dirty = false; + } + + static byte[] Raw(Mask m) { var raw = new byte[Res * Res * 3]; System.Buffer.BlockCopy(m.left, 0, raw, 0, Res * Res * 2); for (int i = 0; i < Res * Res; i++) raw[Res * Res * 2 + i] = m.rg[i * 2]; + return raw; + } + + static byte[] Deflate(byte[] raw) + { using (var mem = new MemoryStream()) { using (var z = new DeflateStream(mem, System.IO.Compression.CompressionLevel.Fastest, true)) z.Write(raw, 0, raw.Length); - m.packed = mem.ToArray(); + return mem.ToArray(); } - m.dirty = false; + } + + /// A sector packed off the main thread for a save: its bytes go back on the mask if nothing changed since. + sealed class Packing { public Mask m; public byte[] raw, packed; } + static readonly System.Collections.Concurrent.ConcurrentQueue s_packed = new System.Collections.Concurrent.ConcurrentQueue(); + + static void TakePacked() + { + while (s_packed.TryDequeue(out var p)) + if (p.m.packed == null && !p.m.dirty && p.m.left != null) p.m.packed = p.packed; } static byte[] Inflate(byte[] packed) @@ -241,6 +261,7 @@ namespace GrassCutter /// Too many maps in memory: squeeze the ones furthest from here. public static void Trim(Vector3 dir) { + TakePacked(); int open = 0; foreach (var m in s_masks.Values) if (m.left != null) open++; if (open <= MaxOpen) return; @@ -646,30 +667,60 @@ namespace GrassCutter const int Magic = 0x314D4347; // "GCM1" /// Everything cut so far, as one block of bytes (the save file, and what a late joiner is sent). - public static byte[] Serialize() + public static byte[] Serialize() => SerializeLater()(); + + /// + /// The mow map as it stands now, put into bytes later, off the main thread if wanted: only the sectors cut since the + /// last time are packed here, the ten-odd megabytes are laid out by the function it hands back. A packed array is + /// only ever replaced, never written into, so holding on to them is safe. + /// + public static System.Func SerializeLater() { - using (var mem = new MemoryStream()) - using (var w = new BinaryWriter(mem)) + TakePacked(); + var rows = new List<(int id, float total, float mown, bool done, byte[] packed, Packing job)>(s_masks.Count); + foreach (var m in s_masks.Values) { - int count = 0; - foreach (var m in s_masks.Values) if (m.keep) count++; - w.Write(Magic); - w.Write(count); - foreach (var m in s_masks.Values) + if (!m.keep) continue; + if (!m.done && (m.dirty || m.packed == null) && m.left != null) { - if (!m.keep) continue; - if (!m.done && (m.dirty || m.packed == null) && m.left != null) Pack(m); - w.Write(m.s.id); - w.Write(m.total); - w.Write(m.mown); - w.Write(m.done); - int len = m.done || m.packed == null ? 0 : m.packed.Length; - w.Write(len); - if (len > 0) w.Write(m.packed); + // only the copy is made here, the squeezing happens with the rest of the save; till its bytes come + // back the mask has none, so anything that needs them packs it again itself + var job = new Packing { m = m, raw = Raw(m) }; + m.packed = null; + m.dirty = false; + rows.Add((m.s.id, m.total, m.mown, false, null, job)); + continue; } - w.Flush(); - return mem.ToArray(); + rows.Add((m.s.id, m.total, m.mown, m.done, m.done ? null : m.packed, null)); } + return () => + { + using (var mem = new MemoryStream()) + using (var w = new BinaryWriter(mem)) + { + w.Write(Magic); + w.Write(rows.Count); + foreach (var (id, total, mown, done, had, job) in rows) + { + var packed = had; + if (job != null) + { + packed = job.packed = Deflate(job.raw); + job.raw = null; + s_packed.Enqueue(job); + } + w.Write(id); + w.Write(total); + w.Write(mown); + w.Write(done); + int len = packed == null ? 0 : packed.Length; + w.Write(len); + if (len > 0) w.Write(packed); + } + w.Flush(); + return mem.ToArray(); + } + }; } /// Take in a saved game. What this peer has cut in the meantime stays cut.