using UnityEngine;
namespace GrassCutter
{
///
/// The twelve stations, one on each corner of the sector lattice, the base being the first. The other eleven are found by
/// walking up to them: each has a depot (a build piece the server spawns), a supply wall, a console and a travel terminal.
/// They stand in the same places on every peer and only the ones nearby are switched on.
///
public class Stations : MonoBehaviour
{
public static Stations Instance { get; private set; }
public const int Count = 12;
const float DrawDistance = 900f, Found = 45f, Bare = 11f;
public static readonly string[] Names = { "Base", "Fescue", "Clover", "Rye", "Timothy", "Bentgrass", "Sedge", "Vetch", "Yarrow", "Sorrel", "Tansy", "Thistle" };
/// As shown: the base is a word in the player's language, the eleven others are names.
public static string Name(int i) => i == 0 ? Loc.T("Base") : Names[i];
public GameObject rig;
readonly GameObject[] _rigs = new GameObject[Count];
readonly Vector3[] _spots = new Vector3[Count];
float _next;
public static Vector3 Dir(int i) => HexGrid.Centre(i);
public static Vector3 Spot(int i) => Planet.OnSurface(Dir(i));
public static Quaternion Turn(int i)
{
var up = Dir(i);
return Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, up), up);
}
/// Where a traveller steps out.
public static Vector3 Arrival(int i) => i == 0 ? new Vector3(0f, 0.15f, -5.5f) : Spot(i) + Turn(i) * new Vector3(0f, 0.2f, -5f);
/// The station nearest a spot on the ball.
public static int Nearest(Vector3 p)
{
var up = Planet.Up(p);
int best = 0;
for (int i = 1; i < Count; i++) if (Vector3.Dot(up, Dir(i)) > Vector3.Dot(up, Dir(best))) best = i;
return best;
}
void Awake() => Instance = this;
void Start()
{
for (int i = 1; i < Count; i++)
{
_spots[i] = Spot(i);
MowMap.BlockRound(_spots[i], Bare);
_rigs[i] = Instantiate(rig, _spots[i], Turn(i), transform);
_rigs[i].SetActive(false);
}
}
/// The ball changed size: the far stations stand again where they belong on it.
public void Replace()
{
foreach (var r in _rigs) if (r) Destroy(r);
Start();
}
void Update()
{
if (Time.time < _next) return;
_next = Time.time + 0.5f;
var me = PlayerAgent.Local;
var ts = TeamState.Instance;
if (!me || !ts) return;
var at = me.transform.position;
for (int i = 1; i < Count; i++)
{
float far = Vector3.Distance(_spots[i], at);
_rigs[i].SetActive(far < DrawDistance);
if (far < Found && !ts.StationOpen(i)) ts.OpenStationRpc(i);
}
}
}
}