using System.Collections.Generic;
using Unity.Netcode;
using Unity.Netcode.Components;
using UnityEngine;
namespace GrassCutter
{
///
/// 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.
///
[RequireComponent(typeof(Rigidbody))]
public class Grabbable : NetworkBehaviour
{
public static readonly List All = new List();
public const ulong Nobody = ulong.MaxValue;
public string displayName = "Thing";
public bool trash;
public bool trashIsBox;
public float holdDistance = 1.4f;
/// Recycler payout multiplier (pallets are worth more than a wrap ball).
public float valueMul = 1f;
public readonly NetworkVariable Holder = new NetworkVariable(Nobody);
public readonly NetworkVariable IsTrashNet = new NetworkVariable();
public readonly NetworkVariable Scale = new NetworkVariable(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();
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(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();
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);
}
/// Called by the holder (owner) to let go; velocity is applied locally since the holder owns the body.
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;
}
/// Server: forcibly drop (e.g. the holder disconnected or the item got recycled).
public void ServerForceRelease()
{
if (IsServer) Holder.Value = Nobody;
}
/// Ask the owner to apply an impulse (used by the recycler to spit out non-trash).
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();
if (!c) return "plastic_grab";
return c.kind == CargoKind.Brick ? "ice_clink" : "barrel_clunk";
}
}
float _lastPush;
/// Nudge from a walking player. Applied directly when we simulate the body, otherwise forwarded to the owner.
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;
/// One physics step, from .
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(); _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(); _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;
/// Cargo riding a belt: the belts' catch triggers (and the static world) don't see it, everything else does.
public const int Riding = 14;
/// Loose cargo and cargo on a belt, for the casts that look for either.
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);
}
/// Things the player's interaction ray can hit.
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Riding) | (1 << Vehicle) | (1 << Player) | (1 << Build);
}
}