Files
grass-cutters/Assets/Scripts/Gameplay/Vehicle.Auto.cs
NiemandKG 86c8403c2a Train lines that grow, station yards, a cab to ride, a wagon per upgrade; autopilot unloads where it can
- The grass train lays on to the next station by itself once its newest stretch is mown as far as the cutters reach,
  rounding each station at the edge of its yard, until no station is left within reach; it runs three times as fast
  over the stretches already mown.
- Every station on a line has a yard at the end of the rails: machines (the autopilot too) unload there, the train
  picks it up as it passes and it is paid when the train gets home. With nothing left to cut it carries for the yards.
- E on the locomotive puts you in the cab: W on up the line, S back home, E to get off; it carries on by itself after.
- Three wagons, one more per upgrade (six at Mk IV), 2 t each; the heaps grow as they fill. The upgrade text says so.
- The autopilot only drives to places a machine can unload (garage pads, unload bays, the yard, train yards), not to
  drone pads, binders or catchers, where it used to stop and stand; at a spot that won't take it, it tries the next.
  The HUD unload markers skip those too.
- -demotrain checks the line growing, a yard filling and emptying, the cab ride and six wagons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 22:31:45 +06:00

409 lines
19 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// 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.
/// </summary>
public partial class Vehicle
{
public enum AutoJob : byte { Off, Mowing, Unloading, Done }
/// <summary>What the autopilot is doing (the host writes it).</summary>
public readonly NetworkVariable<byte> Auto = new NetworkVariable<byte>();
public AutoJob Job => (AutoJob)Auto.Value;
public bool OnAuto => Auto.Value != (byte)AutoJob.Off;
/// <summary>Has an autopilot, and a cutter for it to mow with.</summary>
public bool CanAuto => GameDefs.TuneFits(kind, TuneId.Autopilot) && Level(TuneId.Autopilot) > 0;
/// <summary>A field is this many metres a side; it works this many rings of fields round the first.</summary>
const float FieldSize = 34f;
const int FieldRings = 4;
Vector3 _home, _homeFwd;
/// <summary>Strokes as pairs of points on the ground: start, end, start, end...</summary>
readonly List<Vector3> _strokes = new List<Vector3>();
int _next, _field;
float _stuck, _lastSteer;
int _stuckTimes;
/// <summary>The closest it has come to where it's going, and when: circling round a point inside its turn, it gives up on it.</summary>
float _bestDist, _bestAt;
int _goalKey = -1;
Vector3 _unloadAt;
/// <summary>Pads it got to and couldn't unload on this trip (walled in, say): it tries the next place.</summary>
readonly HashSet<SiloPiece> _badPads = new HashSet<SiloPiece>();
float _thereSince = -1f;
/// <summary>
/// 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.
/// </summary>
const int GhostMask = ~0;
/// <summary>What it steers round (not the deck rails: it rolls over those).</summary>
const int SolidMask = (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle) | (1 << Layers.Player) | (1 << Layers.LocalPlayer);
bool _ghost, _avoiding;
/// <summary>For the demo: how often an autopilot steered round something, went through it, hopped.</summary>
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<DeckTileView>());
/// <summary>How far ahead the way is blocked this way (MaxValue: it's clear), not counting what's near the goal.</summary>
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;
}
/// <summary>Steering to take it round what stands ahead: toward the clearer side, harder the closer it is.</summary>
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];
/// <summary>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).</summary>
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<DeckTileView>())
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;
}
/// <summary>The last way out: picks the machine up and sets it down a few metres on, facing where it's going.</summary>
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<Vector2Int> s_fields = new List<Vector2Int>();
static readonly List<(Vector3 at, string name)> s_yards = new List<(Vector3, string)>();
static readonly Collider[] s_block = new Collider[4];
/// <summary>The driver hands over: they step off, it carries on.</summary>
[Rpc(SendTo.Server)]
void AutoRpc(RpcParams rpc = default)
{
if (Driver.Value != rpc.Receive.SenderClientId || !CanAuto) return;
ServerEject();
ServerStartAuto(transform.position, transform.forward);
}
/// <summary>Host: start working round this spot, the strokes running this way.</summary>
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;
/// <summary>Host, loading a save: back to work once the world round it has been built.</summary>
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);
}
/// <summary>Where the autopilot was started, for the save (Off: it wasn't).</summary>
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));
}
}
/// <summary>Plans the next field that has grass on it. False when there is none left.</summary>
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<int>();
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;
}
}
/// <summary>Adds the stretches of a row that are free to drive and have grass on them. True if any were.</summary>
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;
}
/// <summary>Open ground: no deck, rock, building or scenery in the way.</summary>
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;
}
/// <summary>The nearest place to empty the hopper: a pad (garage, unload bay) or the base yard.</summary>
bool FindUnload(out Vector3 at)
{
at = default;
float best = float.MaxValue;
var p = transform.position;
foreach (var s in SiloPiece.Pads)
{
// only what a machine can drive onto (a garage, an unload bay): a drone pad or a binder holds grass too
if (!s || !s.IsSpawned || !s.OnPad(s.PadSpot) || _badPads.Contains(s)) 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; }
// a yard at a station on a train's line: the train takes it home
s_yards.Clear();
Train.Yards(s_yards);
foreach (var y in s_yards)
if ((y.at - p).sqrMagnitude < best) { best = (y.at - p).sqrMagnitude; at = y.at; }
return best < float.MaxValue;
}
// ───────────────────────── driving (host) ─────────────────────────
/// <summary>The stick the autopilot holds this physics step.</summary>
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) { _thereSince = -1f; return Vector2.zero; }
if (Tank.Value <= 0.1f) { Auto.Value = (byte)AutoJob.Mowing; _stuckTimes = 0; _badPads.Clear(); return Vector2.zero; }
// at the spot and still not unloading: that place won't take it, so the next one
if (Vector3.ProjectOnPlane(_unloadAt - p, up).sqrMagnitude < 25f)
{
if (_thereSince < 0f) _thereSince = Time.time;
else if (Time.time - _thereSince > 4f)
{
_thereSince = -1f;
var bad = SiloPiece.Pads.Find(s => s && (s.PadSpot - _unloadAt).sqrMagnitude < 1f);
if (bad) _badPads.Add(bad);
if (!bad) Hop(_unloadAt, 5f); // the yard: right onto the spot
else if (!FindUnload(out _unloadAt)) { Auto.Value = (byte)AutoJob.Done; return Vector2.zero; }
}
}
else _thereSince = -1f;
}
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);
}
}
}