Frame time on a big farm: batched grass, sleeping bundles, no light probes

Measured in a real 2560x1440 window on the player's Mommy save (RTX 4090):
the GPU took ~5 ms, the main thread the rest.

- Grass: a fully mown sector draws only its floor (one draw, not up to six);
  untouched and fully mown sectors share a mow map look, so the fur pile
  draws them all in one instanced call per pile (GC_SECTOR_BUFFER, sector
  frames from a structured buffer). Grass draws 1112 -> 337 at the base,
  876 -> 439 in the meadow.
- Bundles: loose ones sleep when they come to rest (our gravity kept ~600
  bodies awake), ones on belts skip the ground checks, and all of them are
  stepped from one CargoTick instead of two Unity messages each.
- Belts leave a jammed line alone and only look every few steps whether it
  can move; splitters test distance before transforming every bundle.
- Light probes off on everything (the planet has none) and the GPU Resident
  Drawer off: both cost CPU per moving renderer for nothing.
- -demogpu N -onscreen measures frame time with one feature off at a time.

Base view 17-19 ms -> 14-15 ms, meadow 14-16 ms -> 11.5-12 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-09 20:01:02 +06:00
parent 80271aea72
commit 57d0f4d31a
17 changed files with 360 additions and 20 deletions

View File

@ -0,0 +1,96 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
public partial class DemoBot
{
/// <summary>
/// -demogpu N -onscreen: save slot N in a real window, vsync off, and the frame time with one thing switched off at
/// a time (grass, MSAA, SSAO, shadows, post, lights, bundles...), at the base and out in the meadow. The CPU side
/// takes about 7 ms, so anything slower is the GPU. Writes gpu.txt.
/// </summary>
IEnumerator Gpu(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);
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
var asset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
var datas = asset ? typeof(UniversalRenderPipelineAsset).GetField("m_RendererDataList", BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(asset) as ScriptableRendererData[] : null;
var features = datas != null && datas.Length > 0 && datas[0] ? datas[0].rendererFeatures : new List<ScriptableRendererFeature>();
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
var camData = cam ? cam.GetUniversalAdditionalCameraData() : null;
var sun = FindObjectsByType<Light>(FindObjectsSortMode.None).Where(l => l.type == LightType.Directional).OrderByDescending(l => l.intensity).FirstOrDefault();
var outp = new StringBuilder();
outp.AppendLine($"screen {Screen.width}x{Screen.height}, {SystemInfo.graphicsDeviceName}, msaa {asset?.msaaSampleCount}, hdr {asset?.supportsHDR}, shadows {asset?.shadowDistance} m x{asset?.shadowCascadeCount}, features {string.Join(",", features.Select(f => f ? f.name + (f.isActive ? "" : "(off)") : "null"))}");
outp.AppendLine($"{BuildPiece.All.Count} pieces, {Cargo.All.Count} cargo, {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length} renderers, {FindObjectsByType<Light>(FindObjectsSortMode.None).Length} lights");
void Toggle(IEnumerable<Renderer> rs, bool on) { foreach (var r in rs) if (r) r.enabled = on; }
List<Renderer> Of(IEnumerable<Component> cs) => cs.Where(c => c).SelectMany(c => c.GetComponentsInChildren<Renderer>()).ToList();
var tests = new List<(string name, Action off, Action on)>
{
("base", () => { }, () => { }),
("grass off", () => { if (GrassField.Instance) GrassField.Instance.enabled = false; }, () => { if (GrassField.Instance) GrassField.Instance.enabled = true; }),
("msaa 1x", () => asset.msaaSampleCount = 1, () => asset.msaaSampleCount = 4),
("hdr off", () => asset.supportsHDR = false, () => asset.supportsHDR = true),
("post off", () => { if (camData) camData.renderPostProcessing = false; }, () => { if (camData) camData.renderPostProcessing = true; }),
("shadows off", () => asset.shadowDistance = 0f, () => asset.shadowDistance = 90f),
("shadows 2 casc 60 m", () => { asset.shadowCascadeCount = 2; asset.shadowDistance = 60f; }, () => { asset.shadowCascadeCount = 4; asset.shadowDistance = 90f; }),
("hard shadows", () => { if (sun) sun.shadows = LightShadows.Hard; }, () => { if (sun) sun.shadows = LightShadows.Soft; }),
("other lights off", () => { foreach (var l in FindObjectsByType<Light>(FindObjectsSortMode.None)) if (l != sun) l.enabled = false; }, () => { foreach (var l in FindObjectsByType<Light>(FindObjectsInactive.Include, FindObjectsSortMode.None)) if (l != sun) l.enabled = true; }),
("bundles hidden", () => Toggle(Of(Cargo.All), false), () => Toggle(Of(Cargo.All), true)),
("pieces hidden", () => Toggle(Of(BuildPiece.All), false), () => Toggle(Of(BuildPiece.All), true)),
("render scale 0.75", () => asset.renderScale = 0.75f, () => asset.renderScale = 1f),
};
foreach (var f in features)
if (f && f.isActive) { var ff = f; tests.Add(($"feature {ff.name} off", () => ff.SetActive(false), () => ff.SetActive(true))); }
tests.Add(("base again", () => { }, () => { }));
var views = new (string name, Vector3 at, Vector3 look)[]
{
("base", Planet.FromBase(0f, -14f), Planet.FromBase(0f, 6f)),
("meadow", Planet.FromBase(140f, 120f), Planet.FromBase(260f, 220f)),
};
foreach (var v in views)
{
Me.Teleport(Planet.OnSurface(v.at) + v.at * 0.2f);
yield return new WaitForSeconds(2f);
Me.LookAt(Planet.OnSurface(v.look));
yield return new WaitForSeconds(1.5f);
double baseMs = 0;
foreach (var (name, off, on) in tests)
{
off();
yield return new WaitForSeconds(0.6f);
var dts = new List<float>();
float until = Time.realtimeSinceStartup + 4f;
while (Time.realtimeSinceStartup < until) { yield return null; dts.Add(Time.unscaledDeltaTime * 1000f); }
on();
dts.Sort();
double ms = dts.Count > 0 ? dts[dts.Count / 2] : 0;
if (name == "base") baseMs = ms;
if (name == "base") outp.AppendLine($"{v.name}: grass draws {(GrassField.Instance ? GrassField.Instance.Draws : -1)}");
outp.AppendLine($"{v.name,-7} {name,-34} {ms,6:0.0} ms {1000.0 / Math.Max(0.1, ms),5:0} fps {(name == "base" ? "" : $"{ms - baseMs:+0.0;-0.0} ms")}");
yield return new WaitForSeconds(0.3f);
}
yield return Shot($"gpu_{v.name}");
}
File.WriteAllText(Path.Combine(folder, "gpu.txt"), outp.ToString());
Log("gpu done");
Application.Quit();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f67da5b26efc4004580fe49bb92bc022

View File

@ -29,6 +29,12 @@ namespace GrassCutter
foreach (var rb in FindObjectsByType<Rigidbody>(FindObjectsSortMode.None)) { bodies++; if (!rb.isKinematic && !rb.IsSleeping()) awake++; }
outp.AppendLine($"rigidbodies {bodies}, awake {awake}, renderers {FindObjectsByType<Renderer>(FindObjectsSortMode.None).Length}");
if (CommandLine.Has("-tune"))
{
foreach (var r in FindObjectsByType<Renderer>(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);

View File

@ -3003,6 +3003,11 @@ namespace GrassCutter
yield return Sizes();
yield break;
}
if (CommandLine.Get("-demogpu") is string gpuSlot)
{
yield return Gpu(int.Parse(gpuSlot));
yield break;
}
if (CommandLine.Get("-demoperf") is string perfSlot)
{
yield return Perf(int.Parse(perfSlot));

View File

@ -18,11 +18,34 @@ namespace GrassCutter
void Start()
{
NoProbes();
// dev bots render off-screen so they can run with -batchmode without touching the user's desktop
if (CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo"))
// (-onscreen: a real window instead, for measuring what the screen really costs)
if ((CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo")) && !CommandLine.Has("-onscreen"))
BotCapture.Setup(int.TryParse(CommandLine.Get("-shotw", "1600"), out var w) ? w : 1600, int.TryParse(CommandLine.Get("-shoth", "900"), out var h) ? h : 900);
if (CommandLine.Get("-screenshot") is string path) gameObject.AddComponent<AutoScreenshot>().path = path;
if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent<DemoBot>().folder = demo;
}
/// <summary>
/// The planet has no light probes, so interpolating them for every moving thing (two thousand bundles on the belts
/// of a big farm) is work for nothing: the ambient light is the same. Off on every networked prefab and everything
/// in the scene, once at boot.
/// </summary>
static void NoProbes()
{
if (LightmapSettings.lightProbes != null && LightmapSettings.lightProbes.count > 0) return;
void Off(GameObject go)
{
if (!go) return;
foreach (var r in go.GetComponentsInChildren<Renderer>(true)) r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
}
var nm = Unity.Netcode.NetworkManager.Singleton;
// (not in the editor: there the prefab is the asset on disk)
if (!Application.isEditor && nm && nm.NetworkConfig?.Prefabs?.Prefabs != null)
foreach (var p in nm.NetworkConfig.Prefabs.Prefabs) Off(p.Prefab);
foreach (var r in Object.FindObjectsByType<Renderer>(FindObjectsInactive.Include, FindObjectsSortMode.None))
r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
}
}
}

View File

@ -96,10 +96,14 @@ namespace GrassCutter
bool seen = false;
Cargo inJunction = null;
float side = 0f;
var here = transform.position;
foreach (var c in Cargo.All)
{
if (!c) continue;
var l = transform.InverseTransformPoint(c.transform.position);
var at = c.transform.position;
// most of a farm's bundles are nowhere near: the cheap test first
if ((at - here).sqrMagnitude > 4f) continue;
var l = transform.InverseTransformPoint(at);
if (Mathf.Abs(l.x) > 0.55f || Mathf.Abs(l.z) > 0.55f || l.y < -0.2f || l.y > 1.4f) continue;
if (l.z < -0.2f) continue;
inJunction = c;

View File

@ -48,6 +48,7 @@ namespace GrassCutter
public override void OnNetworkSpawn()
{
All.Add(this);
CargoTick.Ensure();
if (Time.timeSinceLevelLoad > 3f) Tween.Scale(transform, Vector3.one * 0.3f, Vector3.one, 0.35f, Ease.OutBack);
}
@ -65,10 +66,14 @@ namespace GrassCutter
float _fallV;
void FixedUpdate()
/// <summary>One physics step, called by <see cref="CargoTick"/> for every bundle at once: two thousand Unity
/// FixedUpdate messages cost more than the work in them.</summary>
internal void Step()
{
if (!IsSpawned) return;
var rb = _g.Body;
// riding a belt or lying still: nothing below needs looking at (most of a big farm's bundles, every step)
if (Belt || (rb && !rb.isKinematic && rb.IsSleeping())) { _fallV = 0f; _wasInGrass = !Belt; return; }
var p = transform.position;
// tossed into a depot

View File

@ -0,0 +1,32 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Steps every bundle and every grabbable thing from one FixedUpdate. A big farm has two thousand bundles, and a Unity
/// message per object per physics step (two scripts each) cost more than what they do, which is mostly nothing.
/// </summary>
public class CargoTick : MonoBehaviour
{
static CargoTick s_on;
public static void Ensure()
{
if (s_on) return;
var go = new GameObject("CargoTick");
DontDestroyOnLoad(go);
s_on = go.AddComponent<CargoTick>();
}
void FixedUpdate()
{
// backwards: a step can hand a bundle to a depot, which takes it off the list
var g = Grabbable.All;
for (int i = g.Count - 1; i >= 0; i--)
if (i < g.Count && g[i]) g[i].Step();
var c = Cargo.All;
for (int i = c.Count - 1; i >= 0; i--)
if (i < c.Count && c[i]) c[i].Step();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c675567074ef89b49b1f9073c8ee1535

View File

@ -46,6 +46,9 @@ namespace GrassCutter
public float blend;
/// <summary>Has it settled which way it's going?</summary>
public bool set;
/// <summary>Where it was last put, and for how many steps it hasn't moved: a jammed line is left alone.</summary>
public float placedD = -1f;
public int still;
}
struct Link
@ -307,6 +310,7 @@ namespace GrassCutter
int i = 0;
while (i < Items.Count && Items[i].d > d) i++;
Items.Insert(i, s);
_idle = 0;
}
/// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary>
@ -334,7 +338,10 @@ namespace GrassCutter
void FixedUpdate()
{
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
float dt = Time.fixedDeltaTime;
// a line that hasn't moved for a while only looks again every few steps whether the front can go on
if (_idle > 40 && ++_idleSkip % 6 != 0) return;
bool moved = false;
float dt = Time.fixedDeltaTime * (_idle > 40 ? 6f : 1f);
float step = Speed * dt;
for (int i = 0; i < Items.Count; i++)
{
@ -347,16 +354,25 @@ namespace GrassCutter
}
float L = Length(s.route);
float limit = Room(i, ref L);
if (s.d < limit) s.d = Mathf.Min(s.d + step, limit);
if (s.d < limit - 1e-5f) { s.d = Mathf.Min(s.d + step, limit); moved = true; }
if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s))
{
Items.RemoveAt(i--);
moved = true;
continue;
}
// stuck behind the one ahead: once it has come square and settled there is nothing to move
if (s.blend >= 1f && Mathf.Abs(s.d - s.placedD) < 1e-5f) { if (++s.still > 40) continue; }
else s.still = 0;
Place(s, dt);
s.placedD = s.d;
if (s.blend < 1f) moved = true;
}
_idle = moved ? 0 : _idle + 1;
}
int _idle, _idleSkip;
/// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary>
float Room(int i, ref float L)
{

View File

@ -44,6 +44,7 @@ namespace GrassCutter
public override void OnNetworkSpawn()
{
CargoTick.Ensure();
All.Add(this);
Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody);
Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s;
@ -155,15 +156,28 @@ namespace GrassCutter
if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange);
}
void FixedUpdate()
int _still;
Cargo _cargo;
bool _cargoLooked;
/// <summary>One physics step, from <see cref="CargoTick"/>.</summary>
internal void Step()
{
if (!IsSpawned || !IsOwner || !Body || Body.isKinematic) return;
// at rest it sleeps: our own gravity, pushed every step, would keep it awake for ever, and a big farm has
// hundreds of bundles lying about. A knock, a grab or a belt wakes it again.
if (Body.IsSleeping()) return;
var p = Body.position;
var up = Planet.Up(p);
if (!IsHeld) Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration);
// there is no collider under the grass: the soil is a number
var c = GetComponent<Cargo>();
float below = Planet.Altitude(p) - (c ? c.halfHeight : 0.3f);
if (!_cargoLooked) { _cargo = GetComponent<Cargo>(); _cargoLooked = true; }
float below = Planet.Altitude(p) - (_cargo ? _cargo.halfHeight : 0.3f);
if (!IsHeld && Body.linearVelocity.sqrMagnitude < 0.004f && Body.angularVelocity.sqrMagnitude < 0.01f)
{
if (++_still > 25) { _still = 0; Body.Sleep(); return; }
}
else _still = 0;
if (below >= 0f) return;
Body.position = p - up * below;
var v = Body.linearVelocity;

View File

@ -97,6 +97,8 @@ namespace GrassCutter
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1;
/// <summary>Grass draws issued last frame (for -demogpu).</summary>
public int Draws { get; private set; }
int _deckHash;
/// <summary>The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.</summary>
@ -119,6 +121,86 @@ namespace GrassCutter
void OnDestroy()
{
if (_furTex) Destroy(_furTex);
foreach (var b in _batches) b.buffer?.Release();
if (_furBatchMat) Destroy(_furBatchMat);
}
// ───────────────────────── batches ─────────────────────────
/// <summary>One sector's frame as the fur shader reads it from <c>_GcSectorBuf</c> (GC_SECTOR_BUFFER).</summary>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
struct SectorData { public Vector4 c, e1, e2, salt, grid, b0, b1, b2, b3, b4, b5; }
/// <summary>The sectors of one pile and one shared mow map look, drawn together at the end of the frame.</summary>
sealed class Batch
{
public Pile pile;
public bool onlyWorked;
public Texture2D mask;
public readonly List<SectorData> items = new List<SectorData>();
public Bounds bounds;
public GraphicsBuffer buffer;
public readonly MaterialPropertyBlock mpb = new MaterialPropertyBlock();
}
static readonly int SectorBufId = Shader.PropertyToID("_GcSectorBuf");
readonly List<Batch> _batches = new List<Batch>();
Material _furBatchMat;
bool Batched(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
if (mask != MowMap.Blank && mask != MowMap.Full) return false;
if (!_furBatchMat && furMat)
{
_furBatchMat = new Material(furMat) { name = furMat.name + " (batched)" };
_furBatchMat.EnableKeyword("GC_SECTOR_BUFFER");
}
if (!_furBatchMat) return false;
Batch b = null;
foreach (var x in _batches)
if (x.mask == mask && x.onlyWorked == onlyWorked && x.pile.shells == p.shells && x.pile.inner == p.inner && x.pile.outer == p.outer && x.pile.fadeA == p.fadeA && x.pile.fadeB == p.fadeB) { b = x; break; }
if (b == null) { b = new Batch { pile = p, onlyWorked = onlyWorked, mask = mask }; _batches.Add(b); }
if (b.items.Count == 0) b.bounds = s.bounds; else b.bounds.Encapsulate(s.bounds);
bool floor = p.shells == 1;
var bs = s.borders;
b.items.Add(new SectorData
{
c = s.c, e1 = s.e1, e2 = s.e2, salt = s.salt,
grid = new Vector4(s.half, s.half * 2f / ((floor ? FloorSide : GridSide) - 1), 0f, 0f),
b0 = bs[0], b1 = bs[1], b2 = bs[2], b3 = bs[3], b4 = bs[4], b5 = bs[5],
});
return true;
}
void DrawBatches()
{
foreach (var b in _batches)
{
int n = b.items.Count;
if (n == 0) continue;
if (b.buffer == null || b.buffer.count < n)
{
b.buffer?.Release();
b.buffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, Mathf.NextPowerOfTwo(Mathf.Max(64, n)), System.Runtime.InteropServices.Marshal.SizeOf<SectorData>());
}
b.buffer.SetData(b.items);
var p = b.pile;
b.mpb.SetBuffer(SectorBufId, b.buffer);
b.mpb.SetTexture(MaskTexId, b.mask);
b.mpb.SetVector(ShellsId, new Vector4(p.shells, b.onlyWorked ? 0f : p.inner, b.onlyWorked ? 1e6f : p.outer, SeamBand));
b.mpb.SetVector(FadeId, new Vector4(p.fadeA, b.onlyWorked ? 1e6f : p.fadeB, b.onlyWorked ? 1f : 0f, 0f));
var rp = new RenderParams(_furBatchMat)
{
worldBounds = b.bounds,
matProps = b.mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, p.shells == 1 ? _floorGrid : _grid, 0, p.shells * n);
_drawn++;
b.items.Clear();
}
}
/// <summary>Meadow height in metres.</summary>
@ -177,6 +259,7 @@ namespace GrassCutter
int here = HexGrid.SectorAt(dir);
if (here != _here || _gatheredReach != FurReach) { _here = here; _gatheredReach = FurReach; GatherNear(here); }
_mpbUsed = 0;
_drawn = 0;
PublishFurAxes(dir);
GeometryUtility.CalculateFrustumPlanes(cam, _frustum);
@ -187,6 +270,13 @@ namespace GrassCutter
float arc = (s.c - dir).magnitude * Planet.Radius;
float reachable = Mathf.Max(arc - s.radius, alt);
var mask = MowMap.TextureFor(s);
// mown to the last blade: only the floor shows (the pile's shells and every plant are cut away in the
// shader anyway), one draw instead of up to six. Near the base that is most of what is in view.
if (mask == MowMap.Full && mask)
{
if (furMat) DrawPile(FurFloor, s, mask, true);
continue;
}
if (furMat)
{
var far = FurFar;
@ -214,8 +304,12 @@ namespace GrassCutter
if (furMat)
foreach (var s in _worked)
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true);
DrawBatches();
Draws = _mpbUsed + _drawn;
}
int _drawn;
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
void GatherNear(int here)
{
@ -276,6 +370,7 @@ namespace GrassCutter
/// <summary>The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.</summary>
void DrawPile(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
if (Batched(p, s, mask, onlyWorked)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
bool floor = p.shells == 1;

View File

@ -60,6 +60,8 @@ namespace GrassCutter
public static IEnumerable<Mask> All => s_masks.Values;
/// <summary>The map of a sector with nothing on it.</summary>
public static Texture2D Blank => s_none;
/// <summary>The look of a sector mown to the last blade (with no rock in it): nothing is left standing on it.</summary>
public static Texture2D Full => s_full;
public static int Started { get; private set; }
public static int Finished { get; private set; }