diff --git a/Assets/Editor/ProjectBuilder.cs b/Assets/Editor/ProjectBuilder.cs
index d0eb87f..9c5cbdb 100644
--- a/Assets/Editor/ProjectBuilder.cs
+++ b/Assets/Editor/ProjectBuilder.cs
@@ -61,6 +61,8 @@ namespace GrassCutter.EditorTools
PlayerSettings.SetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows64, false);
PlayerSettings.SetGraphicsAPIs(BuildTarget.StandaloneWindows64, new[] { UnityEngine.Rendering.GraphicsDeviceType.Direct3D11 });
// GC_BUILD_DIR builds somewhere else, so a copy of the game that is running doesn't lock the build
+ // a development build also reports GPU and render-thread frame times (FrameTimingManager), for -demoperf
+ PlayerSettings.enableFrameTimingStats = CommandLineHas("-devbuild");
var dir = Environment.GetEnvironmentVariable("GC_BUILD_DIR") is string d && d.Length > 0 ? d : "Builds/GrassCutter";
var opts = new BuildPlayerOptions
{
diff --git a/Assets/Scripts/Core/DemoBot.Gpu.cs b/Assets/Scripts/Core/DemoBot.Gpu.cs
new file mode 100644
index 0000000..4fd35d9
--- /dev/null
+++ b/Assets/Scripts/Core/DemoBot.Gpu.cs
@@ -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
+ {
+ ///
+ /// -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.
+ ///
+ 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();
+ var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
+ var camData = cam ? cam.GetUniversalAdditionalCameraData() : null;
+ var sun = FindObjectsByType(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(FindObjectsSortMode.None).Length} renderers, {FindObjectsByType(FindObjectsSortMode.None).Length} lights");
+
+ void Toggle(IEnumerable rs, bool on) { foreach (var r in rs) if (r) r.enabled = on; }
+ List Of(IEnumerable cs) => cs.Where(c => c).SelectMany(c => c.GetComponentsInChildren()).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(FindObjectsSortMode.None)) if (l != sun) l.enabled = false; }, () => { foreach (var l in FindObjectsByType(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 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();
+ }
+ }
+}
diff --git a/Assets/Scripts/Core/DemoBot.Gpu.cs.meta b/Assets/Scripts/Core/DemoBot.Gpu.cs.meta
new file mode 100644
index 0000000..9dbdffa
--- /dev/null
+++ b/Assets/Scripts/Core/DemoBot.Gpu.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f67da5b26efc4004580fe49bb92bc022
\ No newline at end of file
diff --git a/Assets/Scripts/Core/DemoBot.Perf.cs b/Assets/Scripts/Core/DemoBot.Perf.cs
index cc081b0..a4a7623 100644
--- a/Assets/Scripts/Core/DemoBot.Perf.cs
+++ b/Assets/Scripts/Core/DemoBot.Perf.cs
@@ -29,6 +29,12 @@ namespace GrassCutter
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);
diff --git a/Assets/Scripts/Core/DemoBot.cs b/Assets/Scripts/Core/DemoBot.cs
index 2360c87..cd89b3a 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("-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));
diff --git a/Assets/Scripts/Core/GameBoot.cs b/Assets/Scripts/Core/GameBoot.cs
index 5156b22..24bd72c 100644
--- a/Assets/Scripts/Core/GameBoot.cs
+++ b/Assets/Scripts/Core/GameBoot.cs
@@ -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().path = path;
if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent().folder = demo;
}
+
+ ///
+ /// 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.
+ ///
+ 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(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(FindObjectsInactive.Include, FindObjectsSortMode.None))
+ r.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off;
+ }
}
}
diff --git a/Assets/Scripts/Gameplay/BeltSplitter.cs b/Assets/Scripts/Gameplay/BeltSplitter.cs
index 94a0f74..83f2ef7 100644
--- a/Assets/Scripts/Gameplay/BeltSplitter.cs
+++ b/Assets/Scripts/Gameplay/BeltSplitter.cs
@@ -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;
diff --git a/Assets/Scripts/Gameplay/Cargo.cs b/Assets/Scripts/Gameplay/Cargo.cs
index ae2bd05..abf739a 100644
--- a/Assets/Scripts/Gameplay/Cargo.cs
+++ b/Assets/Scripts/Gameplay/Cargo.cs
@@ -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()
+ /// One physics step, called by for every bundle at once: two thousand Unity
+ /// FixedUpdate messages cost more than the work in them.
+ 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
diff --git a/Assets/Scripts/Gameplay/CargoTick.cs b/Assets/Scripts/Gameplay/CargoTick.cs
new file mode 100644
index 0000000..fdabc4e
--- /dev/null
+++ b/Assets/Scripts/Gameplay/CargoTick.cs
@@ -0,0 +1,32 @@
+using UnityEngine;
+
+namespace GrassCutter
+{
+ ///
+ /// 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.
+ ///
+ 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();
+ }
+
+ 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();
+ }
+ }
+}
diff --git a/Assets/Scripts/Gameplay/CargoTick.cs.meta b/Assets/Scripts/Gameplay/CargoTick.cs.meta
new file mode 100644
index 0000000..f5561e9
--- /dev/null
+++ b/Assets/Scripts/Gameplay/CargoTick.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c675567074ef89b49b1f9073c8ee1535
\ No newline at end of file
diff --git a/Assets/Scripts/Gameplay/Conveyor.cs b/Assets/Scripts/Gameplay/Conveyor.cs
index b5062de..0174447 100644
--- a/Assets/Scripts/Gameplay/Conveyor.cs
+++ b/Assets/Scripts/Gameplay/Conveyor.cs
@@ -46,6 +46,9 @@ namespace GrassCutter
public float blend;
/// Has it settled which way it's going?
public bool set;
+ /// Where it was last put, and for how many steps it hasn't moved: a jammed line is left alone.
+ 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;
}
/// Server: take an item off this belt (a player grabbed it, it got despawned).
@@ -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;
+
/// 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.
float Room(int i, ref float L)
{
diff --git a/Assets/Scripts/Gameplay/Grabbable.cs b/Assets/Scripts/Gameplay/Grabbable.cs
index 23625f3..c6fd2e0 100644
--- a/Assets/Scripts/Gameplay/Grabbable.cs
+++ b/Assets/Scripts/Gameplay/Grabbable.cs
@@ -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;
+
+ /// One physics step, from .
+ 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();
- float below = Planet.Altitude(p) - (c ? c.halfHeight : 0.3f);
+ if (!_cargoLooked) { _cargo = GetComponent(); _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;
diff --git a/Assets/Scripts/World/GrassField.cs b/Assets/Scripts/World/GrassField.cs
index 55c22e9..a1d837b 100644
--- a/Assets/Scripts/World/GrassField.cs
+++ b/Assets/Scripts/World/GrassField.cs
@@ -97,6 +97,8 @@ namespace GrassCutter
readonly List _worked = new List();
readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1;
+ /// Grass draws issued last frame (for -demogpu).
+ public int Draws { get; private set; }
int _deckHash;
/// The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.
@@ -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 ─────────────────────────
+
+ /// One sector's frame as the fur shader reads it from _GcSectorBuf (GC_SECTOR_BUFFER).
+ [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
+ struct SectorData { public Vector4 c, e1, e2, salt, grid, b0, b1, b2, b3, b4, b5; }
+
+ /// The sectors of one pile and one shared mow map look, drawn together at the end of the frame.
+ sealed class Batch
+ {
+ public Pile pile;
+ public bool onlyWorked;
+ public Texture2D mask;
+ public readonly List items = new List();
+ public Bounds bounds;
+ public GraphicsBuffer buffer;
+ public readonly MaterialPropertyBlock mpb = new MaterialPropertyBlock();
+ }
+
+ static readonly int SectorBufId = Shader.PropertyToID("_GcSectorBuf");
+ readonly List _batches = new List();
+ 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());
+ }
+ 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();
+ }
}
/// Meadow height in metres.
@@ -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;
+
/// Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.
void GatherNear(int here)
{
@@ -276,6 +370,7 @@ namespace GrassCutter
/// The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.
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;
diff --git a/Assets/Scripts/World/MowMap.cs b/Assets/Scripts/World/MowMap.cs
index c2bab0d..e59767f 100644
--- a/Assets/Scripts/World/MowMap.cs
+++ b/Assets/Scripts/World/MowMap.cs
@@ -60,6 +60,8 @@ namespace GrassCutter
public static IEnumerable All => s_masks.Values;
/// The map of a sector with nothing on it.
public static Texture2D Blank => s_none;
+ /// The look of a sector mown to the last blade (with no rock in it): nothing is left standing on it.
+ public static Texture2D Full => s_full;
public static int Started { get; private set; }
public static int Finished { get; private set; }
diff --git a/Assets/Settings/PC_RPAsset.asset b/Assets/Settings/PC_RPAsset.asset
index e2086e1..f6f3d6b 100644
--- a/Assets/Settings/PC_RPAsset.asset
+++ b/Assets/Settings/PC_RPAsset.asset
@@ -82,7 +82,7 @@ MonoBehaviour:
m_UseFastSRGBLinearConversion: 0
m_SupportDataDrivenLensFlare: 1
m_SupportScreenSpaceLensFlare: 1
- m_GPUResidentDrawerMode: 1
+ m_GPUResidentDrawerMode: 0
m_SmallMeshScreenPercentage: 0
m_ShadowSmallMeshScreenPercentages: {x: 0, y: 0, z: 0, w: 0}
m_GPUResidentDrawerEnableOcclusionCullingInCameras: 0
@@ -132,7 +132,7 @@ MonoBehaviour:
m_PrefilterScreenCoord: 1
m_PrefilterScreenSpaceIrradiance: 1
m_PrefilterNativeRenderPass: 1
- m_PrefilterUseLegacyLightmaps: 1
+ m_PrefilterUseLegacyLightmaps: 0
m_PrefilterBicubicLightmapSampling: 1
m_PrefilterReflectionProbeRotation: 0
m_PrefilterReflectionProbeBlending: 0
diff --git a/Assets/Shaders/GrassFur.shader b/Assets/Shaders/GrassFur.shader
index d975dfc..83a3926 100644
--- a/Assets/Shaders/GrassFur.shader
+++ b/Assets/Shaders/GrassFur.shader
@@ -37,9 +37,26 @@ Shader "GrassCutter/GrassFur"
#pragma multi_compile _ _MAIN_LIGHT_SHADOWS _MAIN_LIGHT_SHADOWS_CASCADE _MAIN_LIGHT_SHADOWS_SCREEN
#pragma multi_compile_fragment _ _SHADOWS_SOFT _SHADOWS_SOFT_LOW _SHADOWS_SOFT_MEDIUM _SHADOWS_SOFT_HIGH
#pragma multi_compile_fog
+ // many sectors in one draw: instance = sector * shells + shell, the sector's frame from a buffer. Only for
+ // sectors that share a mow map look (untouched, or mown to the last blade): on a small planet there are
+ // hundreds of them in view, and one draw each was most of a frame's CPU.
+ #pragma multi_compile_local _ GC_SECTOR_BUFFER
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
+ #if defined(GC_SECTOR_BUFFER)
+ struct GcSectorData { float4 c, e1, e2, salt, grid; float4 b[6]; };
+ StructuredBuffer _GcSectorBuf;
+ static GcSectorData gcS;
+ #define GC_SECTOR_C gcS.c
+ #define GC_SECTOR_E1 gcS.e1
+ #define GC_SECTOR_E2 gcS.e2
+ #define GC_SECTOR_SALT gcS.salt
+ #define GC_SECTOR_BORDER(k) gcS.b[k]
+ #define GC_GRID gcS.grid
+ #else
+ #define GC_GRID _GcGrid
+ #endif
#include "Planet.hlsl"
CBUFFER_START(UnityPerMaterial)
@@ -77,6 +94,7 @@ Shader "GrassCutter/GrassFur"
float4 data : TEXCOORD1; // x = shell 0..1, y = pile height here, z = big patch noise, w = edge fade
float3 root : TEXCOORD2; // undisplaced world position (strand lookup)
float fog : TEXCOORD3;
+ nointerpolation uint sid : TEXCOORD6; // which sector of the draw
float2 plane : TEXCOORD4; // the sector's flat frame (mow map)
float2 air : TEXCOORD5; // x = sun through the clouds, y = gust passing
};
@@ -84,18 +102,23 @@ Shader "GrassCutter/GrassFur"
Varyings vert(Attributes v)
{
float shells = _GcShells.x;
+ uint sid = v.iid / (uint)shells;
+ uint shell = v.iid - sid * (uint)shells;
+ #if defined(GC_SECTOR_BUFFER)
+ gcS = _GcSectorBuf[sid];
+ #endif
// instance 0 is the top shell; a single shell is the solid floor under the strands
- float t = shells > 1 ? 1 - (float)v.iid / (shells - 1) : 0;
- float2 plane = v.positionOS.xz * _GcGrid.x;
- float3 up = normalize(_GcC.xyz * _GcPlanet.w + _GcE1.xyz * plane.x + _GcE2.xyz * plane.y);
+ float t = shells > 1 ? 1 - (float)shell / (shells - 1) : 0;
+ float2 plane = v.positionOS.xz * GC_GRID.x;
+ float3 up = normalize(GC_SECTOR_C.xyz * _GcPlanet.w + GC_SECTOR_E1.xyz * plane.x + GC_SECTOR_E2.xyz * plane.y);
float3 t1, t2;
GcTangents(up, t1, t2);
// a grid cuts corners over bumps: each corner stands on the highest ground within half a cell of it, and a
// little over, so no bump between corners comes up through the floor
- float hs = _GcGrid.y * 0.5 / _GcPlanet.w;
+ float hs = GC_GRID.y * 0.5 / _GcPlanet.w;
float ground = max(GcHeight(up), max(max(GcHeight(normalize(up + t1 * hs)), GcHeight(normalize(up - t1 * hs))),
max(GcHeight(normalize(up + t2 * hs)), GcHeight(normalize(up - t2 * hs)))));
- float3 root = _GcPlanet.xyz + up * (_GcPlanet.w + ground + 0.01 + _GcGrid.y * 0.012);
+ float3 root = _GcPlanet.xyz + up * (_GcPlanet.w + ground + 0.01 + GC_GRID.y * 0.012);
float dist = length(root - _GcCam.xyz);
float fade = 1 - smoothstep(_GcFade.x, _GcFade.y, dist);
@@ -148,6 +171,7 @@ Shader "GrassCutter/GrassFur"
o.plane = plane;
o.fog = ComputeFogFactor(o.positionCS.z);
o.air = float2(GcCloudSun(root, tm), gust);
+ o.sid = sid;
return o;
}
@@ -161,8 +185,11 @@ Shader "GrassCutter/GrassFur"
if ((_GcShells.y > 0 && dist < _GcShells.y + e) || dist >= _GcShells.z + e) discard;
// a sector's square reaches past its borders: each pixel belongs to one sector
+ #if defined(GC_SECTOR_BUFFER)
+ gcS = _GcSectorBuf[i.sid];
+ #endif
float3 d = normalize(i.root - _GcPlanet.xyz);
- for (int b = 0; b < 6; b++) if (dot(d, _GcBorders[b].xyz) > 0) discard;
+ for (int b = 0; b < 6; b++) if (dot(d, GC_SECTOR_BORDER(b).xyz) > 0) discard;
float2 mask = GcMask(i.plane);
bool solid = t < 0.001; // the bottom of the pile: the floor everything stands on
diff --git a/Assets/Shaders/Planet.hlsl b/Assets/Shaders/Planet.hlsl
index 33e114a..e2cec00 100644
--- a/Assets/Shaders/Planet.hlsl
+++ b/Assets/Shaders/Planet.hlsl
@@ -47,6 +47,15 @@ float4 _GcC, _GcE1, _GcE2;
float4 _GcSalt; // xy = seed, z = flat frame metres to mow map uv
float4 _GcBorders[6];
+// a shader that draws many sectors in one go defines these first (GrassFur: GC_SECTOR_BUFFER)
+#ifndef GC_SECTOR_C
+#define GC_SECTOR_C _GcC
+#define GC_SECTOR_E1 _GcE1
+#define GC_SECTOR_E2 _GcE2
+#define GC_SECTOR_SALT _GcSalt
+#define GC_SECTOR_BORDER(k) _GcBorders[k]
+#endif
+
float GcHeight(float3 d)
{
float3 a = abs(d);
@@ -82,22 +91,22 @@ void GcTangents(float3 up, out float3 t1, out float3 t2)
// this sector's mow map at a spot of its flat frame: r = cut (0..1), g = nothing grows here
float2 GcMask(float2 plane)
{
- return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * _GcSalt.z + 0.5, 0).rg;
+ return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * GC_SECTOR_SALT.z + 0.5, 0).rg;
}
// how close a cut is: the map blurred over half a metre, so the grass beside a narrow strip can stand lower than the rest
float GcMaskNear(float2 plane)
{
- return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * _GcSalt.z + 0.5, 1.5).r;
+ return SAMPLE_TEXTURE2D_LOD(_GcMaskTex, sampler_GcMaskTex, plane * GC_SECTOR_SALT.z + 0.5, 1.5).r;
}
// A spot in the flat frame of this draw's sector, on the ball. Each strand belongs to exactly one sector: the one whose
// borders all lie ahead of it. edge = metres to the nearest of them.
bool GcInSector(float2 plane, out float3 dir, out float edge)
{
- dir = normalize(_GcC.xyz * _GcPlanet.w + _GcE1.xyz * plane.x + _GcE2.xyz * plane.y);
+ dir = normalize(GC_SECTOR_C.xyz * _GcPlanet.w + GC_SECTOR_E1.xyz * plane.x + GC_SECTOR_E2.xyz * plane.y);
edge = 1e5;
- for (int k = 0; k < 6; k++) edge = min(edge, -dot(dir, _GcBorders[k].xyz));
+ for (int k = 0; k < 6; k++) edge = min(edge, -dot(dir, GC_SECTOR_BORDER(k).xyz));
return edge >= 0;
}