Files
grass-cutters/Assets/Scripts/UI/Hud.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

880 lines
43 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// In-game HUD: compass (top centre), tool plate with its container (bottom left), tool belt (bottom centre), wallet
/// (bottom right), the sector underfoot and the planet (top right), key hints (right), build palette, crosshair/prompt,
/// floating cash, toasts, banners, name tags and tutorial hints.
/// </summary>
public class Hud
{
public enum ToastKind { Info, Good, Warn, Money }
readonly VisualElement _root, _world;
Label _money, _planetPct, _planetSub, _sectorName, _sectorPct;
VisualElement _sectorHex, _chips;
Label _chipMow, _chipBoost, _chipCruise;
Compass _compass;
int _hexState = -1;
VisualElement _coin;
VisualElement _hotbar;
readonly Dictionary<ToolId, VisualElement> _slots = new Dictionary<ToolId, VisualElement>();
VisualElement _plate, _gauge, _gaugeFill, _buildHint, _bootsHint, _blade, _receipt, _phoneUpHint, _phoneTurnHint;
Label _toolName, _toolKg, _toolRate;
VisualElement _crosshair, _prompt;
Label _promptKey, _promptTitle, _promptText;
VisualElement _promptMore;
string _promptWas;
VisualElement _toasts, _banner, _hint, _players;
Label _hintText;
VisualElement _build, _buildRow, _buildCats;
Label _buildHelp, _buildReason;
readonly List<Label> _floatPool = new List<Label>();
readonly Dictionary<PlayerAgent, Label> _tags = new Dictionary<PlayerAgent, Label>();
double _shownMoney, _targetMoney, _slipKg, _slipPay;
float _slipAt = -9f;
float _lastTick, _tankPunch;
PlayerAgent _local;
string _beltKey = "";
int _buildKey = -1;
static Hud Instance => UIRoot.I ? UIRoot.I.Hud : null;
public Hud(VisualElement root, VisualElement world)
{
_root = root;
_world = world;
Build();
TeamState.MoneyChanged += OnMoney;
TeamState.Purchased += OnPurchased;
TeamState.Announcement += OnAnnouncement;
TeamState.Deposited += OnDeposited;
TeamState.SectorClosed += OnSectorClosed;
TeamState.MarkFound += OnMarkFound;
}
/// <summary>The language changed and a new HUD takes over: this one lets go of the game's events and the world layer.</summary>
public void Detach()
{
TeamState.MoneyChanged -= OnMoney;
TeamState.Purchased -= OnPurchased;
TeamState.Announcement -= OnAnnouncement;
TeamState.Deposited -= OnDeposited;
TeamState.SectorClosed -= OnSectorClosed;
TeamState.MarkFound -= OnMarkFound;
_treats?.Detach();
if (_local != null && _onTool != null) _local.Tools.ToolChanged -= _onTool;
foreach (var t in _tags.Values) t.RemoveFromHierarchy();
_tags.Clear();
foreach (var d in _drops) d.RemoveFromHierarchy();
foreach (var f in _floatPool) f.RemoveFromHierarchy();
_local = null;
}
System.Action<ToolId> _onTool;
void OnPurchased(string who, string what)
{
Toast(Loc.F("{0} bought {1}!", who, Loc.Unpack(what)), ToastKind.Good);
Sfx.Play("perk_unlock", 0.8f);
Sfx.Play("cash_register", 0.6f);
}
void OnAnnouncement(string a) => Toast(Loc.Unpack(a), ToastKind.Info);
// closed sectors add up on one line instead of a toast and a chime each: a tractor closes them back to back
Label _closedLine;
int _closedCount;
double _closedPay;
float _closedAt = -99f, _chimeAt = -99f;
void OnSectorClosed(int id, double pay)
{
bool fresh = _closedLine == null || _closedLine.parent == null || Time.unscaledTime - _closedAt > 8f;
_closedAt = Time.unscaledTime;
if (fresh) { _closedCount = 0; _closedPay = 0d; }
_closedCount++;
_closedPay += pay;
string text = _closedCount == 1
? Loc.F("Sector {0:N0} mown clean! +{1}", id + 1, UIK.Money(pay))
: Loc.F("{0} sectors mown clean +{1}", _closedCount, UIK.Money(_closedPay));
if (fresh) _closedLine = Toast(text, ToastKind.Money, 5f);
else { _closedLine.text = text; Linger(_closedLine, 5f); }
if (Time.unscaledTime - _chimeAt > 45f) { _chimeAt = Time.unscaledTime; Sfx.Play("perk_unlock", 0.3f); }
}
void OnMarkFound(string who, int id, double pay)
{
var ts = TeamState.Instance;
bool point = Landmarks.IsPoint(id);
Toast(point ? Loc.F("{0} read a survey point +{1} ({2} / {3})", who, UIK.Money(pay), ts ? ts.FoundCount(true) : 0, Landmarks.Points) : Loc.F("{0} untangled a stake +{1} ({2} / {3})", who, UIK.Money(pay), ts ? ts.FoundCount(false) : 0, Landmarks.Stakes), ToastKind.Money);
Sfx.Play("cash_register", 0.8f);
}
void Build()
{
var bank = AssetBank.I;
// wallet
var m = UIK.El("hud-money", _root);
_coin = UIK.Img(bank.Tex("icon_coin"), "coin", m);
_money = UIK.Text("$0", "money-text t-outline", m);
// the planet: how much of Herbaria-7 is mown
var s = UIK.El("hud-sector", _root);
var head = UIK.El("sector-head", s);
var names = UIK.El("sector-names", head);
_sectorName = UIK.Text("", "t-h2 t-outline", names);
_sectorPct = UIK.Text("", "t-small t-outline", names, false);
_sectorHex = UIK.El("sector-hex", head);
_sectorHex.generateVisualContent += DrawHex;
_planetPct = UIK.Text("", "planet-pct t-outline", s, false);
_planetSub = UIK.Text("", "t-small t-outline", s, false);
// key hints
var hints = _hints = UIK.El("hud-hints", _root);
HintRow(hints, Act.Stats, Loc.T("Stats"));
HintRow(hints, Act.Map, Loc.T("Map"));
HintRow(hints, Act.Pack, Loc.T("Bundle"));
HintRow(hints, Act.Notebook, Loc.T("Notebook"));
_buildHint = HintRow(hints, Act.Build, Loc.T("Build"));
_bootsHint = HintRow(hints, Act.Boots, Loc.T("Boots"));
HintRow(hints, Act.Lamp, Loc.T("Lamp"));
HintRow(hints, Act.Phone, Loc.T("Phone"));
_phoneUpHint = HintRow(hints, Act.PhoneTap, Loc.T("Tap the phone"));
_phoneTurnHint = HintRow(hints, Act.PhoneTurn, Loc.T("Turn the phone"));
RefreshHints();
// tool belt
_hotbar = UIK.El("hotbar", _root);
// the tool in hand and its container (bottom left)
_plate = UIK.El("tool-plate", _root);
_gauge = UIK.El("tank-glass tool-gauge", _plate);
_gaugeFill = UIK.El("tank-fill", _gauge);
var col = UIK.El("tool-col", _plate);
_toolRate = UIK.Text("", "tank-rate t-outline", col, false);
_toolKg = UIK.Text("", "tool-kg t-outline", col);
_toolName = UIK.Text("", "tool-name", col);
_chips = UIK.El("drive-chips", col);
_chipMow = UIK.Text(Loc.T("MOWING"), "drive-chip", _chips);
_chipBoost = UIK.Text(Loc.T("BOOST"), "drive-chip", _chips);
_chipCruise = UIK.Text(Loc.T("CRUISE"), "drive-chip", _chips);
_chips.style.display = DisplayStyle.None;
_compass = new Compass(_root);
// build palette
_build = UIK.El("build-panel", _root);
_buildCats = UIK.El("build-cats", _build);
_buildRow = UIK.El("build-row", _build);
_buildReason = UIK.Text("", "t-body t-outline build-reason", _build, false);
_buildHelp = UIK.Text(Loc.T("WHEEL piece · LMB place · R rotate · T move · MMB copy · RMB remove · CTRL+WHEEL height · F free"), "t-small t-outline", _build, false);
_build.style.display = DisplayStyle.None;
// how wide the blade in hand cuts, drawn to scale across the aim
_blade = UIK.El("blade-bar", _root);
_blade.style.display = DisplayStyle.None;
// the depot's receipt
_receipt = UIK.El("receipt", _root);
_receipt.style.display = DisplayStyle.None;
// crosshair & prompt
_crosshair = UIK.El("crosshair", _root);
// what you look at: a card under the crosshair, out of the way of the thing itself. The name on top, the details
// a line each underneath, and the other keys as chips of their own
_prompt = UIK.El("prompt", _root);
_prompt.pickingMode = PickingMode.Ignore;
_promptKey = UIK.Text("E", "key", _prompt);
var promptCol = UIK.El("prompt-col", _prompt);
_promptTitle = UIK.Text("", "prompt-title", promptCol, false);
_promptText = UIK.Text("", "prompt-body", promptCol, false);
_promptMore = UIK.El("prompt-more", promptCol);
_prompt.style.display = DisplayStyle.None;
_toasts = UIK.El("toasts", _root);
_banner = UIK.El("banner", _root);
_hint = UIK.El("hint", _root);
_hintText = UIK.Text("", "t-body t-dark", _hint, false);
_hint.style.display = DisplayStyle.None;
_players = UIK.El("card players", _root);
_players.style.display = DisplayStyle.None;
// the boosts from the vending machines, top left, and the flash when one lands
_treats = new TreatHud(_root);
}
TreatHud _treats;
VisualElement _hints;
readonly List<(Label cap, Act act)> _caps = new List<(Label, Act)>();
VisualElement HintRow(VisualElement parent, Act act, string label)
{
var row = UIK.El("hud-hint", parent);
_caps.Add((UIK.Text(Binds.Cap(act), "key", row), act));
UIK.Text(label, "t-small t-outline", row);
return row;
}
/// <summary>The key caps show the keys as now set, or hide if the player turned them off.</summary>
public void RefreshHints()
{
foreach (var (cap, act) in _caps) cap.text = Binds.Cap(act);
if (_hints != null) _hints.style.display = GameSettings.KeyHints ? DisplayStyle.Flex : DisplayStyle.None;
}
// ───────────────────────── static api ─────────────────────────
/// <summary>Every toast off the screen at once.</summary>
public static void ClearToasts()
{
if (Instance != null) Instance._toasts.Clear();
}
public static void Toast(string text, ToastKind kind = ToastKind.Info) => Instance?.Toast(text, kind, 3.5f);
/// <summary>A line under the compass, out of the way of the phone and the hands: three at most, gone in a few seconds.</summary>
Label Toast(string text, ToastKind kind, float hold)
{
// don't stack the same message: the one showing stays a little longer
foreach (var c in _toasts.Children()) if (c is Label l && l.text == text) { Linger(l, hold); return l; }
var t = UIK.Text(text, "toast t-body", _toasts, false);
t.AddToClassList(kind switch { ToastKind.Good => "toast-good", ToastKind.Warn => "toast-warn", ToastKind.Money => "toast-money", _ => "" });
UIK.SlideIn(t, new Vector2(0, -24), 0f, 0.3f);
Linger(t, hold);
while (_toasts.childCount > 3) _toasts.RemoveAt(0);
return t;
}
static void Linger(Label t, float hold)
{
Tween.Kill(t);
t.style.opacity = 1f;
Tween.Delay(t, hold, () => UIK.Fade(t, 0f, 0.4f, () => t.RemoveFromHierarchy()));
}
public static void OnLocalPlayerSpawned(PlayerAgent p)
{
var h = Instance;
if (h == null) return;
if (h._local != null && h._onTool != null) h._local.Tools.ToolChanged -= h._onTool;
h._local = p;
h._onTool = _ => h.RefreshHotbar(true);
p.Tools.ToolChanged += h._onTool;
var vm = Object.FindAnyObjectByType<ViewModel>(FindObjectsInactive.Include);
if (vm) vm.Bind(p);
}
public void OnGameStarted()
{
_shownMoney = _targetMoney = TeamState.Instance ? TeamState.Instance.Money.Value : 0;
_beltKey = "";
Banner(Loc.T("WELCOME TO HERBARIA-7"), Loc.T("Earth has run out of grass. Cut it, bundle it, ship it home."), 3.2f);
}
public void OnGameEnded()
{
foreach (var t in _tags.Values) t.RemoveFromHierarchy();
_tags.Clear();
_local = null;
}
// ───────────────────────── events ─────────────────────────
void OnMoney(double from, double to)
{
_targetMoney = to;
if (to > from)
{
if (to - from >= 10d) { UIK.Punch(_money, 0.18f); UIK.Punch(_coin, 0.3f); }
else if (Time.unscaledTime - _lastTick > 0.12f) UIK.Punch(_coin, 0.12f, 0.2f);
}
else if (to < from) UIK.Punch(_money, 0.12f);
}
void OnDeposited(Vector3 at, double pay, double kg)
{
var ear = CameraFx.Cam ? CameraFx.Cam.transform.position : at;
bool mine = _local != null && (at - _local.transform.position).sqrMagnitude < 196f;
// belts and drones hand in all the time: the till rings for your own hand-ins, and then not every second
if (mine && Time.unscaledTime - _tillAt > 2.5f && (ear - at).sqrMagnitude < 30f * 30f)
{
_tillAt = Time.unscaledTime;
Sfx.PlayAt("cash_register", at, 0.2f, 1f, 0.08f, 0.35f);
}
// one number per spot, adding up while it keeps arriving
bool same = _floatLine != null && _floatLine.parent != null && Time.unscaledTime - _floatAt < 1.2f && (at - _floatSpot).sqrMagnitude < 64f;
if (same) { _floatPay += pay; _floatKg += kg; }
else { _floatPay = pay; _floatKg = kg; _floatSpot = at; }
_floatAt = Time.unscaledTime;
var line = Loc.F("+{0} · {1} for Earth", UIK.Money(_floatPay), GameDefs.Kilos(_floatKg));
if (same) _floatLine.text = line;
else _floatLine = FloatText(line, at + Planet.Up(at) * 0.8f, new Color(0.45f, 1f, 0.62f), 0.7f);
if (mine) Receipt(pay, kg);
}
/// <summary>What the depot took, added up while it keeps arriving.</summary>
Label _floatLine;
Vector3 _floatSpot;
double _floatPay, _floatKg;
float _floatAt = -99f, _tillAt = -99f, _tickUntil;
void Receipt(double pay, double kg)
{
_tickUntil = Time.unscaledTime + 1.5f;
if (Time.unscaledTime - _slipAt > 3f) _slipKg = _slipPay = 0d;
_slipAt = Time.unscaledTime;
_slipKg += kg;
_slipPay += pay;
var ts = TeamState.Instance;
_receipt.Clear();
UIK.Text(Loc.T("GRASS DEPOT"), "t-h2 t-dark", _receipt);
ReceiptRow(Loc.T("Weight"), GameDefs.Kilos(_slipKg));
ReceiptRow(Loc.T("Rate"), Loc.F("{0} / kg", UIK.Money(_slipPay / _slipKg)));
ReceiptRow(Loc.T("Payout"), UIK.Money(_slipPay));
if (ts) ReceiptRow(Loc.T("Shipped"), GameDefs.Kilos(ts.Shipped.Value));
Tween.Kill(_receipt);
_receipt.style.display = DisplayStyle.Flex;
_receipt.style.opacity = 1f;
var r = _receipt;
Tween.Delay(r, 3.5f, () => UIK.Fade(r, 0f, 0.4f, () => { r.style.display = DisplayStyle.None; r.style.opacity = 1f; }));
}
void ReceiptRow(string name, string value)
{
var row = UIK.El("receipt-row", _receipt);
UIK.Text(name, "t-body t-muted", row, false);
UIK.Text(value, "t-body t-dark", row, false);
}
// ───────────────────────── widgets ─────────────────────────
public void Banner(string title, string sub, float hold)
{
_banner.Clear();
var t = UIK.Text(title, "banner-text t-outline", _banner);
UIK.PopIn(t, 0f, 0.5f);
if (!string.IsNullOrEmpty(sub))
{
var s = UIK.Text(sub, "banner-sub t-outline", _banner);
UIK.SlideIn(s, new Vector2(0, 30), 0.15f);
}
var b = _banner;
Tween.Kill(b);
b.style.opacity = 1f;
Tween.Delay(b, hold, () => UIK.Fade(b, 0f, 0.35f, () => { b.Clear(); b.style.opacity = 1f; }));
}
public Label FloatText(string text, Vector3 world, Color color, float scale = 1f)
{
var cam = CameraFx.Cam;
if (!cam || _root.panel == null) return null;
var vp = cam.WorldToViewportPoint(world);
if (vp.z < 0.1f || vp.z > 80f) return null;
Label l = null;
foreach (var p in _floatPool) if (p.parent == null) { l = p; break; }
if (l == null)
{
if (_floatPool.Count > 40) return null;
l = UIK.Text("", "float-text t-outline");
_floatPool.Add(l);
}
_world.Add(l);
l.text = text;
l.style.color = color;
var start = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, world, cam) + new Vector2(Random.Range(-24f, 24f), Random.Range(-8f, 8f));
Tween.Kill(l);
Tween.Run(l, 1.1f, k =>
{
var pos = start + new Vector2(0, -110f * Easing.Apply(Ease.OutCubic, k));
l.style.left = pos.x - 40;
l.style.top = pos.y - 20;
float pop = k < 0.15f ? Easing.Apply(Ease.OutBack, k / 0.15f) : 1f;
l.style.scale = new Scale(Vector3.one * scale * pop);
l.style.opacity = k < 0.7f ? 1f : 1f - (k - 0.7f) / 0.3f;
}, Ease.Linear, 0f, () => l.RemoveFromHierarchy());
return l;
}
void RefreshHotbar(bool animate)
{
var ts = TeamState.Instance;
if (!ts || _local == null) return;
var key = new System.Text.StringBuilder();
var belt = _local.Tools.Belt;
bool rebuilt = false;
int slots = _local.BeltSlots.Value;
foreach (var t in belt) key.Append((int)t).Append(',');
key.Append('/').Append(slots);
if (key.ToString() != _beltKey)
{
_beltKey = key.ToString();
rebuilt = true;
_hotbar.Clear();
_slots.Clear();
for (int n = 0; n < slots; n++)
{
var slot = UIK.El("slot", _hotbar);
UIK.Text((n + 1).ToString(), "slot-key t-outline", slot);
if (n >= belt.Count) { slot.AddToClassList("slot-empty"); continue; }
var d = GameDefs.Tool(belt[n]);
UIK.Img(AssetBank.I.Tex(d.icon), "slot-icon", slot);
slot.tooltip = d.name;
_slots[belt[n]] = slot;
if (animate) UIK.PopIn(slot);
}
}
foreach (var kv in _slots) kv.Value.EnableInClassList("slot-on", kv.Key == _local.Tools.Current);
if (animate && !rebuilt && _slots.TryGetValue(_local.Tools.Current, out var cur)) UIK.Punch(cur, 0.15f);
}
public void SetTabList(bool show)
{
bool visible = _players.style.display == DisplayStyle.Flex;
if (show == visible) return;
_players.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
if (!show) return;
_players.Clear();
var ts = TeamState.Instance;
UIK.Text(Loc.T("GREENHAUL CREW"), "t-h1 t-dark", _players);
if (ts)
UIK.Text(Loc.F("{0} shipped to Earth · {1:0.0000}% of Herbaria-7 mown · {2} / {3} upgrades", GameDefs.Kilos(ts.Shipped.Value), ts.Mown01 * 100.0, ts.Installs, TeamState.TotalInstalls), "t-small t-muted wrap", _players, false);
if (ts)
UIK.Text(Loc.F("{0:N0} sectors clean · {1} / {2} stakes · {3} / {4} survey points", ts.Closed.Value, ts.FoundCount(false), Landmarks.Stakes, ts.FoundCount(true), Landmarks.Points), "t-small t-muted wrap", _players, false);
foreach (var p in PlayerAgent.All)
{
var row = UIK.El("player-row", _players);
var sw = UIK.El("swatch", row);
sw.style.backgroundColor = p.Tint;
var av = UIK.El("avatar", row);
if (SteamManager.Initialized && p.SteamId.Value != 0)
{
var tex = SteamManager.GetAvatar(new Steamworks.CSteamID(p.SteamId.Value));
if (tex) av.style.backgroundImage = new StyleBackground(tex);
}
var name = UIK.Text(p.IsOwner ? Loc.F("{0} (you)", p.DisplayName) : p.DisplayName, "t-h2 t-dark", row);
name.style.flexGrow = 1;
if (p.IsOwnedByServer) UIK.Text(Loc.T("HOST"), "key", row);
}
UIK.PopIn(_players, 0f, 0.25f);
}
// ───────────────────────── per frame ─────────────────────────
public void Tick(bool active)
{
var ts = TeamState.Instance;
if (ts) _targetMoney = ts.Money.Value;
if (System.Math.Abs(_shownMoney - _targetMoney) > 0.004)
{
double diff = _targetMoney - _shownMoney;
_shownMoney += diff * Mathf.Min(1f, Time.unscaledDeltaTime * 9f);
if (System.Math.Abs(_shownMoney - _targetMoney) < 0.02) _shownMoney = _targetMoney;
// only while your own hand-in counts up: the robots' and belts' money comes in quietly
if (diff > 0 && Time.unscaledTime < _tickUntil && Time.unscaledTime - _lastTick > 0.12f) { _lastTick = Time.unscaledTime; Sfx.Play("coin_tick", 0.07f, 1.2f, 0.1f); }
}
_money.text = UIK.Money(_shownMoney);
if (!ts || _local == null) return;
RefreshHotbar(false);
UpdatePlanet(ts);
UpdateTool(ts);
UpdateBuild(active);
UpdateAim(active);
UpdateTags();
UpdateDrops();
UpdateHints(ts);
_compass.Tick(_local, active);
Achievements.Tick();
}
void UpdatePlanet(TeamState ts)
{
int id = HexGrid.SectorAt(Planet.LocalUp);
float clean = MowMap.Cleared(id);
_sectorName.text = Crops.Name(Crops.At(id)).ToUpper(Loc.Culture) + " " + Loc.Num(id + 1);
_sectorPct.text = Loc.F("{0:0.#}% mown", clean * 100f);
int state = clean >= 1f ? 2 : clean > 0f ? 1 : 0;
if (state != _hexState) { _hexState = state; _sectorHex.MarkDirtyRepaint(); }
_planetPct.text = Loc.F("{0:0.0000}%", ts.Mown01 * 100.0);
_planetSub.text = Loc.F("of Herbaria-7 · {0} shipped", GameDefs.Kilos(ts.Shipped.Value));
}
void DrawHex(MeshGenerationContext ctx)
{
var r = _sectorHex.contentRect;
var p = ctx.painter2D;
p.fillColor = _hexState == 2 ? new Color(0.9f, 0.84f, 0.56f) : _hexState == 1 ? new Color(0.93f, 0.71f, 0.22f) : new Color(0.36f, 0.62f, 0.22f);
p.strokeColor = new Color(0.165f, 0.13f, 0.08f);
p.lineWidth = 4f;
p.BeginPath();
for (int i = 0; i < 6; i++)
{
float a = (i * 60f + 30f) * Mathf.Deg2Rad;
var at = r.center + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * (r.width * 0.46f);
if (i == 0) p.MoveTo(at); else p.LineTo(at);
}
p.ClosePath();
p.Fill();
p.Stroke();
}
/// <summary>The plate shows the machine you're driving, or the tool in your hands.</summary>
void UpdateTool(TeamState ts)
{
var tools = _local.Tools;
var v = _local.Vehicle;
bool has = v || tools.Current != ToolId.None;
_plate.style.display = has ? DisplayStyle.Flex : DisplayStyle.None;
_buildHint.style.display = tools.Belt.Contains(ToolId.Hammer) ? DisplayStyle.Flex : DisplayStyle.None;
_bootsHint.style.display = _local.HasGear(GearId.Boots) ? DisplayStyle.Flex : DisplayStyle.None;
_phoneUpHint.style.display = Phone.IsOut ? DisplayStyle.Flex : DisplayStyle.None;
_phoneTurnHint.style.display = Phone.TakesWheel ? DisplayStyle.Flex : DisplayStyle.None;
_chips.style.display = v ? DisplayStyle.Flex : DisplayStyle.None;
if (v)
{
_chipMow.EnableInClassList("drive-chip-on", v.Slurping.Value);
_chipBoost.EnableInClassList("drive-chip-on", Ctl.Sprint);
_chipCruise.EnableInClassList("drive-chip-on", v.Cruising);
}
if (!has) return;
float kg = v ? v.Load : tools.Bin(tools.Current);
float cap = v ? v.Capacity : tools.CurrentCap;
bool bin = cap > 0f;
_toolName.text = v ? v.Def.name : GameDefs.Tool(tools.Current).name;
_gauge.style.display = bin ? DisplayStyle.Flex : DisplayStyle.None;
_toolKg.style.display = bin ? DisplayStyle.Flex : DisplayStyle.None;
if (!bin) { _toolRate.text = ""; return; }
float f = Mathf.Clamp01(kg / cap);
_gaugeFill.style.height = Length.Percent(f * 100f);
_toolKg.text = cap < 100f ? Loc.F("{0:0.00} / {1:0.##} KG", kg, cap) : Loc.F("{0:0} / {1:0} KG", kg, cap);
bool full = f >= 0.999f;
_plate.EnableInClassList("tank-full", full);
_toolRate.text = v ? Loc.F("{0:0} KM/H", v.Body ? v.Body.linearVelocity.magnitude * 3.6f : 0f) : tools.IsCutting ? Loc.F("+{0:0.##} kg/s", tools.LastRate) : full ? Loc.T("FULL") : "";
if (full && Time.unscaledTime - _tankPunch > 2f) { _tankPunch = Time.unscaledTime; UIK.Punch(_plate, 0.08f); }
}
static readonly string[] CatNames = { Loc.N("SERVICES"), Loc.N("LOGISTICS"), Loc.N("PRODUCTION"), Loc.N("POWER"), Loc.N("STRUCTURES"), Loc.N("DECOR") };
void UpdateBuild(bool active)
{
var b = PlayerBuild.Local;
bool show = active && b && b.Active;
_build.style.display = show ? DisplayStyle.Flex : DisplayStyle.None;
if (!show) { _buildKey = -1; return; }
var list = b.Available();
var ts = TeamState.Instance;
int key = (int)b.Category * 10000 + list.Count * 100 + b.Selected;
if (key != _buildKey)
{
bool first = _buildKey < 0;
_buildKey = key;
_buildCats.Clear();
for (int c = 0; c < CatNames.Length; c++)
{
if (!b.CategoryUnlocked((PieceCat)c)) continue;
var chip = UIK.Text(Loc.T(CatNames[c]), "build-cat", _buildCats);
if (c == (int)b.Category) chip.AddToClassList("build-cat-on");
}
_buildRow.Clear();
for (int i = 0; i < list.Count; i++)
{
var d = list[i];
var card = UIK.El("build-card", _buildRow);
if (i == b.Selected) card.AddToClassList("build-card-on");
UIK.Img(AssetBank.I.Tex(d.icon), "build-icon", card);
UIK.Text(d.name, "build-name", card);
UIK.Text(d.id == PieceId.Belt ? Loc.F("{0}/m", UIK.Money(d.price)) : UIK.Money(d.price), "build-price", card);
if (first) UIK.PopIn(card, i * 0.03f, 0.3f);
else if (i == b.Selected) UIK.Punch(card, 0.12f);
}
}
var cur = b.Current;
bool bad = !b.Valid && !string.IsNullOrEmpty(b.Reason);
_buildReason.text = bad ? b.Reason : !string.IsNullOrEmpty(b.Note) ? b.Note : cur != null ? Loc.F("{0}: {1}", cur.name, cur.desc) : "";
_buildReason.EnableInClassList("t-red", bad && !b.Target);
}
void UpdateAim(bool active)
{
bool building = PlayerBuild.Local && PlayerBuild.Local.Active;
// not over the phone held up in front of the face (it would sit on the Director's forehead)
bool phoneUp = Phone.I && Phone.I.Mode == PhoneMode.Up;
_crosshair.style.display = active && !phoneUp ? DisplayStyle.Flex : DisplayStyle.None;
var p = _local;
var tools = p.Tools;
string prompt = null, key = Binds.Cap(Act.Interact);
bool hot = false;
if (active && building) { }
else if (active && p.Driving.Value)
{
// only when it matters: standing still, unloading, feeding a belt or full. The markers show where to go.
var v = p.Vehicle;
bool still = v && v.Body && v.Body.linearVelocity.magnitude < 0.6f;
if (v && v.Def.bed > 0) { key = Binds.Cap(Act.MovePiece); prompt = v.Bed.Count > 0 ? Loc.T("Tip the bundles out behind") : still ? Loc.T("Empty bed · E with a bundle in your arms loads it") : null; }
else if (v && v.Baling) { key = ""; prompt = Loc.T("Baling onto the belt…"); }
else if (v && v.Unloading) { key = ""; prompt = Loc.T("Unloading…"); hot = true; }
else if (v && v.Capacity > 0f && v.Load >= v.Capacity * 0.9f) { key = ""; prompt = Loc.T("Hopper full: drive to an UNLOAD marker"); }
else if (v && VehicleShed.Near(v.transform.position)) { key = Binds.Cap(Act.Boots); prompt = Loc.T("Garage: upgrade this machine"); hot = true; }
else if (still) prompt = Loc.T("Hop off [R] View");
}
else if (active && p.Grab.Holding)
{
bool bundle = p.Grab.Held && p.Grab.Held.GetComponent<Cargo>();
if (bundle && p.AimInteractable is Depot)
{
prompt = Loc.T("Hand in this bundle");
hot = true;
}
else
{
key = Binds.Cap(Act.Use);
prompt = bundle ? Loc.T("Throw it in the DEPOT or onto a belt [E] Drop [R] Turn") : Loc.T("Throw [E] Drop [R] Turn");
}
}
else if (active && p.HasAim && p.AimHit.collider)
{
if (p.AimInteractable != null && (p.AimInteractable as Component) && p.AimInteractable.Prompt != null)
{
prompt = p.AimInteractable.Prompt;
hot = p.AimInteractable.CanInteract;
if (!hot) key = "";
}
var aimed = p.AimPiece;
if (aimed && !building)
{
string tier = aimed.Upgrades != UpgradeKind.None ? aimed.Switched ? Loc.F("{0}, stopped", GameDefs.TierName(aimed.Tier.Value)) : GameDefs.TierName(aimed.Tier.Value) : "";
prompt = Loc.F("{0} [T] Upgrades & settings", prompt ?? aimed.Def.name + (tier.Length > 0 ? " " + tier : ""));
}
else if (prompt == null && p.AimGrabbable && !p.AimGrabbable.IsHeld)
{
var c = p.AimGrabbable.GetComponent<Cargo>();
prompt = !c ? Loc.T("Pick up") : Loc.F(c.kind == CargoKind.Hay ? Loc.N("Pick up hay ({0})") : c.kind == CargoKind.Brick ? Loc.N("Pick up pressed brick ({0})") : Loc.N("Pick up grass bundle ({0})"), GameDefs.Kilos(c.Kg.Value));
hot = true;
}
}
else if (active && !tools.IsCutting && Ctl.UseHeld && tools.OutOfRange && GameDefs.IsBlade(tools.Current))
{
key = "LMB";
prompt = Loc.T("Too far — get closer to the grass");
}
_crosshair.EnableInClassList("crosshair-hot", hot || tools.IsCutting);
// the Director's words run along the same strip of screen: the hint waits until he hangs up
if (DirectorCall.Busy) prompt = null;
if (prompt != null)
{
_prompt.style.display = DisplayStyle.Flex;
_promptKey.text = key;
_promptKey.style.display = string.IsNullOrEmpty(key) ? DisplayStyle.None : DisplayStyle.Flex;
ShowPrompt(prompt);
}
else { _prompt.style.display = DisplayStyle.None; _promptWas = null; }
var cam = CameraFx.Cam;
bool blade = active && cam && tools.BladeOn && GameDefs.IsBlade(tools.Current) && !p.Driving.Value && _root.panel != null;
_blade.style.display = blade ? DisplayStyle.Flex : DisplayStyle.None;
if (!blade) return;
var side = cam.transform.right * TeamState.Instance.ToolWidth(tools.Current) * 0.5f;
var a = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, tools.BladeAt - side, cam);
var b = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, tools.BladeAt + side, cam);
_blade.style.left = a.x;
_blade.style.top = (a.y + b.y) * 0.5f - 3f;
_blade.style.width = Mathf.Max(8f, b.x - a.x);
}
readonly List<Label> _drops = new List<Label>();
static Transform s_yard;
/// <summary>
/// Driving with grass in the hopper: every place that takes it gets a marker, the base yard (paid at once) and each garage pad
/// and Unload Bay (into the bin, out as bundles onto belts). Off screen they slide to the edge, so you know which way to turn.
/// A baler also sees the belt starts it can feed.
/// </summary>
void UpdateDrops()
{
var v = _local.Vehicle;
var cam = CameraFx.Cam;
int n = 0;
bool show = v && cam && _root.panel != null && v.Def.width > 0f && v.Load >= Mathf.Max(1f, v.Capacity * 0.25f) && !v.Unloading;
_dropSpots.Clear();
if (show)
{
if (!s_yard) { var d = GameObject.Find("DockZone"); s_yard = d ? d.transform : null; }
if (s_yard) _dropSpots.Add((s_yard.position, Loc.T("Yard")));
foreach (var pad in SiloPiece.Pads)
if (pad && pad.IsSpawned && pad.OnPad(pad.PadSpot) && _dropSpots.Count < 12) _dropSpots.Add((pad.PadSpot, pad.PadName));
Train.Yards(_dropSpots);
// only the nearest one may sit on the screen edge; the rest show only when in view
var from = v.transform.position;
_dropSpots.Sort((x, y) => (x.at - from).sqrMagnitude.CompareTo((y.at - from).sqrMagnitude));
_placed.Clear();
foreach (var spot in _dropSpots) if (Drop(n, spot.at, spot.name, cam, from, n == 0)) n++;
}
for (int i = n; i < _drops.Count; i++) _drops[i].style.display = DisplayStyle.None;
}
readonly List<(Vector3 at, string name)> _dropSpots = new List<(Vector3, string)>();
readonly List<Rect> _placed = new List<Rect>();
/// <summary>A small pill over an unload spot: the name and the distance on one line, stacked clear of the others.</summary>
bool Drop(int i, Vector3 at, string what, Camera cam, Vector3 from, bool nearest)
{
var world = at + Planet.Up(at) * 3f;
var vp = cam.WorldToViewportPoint(world);
bool behind = vp.z < 0f;
if (behind) { vp.x = 1f - vp.x; vp.y = 1f - vp.y; }
float W = _root.layout.width, H = _root.layout.height;
if (float.IsNaN(W) || W < 10f) return false;
var pos = new Vector2(vp.x * W, (1f - vp.y) * H);
bool off = behind || pos.x < 0f || pos.x > W || pos.y < 0f || pos.y > H;
if (off && !nearest) return false;
if (i >= _drops.Count) _drops.Add(UIK.Text("", "drop-marker t-outline", _world, false));
var tag = _drops[i];
float dist = Vector3.Distance(at, from);
tag.text = nearest ? Loc.F("UNLOAD · {0} {1:0} m", what, dist) : Loc.F("{0} {1:0} m", what, dist);
tag.EnableInClassList("drop-marker-near", nearest);
tag.style.display = DisplayStyle.Flex;
if (off)
{
// slide along the edge toward it
var c = new Vector2(W, H) * 0.5f;
var d = pos - c;
if (behind && d.sqrMagnitude < 1f) d = Vector2.down;
float k = Mathf.Min((W * 0.5f - 70f) / Mathf.Max(1e-3f, Mathf.Abs(d.x)), (H * 0.5f - 40f) / Mathf.Max(1e-3f, Mathf.Abs(d.y)));
pos = c + d * k;
}
float w = tag.resolvedStyle.width, h = tag.resolvedStyle.height;
if (float.IsNaN(w)) w = 80f;
if (float.IsNaN(h)) h = 20f;
var r = new Rect(pos.x - w * 0.5f, pos.y - h, w, h);
// stack upward clear of the pills already placed this frame
for (int guard = 0; guard < 12; guard++)
{
bool hit = false;
foreach (var q in _placed) if (q.Overlaps(r)) { r.y = q.y - h - 2f; hit = true; }
if (!hit) break;
}
_placed.Add(r);
tag.style.left = r.x;
tag.style.top = r.y;
tag.style.opacity = off ? 0.8f : 1f;
tag.style.scale = new Scale(Vector3.one);
return true;
}
void UpdateTags()
{
var cam = CameraFx.Cam;
foreach (var p in PlayerAgent.All)
{
if (!p || p.IsOwner) continue;
if (!_tags.TryGetValue(p, out var tag))
{
tag = UIK.Text("", "nametag t-outline", _world);
_tags[p] = tag;
}
tag.text = p.DisplayName;
tag.style.color = Color.Lerp(p.Tint, Color.white, 0.35f);
var head = p.transform.position + p.transform.up * 1.75f;
var vp = cam ? cam.WorldToViewportPoint(head) : Vector3.back;
bool visible = vp.z > 0.2f && vp.z < 60f;
tag.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
if (!visible || _root.panel == null) continue;
var pos = RuntimePanelUtils.CameraTransformWorldToPanel(_root.panel, head, cam);
float w = tag.resolvedStyle.width;
tag.style.left = pos.x - (float.IsNaN(w) ? 50 : w * 0.5f);
tag.style.top = pos.y - 20;
float s = Mathf.Clamp(6f / vp.z, 0.55f, 1.1f);
tag.style.scale = new Scale(new Vector3(s, s, 1));
}
var dead = new List<PlayerAgent>();
foreach (var kv in _tags) if (!kv.Key || !PlayerAgent.All.Contains(kv.Key)) dead.Add(kv.Key);
foreach (var d in dead) { _tags[d].RemoveFromHierarchy(); _tags.Remove(d); }
}
/// <summary>"Battery Bank: 0.3 of 25 kWh, charging. Nothing to run [T] Upgrades" as a title, a line per sentence,
/// and a chip per extra key. Rebuilt only when the words change.</summary>
void ShowPrompt(string prompt)
{
if (prompt == _promptWas) return;
_promptWas = prompt;
var parts = prompt.Split(new[] { " [" }, System.StringSplitOptions.None);
string main = parts[0].Trim();
_promptMore.Clear();
for (int i = 1; i < parts.Length; i++)
{
int close = parts[i].IndexOf(']');
if (close <= 0) continue;
var chip = UIK.El("prompt-chip", _promptMore);
UIK.Text(parts[i].Substring(0, close), "key key-small", chip);
UIK.Text(parts[i].Substring(close + 1).Trim(), "prompt-chip-text", chip, false);
}
_promptMore.style.display = _promptMore.childCount > 0 ? DisplayStyle.Flex : DisplayStyle.None;
string title = main, body = "";
// translations: Chinese and Japanese write their own colon and full stop
int colon = main.IndexOf(": "), wide = main.IndexOf(':'), cut = colon + 2;
if (wide > 0 && (colon < 0 || wide < colon)) { colon = wide; cut = wide + 1; }
if (colon > 0 && colon <= 32) { title = main.Substring(0, colon).TrimEnd(); body = main.Substring(cut); }
var lines = new List<string>();
foreach (var s in body.Split(new[] { ". ", "。" }, System.StringSplitOptions.RemoveEmptyEntries))
{
var t = s.Trim().TrimEnd('.');
if (t.Length > 0) lines.Add(char.ToUpper(t[0], Loc.Culture) + t.Substring(1));
}
_promptTitle.text = title;
_promptText.text = string.Join("\n", lines);
_promptText.style.display = lines.Count > 0 ? DisplayStyle.Flex : DisplayStyle.None;
}
void UpdateHints(TeamState ts)
{
string hint = null, voice = null;
var tools = _local.Tools;
float cap = tools.CurrentCap;
if (tools.Belt.Count == 0)
{
hint = Loc.T("Empty hands! Walk to the SUPPLY WALL on the west side of the deck and take the nail scissors (E).");
voice = "asst_tools";
}
else if (ts.Shipped.Value < 5d)
{
if (GameDefs.IsBlade(tools.Current) && _local.Tank.Value >= cap - 0.01f)
{
hint = Loc.T("Container full! Press E at the DEPOT to hand it all in, or Q to tie a 1 kg bundle you can carry and throw.");
voice = "asst_full";
}
else if (GameDefs.IsBlade(tools.Current) && _local.Tank.Value < 0.01f)
{
hint = Loc.T("Hop down to the meadow (SPACE at the railing) and HOLD LEFT CLICK: sweep the blade over the grass. Earth needs every blade of it.");
voice = "asst_mow";
}
}
else if (ts.Shipped.Value < 40d && ts.Money.Value >= 5d)
{
hint = Loc.T("Spend your cash: better tools at the SUPPLY WALL, upgrades at the CONSOLE. Mowers are sold at a GARAGE: build one with the Hammer.");
voice = "asst_spend";
}
// during the Director's call his words run along the same strip of screen: the hint waits until he hangs up
bool show = hint != null && !(PlayerBuild.Local && PlayerBuild.Local.Active) && !_local.Driving.Value && !DirectorCall.Busy;
bool shown = _hint.style.display == DisplayStyle.Flex;
if (show && _hintText.text != hint)
{
_hintText.text = hint;
_hint.style.display = DisplayStyle.Flex;
UIK.PopIn(_hint, 0.1f);
}
// the assistant says it too, once she may talk (and again after a good while, if it's still up)
if (show && voice != null) Assistant.Say(voice);
else if (!show && shown) { _hint.style.display = DisplayStyle.None; _hintText.text = ""; }
}
}
}