From d61167e22b852ede9891ba8f46e9cf5f77b55074 Mon Sep 17 00:00:00 2001 From: NiemandKG <74151950+NiemandKG@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:33:03 +0600 Subject: [PATCH] Map sectors show again, clients get their own machines and the train's swath, machines stay out of the ground - Map: the sectors are wound the screen's way (most were wound the other way and culled, leaving a blank chart), kept inside the chart, and drawn as ball, sectors and marks layers; the scale bar is no longer sized mid-draw. - Players' save keys are replicated, so a client's garage finds its machines and their upgrades; two players under one key get separate ones. - The grass train sends its mowing to the clients; moving the depot or resizing the planet relays its line. - A hard floor under vehicle springs: hard landings, steep rises and hand-overs no longer sink a machine. - Tests: -demosink, -demorep host|client. Co-Authored-By: Claude Opus 5.5 --- Assets/Scripts/Core/DemoBot.Replica.cs | 110 ++++++++++++++ Assets/Scripts/Core/DemoBot.Replica.cs.meta | 11 ++ Assets/Scripts/Core/DemoBot.Sink.cs | 116 ++++++++++++++ Assets/Scripts/Core/DemoBot.Sink.cs.meta | 11 ++ Assets/Scripts/Core/DemoBot.cs | 10 ++ Assets/Scripts/Gameplay/BuildPiece.cs | 2 + Assets/Scripts/Gameplay/Train.cs | 44 +++++- Assets/Scripts/Gameplay/Vehicle.cs | 31 ++++ Assets/Scripts/Player/PlayerAgent.cs | 12 +- Assets/Scripts/UI/MapScreen.cs | 160 ++++++++++++++++---- 10 files changed, 474 insertions(+), 33 deletions(-) create mode 100644 Assets/Scripts/Core/DemoBot.Replica.cs create mode 100644 Assets/Scripts/Core/DemoBot.Replica.cs.meta create mode 100644 Assets/Scripts/Core/DemoBot.Sink.cs create mode 100644 Assets/Scripts/Core/DemoBot.Sink.cs.meta diff --git a/Assets/Scripts/Core/DemoBot.Replica.cs b/Assets/Scripts/Core/DemoBot.Replica.cs new file mode 100644 index 0000000..0ec549f --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Replica.cs @@ -0,0 +1,110 @@ +using System.Collections; +using UnityEngine; + +namespace GrassCutter +{ + public partial class DemoBot + { + /// + /// -demorep host|client: what a client sees of the host's world. A grass train at Mk IV mowing its line (the + /// grass it takes must go on the client too, the train must stand the same), the client buying a machine of its + /// own and an upgrade for it, and driving it and hopping off (it must stay on the ground). + /// + IEnumerator ReplicaDemo(bool host) + { + string me = host ? "host" : "client"; + yield return new WaitForSeconds(2f); + if (host) { TeamState.DeleteSave(); NetSession.Instance.HostLocal(); } + else { yield return new WaitForSeconds(10f); NetSession.Instance.JoinLocal("127.0.0.1"); } + while (!Me || !Ts) yield return null; + Quaternion Face(Vector3 p, Vector3 way) => Quaternion.LookRotation(Vector3.ProjectOnPlane(way, Planet.Up(p)), Planet.Up(p)); + var sAt = Soil17(-40f, -70f); + if (host) + { + Clock(11f); + Ts.ServerSetMoney(500000d); + var piece = Spawner.Instance.SpawnPiece(PieceId.Train, sAt, Face(sAt, Vector3.ProjectOnPlane(sAt - Planet.FromBase(0f, 0f) * Planet.Radius, Planet.Up(sAt))), sAt, true); + yield return new WaitForSeconds(1f); + piece.Tier.Value = GameDefs.MaxTier; + var tr = piece.GetComponent(); + yield return new WaitForSeconds(0.5f); + // its first stretch laid: it goes home mowing out either side + tr.State = new[] { (float)tr.Target.Value, tr.LineLength, tr.LineLength, 1f, 0f }; + } + float t0 = Time.time; + while (PlayerAgent.All.Count < 2 && Time.time - t0 < 60f) yield return null; + Log($"{me}: {PlayerAgent.All.Count} players"); + if (PlayerAgent.All.Count < 2) { Application.Quit(); yield break; } + yield return new WaitForSeconds(4f); + var other = PlayerAgent.All.Find(p => p != Me); + Log($"{me}: my save key '{Me.SaveId}', the other's '{other.SaveId}'"); + + // the train mows: the same strip on both + var train = Train.All.Count > 0 ? Train.All[0] : null; + if (!train) { Log($"{me}: no train"); Application.Quit(); yield break; } + MowMap.Count(); + float mown0 = MowMap.MownArea(); + float at0 = train.At.Value; + yield return new WaitForSeconds(12f); + MowMap.Count(); + Log($"{me}: train went {at0 - train.At.Value:0} m, {MowMap.MownArea() - mown0:0} m² mown meanwhile, {train.Hopper.Value:0} kg on board"); + var lp = train.loco.position; + var lu = Planet.Up(lp); + Log($"{me}: loco at {lp.x:0.00},{lp.y:0.00},{lp.z:0.00} leaning {Vector3.Angle(train.loco.up, lu):0.0} deg, {Planet.Altitude(lp):0.00} m up; wagon 1 at {(train.wagons.Length > 0 && train.wagons[0] ? train.wagons[0].position.ToString("F2") : "-")}, {train.LineLength:0} m of line"); + Time.timeScale = 1f; + yield return Look(host ? "rep_host_train" : "rep_client_train", lp + lu * 8f + Vector3.Cross(lu, train.loco.forward).normalized * 15f + train.loco.forward * 10f, lp - train.loco.forward * 10f, 0.4f); + + // the client buys a machine, finds it is its own, and upgrades it + Vehicle mine = null; + if (!host) + { + Ts.BuyVehicleRpc((byte)VehicleKind.Tractor, 0UL); + yield return new WaitForSeconds(3f); + mine = Vehicle.Mine(VehicleKind.Tractor, Me.SaveId); + Log($"client: bought a tractor, the garage sees it as mine: {(mine ? "yes" : "NO")}"); + if (mine) + { + int was = mine.Level(TuneId.Motors); + Ts.TuneVehicleRpc(mine.NetworkObjectId, (byte)TuneId.Motors); + yield return new WaitForSeconds(1.5f); + Log($"client: motors {was} -> {mine.Level(TuneId.Motors)}"); + } + } + else yield return new WaitForSeconds(4.5f); + yield return new WaitForSeconds(1f); + if (host) + { + var theirs = Vehicle.Mine(VehicleKind.Tractor, other.SaveId); + Log($"host: the client's tractor {(theirs ? "is here" : "MISSING")}, mine {(Vehicle.Mine(VehicleKind.Tractor, Me.SaveId) ? "too" : "none (right)")}"); + } + + // the client drives it and hops off; both watch how it stands + var v = Vehicle.All.Find(x => x && x.kind == VehicleKind.Tractor); + if (!host && v) + { + Me.Teleport(v.transform.position + v.transform.right * 3f + Planet.Up(v.transform.position)); + yield return new WaitForSeconds(0.5f); + v.Interact(); + yield return new WaitForSeconds(1f); + Ctl.BotMove = new Vector2(0.3f, 1f); + yield return new WaitForSeconds(5f); + Ctl.BotMove = Vector2.zero; + yield return new WaitForSeconds(1f); + v.RequestExit(); + } + else yield return new WaitForSeconds(7.5f); + float low = 0f; + if (v) for (float t = 0f; t < 4f; t += Time.deltaTime) { low = Mathf.Min(low, Lowest(v)); yield return null; } + if (v) Log($"{me}: after the client hopped off, deepest {low:0.00} m, now {Lowest(v):0.00} m, driver {(v.HasDriver ? "STILL" : "none")}, owned by {(v.IsOwnedByServer ? "the host" : "a client")}, sinks caught here {Vehicle.Sinks}"); + if (v) + { + var vp = v.transform.position; + var vu = Planet.Up(vp); + yield return Look(host ? "rep_host_tractor" : "rep_client_tractor", vp + vu * 2.5f + v.transform.right * 8f, vp, 0.3f); + } + yield return new WaitForSeconds(3f); + Log($"{me}: rep done"); + Application.Quit(); + } + } +} diff --git a/Assets/Scripts/Core/DemoBot.Replica.cs.meta b/Assets/Scripts/Core/DemoBot.Replica.cs.meta new file mode 100644 index 0000000..f8e3c48 --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Replica.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b0d9abdb827442aea18206094c4586b8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Core/DemoBot.Sink.cs b/Assets/Scripts/Core/DemoBot.Sink.cs new file mode 100644 index 0000000..9501088 --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Sink.cs @@ -0,0 +1,116 @@ +using System.Collections; +using UnityEngine; + +namespace GrassCutter +{ + public partial class DemoBot + { + /// + /// -demosink: a tractor on the steepest bit of meadow round the base. Each round drives it up the slope, hops off, + /// and drops it from eight metres; the log says how far below the ground its lowest corner or its nose went. The + /// first round has the hard floor off (how it was), the second on. + /// + IEnumerator SinkDemo() + { + TeamState.DeleteSave(); + yield return new WaitForSeconds(2f); + NetSession.Instance.HostLocal(); + while (!Me || !Ts) yield return null; + yield return new WaitForSeconds(3f); + Clock(11f); + Ts.ServerSetMoney(100000d); + + // the steepest clear slope within 70 m + Vector3 steep = Soil17(60f, 40f), downhill = Vector3.forward; + float worst = -1f; + for (int a = 0; a < 48; a++) + for (float r = 30f; r <= 70f; r += 8f) + { + var q = Soil17(Mathf.Cos(a * 7.5f * Mathf.Deg2Rad) * r, Mathf.Sin(a * 7.5f * Mathf.Deg2Rad) * r); + var u = Planet.Up(q); + var e1 = Vector3.Cross(u, Vector3.forward).normalized; + var e2 = Vector3.Cross(u, e1); + float h1 = Planet.Altitude(q + e1 * 2f + u * 0f) - Planet.Altitude(q - e1 * 2f); + float h2 = Planet.Altitude(q + e2 * 2f) - Planet.Altitude(q - e2 * 2f); + float slope = Mathf.Atan2(new Vector2(h1, h2).magnitude, 4f) * Mathf.Rad2Deg; + if (slope > worst && !Ts.OnDeck(q) && !(Ground.Instance && Ground.Instance.RockAt(q)) && !Physics.CheckSphere(q + u * 3f, 9f, 1 << Layers.Default, QueryTriggerInteraction.Ignore)) + { + worst = slope; steep = q; + // altitude grows the way the ground falls away under the probe, so "uphill" is against it + downhill = (e1 * h1 + e2 * h2).normalized; + } + } + var up = Planet.Up(steep); + var start = steep + downhill * 18f; + start = Planet.Surface(start); + var uphill = Vector3.ProjectOnPlane(-downhill, Planet.Up(start)).normalized; + Log($"slope {worst:0} deg at {steep}"); + + var v = Spawner.Instance.SpawnVehicle(VehicleKind.Tractor, Me.SaveId, start + Planet.Up(start) * 0.6f, Quaternion.LookRotation(uphill, Planet.Up(start))); + yield return new WaitForSeconds(1.5f); + if (!v) { Log("tractor NOT spawned"); Application.Quit(); yield break; } + + for (int round = 0; round < 2; round++) + { + Vehicle.NoFloor = round == 0; + string tag = round == 0 ? "floor OFF" : "floor ON "; + v.ServerPut(start + Planet.Up(start) * 0.6f, Quaternion.LookRotation(uphill, Planet.Up(start))); + yield return new WaitForSeconds(2f); + int sinks = Vehicle.Sinks; + + // up the slope, flat out + v.Interact(); + yield return new WaitForSeconds(0.6f); + Ctl.BotMove = Vector2.up; + float climb = 0f; + for (float t = 0f; t < 5f; t += Time.fixedDeltaTime) { climb = Mathf.Min(climb, Lowest(v)); yield return new WaitForFixedUpdate(); } + Ctl.BotMove = Vector2.zero; + yield return new WaitForSeconds(1f); + if (round == 1) yield return Look("sink_climb", v.transform.position + Planet.Up(v.transform.position) * 1.5f + v.transform.right * 7f, v.transform.position, 0.3f); + + // hop off and watch it stand + v.RequestExit(); + float off = 0f; + for (float t = 0f; t < 4f; t += Time.fixedDeltaTime) { off = Mathf.Min(off, Lowest(v)); yield return new WaitForFixedUpdate(); } + float rest = Lowest(v); + + // and dropped from eight metres + var p = v.transform.position; + v.ServerPut(p + Planet.Up(p) * 8f, v.transform.rotation); + float land = 0f; + for (float t = 0f; t < 5f; t += Time.fixedDeltaTime) { land = Mathf.Min(land, Lowest(v)); yield return new WaitForFixedUpdate(); } + Log($"{tag}: deepest on the climb {climb:0.00} m, after hopping off {off:0.00} m (at rest {rest:0.00}), landing {land:0.00} m, caught {Vehicle.Sinks - sinks} times, now {Planet.Altitude(v.transform.position):0.00} m up"); + } + Vehicle.NoFloor = false; + // and the map, close in, with the sectors round here + Cheats.Run("tool all"); + Me.Teleport(v.transform.position + v.transform.right * 4f + Planet.Up(v.transform.position)); + yield return Sweep(Me.transform.position, new Vector3(0f, 0f, 1.6f), 3f); + UIRoot.I.OpenMap(); + yield return new WaitForSeconds(1.5f); + BotCapture.From = null; + yield return Shot("sink_map"); + Log($"map: {MapScreen.Drawn} sectors drawn close in, {MapScreen.Flipped} turned round"); + UIRoot.I.CloseTopModal(); + yield return new WaitForSeconds(0.3f); + UIRoot.I.OpenMap(1.6f); + yield return new WaitForSeconds(1.5f); + yield return Shot("sink_map_far"); + Log("sink done"); + Application.Quit(); + } + + /// The lowest of its four corners, nose and tail, against the ground (below it is negative). + static float Lowest(Vehicle v) + { + float low = float.MaxValue; + var t = v.transform; + for (int x = -1; x <= 1; x += 2) + for (int z = -1; z <= 1; z += 2) + low = Mathf.Min(low, Planet.Altitude(t.TransformPoint(new Vector3(x * 0.5f * v.width, 0f, z * 0.42f * v.length)))); + low = Mathf.Min(low, Planet.Altitude(t.TransformPoint(new Vector3(0f, 0f, 0.5f * v.length)))); + low = Mathf.Min(low, Planet.Altitude(t.TransformPoint(new Vector3(0f, 0f, -0.5f * v.length)))); + return low; + } + } +} diff --git a/Assets/Scripts/Core/DemoBot.Sink.cs.meta b/Assets/Scripts/Core/DemoBot.Sink.cs.meta new file mode 100644 index 0000000..31ae69f --- /dev/null +++ b/Assets/Scripts/Core/DemoBot.Sink.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 20733dbba1c04b8395fe845276378d8f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Core/DemoBot.cs b/Assets/Scripts/Core/DemoBot.cs index c2448ef..615fe9e 100644 --- a/Assets/Scripts/Core/DemoBot.cs +++ b/Assets/Scripts/Core/DemoBot.cs @@ -2957,6 +2957,11 @@ namespace GrassCutter yield return TwoPlayers(role == "host"); yield break; } + if (CommandLine.Get("-demorep") is string rep) + { + yield return ReplicaDemo(rep == "host"); + yield break; + } if (CommandLine.Get("-democrowd") is string crowd) { yield return Crowd(crowd == "host"); @@ -3013,6 +3018,11 @@ namespace GrassCutter yield return Perf(int.Parse(perfSlot)); yield break; } + if (CommandLine.Has("-demosink")) + { + yield return SinkDemo(); + yield break; + } if (CommandLine.Has("-demotrain")) { yield return TrainDemo(); diff --git a/Assets/Scripts/Gameplay/BuildPiece.cs b/Assets/Scripts/Gameplay/BuildPiece.cs index ce8c1c2..c7b22cb 100644 --- a/Assets/Scripts/Gameplay/BuildPiece.cs +++ b/Assets/Scripts/Gameplay/BuildPiece.cs @@ -133,6 +133,8 @@ namespace GrassCutter transform.SetPositionAndRotation(at, rot); var bot = GetComponent(); if (bot) bot.Moved(at); + var train = GetComponent(); + if (train) train.Moved(); if (Stands && Planet.Altitude(at) < 1f) MowMap.BlockRound(at, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f); Fx.Build(at, new Vector2(Def.sizeX, Def.sizeZ)); Sfx.PlayAt("build_place", at, 0.9f); diff --git a/Assets/Scripts/Gameplay/Train.cs b/Assets/Scripts/Gameplay/Train.cs index 8880936..fd900d9 100644 --- a/Assets/Scripts/Gameplay/Train.cs +++ b/Assets/Scripts/Gameplay/Train.cs @@ -149,6 +149,7 @@ namespace GrassCutter if (!All.Contains(this)) All.Add(this); Target.OnValueChanged += (_, __) => Route(); Legs.OnValueChanged += (_, __) => Route(); + Planet.Rescaled += Route; if (IsServer) { while (Bins.Count < Stations.Count) Bins.Add(0f); @@ -157,8 +158,24 @@ namespace GrassCutter Route(); } + /// Everyone: the depot was picked up and set down elsewhere. The line starts from there now, so it is laid again. + public void Moved() + { + if (IsServer) + { + Laid.Value = 0f; + At.Value = 0f; + Runs.Value = 0; + _wait = 0f; + _noMore = false; + } + _shown = 0f; + Route(); + } + public override void OnNetworkDespawn() { + Planet.Rescaled -= Route; All.Remove(this); if (_track) Destroy(_track); } @@ -375,6 +392,7 @@ namespace GrassCutter { if (!IsSpawned) return; if (IsServer && _length > 0f) Run(Time.deltaTime); + if (IsServer && _sendW > 0f && Time.time - _sendT > 0.25f) SendCut(); Draw(); } @@ -471,10 +489,32 @@ namespace GrassCutter Hopper.Value = 0f; } - /// Mows along the track from a to b: under it (offset 0), or a strip either side starting this far out. + /// Host: mows along the track from a to b into the hopper, and has everyone else mow the same. void Cut(float a, float b, float offset, float width) { if (width <= 0.05f || Mathf.Abs(b - a) < 1e-4f) return; + Hopper.Value = Mathf.Min(Hold, Hopper.Value + Mow(a, b, offset, width) * GameDefs.GrassDensity); + // each peer cuts its own copy of the meadow: the stroke goes out to the others, joined up into a few a second + if (_sendW > 0f && (_sendOff != offset || _sendW != width || Mathf.Abs(_sendB - a) > 0.01f || (b > a) != (_sendB > _sendA))) SendCut(); + if (_sendW <= 0f) { _sendA = a; _sendOff = offset; _sendW = width; _sendT = Time.time; } + _sendB = b; + if (Time.time - _sendT > 0.25f) SendCut(); + } + + float _sendA, _sendB, _sendOff, _sendW, _sendT; + + void SendCut() + { + if (_sendW > 0f && Mathf.Abs(_sendB - _sendA) > 1e-4f) CutRpc(_sendA, _sendB, _sendOff, _sendW); + _sendW = 0f; + } + + [Rpc(SendTo.NotServer)] + void CutRpc(float a, float b, float offset, float width) => Mow(a, b, offset, width); + + /// Mows along the track from a to b: under it (offset 0), or a strip either side starting this far out. The kilos cut. + float Mow(float a, float b, float offset, float width) + { float kg = 0f; int n = Mathf.Max(1, Mathf.CeilToInt(Mathf.Abs(b - a) / Step)); for (int k = 0; k < n; k++) @@ -489,7 +529,7 @@ namespace GrassCutter kg += MowMap.Cut(Planet.Surface(p0 + side * o), Planet.Surface(p1 + side * o), width, 0f, MowMap.PaintFeather); kg += MowMap.Cut(Planet.Surface(p0 - side * o), Planet.Surface(p1 - side * o), width, 0f, MowMap.PaintFeather); } - Hopper.Value = Mathf.Min(Hold, Hopper.Value + kg * GameDefs.GrassDensity); + return kg; } // ───────────────────────── riding ───────────────────────── diff --git a/Assets/Scripts/Gameplay/Vehicle.cs b/Assets/Scripts/Gameplay/Vehicle.cs index 51fdebe..dfbfa62 100644 --- a/Assets/Scripts/Gameplay/Vehicle.cs +++ b/Assets/Scripts/Gameplay/Vehicle.cs @@ -274,6 +274,35 @@ namespace GrassCutter // ───────────────────────── physics (owner) ───────────────────────── + readonly float[] _clear = new float[4]; + /// The nose and the tail, along the middle, past the springs: what digs in first on a rise or a hard landing. + static readonly float[] Ends = { 0.5f, -0.5f, 0f }; + + /// + /// A hard floor under the springs. They are soft enough to ride a meadow, so a hard landing, a steep rise or the + /// moment after a hand-over squeezed them right through and a corner (or the nose) went into the ground; nothing + /// else holds a machine up, the ground itself has no collider. Whatever is below the ground comes straight back + /// up, and stops falling. + /// + void Floor(Vector3 up) + { + float sink = 0f; + for (int i = 0; i < _clear.Length; i++) sink = Mathf.Max(sink, -_clear[i]); + for (int i = 0; i < Ends.Length; i++) + sink = Mathf.Max(sink, -Planet.Altitude(transform.TransformPoint(new Vector3(0f, 0f, Ends[i] * length)))); + if (sink < 0.02f || NoFloor) return; + sink = Mathf.Min(sink, 3f); + Body.position += up * sink; + float down = Vector3.Dot(Body.linearVelocity, up); + if (down < 0f) Body.linearVelocity -= up * down; + Sinks++; + } + + /// How often the floor had to catch a machine (the tests read it). + public static int Sinks; + /// Tests: the floor off, to see how it was. + public static bool NoFloor; + static readonly Vector2[] Probes = { new Vector2(-0.5f, 0.42f), new Vector2(0.5f, 0.42f), new Vector2(-0.5f, -0.42f), new Vector2(0.5f, -0.42f) }; void FixedUpdate() @@ -311,6 +340,7 @@ namespace GrassCutter if (_ghost) clearance = Mathf.Min(clearance, DeckClearance(wp, up, 1.2f + ride + 1.5f)); else if (Physics.Raycast(wp + up * 1.2f, -up, out var sh, 1.2f + ride + 1.5f, groundMask, QueryTriggerInteraction.Ignore)) clearance = Mathf.Min(clearance, sh.distance - 1.2f); + _clear[i] = clearance; float depth = ride - clearance; if (depth > 0f) { @@ -321,6 +351,7 @@ namespace GrassCutter } } bool onGround = wet > 0; + Floor(up); // drive var fwd = Vector3.ProjectOnPlane(transform.forward, up).normalized; diff --git a/Assets/Scripts/Player/PlayerAgent.cs b/Assets/Scripts/Player/PlayerAgent.cs index 21ad5c2..2206a97 100644 --- a/Assets/Scripts/Player/PlayerAgent.cs +++ b/Assets/Scripts/Player/PlayerAgent.cs @@ -27,6 +27,8 @@ namespace GrassCutter new Color(0.96f, 0.96f, 0.94f),// white }; + /// The key of this player's things in the host's save, as the host settled it: everyone needs it, the garage looks up "my machine" by it. + public readonly NetworkVariable SaveKey = new NetworkVariable(""); public readonly NetworkVariable NetName = new NetworkVariable("", NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable SteamId = new NetworkVariable(0, NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); public readonly NetworkVariable ColorIndex = new NetworkVariable(); @@ -75,7 +77,7 @@ namespace GrassCutter /// Gravity boots on: Earth's pull instead of Herbaria's. public bool BootsOn { get; set; } /// Key of this player's tools in the host's save. - public string SaveId { get; private set; } + public string SaveId => SaveKey.Value.IsEmpty ? null : SaveKey.Value.ToString(); public bool ClaimedSave => SaveId != null; public Vehicle Vehicle => _vehicle; @@ -215,12 +217,16 @@ namespace GrassCutter [Rpc(SendTo.Server)] void ClaimSaveRpc(FixedString64Bytes id) { - SaveId = id.ToString(); - if (Ts && OwnerClientId != NetworkManager.ServerClientId && Ts.Banned(SaveId)) + string key = id.ToString(); + if (Ts && OwnerClientId != NetworkManager.ServerClientId && Ts.Banned(key)) { NetworkManager.DisconnectClient(OwnerClientId, Loc.Pack("You are banned from this game")); return; } + // two players under one key (no Steam, or one account on two copies) would share one fleet and one set of + // tools: the second one gets a key of its own + if (All.Exists(p => p && p != this && p.SaveId == key)) key += "#" + OwnerClientId; + SaveKey.Value = new FixedString64Bytes(key); if (Ts) { Ts.ServerRestoreCrew(this); diff --git a/Assets/Scripts/UI/MapScreen.cs b/Assets/Scripts/UI/MapScreen.cs index b775fc2..da07259 100644 --- a/Assets/Scripts/UI/MapScreen.cs +++ b/Assets/Scripts/UI/MapScreen.cs @@ -24,7 +24,7 @@ namespace GrassCutter const int MaxHexes = 9000; public VisualElement Card { get; } - readonly VisualElement _chart, _scaleBar; + readonly VisualElement _chart, _ball, _ground, _marks, _scaleBar; readonly Label _stats, _scaleText; Quaternion _view; float _zoom = -1f; @@ -61,13 +61,18 @@ namespace GrassCutter UIK.Btn(Loc.T("ME"), () => { _follow = true; Centre(); }, "btn btn-small", tools); UIK.Btn("+", () => ZoomBy(1.6f), "btn btn-small", tools); UIK.Btn("−", () => ZoomBy(1f / 1.6f), "btn btn-small", tools); - UIK.Btn(Loc.T("GLOBE"), () => { _zoom = 1f; _chart.MarkDirtyRepaint(); }, "btn btn-small", tools); + UIK.Btn(Loc.T("GLOBE"), () => { _zoom = 1f; Repaint(); }, "btn btn-small", tools); 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.focusable = true; - _chart.generateVisualContent += Draw; + // space is the chart's own colour; over it three layers, each its own element so the order is plain: the + // ball, the sectors on it, the marks. + _chart.style.backgroundColor = Space; + _ball = Layer(DrawBall); + _ground = Layer(DrawGround); + _marks = Layer(DrawMarks); _chart.RegisterCallback(e => ZoomBy(e.delta.y > 0 ? 0.8f : 1.25f)); _chart.RegisterCallback(e => { _dragging = true; _follow = false; _last = e.position; _chart.CapturePointer(e.pointerId); }); _chart.RegisterCallback(e => { _dragging = false; _chart.ReleasePointer(e.pointerId); }); @@ -78,7 +83,7 @@ namespace GrassCutter _last = e.position; float k = 57.3f / (Radius * Zoom); _view = Quaternion.Euler(d.y * k, d.x * k, 0f) * _view; - _chart.MarkDirtyRepaint(); + Repaint(); }); _chart.schedule.Execute(() => { @@ -102,6 +107,8 @@ namespace GrassCutter Key(legend, Station, Loc.T("Station")); UIK.Text(Loc.T("DRAG move · WHEEL zoom · SPACE back to you · M close"), "t-small t-muted", legend, false); + // asked to open at a zoom of its own (1 is "close in on you", the usual) + if (zoom != 1f) _zoom = Mathf.Max(1f, zoom); Centre(); Refresh(); _chart.schedule.Execute(Refresh).Every(500); @@ -113,18 +120,18 @@ namespace GrassCutter get { // the first time it knows its size: open a few hundred metres across - if (_zoom < 0f && _chart.contentRect.width > 4f) _zoom = Mathf.Clamp(PxPerMetre(OpenMetres) * Planet.Radius / Radius, 1f, MaxZoom); + if (_zoom < 0f && Area.width > 4f) _zoom = Mathf.Clamp(PxPerMetre(OpenMetres) * Planet.Radius / Radius, 1f, MaxZoom); return _zoom < 0f ? 1f : _zoom; } } float MaxZoom => Mathf.Max(1f, PxPerMetre(NearestMetres) * Planet.Radius / Radius); - float PxPerMetre(float across) => Mathf.Max(100f, _chart.contentRect.width) / across; + float PxPerMetre(float across) => Mathf.Max(100f, Area.width) / across; void ZoomBy(float k) { _zoom = Mathf.Clamp(Zoom * k, 1f, MaxZoom); - _chart.MarkDirtyRepaint(); + Repaint(); } /// You in the middle, north up. @@ -135,7 +142,7 @@ namespace GrassCutter var north = Vector3.ProjectOnPlane(Vector3.up, up); if (north.sqrMagnitude < 1e-4f) north = Vector3.forward; _view = Quaternion.Inverse(Quaternion.LookRotation(up, north)); - _chart?.MarkDirtyRepaint(); + Repaint(); } void Refresh() @@ -145,7 +152,7 @@ namespace GrassCutter 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); // keeps up with you as you go, until you drag it somewhere else if (_follow) Centre(); - _chart.MarkDirtyRepaint(); + Repaint(); } static void Key(VisualElement parent, Color c, string label) @@ -159,7 +166,7 @@ namespace GrassCutter { get { - var r = _chart.contentRect; + var r = Area; return Mathf.Max(40f, Mathf.Min(r.width, r.height) * 0.47f); } } @@ -168,7 +175,7 @@ namespace GrassCutter { var v = _view * d; front = v.z > 0f; - return _chart.contentRect.center + new Vector2(v.x, -v.y) * Radius * Zoom; + return Area.center + new Vector2(v.x, -v.y) * Radius * Zoom; } /// A sector's corners, in order round its middle. @@ -188,24 +195,94 @@ namespace GrassCutter static Color Shade(MowMap.Mask m) => m == null || !m.keep ? Meadow : m.done ? Done : Begun; - void Draw(MeshGenerationContext ctx) + VisualElement Layer(Action draw) { - var r = _chart.contentRect; + var e = new VisualElement { pickingMode = PickingMode.Ignore }; + e.style.position = Position.Absolute; + e.style.left = 0f; e.style.top = 0f; e.style.right = 0f; e.style.bottom = 0f; + e.generateVisualContent += draw; + _chart.Add(e); + return e; + } + + void Repaint() + { + _ball?.MarkDirtyRepaint(); + _ground?.MarkDirtyRepaint(); + _marks?.MarkDirtyRepaint(); + // the scale bar is an element: sized here, never while drawing + if (_scaleBar != null && Area.width > 4f) Scale(Radius * Zoom); + } + + /// The chart's drawing area, in the layers' own space. + Rect Area => _ground != null ? _ground.contentRect : _chart.contentRect; + + float HexPx(float size) => Mathf.Sqrt(GameDefs.SectorArea) / Planet.Radius * size; + + void DrawBall(MeshGenerationContext ctx) + { + var r = Area; if (r.width < 4f) return; - var ts = TeamState.Instance; + _clip = r; float size = Radius * Zoom; - float hexPx = Mathf.Sqrt(GameDefs.SectorArea) / Planet.Radius * size; - - 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(); - p.fillColor = hexPx >= HexPixels ? Grid : Meadow; - p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Fill(); + Disc(r, size, HexPx(size) >= HexPixels ? Grid : Meadow); + Flush(ctx); + } + /// The sectors on the ball, one mesh, kept inside the chart. + void DrawGround(MeshGenerationContext ctx) + { + var r = Area; + if (r.width < 4f) return; + _clip = r; + float size = Radius * Zoom; + float hexPx = HexPx(size); _masks.Clear(); foreach (var m in MowMap.All) _masks[m.s.id] = m; if (hexPx >= HexPixels) Hexes(ctx, r); else Dots(ctx, r, Mathf.Max(1.5f, hexPx * 0.5f)); + Flush(ctx); + } + + /// The ball as a fan, cut to the part of it that shows (close in it is far bigger than the chart). + void Disc(Rect r, float size, Color32 col) + { + var c = r.center; + float reach = new Vector2(r.width, r.height).magnitude * 0.5f; + if (size > reach * 1.5f) + { + // the chart sits wholly inside the ball: a plain quad + int q = _verts.Count; + Vert(new Vector2(r.xMin, r.yMin), col); Vert(new Vector2(r.xMax, r.yMin), col); + Vert(new Vector2(r.xMax, r.yMax), col); Vert(new Vector2(r.xMin, r.yMax), col); + _tris.Add((ushort)q); _tris.Add((ushort)(q + 1)); _tris.Add((ushort)(q + 2)); + _tris.Add((ushort)q); _tris.Add((ushort)(q + 2)); _tris.Add((ushort)(q + 3)); + return; + } + const int Steps = 96; + int k = _verts.Count; + Vert(c, col); + for (int i = 0; i < Steps; i++) + { + float a = i * Mathf.PI * 2f / Steps; + Vert(c + new Vector2(Mathf.Cos(a), Mathf.Sin(a)) * size, col); + } + for (int i = 0; i < Steps; i++) + { + _tris.Add((ushort)k); + _tris.Add((ushort)(k + 1 + i)); + _tris.Add((ushort)(k + 1 + (i + 1) % Steps)); + } + } + + /// Over the ground: the lattice, the rim, and everything that stands on the ball. + void DrawMarks(MeshGenerationContext ctx) + { + var r = Area; + if (r.width < 4f) return; + var ts = TeamState.Instance; + float size = Radius * Zoom; + var p = ctx.painter2D; if (Zoom < 6f) Lattice(p); p.strokeColor = Rim; p.lineWidth = 3f; @@ -228,14 +305,13 @@ namespace GrassCutter 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); - Scale(size); } /// A round number of metres about a fifth of the chart wide. void Scale(float size) { float pxPerM = size / Planet.Radius; - float want = _chart.contentRect.width * 0.18f / pxPerM; + float want = Area.width * 0.18f / pxPerM; float step = Mathf.Pow(10f, Mathf.Floor(Mathf.Log10(Mathf.Max(1f, want)))); float metres = want >= step * 5f ? step * 5f : want >= step * 2f ? step * 2f : step; _scaleBar.style.width = metres * pxPerM; @@ -254,6 +330,14 @@ namespace GrassCutter // ───────────────────────── the sectors, as a mesh ───────────────────────── + /// The sectors go out in pieces of this size at most, well inside what one mesh may hold. + const int ChunkVerts = 6000, ChunkIndices = 18000; + + void Room(MeshGenerationContext ctx, int verts, int indices) + { + if (_verts.Count + verts > ChunkVerts || _tris.Count + indices > ChunkIndices) Flush(ctx); + } + void Flush(MeshGenerationContext ctx) { if (_verts.Count == 0) return; @@ -264,7 +348,15 @@ namespace GrassCutter _tris.Clear(); } - void Vert(Vector2 at, Color32 c) => _verts.Add(new Vertex { position = new Vector3(at.x, at.y, Vertex.nearZ), tint = c }); + /// Every corner is held inside the chart, so a sector across its edge is cut off there instead of spilling + /// past it onto the card (the chart's rounded edge doesn't clip a hand-made mesh). + Rect _clip = new Rect(-1e6f, -1e6f, 2e6f, 2e6f); + + void Vert(Vector2 at, Color32 c) + { + at = new Vector2(Mathf.Clamp(at.x, _clip.xMin, _clip.xMax), Mathf.Clamp(at.y, _clip.yMin, _clip.yMax)); + _verts.Add(new Vertex { position = new Vector3(at.x, at.y, Vertex.nearZ), tint = c }); + } /// Far out each worked sector is a speck. void Dots(MeshGenerationContext ctx, Rect r, float half) @@ -275,7 +367,7 @@ namespace GrassCutter if (!m.keep) continue; var at = Screen(m.s.c, out bool front); if (!front || !view.Contains(at)) continue; - if (_verts.Count > 60000) Flush(ctx); + Room(ctx, 4, 6); Color32 c = m.done ? Done : Begun; int k = _verts.Count; Vert(at + new Vector2(-half, -half), c); @@ -298,6 +390,7 @@ namespace GrassCutter _seen.Add(first); var view = new Rect(r.x - 60f, r.y - 60f, r.width + 120f, r.height + 120f); int drawn = 0; + Flipped = 0; while (_queue.Count > 0 && drawn < MaxHexes) { var s = HexGrid.Get(_queue.Dequeue()); @@ -307,22 +400,33 @@ namespace GrassCutter _masks.TryGetValue(s.id, out var m); Color32 col = Shade(m); var c = Corners(s); - if (_verts.Count + c.Length + 1 > 65000) Flush(ctx); + Room(ctx, c.Length + 1, c.Length * 3); int k = _verts.Count; Vert(at, col); for (int i = 0; i < c.Length; i++) Vert(Vector2.LerpUnclamped(at, Screen(c[i], out _), 0.92f), col); + // the screen drops faces wound the wrong way round, and the corners go round whichever way the + // sector's own frame does: turned the screen's way here, or half the map never shows + var e0 = (Vector2)_verts[k + 1].position - at; + var e1 = (Vector2)_verts[k + 2].position - at; + bool flip = e0.x * e1.y - e0.y * e1.x < 0f; + if (flip) Flipped++; for (int i = 0; i < c.Length; i++) { + int i0 = k + 1 + i, i1 = k + 1 + (i + 1) % c.Length; _tris.Add((ushort)k); - _tris.Add((ushort)(k + 1 + i)); - _tris.Add((ushort)(k + 1 + (i + 1) % c.Length)); + _tris.Add((ushort)(flip ? i1 : i0)); + _tris.Add((ushort)(flip ? i0 : i1)); } foreach (int n in s.neighbours) if (_seen.Add(n)) _queue.Enqueue(n); } Flush(ctx); + Drawn = drawn; } + /// Tests: sectors in the last close-in drawing, and how many of them had to be turned round. + public static int Drawn, Flipped; + /// Latitude and longitude every 30°. void Lattice(Painter2D p) {