Files
grass-cutters/Assets/Scripts/UI/MapScreen.cs
NiemandKG d1c3761e58 Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:44:40 +06:00

284 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
/// <summary>
/// M: the globe of Herbaria-7. Drag turns it, the wheel zooms in until every sector is its own hexagon. Sectors nobody
/// has touched are the meadow, begun ones gold, finished ones the pale straw of mown ground.
/// </summary>
public class MapScreen
{
const float MaxZoom = 60f, HexZoom = 14f;
const int MaxHexes = 1400;
public VisualElement Card { get; }
readonly VisualElement _chart;
readonly Label _stats;
Quaternion _view;
float _zoom;
bool _dragging;
Vector2 _last;
static readonly Color Meadow = new Color(0.27f, 0.47f, 0.17f);
static readonly Color Space = new Color(0.09f, 0.11f, 0.13f);
static readonly Color Lines = new Color(1f, 1f, 1f, 0.1f);
static readonly Color Rim = new Color(0.72f, 0.86f, 0.5f, 0.8f);
static readonly Color Begun = new Color(0.93f, 0.71f, 0.22f);
static readonly Color Done = new Color(0.9f, 0.84f, 0.56f);
static readonly Color Base = new Color(0.78f, 0.28f, 0.18f);
static readonly Color Stake = new Color(1f, 0.45f, 0.35f);
static readonly Color Robot = new Color(0.55f, 0.8f, 1f);
static readonly Color Station = new Color(1f, 0.85f, 0.3f);
static readonly Color Border = new Color(0.1f, 0.14f, 0.05f, 0.5f);
static readonly Dictionary<int, Vector3[]> s_corners = new Dictionary<int, Vector3[]>();
readonly HashSet<int> _seen = new HashSet<int>();
readonly Queue<int> _queue = new Queue<int>();
public MapScreen(VisualElement layer, Action close, float zoom = 1f)
{
_zoom = zoom;
Card = UIK.El("card rig-map", layer);
var header = UIK.El("card-header", Card);
UIK.Text("HERBARIA-7", "t-h1 t-dark", header);
_stats = UIK.Text("", "t-body t-dark", header, false);
UIK.Btn("X", close, "btn btn-red btn-small", header);
_chart = UIK.El("map-chart", Card);
_chart.pickingMode = PickingMode.Position;
_chart.style.overflow = Overflow.Hidden;
_chart.generateVisualContent += Draw;
_chart.RegisterCallback<WheelEvent>(e => { _zoom = Mathf.Clamp(_zoom * (e.delta.y > 0 ? 0.8f : 1.25f), 1f, MaxZoom); _chart.MarkDirtyRepaint(); });
_chart.RegisterCallback<PointerDownEvent>(e => { _dragging = true; _last = e.position; _chart.CapturePointer(e.pointerId); });
_chart.RegisterCallback<PointerUpEvent>(e => { _dragging = false; _chart.ReleasePointer(e.pointerId); });
_chart.RegisterCallback<PointerMoveEvent>(e =>
{
if (!_dragging) return;
var d = (Vector2)e.position - _last;
_last = e.position;
float k = 57.3f / (Radius * _zoom);
_view = Quaternion.Euler(d.y * k, d.x * k, 0f) * _view;
_chart.MarkDirtyRepaint();
});
var legend = UIK.El("map-legend", Card);
Key(legend, Meadow, Loc.T("Untouched"));
Key(legend, Begun, Loc.T("Started"));
Key(legend, Done, Loc.T("Mown"));
Key(legend, Base, Loc.T("Base"));
Key(legend, Stake, Loc.T("Stake or point done"));
Key(legend, Robot, Loc.T("Robot"));
Key(legend, Station, Loc.T("Station"));
UIK.Text(Loc.T("DRAG turn · WHEEL zoom · M close"), "t-small t-muted", legend, false);
var me = PlayerAgent.Local;
var up = me ? Planet.Up(me.transform.position) : Vector3.up;
var north = Vector3.ProjectOnPlane(Vector3.up, up);
if (north.sqrMagnitude < 1e-4f) north = Vector3.forward;
_view = Quaternion.Inverse(Quaternion.LookRotation(up, north));
Refresh();
_chart.schedule.Execute(Refresh).Every(300);
}
void Refresh()
{
var ts = TeamState.Instance;
MowMap.Count();
if (ts) _stats.text = Loc.F("{0:N0} started · {1:N0} mown · {2:0.0000}% of the planet", MowMap.Started, ts.Closed.Value, ts.Mown01 * 100.0);
_chart.MarkDirtyRepaint();
}
static void Key(VisualElement parent, Color c, string label)
{
var row = UIK.El("map-key", parent);
UIK.El("swatch", row).style.backgroundColor = c;
UIK.Text(label, "t-small t-dark", row, false);
}
float Radius
{
get
{
var r = _chart.contentRect;
return Mathf.Max(40f, Mathf.Min(r.width, r.height) * 0.47f);
}
}
Vector2 Screen(Vector3 d, out bool front)
{
var v = _view * d;
front = v.z > 0f;
return _chart.contentRect.center + new Vector2(v.x, -v.y) * Radius * _zoom;
}
/// <summary>A sector's corners, in order round its middle.</summary>
static Vector3[] Corners(HexGrid.Sector s)
{
if (s_corners.TryGetValue(s.id, out var c)) return c;
var near = new List<Vector3>();
foreach (int n in s.neighbours) near.Add(HexGrid.Get(n).c);
near.Sort((a, b) => Angle(s, a).CompareTo(Angle(s, b)));
c = new Vector3[near.Count];
for (int i = 0; i < c.Length; i++) c[i] = (s.c + near[i] + near[(i + 1) % c.Length]).normalized;
s_corners[s.id] = c;
return c;
}
static float Angle(HexGrid.Sector s, Vector3 n) => Mathf.Atan2(Vector3.Dot(n - s.c, s.e2), Vector3.Dot(n - s.c, s.e1));
void Hex(Painter2D p, HexGrid.Sector s)
{
var c = Corners(s);
p.BeginPath();
p.MoveTo(Screen(c[0], out _));
for (int i = 1; i < c.Length; i++) p.LineTo(Screen(c[i], out _));
p.ClosePath();
}
static Color Shade(MowMap.Mask m) => m == null || !m.keep ? Meadow : m.done ? Done : Begun;
void Draw(MeshGenerationContext ctx)
{
var r = _chart.contentRect;
if (r.width < 4f) return;
var ts = TeamState.Instance;
var p = ctx.painter2D;
p.fillColor = Space;
p.BeginPath(); p.MoveTo(new Vector2(r.xMin, r.yMin)); p.LineTo(new Vector2(r.xMax, r.yMin)); p.LineTo(new Vector2(r.xMax, r.yMax)); p.LineTo(new Vector2(r.xMin, r.yMax)); p.ClosePath(); p.Fill();
float size = Radius * _zoom;
p.fillColor = Meadow;
p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Fill();
if (_zoom >= HexZoom) Hexes(p, r);
else Dots(p);
Lattice(p);
p.strokeColor = Rim;
p.lineWidth = 3f;
p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Stroke();
// what stands on the ball
Dot(p, Vector3.up, 7f, Base);
if (ts)
{
foreach (int id in ts.Found)
Dot(p, Planet.Up(Landmarks.Spot(id)), 4f, Stake);
for (int i = 1; i < Stations.Count; i++)
if (ts.StationOpen(i)) Dot(p, Stations.Dir(i), 6f, Station);
}
foreach (var m in Mowbot.All)
if (m) Dot(p, Planet.Up(m.At.Value), 4f, Robot);
foreach (var v in Vehicle.All)
if (v) Arrow(p, v.transform, 7f, new Color(0.96f, 0.9f, 0.72f));
foreach (var pl in PlayerAgent.All)
if (pl) Arrow(p, pl.transform, pl.IsOwner ? 11f : 8f, pl.Tint);
}
void Dot(Painter2D p, Vector3 dir, float size, Color col)
{
var at = Screen(dir, out bool front);
if (!front) return;
p.fillColor = col;
p.strokeColor = Color.white;
p.lineWidth = 2f;
p.BeginPath(); p.Arc(at, size, 0f, 360f); p.Fill(); p.Stroke();
}
/// <summary>Far out each worked sector is a speck.</summary>
void Dots(Painter2D p)
{
float size = Mathf.Max(1.5f, 13f / Planet.Radius * Radius * _zoom);
foreach (bool done in new[] { false, true })
{
p.fillColor = done ? Done : Begun;
p.BeginPath();
foreach (var m in MowMap.All)
{
if (!m.keep || m.done != done) continue;
var at = Screen(m.s.c, out bool front);
if (!front) continue;
p.MoveTo(at + new Vector2(size, 0f));
p.Arc(at, size, 0f, 360f);
}
p.Fill();
}
}
/// <summary>Close up, every sector in view, walking out from the one in the middle.</summary>
void Hexes(Painter2D p, Rect r)
{
var masks = new Dictionary<int, MowMap.Mask>();
foreach (var m in MowMap.All) masks[m.s.id] = m;
_seen.Clear();
_queue.Clear();
int first = HexGrid.SectorAt(Quaternion.Inverse(_view) * Vector3.forward);
_queue.Enqueue(first);
_seen.Add(first);
var view = new Rect(r.x - 40f, r.y - 40f, r.width + 80f, r.height + 80f);
p.strokeColor = Border;
p.lineWidth = 1f;
int drawn = 0;
while (_queue.Count > 0 && drawn < MaxHexes)
{
var s = HexGrid.Get(_queue.Dequeue());
var at = Screen(s.c, out bool front);
if (!front || !view.Contains(at)) continue;
drawn++;
masks.TryGetValue(s.id, out var m);
p.fillColor = Shade(m);
Hex(p, s);
p.Fill();
p.Stroke();
foreach (int n in s.neighbours)
if (_seen.Add(n)) _queue.Enqueue(n);
}
}
/// <summary>Latitude and longitude every 30°.</summary>
void Lattice(Painter2D p)
{
p.strokeColor = Lines;
p.lineWidth = 1.5f;
for (int lat = -60; lat <= 60; lat += 30) Trace(p, t => Planet.FromLatLon(lat, t * 360f));
for (int lon = 0; lon < 360; lon += 30) Trace(p, t => Planet.FromLatLon(-90f + t * 180f, lon));
}
void Trace(Painter2D p, Func<float, Vector3> along)
{
bool open = false;
p.BeginPath();
for (int i = 0; i <= 60; i++)
{
var at = Screen(along(i / 60f), out bool front);
if (!front) { open = false; continue; }
if (open) p.LineTo(at); else p.MoveTo(at);
open = true;
}
p.Stroke();
}
void Arrow(Painter2D p, Transform t, float size, Color col)
{
var d = Planet.Up(t.position);
var at = Screen(d, out bool front);
if (!front) return;
var ahead = Screen((d + t.forward * 0.02f).normalized, out _);
var f = (ahead - at).normalized;
if (f.sqrMagnitude < 0.01f) f = Vector2.up;
var side = new Vector2(-f.y, f.x);
p.fillColor = col;
p.strokeColor = Color.white;
p.lineWidth = 2f;
p.BeginPath();
p.MoveTo(at + f * size);
p.LineTo(at - f * size * 0.7f + side * size * 0.7f);
p.LineTo(at - f * size * 0.35f);
p.LineTo(at - f * size * 0.7f - side * size * 0.7f);
p.ClosePath();
p.Fill();
p.Stroke();
}
}
}