Files
grass-cutters/Assets/Scripts/Gameplay/Grabbable.cs
NiemandKG 57d0f4d31a 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>
2026-11-09 20:01:02 +06:00

225 lines
8.4 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// A physics prop that players can pick up, carry and throw. Ownership moves to whoever grabs it so the
/// holder simulates it locally (no lag); NetworkTransform runs in owner-authority mode.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class Grabbable : NetworkBehaviour
{
public static readonly List<Grabbable> All = new List<Grabbable>();
public const ulong Nobody = ulong.MaxValue;
public string displayName = "Thing";
public bool trash;
public bool trashIsBox;
public float holdDistance = 1.4f;
/// <summary>Recycler payout multiplier (pallets are worth more than a wrap ball).</summary>
public float valueMul = 1f;
public readonly NetworkVariable<ulong> Holder = new NetworkVariable<ulong>(Nobody);
public readonly NetworkVariable<bool> IsTrashNet = new NetworkVariable<bool>();
public readonly NetworkVariable<float> Scale = new NetworkVariable<float>(1f);
public Rigidbody Body { get; private set; }
public bool IsTrash => trash || IsTrashNet.Value;
public bool IsHeld => Holder.Value != Nobody;
public bool Consumed { get; set; }
int _baseLayer;
Vector3 _baseScale;
void Awake()
{
Body = GetComponent<Rigidbody>();
Body.useGravity = false;
_baseLayer = gameObject.layer;
_baseScale = transform.localScale;
}
public override void OnNetworkSpawn()
{
CargoTick.Ensure();
All.Add(this);
Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody);
Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s;
transform.localScale = _baseScale * Scale.Value;
ApplyHeldLayer(IsHeld);
}
public override void OnNetworkDespawn() { All.Remove(this); }
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
void ApplyHeldLayer(bool held)
{
int layer = held ? Layers.Held : _baseLayer;
foreach (var t in GetComponentsInChildren<Transform>(true)) t.gameObject.layer = layer;
}
// ───────────────────────── grabbing ─────────────────────────
public void RequestGrab()
{
if (IsHeld) return;
GrabRpc();
}
[Rpc(SendTo.Server)]
void GrabRpc(RpcParams rpc = default)
{
if (IsHeld || Consumed) return;
// grabbing something off a belt unlocks it from the queue
var cargo = GetComponent<Cargo>();
if (cargo && cargo.Belt) cargo.ServerLeaveBelt(Vector3.zero);
ulong who = rpc.Receive.SenderClientId;
Holder.Value = who;
if (OwnerClientId != who) NetworkObject.ChangeOwnership(who);
GrabbedRpc(who);
}
[Rpc(SendTo.Everyone)]
void GrabbedRpc(ulong who)
{
Sfx.PlayAt(GrabClip, transform.position, 0.7f, 1.1f);
if (who == NetworkManager.LocalClientId) PlayerAgent.Local?.Grab.OnGrantedGrab(this);
}
/// <summary>Called by the holder (owner) to let go; velocity is applied locally since the holder owns the body.</summary>
public void Release(Vector3 velocity, Vector3 angular)
{
if (IsOwner && Body && !Body.isKinematic)
{
Body.linearVelocity = velocity;
Body.angularVelocity = angular;
}
ReleaseRpc();
}
[Rpc(SendTo.Server)]
void ReleaseRpc(RpcParams rpc = default)
{
if (Holder.Value == rpc.Receive.SenderClientId) Holder.Value = Nobody;
}
/// <summary>Server: forcibly drop (e.g. the holder disconnected or the item got recycled).</summary>
public void ServerForceRelease()
{
if (IsServer) Holder.Value = Nobody;
}
/// <summary>Ask the owner to apply an impulse (used by the recycler to spit out non-trash).</summary>
public void ServerKick(Vector3 velocity)
{
KickRpc(velocity, RpcTarget.Single(OwnerClientId, RpcTargetUse.Temp));
}
[Rpc(SendTo.SpecifiedInParams)]
void KickRpc(Vector3 velocity, RpcParams p = default)
{
if (Body && !Body.isKinematic) { Body.linearVelocity = velocity; Body.angularVelocity = Random.insideUnitSphere * 6f; }
}
string GrabClip
{
get
{
var c = GetComponent<Cargo>();
if (!c) return "plastic_grab";
return c.kind == CargoKind.Brick ? "ice_clink" : "barrel_clunk";
}
}
float _lastPush;
/// <summary>Nudge from a walking player. Applied directly when we simulate the body, otherwise forwarded to the owner.</summary>
public void Push(Vector3 velocity)
{
if (Time.time - _lastPush < 0.12f || !IsSpawned) return;
_lastPush = Time.time;
if (IsOwner) { if (Body && !Body.isKinematic) Body.AddForce(velocity, ForceMode.VelocityChange); }
else PushRpc(velocity);
}
[Rpc(SendTo.Owner)]
void PushRpc(Vector3 velocity)
{
if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange);
}
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
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;
float fall = Vector3.Dot(v, up);
if (fall < 0f) v -= up * fall;
Body.linearVelocity = v * 0.9f;
Body.angularVelocity *= 0.9f;
}
void OnCollisionEnter(Collision c)
{
float v = c.relativeVelocity.magnitude;
if (v < 2.2f || !IsSpawned) return;
string clip = GrabClip;
Sfx.PlayAt(clip, transform.position, Mathf.Clamp01(v / 8f) * 0.8f, 1f, 0.1f, 0.05f);
}
}
public static class Layers
{
public const int Default = 0;
public const int Player = 6;
public const int Wrap = 7;
public const int Prop = 8;
public const int Vehicle = 9;
public const int Held = 10;
public const int ViewModel = 11;
public const int LocalPlayer = 12;
public const int Build = 13;
public static void SetupCollisions()
{
Physics.IgnoreLayerCollision(Held, Player);
Physics.IgnoreLayerCollision(Held, LocalPlayer);
Physics.IgnoreLayerCollision(Held, Held);
Physics.IgnoreLayerCollision(Wrap, Vehicle);
Physics.IgnoreLayerCollision(ViewModel, Default);
for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i);
}
/// <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);
}
}