Files
grass-cutters/Assets/Scripts/Gameplay/Vehicle.Auto.cs
NiemandKG 29485df9e1 Train and autopilot tried in the game: prefab, wagons upright, no circling
The train piece is in the scene's prefab list, its icon is made, and the
wagons keep the axis turn their FBX root brings. The autopilot gives up on a
point it has circled for seven seconds without getting closer, and takes sharp
turns close by slowly. -demoauto: on the easy planet the tractor unloads and
goes back to mowing, and the train lays 826 m of track to Timothy, closes 532
sectors and earns about 13.7k by the time its reach is mown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 12:17:41 +06:00

308 lines
13 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, _back, _backSteer, _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;
static readonly List<Vector2Int> s_fields = new List<Vector2Int>();
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)
{
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) ─────────────────────────
/// <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) 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)
_goalKey = -1;
if (job == AutoJob.Mowing) _next++;
else if (++_stuckTimes >= 5) Auto.Value = (byte)AutoJob.Done;
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;
// backing out of something it ran into
if (_back > 0f)
{
_back -= dt;
return new Vector2(_backSteer, -1f);
}
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);
_lastSteer = steer;
if (speed < 0.5f && thr > 0.2f)
{
_stuck += dt;
if (_stuck > 2.2f)
{
_stuck = 0f;
_back = 1.5f;
_backSteer = ang > 0f ? -1f : 1f;
if (++_stuckTimes >= 4)
{
// can't get there: the next stroke, or another way home
_stuckTimes = 0;
if (job == AutoJob.Mowing) _next += (_next % 2 == 0) ? 2 : 1;
else Auto.Value = (byte)AutoJob.Done;
}
}
}
else _stuck = 0f;
return new Vector2(steer, thr);
}
}
}