Frame time on a big farm, round two: riding layer, instanced bundles
- Bundles on a belt move to a Riding layer that ignores the belts and the static world: every belt's catch trigger called OnTriggerStay (with a GetComponent) for each bundle riding it, every physics step. - Bundles draw as instanced batches from CargoTick (their own renderers off, one in someone's hands draws itself), not as 2000 renderers to cull, sort and draw in the view and every shadow cascade. - The main camera skips front-to-back sorting: the GPU has time to spare. - BeltNet.Belted and DronePad.Belted are cached until the build changes; splitters on the host look only at their own items. On the player's Mommy save, 2560x1440: base 14-15 ms -> 7.7 ms (~130 fps), meadow 11.5-12 ms -> 6.8-7.5 ms (~135-145 fps). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -93,7 +93,7 @@ namespace GrassCutter.EditorTools
|
||||
var tm = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
|
||||
var layers = tm.FindProperty("layers");
|
||||
void L(int i, string n) { layers.GetArrayElementAtIndex(i).stringValue = n; }
|
||||
L(6, "Player"); L(7, "Cargo"); L(8, "Prop"); L(9, "Vehicle"); L(10, "Held"); L(11, "ViewModel"); L(12, "LocalPlayer"); L(13, "Build");
|
||||
L(6, "Player"); L(7, "Cargo"); L(8, "Prop"); L(9, "Vehicle"); L(10, "Held"); L(11, "ViewModel"); L(12, "LocalPlayer"); L(13, "Build"); L(14, "Riding");
|
||||
tm.ApplyModifiedPropertiesWithoutUndo();
|
||||
|
||||
PlayerSettings.companyName = "GreenHaul";
|
||||
|
||||
@ -219,7 +219,7 @@ namespace GrassCutter
|
||||
var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head;
|
||||
var dir = cam.forward;
|
||||
float d = ahead;
|
||||
if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Prop), QueryTriggerInteraction.Ignore))
|
||||
if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | Layers.CargoMask, QueryTriggerInteraction.Ignore))
|
||||
d = Mathf.Max(0.6f, hit.distance - 0.6f);
|
||||
var p = cam.position + dir * d;
|
||||
float above = Vector3.Dot(p - Me.transform.position, Me.transform.up);
|
||||
|
||||
@ -53,6 +53,8 @@ namespace GrassCutter
|
||||
("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)),
|
||||
("bundles not instanced", () => CargoTick.Instanced = false, () => CargoTick.Instanced = true),
|
||||
("distance sort on", () => { if (cam) cam.opaqueSortMode = OpaqueSortMode.Default; }, () => { if (cam) cam.opaqueSortMode = OpaqueSortMode.NoDistanceSort; }),
|
||||
("render scale 0.75", () => asset.renderScale = 0.75f, () => asset.renderScale = 1f),
|
||||
};
|
||||
foreach (var f in features)
|
||||
|
||||
@ -97,8 +97,13 @@ namespace GrassCutter
|
||||
Cargo inJunction = null;
|
||||
float side = 0f;
|
||||
var here = transform.position;
|
||||
foreach (var c in Cargo.All)
|
||||
// the host has its own items in a list; a joined peer looks round every few frames
|
||||
bool mine = Server;
|
||||
if (!mine && (Time.frameCount + _phase) % 4 != 0) { Paddle(); return; }
|
||||
int count = mine ? Items.Count : Cargo.All.Count;
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
var c = mine ? Items[k].c : Cargo.All[k];
|
||||
if (!c) continue;
|
||||
var at = c.transform.position;
|
||||
// most of a farm's bundles are nowhere near: the cheap test first
|
||||
@ -117,11 +122,17 @@ namespace GrassCutter
|
||||
_paddleTarget = -side * 38f;
|
||||
Sfx.PlayAt("splitter_flip", transform.position + transform.up * 0.4f, 0.55f, 1f, 0.08f);
|
||||
}
|
||||
if (paddle)
|
||||
{
|
||||
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
|
||||
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest;
|
||||
}
|
||||
Paddle();
|
||||
}
|
||||
|
||||
static int s_phases;
|
||||
readonly int _phase = s_phases++;
|
||||
|
||||
void Paddle()
|
||||
{
|
||||
if (!paddle) return;
|
||||
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
|
||||
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -21,11 +21,42 @@ namespace GrassCutter
|
||||
Grabbable _g;
|
||||
bool _wasInGrass;
|
||||
public bool Loaded { get; set; }
|
||||
/// <summary>Server: the belt this item is locked onto (null when loose).</summary>
|
||||
public Conveyor Belt { get; set; }
|
||||
/// <summary>Server: the belt this item is locked onto (null when loose). On a belt it is on the Riding layer.</summary>
|
||||
public Conveyor Belt
|
||||
{
|
||||
get => _belt;
|
||||
set
|
||||
{
|
||||
bool was = !ReferenceEquals(_belt, null), now = !ReferenceEquals(value, null);
|
||||
_belt = value;
|
||||
if (was != now) Ride(now);
|
||||
}
|
||||
}
|
||||
Conveyor _belt;
|
||||
Transform[] _parts;
|
||||
|
||||
void Ride(bool riding)
|
||||
{
|
||||
if (_parts == null) _parts = GetComponentsInChildren<Transform>(true);
|
||||
int layer = riding ? Layers.Riding : Layers.Prop;
|
||||
foreach (var t in _parts)
|
||||
if (t && (t.gameObject.layer == Layers.Prop || t.gameObject.layer == Layers.Riding)) t.gameObject.layer = layer;
|
||||
}
|
||||
public Grabbable Grab => _g ? _g : (_g = GetComponent<Grabbable>());
|
||||
|
||||
void Awake() { _g = GetComponent<Grabbable>(); }
|
||||
void Awake()
|
||||
{
|
||||
_g = GetComponent<Grabbable>();
|
||||
// what it looks like, for CargoTick to draw it with all the others
|
||||
Look = GetComponentInChildren<MeshRenderer>(true);
|
||||
var mf = Look ? Look.GetComponent<MeshFilter>() : null;
|
||||
LookMesh = mf ? mf.sharedMesh : null;
|
||||
LookMats = Look ? Look.sharedMaterials : null;
|
||||
}
|
||||
|
||||
public MeshRenderer Look { get; private set; }
|
||||
public Mesh LookMesh { get; private set; }
|
||||
public Material[] LookMats { get; private set; }
|
||||
|
||||
/// <summary>Server: unlock from the belt and become a loose physics body again.</summary>
|
||||
public void ServerLeaveBelt(Vector3 velocity)
|
||||
@ -70,6 +101,7 @@ namespace GrassCutter
|
||||
/// FixedUpdate messages cost more than the work in them.</summary>
|
||||
internal void Step()
|
||||
{
|
||||
if (_belt) return;
|
||||
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)
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
@ -28,5 +30,90 @@ namespace GrassCutter
|
||||
for (int i = c.Count - 1; i >= 0; i--)
|
||||
if (i < c.Count && c[i]) c[i].Step();
|
||||
}
|
||||
|
||||
// ───────────────────────── drawing ─────────────────────────
|
||||
//
|
||||
// Two thousand bundles were two thousand renderers: culled, sorted and drawn one by one, in the main view and
|
||||
// every shadow cascade. Their own renderers are off and they go down here as a few instanced draws, one per
|
||||
// model. One in someone's hands draws itself as before (it may be on another layer, in first person).
|
||||
|
||||
/// <summary>Off: every bundle draws itself again (a switch for tests).</summary>
|
||||
public static bool Instanced = true;
|
||||
|
||||
sealed class Group
|
||||
{
|
||||
public Mesh mesh;
|
||||
public int sub;
|
||||
public Material mat;
|
||||
public Matrix4x4[] m = new Matrix4x4[256];
|
||||
public int n;
|
||||
public Bounds bounds;
|
||||
}
|
||||
|
||||
readonly Dictionary<(Mesh, int, Material), Group> _groups = new Dictionary<(Mesh, int, Material), Group>();
|
||||
readonly List<Group> _order = new List<Group>();
|
||||
static readonly Dictionary<Material, Material> s_instanced = new Dictionary<Material, Material>();
|
||||
const int Chunk = 1023;
|
||||
|
||||
static Material InstancedCopy(Material m)
|
||||
{
|
||||
if (!s_instanced.TryGetValue(m, out var copy))
|
||||
{
|
||||
copy = new Material(m) { name = m.name + " (instanced)", enableInstancing = true };
|
||||
s_instanced[m] = copy;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
foreach (var g in _order) g.n = 0;
|
||||
var all = Cargo.All;
|
||||
for (int i = 0; i < all.Count; i++)
|
||||
{
|
||||
var c = all[i];
|
||||
if (!c) continue;
|
||||
var r = c.Look;
|
||||
if (!r) continue;
|
||||
bool mine = Instanced && !c.Grab.IsHeld && c.gameObject.activeInHierarchy;
|
||||
if (r.enabled == mine) r.enabled = !mine;
|
||||
if (!mine) continue;
|
||||
var mesh = c.LookMesh;
|
||||
var mats = c.LookMats;
|
||||
if (!mesh || mats == null) { r.enabled = true; continue; }
|
||||
var m = r.localToWorldMatrix;
|
||||
var at = new Vector3(m.m03, m.m13, m.m23);
|
||||
for (int sub = 0; sub < mesh.subMeshCount && sub < mats.Length; sub++)
|
||||
{
|
||||
var mat = mats[sub];
|
||||
if (!mat) continue;
|
||||
var key = (mesh, sub, mat);
|
||||
if (!_groups.TryGetValue(key, out var g))
|
||||
{
|
||||
g = new Group { mesh = mesh, sub = sub, mat = InstancedCopy(mat) };
|
||||
_groups[key] = g;
|
||||
_order.Add(g);
|
||||
}
|
||||
if (g.n == g.m.Length) System.Array.Resize(ref g.m, g.m.Length * 2);
|
||||
if (g.n == 0) g.bounds = new Bounds(at, Vector3.one); else g.bounds.Encapsulate(at);
|
||||
g.m[g.n++] = m;
|
||||
}
|
||||
}
|
||||
foreach (var g in _order)
|
||||
{
|
||||
if (g.n == 0) continue;
|
||||
g.bounds.Expand(2f);
|
||||
var rp = new RenderParams(g.mat)
|
||||
{
|
||||
worldBounds = g.bounds,
|
||||
layer = Layers.Prop,
|
||||
shadowCastingMode = ShadowCastingMode.On,
|
||||
receiveShadows = true,
|
||||
lightProbeUsage = LightProbeUsage.Off,
|
||||
};
|
||||
for (int start = 0; start < g.n; start += Chunk)
|
||||
Graphics.RenderMeshInstanced(rp, g.mesh, g.sub, g.m, Mathf.Min(Chunk, g.n - start), start);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -434,7 +434,7 @@ namespace GrassCutter
|
||||
}
|
||||
// nothing there: drop it off the end, but only onto a free spot (one item waits there at a time)
|
||||
var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f;
|
||||
int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
|
||||
int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore);
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var other = s_hits[k].GetComponentInParent<Cargo>();
|
||||
@ -510,7 +510,7 @@ namespace GrassCutter
|
||||
port = index;
|
||||
if (belt && !belt.HasRoom) return false;
|
||||
}
|
||||
else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore) > 0) return false;
|
||||
else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore) > 0) return false;
|
||||
var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f);
|
||||
if (!made) return false;
|
||||
if (belt) belt.ServerAcceptPort(made, port);
|
||||
@ -544,9 +544,21 @@ namespace GrassCutter
|
||||
static readonly List<Port> s_belted = new List<Port>();
|
||||
|
||||
/// <summary>Does a belt leave any of this piece's hatches?</summary>
|
||||
static readonly Dictionary<BuildPiece, (int ver, bool on)> s_beltedAt = new Dictionary<BuildPiece, (int, bool)>();
|
||||
|
||||
public static bool Belted(BuildPiece piece)
|
||||
{
|
||||
if (!piece) return false;
|
||||
// asked every frame by every pad and dock: the answer only changes when the build does
|
||||
if (s_beltedAt.TryGetValue(piece, out var had) && had.ver == BuildPiece.Version) return had.on;
|
||||
bool on = Look(piece);
|
||||
if (s_beltedAt.Count > 512) s_beltedAt.Clear();
|
||||
s_beltedAt[piece] = (BuildPiece.Version, on);
|
||||
return on;
|
||||
}
|
||||
|
||||
static bool Look(BuildPiece piece)
|
||||
{
|
||||
s_belted.Clear();
|
||||
piece.Ports(s_belted);
|
||||
foreach (var p in s_belted)
|
||||
|
||||
@ -219,7 +219,17 @@ namespace GrassCutter
|
||||
static readonly List<Port> s_ports = new List<Port>();
|
||||
|
||||
/// <summary>Is a belt joined to the hatch?</summary>
|
||||
int _beltedVer = -1;
|
||||
bool _belted;
|
||||
|
||||
bool Belted()
|
||||
{
|
||||
if (_beltedVer == BuildPiece.Version) return _belted;
|
||||
_beltedVer = BuildPiece.Version;
|
||||
return _belted = LookForBelt();
|
||||
}
|
||||
|
||||
bool LookForBelt()
|
||||
{
|
||||
s_ports.Clear();
|
||||
Ports(s_ports);
|
||||
|
||||
@ -163,6 +163,9 @@ namespace GrassCutter
|
||||
/// <summary>One physics step, from <see cref="CargoTick"/>.</summary>
|
||||
internal void Step()
|
||||
{
|
||||
// riding a belt (most bundles on a big farm): nothing to do, and the managed test is the cheap one
|
||||
if (!_cargoLooked) { _cargo = GetComponent<Cargo>(); _cargoLooked = true; }
|
||||
if (_cargo && _cargo.Belt) return;
|
||||
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.
|
||||
@ -207,6 +210,10 @@ namespace GrassCutter
|
||||
public const int ViewModel = 11;
|
||||
public const int LocalPlayer = 12;
|
||||
public const int Build = 13;
|
||||
/// <summary>Cargo riding a belt: the belts' catch triggers (and the static world) don't see it, everything else does.</summary>
|
||||
public const int Riding = 14;
|
||||
/// <summary>Loose cargo and cargo on a belt, for the casts that look for either.</summary>
|
||||
public const int CargoMask = (1 << Prop) | (1 << Riding);
|
||||
|
||||
public static void SetupCollisions()
|
||||
{
|
||||
@ -216,9 +223,14 @@ namespace GrassCutter
|
||||
Physics.IgnoreLayerCollision(Wrap, Vehicle);
|
||||
Physics.IgnoreLayerCollision(ViewModel, Default);
|
||||
for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i);
|
||||
// a bundle on a belt is kinematic: against the belts and the static world it only ever made trigger calls,
|
||||
// one per bundle per belt per physics step (two thousand on a big farm), all of them for nothing
|
||||
Physics.IgnoreLayerCollision(Riding, Build);
|
||||
Physics.IgnoreLayerCollision(Riding, Default);
|
||||
Physics.IgnoreLayerCollision(Riding, Riding);
|
||||
}
|
||||
|
||||
/// <summary>Things the player's interaction ray can hit.</summary>
|
||||
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Vehicle) | (1 << Player) | (1 << Build);
|
||||
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Riding) | (1 << Vehicle) | (1 << Player) | (1 << Build);
|
||||
}
|
||||
}
|
||||
|
||||
@ -157,7 +157,7 @@ namespace GrassCutter
|
||||
{
|
||||
var at = TwisterPos(Now);
|
||||
var up = Planet.Up(at);
|
||||
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
|
||||
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, Layers.CargoMask, QueryTriggerInteraction.Ignore);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var rb = s_hits[i].attachedRigidbody;
|
||||
|
||||
@ -21,6 +21,8 @@ namespace GrassCutter
|
||||
{
|
||||
_i = this;
|
||||
Cam = GetComponent<Camera>();
|
||||
// the GPU has time to spare, the CPU doesn't: sorting thousands of draws front to back cost more than the overdraw it saves
|
||||
if (Cam) Cam.opaqueSortMode = UnityEngine.Rendering.OpaqueSortMode.NoDistanceSort;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -12,7 +12,7 @@ namespace GrassCutter
|
||||
public class CrewBody : MonoBehaviour
|
||||
{
|
||||
const float Skin = 0.03f, StepUp = 0.4f, FloorDot = 0.6f, StickDown = 0.3f;
|
||||
const int Solid = (1 << Layers.Default) | (1 << Physics.IgnoreRaycastLayer) | (1 << Layers.Prop) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.Build);
|
||||
const int Solid = (1 << Layers.Default) | (1 << Physics.IgnoreRaycastLayer) | (1 << Layers.Prop) | (1 << Layers.Riding) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.Build);
|
||||
|
||||
public bool isGrounded { get; private set; }
|
||||
/// <summary>Walked into something: what was hit and which way we were going.</summary>
|
||||
|
||||
Reference in New Issue
Block a user