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

237 lines
9.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()
{
// 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.
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;
/// <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()
{
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);
// 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 << Riding) | (1 << Vehicle) | (1 << Player) | (1 << Build);
}
}