using System.Collections.Generic; using Unity.Netcode; using UnityEngine; namespace GrassCutter { /// /// The autopilot, bought for a machine at the garage. C hands the machine over and the driver steps off: it mows a field /// round where it was let go in long strokes (every other row first, so it has room to turn), then the fields round /// that one, ring by ring. With the hopper full it drives to the nearest place to unload (a garage pad, an unload bay or /// the base yard), empties it and comes back to the stroke it left. Getting in takes it back. The host drives it. /// public partial class Vehicle { public enum AutoJob : byte { Off, Mowing, Unloading, Done } /// What the autopilot is doing (the host writes it). public readonly NetworkVariable Auto = new NetworkVariable(); public AutoJob Job => (AutoJob)Auto.Value; public bool OnAuto => Auto.Value != (byte)AutoJob.Off; /// Has an autopilot, and a cutter for it to mow with. public bool CanAuto => GameDefs.TuneFits(kind, TuneId.Autopilot) && Level(TuneId.Autopilot) > 0; /// A field is this many metres a side; it works this many rings of fields round the first. const float FieldSize = 34f; const int FieldRings = 4; Vector3 _home, _homeFwd; /// Strokes as pairs of points on the ground: start, end, start, end... readonly List _strokes = new List(); int _next, _field; float _stuck, _lastSteer; int _stuckTimes; /// The closest it has come to where it's going, and when: circling round a point inside its turn, it gives up on it. float _bestDist, _bestAt; int _goalKey = -1; Vector3 _unloadAt; /// /// An autopilot touches nothing, so nothing can wedge it, climb it or tip it: it rides on the soil and on the base /// deck, steers round what stands in its way and goes through what it can't get round. /// const int GhostMask = ~0; /// What it steers round (not the deck rails: it rolls over those). const int SolidMask = (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.LocalPlayer); bool _ghost, _avoiding; /// For the demo: how often an autopilot steered round something, went through it, hopped. public static int Swerves, Hops; static readonly RaycastHit[] s_ahead = new RaycastHit[8]; bool Solid(Collider c) => c && !c.transform.IsChildOf(transform) && !(c is BoxCollider && c.GetComponent()); /// How far ahead the way is blocked this way (MaxValue: it's clear), not counting what's near the goal. float Blocked(Vector3 from, Vector3 dir, float radius, float reach, Vector3 goal) { int n = Physics.SphereCastNonAlloc(from, radius, dir, s_ahead, reach, SolidMask, QueryTriggerInteraction.Ignore); float best = float.MaxValue; for (int i = 0; i < n; i++) { var h = s_ahead[i]; if (!Solid(h.collider) || h.distance <= 0f) continue; if ((h.point - goal).sqrMagnitude < 36f) continue; best = Mathf.Min(best, h.distance); } return best; } /// Steering to take it round what stands ahead: toward the clearer side, harder the closer it is. float Avoid(Vector3 p, Vector3 up, Vector3 fwd, float dist, Vector3 goal) { float reach = Mathf.Min(9f, dist - 1.5f); if (reach < 2f) return 0f; var from = p + up * 1.1f; float r = Mathf.Max(0.6f, width * 0.5f); float ahead = Blocked(from, fwd, r, reach, goal); if (ahead == float.MaxValue) return 0f; float left = Blocked(from, Quaternion.AngleAxis(-40f, up) * fwd, r, reach, goal); float right = Blocked(from, Quaternion.AngleAxis(40f, up) * fwd, r, reach, goal); float side = left > right ? -1f : left < right ? 1f : (Vector3.SignedAngle(fwd, goal - p, up) < 0f ? -1f : 1f); return side * Mathf.Lerp(1.4f, 0.5f, ahead / reach); } static readonly RaycastHit[] s_deckHits = new RaycastHit[8]; /// How high this wheel stands over the base deck's slab under it, if there is one (it keeps to the deck, not to what's on it). static float DeckClearance(Vector3 wp, Vector3 up, float reach) { int n = Physics.RaycastNonAlloc(wp + up * 1.2f, -up, s_deckHits, reach, 1 << Layers.Default, QueryTriggerInteraction.Ignore); float best = float.MaxValue; for (int i = 0; i < n; i++) if (s_deckHits[i].collider is BoxCollider && s_deckHits[i].collider.GetComponent()) best = Mathf.Min(best, s_deckHits[i].distance - 1.2f); return best; } void Ghost(bool on) { if (_ghost == on) return; _ghost = on; Body.excludeLayers = on ? (LayerMask)GhostMask : (LayerMask)0; } /// The last way out: picks the machine up and sets it down a few metres on, facing where it's going. void Hop(Vector3 goal, float metres) { var p = transform.position; var up = Planet.Up(p); var to = Vector3.ProjectOnPlane(goal - p, up); float d = to.magnitude; if (d < 0.5f) return; var dir = to / d; Hops++; var at = Planet.Surface(p + dir * Mathf.Min(metres, d)); var nu = Planet.Up(at); // onto the base deck, not under it if (Ts && Ts.OnDeck(at)) { float c = DeckClearance(at + nu * 4f, nu, 8f); if (c < 50f) at += nu * (4f - c); } Body.position = at + nu * 0.6f; Body.rotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(dir, nu).normalized, nu); Body.linearVelocity = Vector3.zero; Body.angularVelocity = Vector3.zero; _hasCut = false; } static readonly List s_fields = new List(); static readonly Collider[] s_block = new Collider[4]; /// The driver hands over: they step off, it carries on. [Rpc(SendTo.Server)] void AutoRpc(RpcParams rpc = default) { if (Driver.Value != rpc.Receive.SenderClientId || !CanAuto) return; ServerEject(); ServerStartAuto(transform.position, transform.forward); } /// Host: start working round this spot, the strokes running this way. public void ServerStartAuto(Vector3 home, Vector3 forward) { if (!IsServer || !CanAuto) return; var up = Planet.Up(home); _home = home; _homeFwd = Vector3.ProjectOnPlane(forward, up).normalized; if (_homeFwd.sqrMagnitude < 0.5f) _homeFwd = Vector3.ProjectOnPlane(Vector3.forward, up).normalized; _field = -1; _strokes.Clear(); _next = 0; _stuckTimes = 0; Auto.Value = (byte)AutoJob.Mowing; if (!NextField()) Auto.Value = (byte)AutoJob.Done; } float _resumeAt; /// Host, loading a save: back to work once the world round it has been built. public void ServerResumeAuto(Vector3 home, Vector3 forward) { _home = home; _homeFwd = forward; _resumeAt = Time.time + 4f; } void AutoResume() { if (_resumeAt <= 0f || Time.time < _resumeAt) return; _resumeAt = 0f; if (!HasDriver) ServerStartAuto(_home, _homeFwd); } /// Where the autopilot was started, for the save (Off: it wasn't). public void AutoState(out int job, out Vector3 home, out Vector3 fwd) { job = Auto.Value; home = _home; fwd = _homeFwd; } string AutoPrompt => Job == AutoJob.Unloading ? Loc.T("autopilot: off to unload") : Job == AutoJob.Done ? Loc.T("autopilot: nothing left to mow round here") : Loc.T("autopilot: mowing"); // ───────────────────────── planning ───────────────────────── static void Fields() { if (s_fields.Count > 0) return; s_fields.Add(Vector2Int.zero); for (int r = 1; r <= FieldRings; r++) { // round the ring: along the top, down the right, back along the bottom, up the left for (int x = -r; x < r; x++) s_fields.Add(new Vector2Int(x, r)); for (int z = r; z > -r; z--) s_fields.Add(new Vector2Int(r, z)); for (int x = r; x > -r; x--) s_fields.Add(new Vector2Int(x, -r)); for (int z = -r; z < r; z++) s_fields.Add(new Vector2Int(-r, z)); } } /// Plans the next field that has grass on it. False when there is none left. bool NextField() { Fields(); _strokes.Clear(); _next = 0; while (++_field < s_fields.Count) { Plan(s_fields[_field]); if (_strokes.Count > 0) return true; } return false; } void Plan(Vector2Int f) { var up = Planet.Up(_home); var fwd = _homeFwd; var right = Vector3.Cross(up, fwd); var centre = _home + right * (f.x * FieldSize) + fwd * (f.y * FieldSize); float w = Mathf.Max(0.8f, CutWidth * 0.85f); int rows = Mathf.Max(1, Mathf.CeilToInt(FieldSize / w)); // every other row out, the rest on the way back: a turn is two strips wide, not one var order = new List(); for (int i = 0; i < rows; i += 2) order.Add(i); for (int i = rows - 1 - (rows % 2 == 0 ? 0 : 1); i >= 1; i -= 2) order.Add(i); bool flip = false; foreach (int i in order) { float u = -FieldSize * 0.5f + (i + 0.5f) * w; var a = centre + right * u - fwd * (FieldSize * 0.5f); var b = centre + right * u + fwd * (FieldSize * 0.5f); if (flip) (a, b) = (b, a); if (Stroke(a, b)) flip = !flip; } } /// Adds the stretches of a row that are free to drive and have grass on them. True if any were. bool Stroke(Vector3 a, Vector3 b) { const float Step = 1.5f; int n = Mathf.Max(2, Mathf.CeilToInt(Vector3.Distance(a, b) / Step)); bool any = false; int start = -1, grass = 0; Vector3 first = default, last = default; for (int k = 0; k <= n; k++) { var p = Planet.Surface(Vector3.Lerp(a, b, k / (float)n)); bool free = Free(p); if (free) { if (start < 0) { start = k; first = p; grass = 0; } last = p; if (MowMap.Yield(p) > 0.3f) grass++; } if (!free || k == n) { if (start >= 0 && grass >= 2 && Vector3.Distance(first, last) > 3f) { _strokes.Add(first); _strokes.Add(last); any = true; } start = -1; } } return any; } /// Open ground: no deck, rock, building or scenery in the way. bool Free(Vector3 p) { if (Ts && Ts.OnDeck(p)) return false; if (Ground.Instance && Ground.Instance.RockAt(p)) return false; var up = Planet.Up(p); int n = Physics.OverlapSphereNonAlloc(p + up * 1.3f, width * 0.5f + 1f, s_block, (1 << Layers.Default) | (1 << Layers.Build), QueryTriggerInteraction.Ignore); for (int i = 0; i < n; i++) if (s_block[i] && !s_block[i].transform.IsChildOf(transform)) return false; return true; } /// The nearest place to empty the hopper: a pad (garage, unload bay) or the base yard. bool FindUnload(out Vector3 at) { at = default; float best = float.MaxValue; var p = transform.position; foreach (var s in SiloPiece.Pads) { if (!s || !s.IsSpawned) continue; float d = (s.PadSpot - p).sqrMagnitude; if (d < best) { best = d; at = s.PadSpot; } } if (!s_dock) { var dz = GameObject.Find("DockZone"); s_dock = dz ? dz.transform : null; } if (s_dock && (s_dock.position - p).sqrMagnitude < best) { best = (s_dock.position - p).sqrMagnitude; at = s_dock.position; } return best < float.MaxValue; } // ───────────────────────── driving (host) ───────────────────────── /// The stick the autopilot holds this physics step. Vector2 AutoInput(float dt) { var p = transform.position; var up = Planet.Up(p); var job = Job; if (job == AutoJob.Off || job == AutoJob.Done) return Vector2.zero; if (job == AutoJob.Mowing && Tank.Value >= Capacity - 0.5f) { if (FindUnload(out _unloadAt)) { Auto.Value = (byte)(job = AutoJob.Unloading); _stuckTimes = 0; } else { Auto.Value = (byte)AutoJob.Done; return Vector2.zero; } } if (job == AutoJob.Unloading) { // on the pad: stand still until it's empty, then back to work if (Unloading) return Vector2.zero; if (Tank.Value <= 0.1f) { Auto.Value = (byte)AutoJob.Mowing; _stuckTimes = 0; return Vector2.zero; } } Vector3 goal; if (job == AutoJob.Unloading) goal = _unloadAt; else { if (_next >= _strokes.Count && !NextField()) { // all done round here: what's in the hopper goes home first if (Tank.Value > 0.1f && FindUnload(out _unloadAt)) Auto.Value = (byte)AutoJob.Unloading; else Auto.Value = (byte)AutoJob.Done; return Vector2.zero; } goal = _strokes[_next]; } var to = Vector3.ProjectOnPlane(goal - p, up); float dist = to.magnitude; if (job == AutoJob.Mowing && dist < 2.2f) { _next++; _stuckTimes = 0; return new Vector2(_lastSteer, 0.4f); } int key = (int)job * 100000 + (job == AutoJob.Mowing ? _next : 0); if (key != _goalKey) { _goalKey = key; _bestDist = dist; _bestAt = Time.time; } else if (dist < _bestDist - 1f) { _bestDist = dist; _bestAt = Time.time; } else if (Time.time - _bestAt > 7f) { // round and round a point it can't turn into: on to the next one (or the next stroke); // on the way to unload it gets there anyway, a hop at a time _goalKey = -1; if (job == AutoJob.Mowing) _next++; else Hop(goal, Mathf.Min(dist, 8f)); return new Vector2(_lastSteer, 0.4f); } var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized; float ang = Vector3.SignedAngle(fwd, to, up); float speed = Vector3.ProjectOnPlane(Body.linearVelocity, up).magnitude; float steer = Mathf.Clamp(ang / 30f, -1f, 1f); // mowing it keeps to a pace it can turn at; on the way somewhere far it goes faster float cap = job == AutoJob.Mowing ? 0.7f : dist > 20f ? 1f : 0.6f; float thr = cap * Mathf.Lerp(1f, 0.4f, Mathf.Clamp01(Mathf.Abs(ang) / 90f)); if (dist < 6f) thr = Mathf.Min(thr, 0.3f + dist * 0.08f); // a sharp turn close by is taken slowly: the slower it goes, the tighter it turns if (Mathf.Abs(ang) > 50f && dist < 10f) thr = Mathf.Min(thr, 0.22f); // round what stands in the way; what it can't get round it goes through float avoid = Avoid(p, up, fwd, dist, goal); if (avoid == 0f) _avoiding = false; else { if (!_avoiding) Swerves++; _avoiding = true; steer = Mathf.Clamp(steer + avoid, -1f, 1f); thr = Mathf.Min(thr, 0.5f); } _lastSteer = steer; // nothing stops it, so not moving means wedged on the ground somehow: it hops on if (speed < 0.5f && thr > 0.2f) { _stuck += dt; if (_stuck > 3f) { _stuck = 0f; Hop(goal, 4f); } } else _stuck = 0f; return new Vector2(steer, thr); } } }