Files
grass-cutters/Assets/Scripts/UI/ShopScreen.cs
NiemandKG 6b2a9931b9 Upgrade matrix you can read at a glance
- Each tree sits centred under the Earth Uplink; links run square between
  rows and down the gaps between columns, never through a node or a name
- Clear node states: gold is done, a green ring is buyable now, green tint
  is started, grey is not open yet; the selected node has a blue ring
- Every node shows the price of its next level and pips for its levels
- The detail panel lists every level with what it gives and what it costs;
  requirements turn green as they are met
- Tabs show how much of each tree is bought
- -demoshop [slot] shoots every tab

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 13:08:46 +06:00

455 lines
22 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// The upgrade matrix as node graphs: the GreenHaul console shows CONTAINERS · CUTTING · SUIT · LOGISTICS · ECONOMY · AUTOMATION,
/// each branch growing out of the free Earth Uplink. Click a node to inspect it, buy it from the shared crew wallet.
/// Each tree sits in the middle under the uplink, its links run square between the rows (never through a node or a
/// name), every node says what it costs, and the detail panel lays out every level with what it gives and costs.
/// </summary>
public class ShopScreen
{
public VisualElement Card { get; }
readonly Label _money, _installs;
readonly Action _close;
public static readonly PerkTree[] TerminalTrees = { PerkTree.Containers, PerkTree.Cutting, PerkTree.Suit, PerkTree.Logistics, PerkTree.Economy, PerkTree.Automation };
readonly PerkTree[] _trees;
bool Hub => _trees == TerminalTrees;
int TreeCount => _trees.Length;
readonly Button[] _tabs;
readonly Label[] _tabBadges;
readonly VisualElement[] _tabFill;
readonly VisualElement _graph, _canvas, _lines, _detail;
readonly Dictionary<PerkId, VisualElement> _nodes = new Dictionary<PerkId, VisualElement>();
VisualElement _hubNode;
PerkTree _tree = PerkTree.Containers;
PerkId _selected = PerkId.BinScissors;
// Node matches .node in the style sheet; a big step is drawn a size up
const float ColW = 236f, RowH = 228f, HubH = 196f, Node = 118f, BigNode = 140f, PadX = 30f, PadY = 22f;
/// <summary>How far above a row its links turn: below the names of the row before, above the nodes of this one.</summary>
const float Bus = 30f;
const float Corner = 16f;
// the canvas fits the widest / deepest tree so every tab has the same scale
static int MaxCol { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.col); return m; } }
static int MaxRow { get { int m = 0; foreach (var d in GameDefs.Perks) m = Mathf.Max(m, d.row); return m; } }
// (below the last row only its nodes and their names)
static readonly float CanvasW = PadX * 2f + ColW * (MaxCol + 1), CanvasH = PadY + HubH + RowH * MaxRow + Node + 86f;
static readonly string[] TreeNames = { Loc.N("CONTAINERS"), Loc.N("CUTTING"), Loc.N("SUIT"), Loc.N("LOGISTICS"), Loc.N("ECONOMY"), Loc.N("AUTOMATION") };
static readonly Color[] TreeColors =
{
new Color(0.9f, 0.72f, 0.24f), new Color(0.45f, 0.8f, 0.2f), new Color(0.85f, 0.75f, 0.4f), new Color(1f, 0.8f, 0.25f),
new Color(0.25f, 0.7f, 0.45f), new Color(0.3f, 0.66f, 0.86f),
};
static readonly Color Ink = new Color(0.165f, 0.13f, 0.08f, 1f);
static readonly Color Open = new Color(1f, 0.99f, 0.94f), Shut = new Color(0.7f, 0.66f, 0.56f);
TeamState Ts => TeamState.Instance;
public ShopScreen(VisualElement layer, Action close, PerkTree[] trees = null, string title = null)
{
_close = close;
_trees = trees ?? TerminalTrees;
_tabs = new Button[_trees.Length];
_tabBadges = new Label[_trees.Length];
_tabFill = new VisualElement[_trees.Length];
_tree = _trees[0];
Card = UIK.El("card shop", layer);
Card.pickingMode = PickingMode.Position;
var header = UIK.El("card-header", Card);
var left = UIK.El(null, header);
left.style.flexDirection = FlexDirection.Row;
left.style.alignItems = Align.Center;
UIK.Text(title ?? Loc.T("UPGRADE MATRIX"), "t-h1 t-dark", left).style.marginRight = 20;
if (_trees == TerminalTrees) _installs = UIK.Text("", "t-h2 t-muted", left);
var right = UIK.El(null, header);
right.style.flexDirection = FlexDirection.Row;
right.style.alignItems = Align.Center;
var wallet = UIK.El("pill", right);
UIK.Img(AssetBank.I.Tex("icon_coin"), "check-icon", wallet);
_money = UIK.Text("$0", "t-h2 t-dark", wallet);
wallet.style.marginRight = 16;
UIK.Btn("X", close, "btn btn-red btn-small", right);
// tree tabs get their own row so they never collide with the wallet
var tabs = UIK.El("shop-tabs", Card);
for (int i = 0; i < TreeCount; i++)
{
int t = i;
// label as a child: a Button that has children is no longer measured by its own text
_tabs[i] = UIK.Btn("", () => SetTree(_trees[t], true), "tab", tabs);
UIK.Text(Loc.T(TreeNames[(int)_trees[i]]), "tab-label", _tabs[i]).pickingMode = PickingMode.Ignore;
// how much of the tree is bought, as a strip along the bottom of the tab
var bar = UIK.El("tab-progress", _tabs[i]);
bar.pickingMode = PickingMode.Ignore;
_tabFill[i] = UIK.El("tab-progress-fill", bar);
_tabFill[i].style.backgroundColor = TreeColors[(int)_trees[i]];
_tabBadges[i] = UIK.Text("", "tab-badge", _tabs[i]);
}
var body = UIK.El("tree-body", Card);
_graph = UIK.El("tree-graph", body);
// nodes live on a fixed-size canvas that is scaled down to fit whatever room the graph gets
_canvas = UIK.El("tree-canvas", _graph);
_canvas.pickingMode = PickingMode.Ignore;
_canvas.style.width = CanvasW; _canvas.style.height = CanvasH;
_graph.RegisterCallback<GeometryChangedEvent>(_ => FitCanvas());
_lines = UIK.El("tree-lines", _canvas);
_lines.pickingMode = PickingMode.Ignore;
_lines.generateVisualContent += DrawLines;
_detail = UIK.El("tree-detail", body);
TeamState.Changed += Refresh;
Card.RegisterCallback<DetachFromPanelEvent>(_ => TeamState.Changed -= Refresh);
// the wallet moves all the time: it recolours the prices, the pill and the tab counts, it doesn't rebuild the tree
UIK.FollowWallet(Card);
Card.schedule.Execute(Wallet).Every(250);
// a single tree needs no tab row
if (TreeCount == 1) tabs.style.display = DisplayStyle.None;
// open on the first tree that has something affordable
for (int i = 0; i < TreeCount; i++) if (Affordable(_trees[i]) > 0) { _tree = _trees[i]; break; }
SetTree(_tree, true);
}
int Affordable(PerkTree tree)
{
var ts = Ts;
if (!ts) return 0;
int n = 0;
foreach (var d in GameDefs.Perks)
if (d.tree == tree && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && ts.Money.Value >= d.PriceFor(ts.Level(d.id))) n++;
return n;
}
/// <summary>Levels bought in a tree, out of all it has.</summary>
float Bought(PerkTree tree)
{
var ts = Ts;
if (!ts) return 0f;
int have = 0, all = 0;
foreach (var d in GameDefs.Perks)
{
if (d.tree != tree) continue;
have += Mathf.Min(ts.Level(d.id), d.maxLevel);
all += d.maxLevel;
}
return all > 0 ? (float)have / all : 0f;
}
public void SetTree(PerkTree tree, bool animate)
{
_tree = tree;
for (int i = 0; i < TreeCount; i++) _tabs[i].EnableInClassList("tab-on", _trees[i] == tree);
// select the cheapest thing you can buy right now, else the root
PerkDef pick = null;
var ts = Ts;
foreach (var d in GameDefs.Perks)
{
if (d.tree != tree) continue;
if (pick == null) pick = d;
if (ts && ts.Level(d.id) < d.maxLevel && ts.PerkAvailable(d) && (pick == null || !ts.PerkAvailable(pick) || ts.Level(pick.id) >= pick.maxLevel || d.PriceFor(ts.Level(d.id)) < pick.PriceFor(ts.Level(pick.id))))
pick = d;
}
if (pick != null) _selected = pick.id;
Rebuild(animate);
}
void Refresh() => Rebuild(false);
void FitCanvas()
{
var r = _graph.contentRect;
if (r.width < 1f || r.height < 1f) return;
float k = Mathf.Min(1f, Mathf.Min(r.width / CanvasW, r.height / CanvasH));
_canvas.style.transformOrigin = new TransformOrigin(0, 0);
_canvas.style.scale = new Scale(new Vector3(k, k, 1f));
_canvas.style.left = (r.width - CanvasW * k) * 0.5f;
_canvas.style.top = (r.height - CanvasH * k) * 0.5f;
}
// ───────────────────────── where things go ─────────────────────────
/// <summary>The tree's columns sit in the middle of the canvas, under the uplink.</summary>
float TreeLeft
{
get
{
int cols = 0;
foreach (var d in GameDefs.Perks) if (d.tree == _tree) cols = Mathf.Max(cols, d.col + 1);
return PadX + (MaxCol + 1 - cols) * ColW * 0.5f;
}
}
static float Size(PerkDef d) => d.big ? BigNode : Node;
int Row(PerkDef d) => d.row + (Hub ? 1 : 0);
float ColX(PerkDef d, float left) => left + d.col * ColW + ColW * 0.5f;
/// <summary>The uplink row is short: it has one node with a one-line name.</summary>
float RowTop(int row) => Hub ? (row == 0 ? PadY : PadY + HubH + (row - 1) * RowH) : PadY + row * RowH;
/// <summary>Top left of a node: centred on its column, its top on its row (a big one stands a little higher).</summary>
Vector2 NodePos(PerkDef d, float left) => new Vector2(ColX(d, left) - Size(d) * 0.5f, RowTop(Row(d)) - (Size(d) - Node) * 0.5f);
static Vector2 HubPos => new Vector2(CanvasW * 0.5f - Node * 0.5f, PadY);
void Wallet()
{
var ts = Ts;
if (!ts) return;
_money.text = UIK.Money(ts.Money.Value);
if (_installs != null) _installs.text = $"{ts.Installs} / {TeamState.TotalInstalls}";
for (int i = 0; i < TreeCount; i++)
{
int n = Affordable(_trees[i]);
_tabBadges[i].text = n > 0 ? n.ToString() : "";
_tabBadges[i].style.display = n > 0 ? DisplayStyle.Flex : DisplayStyle.None;
_tabFill[i].style.width = Length.Percent(Bought(_trees[i]) * 100f);
}
}
// ───────────────────────── the graph ─────────────────────────
void Rebuild(bool animate)
{
var ts = Ts;
if (!ts) return;
Wallet();
foreach (var n in _nodes.Values) n.RemoveFromHierarchy();
_nodes.Clear();
_hubNode?.RemoveFromHierarchy();
if (Hub)
{
_hubNode = UIK.El("node node-maxed node-hub", _canvas);
_hubNode.style.left = HubPos.x; _hubNode.style.top = HubPos.y;
UIK.Img(AssetBank.I.Tex("icon_star"), "node-icon", _hubNode);
var hubName = UIK.Text(Loc.T("Earth Uplink"), "node-name", _hubNode, false);
PlaceName(hubName, Node, false);
}
float left = TreeLeft;
int k = 0;
foreach (var d in GameDefs.Perks)
{
if (d.tree != _tree) continue;
int lvl = ts.Level(d.id);
bool maxed = lvl >= d.maxLevel;
bool avail = ts.PerkAvailable(d);
long price = d.PriceFor(lvl);
float size = Size(d);
var node = UIK.El("node", _canvas);
node.pickingMode = PickingMode.Position;
var pos = NodePos(d, left);
node.style.left = pos.x; node.style.top = pos.y;
node.style.width = size; node.style.height = size;
if (d.big) node.AddToClassList("node-big");
if (maxed) node.AddToClassList("node-maxed");
else if (!avail) node.AddToClassList("node-locked");
else
{
if (lvl > 0) node.AddToClassList("node-owned");
// the wallet keeps this one current: a node you can pay for lights up
UIK.Costs(node, price, "node-afford", "node-available");
}
if (d.id == _selected) node.AddToClassList("node-selected");
var icon = UIK.Img(AssetBank.I.Tex(d.icon), "node-icon", node);
icon.pickingMode = PickingMode.Ignore;
if (d.big) { icon.style.width = 100; icon.style.height = 100; }
if (!avail && !maxed) UIK.Text("?", "node-lock t-outline", node).pickingMode = PickingMode.Ignore;
if (d.maxLevel > 1)
{
var pips = UIK.El("node-pips", node);
pips.pickingMode = PickingMode.Ignore;
for (int i = 0; i < d.maxLevel; i++) UIK.El(i < lvl ? "node-pip node-pip-on" : "node-pip", pips).pickingMode = PickingMode.Ignore;
}
// under the node: what the next level costs, or that it is all bought
bool hasChip = !maxed || d.maxLevel == 1;
if (!maxed && avail) UIK.Costs(UIK.Text(UIK.Money(price), "node-price t-outline", node), price, "node-price-yes", "node-price-no").pickingMode = PickingMode.Ignore;
else if (!maxed) UIK.Text(UIK.Money(price), "node-price node-price-shut t-outline", node).pickingMode = PickingMode.Ignore;
else if (d.maxLevel == 1) UIK.Text(Loc.T("OWNED"), "node-price node-price-done t-outline", node).pickingMode = PickingMode.Ignore;
var name = UIK.Text(d.name, "node-name", node, false);
name.pickingMode = PickingMode.Ignore;
PlaceName(name, size, hasChip);
var id = d.id;
node.RegisterCallback<ClickEvent>(_ => { _selected = id; Sfx.Play("ui_click", 0.6f, 1.1f); Rebuild(false); });
node.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
if (avail && !maxed && ts.Money.Value >= price) Pulse(node);
_nodes[d.id] = node;
if (animate) UIK.PopIn(node, 0.03f * k, 0.35f);
k++;
}
_lines.MarkDirtyRepaint();
BuildDetail(animate);
}
static void PlaceName(Label name, float size, bool chip)
{
name.style.top = size + (chip ? 30f : 12f);
name.style.left = (size - 230f) * 0.5f;
}
static void Pulse(VisualElement e)
{
Tween.Run(e, 1.2f, t => { if (e.panel != null) e.style.scale = new Scale(Vector3.one * (1f + Mathf.Sin(t * Mathf.PI * 2f) * 0.03f)); }, Ease.Linear, 0f, () => { if (e.panel != null) Pulse(e); });
}
struct Link { public Vector2[] pts; public Color color; public int rank; }
readonly List<Link> _links = new List<Link>();
void DrawLines(MeshGenerationContext ctx)
{
var ts = Ts;
if (!ts) return;
float left = TreeLeft;
_links.Clear();
var hubOut = new Vector2(CanvasW * 0.5f, PadY + Node);
foreach (var d in GameDefs.Perks)
{
if (d.tree != _tree) continue;
bool mine = ts.Has(d.id);
var into = new Vector2(ColX(d, left), NodePos(d, left).y);
if (Hub && d.requires.Length == 0) Add(Route(hubOut, 1, into, Row(d), left), mine, true);
foreach (var r in d.requires)
{
var rd = GameDefs.Perk(r);
// a root that needs a perk from another tree has no line to draw (the detail panel names it)
if (rd.tree != d.tree) continue;
var from = new Vector2(ColX(rd, left), NodePos(rd, left).y + Size(rd));
Add(Route(from, Row(rd) + 1, into, Row(d), left), mine, ts.Level(r) >= d.requireLevel);
}
}
// the dull ones first, the bought ones on top, all of them outlined before any is filled: crossings merge cleanly
_links.Sort((a, b) => a.rank.CompareTo(b.rank));
var p = ctx.painter2D;
p.lineCap = LineCap.Round;
p.lineJoin = LineJoin.Round;
p.strokeColor = Ink;
p.lineWidth = 15f;
foreach (var l in _links) Path(p, l.pts);
p.lineWidth = 8f;
foreach (var l in _links)
{
p.strokeColor = l.color;
Path(p, l.pts);
}
}
void Add(Vector2[] pts, bool mine, bool open)
{
_links.Add(new Link { pts = pts, color = mine ? TreeColors[(int)_tree] : open ? Open : Shut, rank = mine ? 2 : open ? 1 : 0 });
}
/// <summary>
/// Down from a node, along the gap above the row it goes to, down into it. One that skips rows goes down the gap
/// between columns instead, so it never runs through a node in between.
/// </summary>
Vector2[] Route(Vector2 a, int fromRow, Vector2 b, int toRow, float left)
{
float busB = b.y - Bus;
if (toRow <= fromRow)
return Mathf.Abs(a.x - b.x) < 1f ? new[] { a, b } : new[] { a, new Vector2(a.x, busB), new Vector2(b.x, busB), b };
float busA = RowTop(fromRow) - Bus;
// the gap beside the column it goes to, on the side it comes from
float gap = b.x + (a.x < b.x ? -ColW * 0.5f : ColW * 0.5f);
return new[] { a, new Vector2(a.x, busA), new Vector2(gap, busA), new Vector2(gap, busB), new Vector2(b.x, busB), b };
}
static void Path(Painter2D p, Vector2[] pts)
{
p.BeginPath();
p.MoveTo(pts[0]);
for (int i = 1; i < pts.Length - 1; i++)
{
// round the corner, but never by more than half of either side of it
float r = Mathf.Min(Corner, (pts[i] - pts[i - 1]).magnitude * 0.5f, (pts[i + 1] - pts[i]).magnitude * 0.5f);
if (r < 1f) p.LineTo(pts[i]);
else p.ArcTo(pts[i], pts[i + 1], r);
}
p.LineTo(pts[pts.Length - 1]);
p.Stroke();
}
// ───────────────────────── the detail panel ─────────────────────────
void BuildDetail(bool animate)
{
var ts = Ts;
_detail.Clear();
var d = GameDefs.Perk(_selected);
if (d.tree != _tree) return;
int lvl = ts.Level(d.id);
bool maxed = lvl >= d.maxLevel;
bool avail = ts.PerkAvailable(d);
long price = d.PriceFor(lvl);
var top = UIK.El("detail-top", _detail);
top.style.backgroundColor = Color.Lerp(TreeColors[(int)_tree], Color.white, 0.55f);
UIK.Img(AssetBank.I.Tex(d.icon), "detail-icon", top);
UIK.Text(d.name, "t-h1 t-dark t-center detail-title", _detail);
var desc = UIK.Text(d.desc, "item-desc t-center detail-desc", _detail, false);
desc.style.whiteSpace = WhiteSpace.Normal;
// every level: what it gives and what it costs, the bought ones ticked off and the next one picked out
if (d.maxLevel > 1 || d.effect != null)
{
var ladder = UIK.El("ladder", _detail);
for (int l = 1; l <= d.maxLevel; l++)
{
bool done = l <= lvl, next = l == lvl + 1;
var row = UIK.El(done ? "ladder-row ladder-done" : next ? "ladder-row ladder-next" : "ladder-row", ladder);
UIK.Text(GameDefs.ToRoman(l), "ladder-lvl t-outline", row);
var fx = UIK.Text(d.EffectFor(l), "ladder-fx", row, false);
fx.style.whiteSpace = WhiteSpace.Normal;
if (!done) UIK.Text(UIK.Money(d.PriceFor(l - 1)), next && avail ? "ladder-price" : "ladder-price ladder-price-later", row);
}
}
// what it waits for, each one green once it is there (including perks from other trees)
if (d.requires.Length > 0 && !maxed)
{
var names = new List<string>();
foreach (var r in d.requires)
{
var rd = GameDefs.Perk(r);
string n = d.requireLevel > 1 ? $"{rd.name} {GameDefs.ToRoman(d.requireLevel)}" : rd.name;
names.Add(ts.Level(r) >= d.requireLevel ? $"<color=#3E8A24>{n}</color>" : $"<color=#B0402C>{n}</color>");
}
var req = UIK.Text(Loc.F("Requires {0}", string.Join(" + ", names)), "t-body t-muted t-center detail-req", _detail, false);
req.style.whiteSpace = WhiteSpace.Normal;
req.enableRichText = true;
}
var spacer = UIK.El(null, _detail);
spacer.style.flexGrow = 1;
if (maxed) UIK.Text(d.maxLevel > 1 ? Loc.T("MAXED OUT!") : Loc.T("OWNED"), "price t-green t-outline t-center detail-maxed", _detail);
else if (avail)
{
var b = UIK.Btn(lvl > 0 ? Loc.F("UPGRADE {0}", UIK.Money(price)) : Loc.F("UNLOCK {0}", UIK.Money(price)), () => Buy(d, UIK.CanPay(price)), "btn", _detail);
UIK.Costs(b, price);
b.style.alignSelf = Align.Stretch;
}
if (animate) UIK.SlideIn(_detail, new Vector2(40, 0), 0.05f, 0.3f);
}
void Buy(PerkDef d, bool afford)
{
_nodes.TryGetValue(d.id, out var node);
if (!afford)
{
Sfx.Play("error", 0.7f);
if (node != null) UIK.Punch(node, 0.08f, 0.3f);
Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn);
return;
}
Ts.BuyPerkRpc((int)d.id);
Sfx.Play("cash_register", 0.9f);
if (node != null) UIK.Punch(node, 0.3f, 0.45f);
var cam = CameraFx.Cam;
if (cam) Fx.Confetti(cam.transform.position + cam.transform.forward * 1.6f - cam.transform.up * 0.5f, 60, 4f);
}
}
}