using System.Collections.Generic; using Unity.Netcode; using UnityEngine; namespace GrassCutter { /// /// A pad of fetching drones. Bundles of grass lying loose within of it (thrown down, dropped off the /// end of a belt, flung by a twister) are flown in, one per drone per trip, and go into the pad's silo, which puts them /// on the belts like any other silo, or with no belt out sends them straight to Earth: tie a bundle, drop it, the drones /// do the walking. A trip is one synced value per drone (where to, when it left), and every peer flies /// the drone along the same plan from it: up, across, down, grab, up, back, down onto the pad. /// public class DronePad : SiloPiece { /// How far the drones go from a Mk I pad; every upgrade adds . public const float Range = 70f, RangePerTier = 25f; const float Room = 60f, Cruise = 7f, Climb = 3f, Speed = 6f, Hover = 1.35f, GrabTime = 0.8f, Carry = 1f, Look = 0.5f; const int Most = 4; /// A drone at rest on the pad. static readonly Vector4 Parked = new Vector4(0f, 0f, 0f, -1f); /// Where each drone sits on the pad, in the piece's space (the perch post is at the back left). static readonly Vector3[] Slots = { new Vector3(0.75f, 0.68f, 0.75f), new Vector3(-0.75f, 0.68f, 0.75f), new Vector3(0.75f, 0.68f, -0.75f), new Vector3(-0.75f, 0.68f, -0.75f) }; /// Bundles some drone is on its way to, so no two go for the same one. static readonly HashSet s_claimed = new HashSet(); public Transform drone; readonly NetworkVariable _trip0 = new NetworkVariable(Parked), _trip1 = new NetworkVariable(Parked); readonly NetworkVariable _trip2 = new NetworkVariable(Parked), _trip3 = new NetworkVariable(Parked); readonly Transform[] _drones = new Transform[Most]; readonly Transform[][] _rotors = new Transform[Most][]; readonly AudioSource[] _hum = new AudioSource[Most]; readonly Cargo[] _for = new Cargo[Most]; readonly bool[] _holding = new bool[Most]; float _nextLook; /// Server: bundles brought in since it was built (for the demo's log). public int Delivered { get; private set; } BuildPiece _piece; BuildPiece Piece => _piece ? _piece : (_piece = GetComponent()); NetworkVariable Trip(int i) => i == 0 ? _trip0 : i == 1 ? _trip1 : i == 2 ? _trip2 : _trip3; /// Two drones at Mk I, one more per upgrade, four at most. int Count => Mathf.Min(Most, 2 + (Piece ? Piece.Tier.Value : 0)); float Fly => Speed * Mathf.Sqrt(Piece ? Piece.TierMul : 1f) * (TeamState.Instance ? TeamState.Instance.DroneSpeedMul : 1f); float Reach => Range + RangePerTier * (Piece ? Piece.Tier.Value : 0) + (TeamState.Instance ? TeamState.Instance.DroneReachAdd : 0f); readonly float[] _idleUntil = new float[Most]; float _shipAt; double Now => NetworkManager ? NetworkManager.ServerTime.Time : Time.timeAsDouble; public override string Prompt { get { int out_ = 0; for (int i = 0; i < Count; i++) if (Trip(i).Value.w >= 0f) out_++; return Loc.F("Drone Pad: {0} drones, {1} out · {2} of {3}", Count, out_, GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room)) + " · " + (BeltNet.Belted(Piece) ? Loc.T("onto the belt") : Loc.F("straight to Earth, {0} m around", Mathf.RoundToInt(Reach))); } } public override void Interact() => Sfx.Play("ui_click", 0.6f); public override void Ports(List into) { into.Add(BeltNet.Front(transform)); } void Start() { if (!drone) return; _drones[0] = drone; for (int i = 1; i < Most; i++) _drones[i] = Instantiate(drone, drone.parent); for (int i = 0; i < Most; i++) { var spin = new List(); foreach (var t in _drones[i].GetComponentsInChildren(true)) if (t.name.StartsWith("Rotor")) spin.Add(t); _rotors[i] = spin.ToArray(); _hum[i] = Sfx.Loop("drone_loop", _drones[i], 0f); } } public override void OnNetworkDespawn() { // whatever was in the air falls where it is for (int i = 0; i < Most; i++) Let(i); base.OnNetworkDespawn(); } // ───────────────────────── the flight plan ───────────────────────── Vector3 Home(int i) => transform.TransformPoint(Slots[i]); static float Ease(float k) => k * k * (3f - 2f * k); /// Where drone i is on its trip right now, which stage it's at (7: back on the pad) and how far through it. Vector3 Where(int i, Vector4 trip, double now, out int leg, out float k, out Vector3 heading) { var home = Home(i); leg = 7; k = 1f; heading = transform.forward; if (trip.w < 0f) return home; var target = new Vector3(trip.x, trip.y, trip.z); var a = home + Planet.Up(home) * Cruise; var b = target + Planet.Up(target) * Cruise; var low = target + Planet.Up(target) * Hover; float across = Vector3.Distance(a, b) / Fly, rise = Cruise / Climb, drop = (Cruise - Hover) / Climb; float t = (float)(now - trip.w); leg = 0; float span = rise; while (leg < 7) { span = leg == 0 || leg == 6 ? rise : leg == 1 || leg == 5 ? across : leg == 3 ? GrabTime : drop; if (t < span) break; t -= span; leg++; } if (leg == 7) return home; k = Mathf.Clamp01(t / Mathf.Max(0.01f, span)); float e = Ease(k); var go = b - a; heading = leg <= 3 ? go : -go; switch (leg) { case 0: return Vector3.Lerp(home, a, e); case 1: return Vector3.Lerp(a, b, e); case 2: return Vector3.Lerp(b, low, e); case 3: return low; case 4: return Vector3.Lerp(low, b, e); case 5: return Vector3.Lerp(b, a, e); default: return Vector3.Lerp(a, home, e); } } // ───────────────────────── every peer: fly them ───────────────────────── void LateUpdate() { if (_drones[0] == null) return; double now = Now; int count = Count; for (int i = 0; i < Most; i++) { var d = _drones[i]; if (!d) continue; bool shown = i < count; if (d.gameObject.activeSelf != shown) d.gameObject.SetActive(shown); if (!shown) continue; var trip = Trip(i).Value; var at = Where(i, trip, now, out int leg, out float k, out var heading); var up = Planet.Up(at); heading = Vector3.ProjectOnPlane(heading, up); var face = heading.sqrMagnitude > 0.01f ? Quaternion.LookRotation(heading, up) : transform.rotation; // nose down while it picks up speed across, a little sway in the hover float lean = leg == 1 || leg == 5 ? Mathf.Sin(k * Mathf.PI) * 14f : 0f; float sway = trip.w >= 0f ? Mathf.Sin(Time.time * 2.1f + i) * 2.5f : 0f; d.SetPositionAndRotation(at, face * Quaternion.Euler(lean, 0f, sway)); float spin = trip.w >= 0f ? 1900f : 70f; foreach (var r in _rotors[i]) if (r) r.Rotate(up, spin * Time.deltaTime, Space.World); if (_hum[i]) _hum[i].volume = trip.w >= 0f ? 0.3f * Sfx.SfxVolume : 0f; } } // ───────────────────────── server: send them out, bring the bundles in ───────────────────────── protected override void Update() { bool belted = Belted(); if (belted) base.Update(); if (!IsServer || !IsSpawned) return; // no belt out: what the drones bring goes straight to Earth, so they never stand idle on a full silo if (!belted) BeltNet.Ship(Silo, transform.position, ref _shipAt); double now = Now; bool look = Time.time >= _nextLook; if (look) _nextLook = Time.time + Look; int count = Count; for (int i = 0; i < Most; i++) { var trip = Trip(i).Value; if (trip.w < 0f) { if (look && i < count && !(Piece && Piece.Switched)) Send(i, now); continue; } var at = Where(i, trip, now, out int leg, out float k, out _); var c = _for[i]; if (c && (!c.IsSpawned || c.Grab.IsHeld || c.Grab.Consumed || (!_holding[i] && (c.Belt || c.Loaded)))) { Let(i); c = null; } if (c && !_holding[i] && leg >= 3 && leg < 7) { // still where it was when the drone set off? then hook it if ((c.transform.position - new Vector3(trip.x, trip.y, trip.z)).sqrMagnitude < 2.5f * 2.5f) Hook(i, c); else { Let(i); c = null; } } if (c && _holding[i]) { var rb = c.Grab.Body; rb.MovePosition(at - Planet.Up(at) * Carry); // down on the pad: into the silo if (leg == 7 || (leg == 6 && k > 0.75f)) { Silo.Value += c.Kg.Value; Delivered++; s_claimed.Remove(c); _for[i] = null; _holding[i] = false; c.Grab.Consumed = true; c.NetworkObject.Despawn(true); DeliveredRpc(); } } if (leg == 7) { if (_for[i]) Let(i); Trip(i).Value = Parked; } } } static readonly List s_ports = new List(); /// Is a belt joined to the hatch? 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); return s_ports.Count > 0 && BeltNet.Nearest(s_ports[0].at, true, BeltNet.Joined, Piece, out var next, out _, out _) && next.GetComponentInChildren(); } /// The nearest loose bundle of grass in reach that nobody is after, if the silo has room for it. void Send(int i, double now) { int out_ = 0; for (int k = 0; k < Most; k++) if (Trip(k).Value.w >= 0f) out_++; if (Silo.Value + (out_ + 1) * GameDefs.BundleKg > Room) return; // found nothing a moment ago: there are often a thousand bundles on a big farm, don't look through them every frame if (Time.time < _idleUntil[i]) return; Cargo best = null; float bestD = Reach * Reach; var here = transform.position; foreach (var c in Cargo.All) { if (!c || !c.IsSpawned || c.kind != CargoKind.Grass || c.Belt || c.Loaded || s_claimed.Contains(c)) continue; var g = c.Grab; if (!g || g.IsHeld || g.Consumed || !g.Body || g.Body.isKinematic || g.Body.linearVelocity.sqrMagnitude > 0.25f) continue; float d = (c.transform.position - here).sqrMagnitude; // out of reach or no nearer than the best so far: the cheap test first, the belt ends only for the few left if (d >= bestD) continue; // right by the pad: just put out of the hatch, or about to be if (d < 3f * 3f) continue; // dropped off the free end of a belt: that's where someone wants it, and it may be this pad's own if (AtBeltEnd(c.transform.position)) continue; bestD = d; best = c; } if (!best) { _idleUntil[i] = Time.time + 1.5f; return; } s_claimed.Add(best); _for[i] = best; _holding[i] = false; var p = best.transform.position; Trip(i).Value = new Vector4(p.x, p.y, p.z, (float)now); } static bool AtBeltEnd(Vector3 p) { foreach (var b in Conveyor.All) if (b is BeltRun r && (r.End - p).sqrMagnitude < 2.5f * 2.5f) return true; return false; } void Hook(int i, Cargo c) { if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId); var rb = c.Grab.Body; rb.linearVelocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.isKinematic = true; c.Loaded = true; _holding[i] = true; HookRpc(i); } /// Drone i lets go of its bundle (or of the claim on it): it drops where it is. void Let(int i) { var c = _for[i]; _for[i] = null; if (!c) { _holding[i] = false; return; } s_claimed.Remove(c); if (_holding[i] && c.IsSpawned && !c.Grab.Consumed) { c.Loaded = false; var rb = c.Grab.Body; if (rb) rb.isKinematic = false; } _holding[i] = false; } [Rpc(SendTo.Everyone)] void HookRpc(int i) { if (_drones[i]) Sfx.PlayAt("drone_grab", _drones[i].position, 0.5f, 1f, 0.1f, 0.2f); } [Rpc(SendTo.Everyone)] void DeliveredRpc() => Sfx.PlayAt("cargo_load", transform.position, 0.5f, 1f, 0.1f, 0.4f); } }