Feedback round: bots that keep working, Sky Mower, calmer HUD, faster menus, new map

- Robot docks and drone pads with no belt ship straight to Earth; robots widen
  their rings up to 4x once everything in reach is mown, travel 2.5x faster
  empty, hoppers 60/150 kg. Drone reach 70 m + 25 m per upgrade.
- New Sky Mower: a big mowing drone on a pad, 91 sectors, flies over the grass.
- Cut paint follows the blade as a strip, no disc ahead of the machine.
- Sector toasts aggregate, chimes and till sounds throttled, toasts moved and
  narrowed.
- Menus no longer rebuild on every money change (price tint follows the
  wallet), scroll position kept.
- Map drawn as one mesh, opens near the player, ME / + / - / GLOBE, scale bar.
- Key-art still (x_key) and -shotsize for the store stills; -demobots test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-09 15:38:37 +06:00
parent d1c3761e58
commit 27d075103b
44 changed files with 6801 additions and 5733 deletions

View File

@ -0,0 +1,60 @@
using System.Collections;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
public partial class DemoBot
{
/// <summary>
/// -demobots: a Robot Mk I, a Sky Mower and a Drone Pad, none of them with a belt. All three should keep earning on
/// their own: the robot and the sky mower widen their rings once they are done, the pad ships what its drones bring.
/// </summary>
IEnumerator Bots()
{
TeamState.DeleteSave();
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(3f);
Clock(11f);
var robotAt = Soil17(140f, -40f);
var skyAt = Soil17(-120f, 60f);
var padAt = Soil17(40f, 150f);
Quaternion Face(Vector3 p) => Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(p)), Planet.Up(p));
var robot = Spawner.Instance.SpawnPiece(PieceId.RobotI, robotAt, Face(robotAt), robotAt, true).GetComponent<RobotDock>();
var sky = Spawner.Instance.SpawnPiece(PieceId.SkyMower, skyAt, Face(skyAt), skyAt, true).GetComponent<RobotDock>();
var pad = Spawner.Instance.SpawnPiece(PieceId.DronePad, padAt, Face(padAt), padAt, true).GetComponent<DronePad>();
for (int i = 0; i < 9; i++)
{
var a = Quaternion.AngleAxis(i * 40f, Planet.Up(padAt)) * Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(padAt)).normalized * (12f + i * 6f);
Spawner.Instance.SpawnCargo(CargoKind.Grass, Planet.Surface(padAt + a) + Planet.Up(padAt + a) * 0.6f, Quaternion.identity, Vector3.zero);
}
yield return new WaitForSeconds(1f);
Log($"bots built: robot {(robot ? "ok" : "MISSING")}, sky {(sky ? "ok" : "MISSING")}, pad {(pad ? "ok" : "MISSING")}");
if (!robot || !sky || !pad) yield break;
double money = Ts.Money.Value;
Mowbot.Haste = 25f;
yield return new WaitForSeconds(3f);
var skyUp = Planet.Up(sky.Shown);
yield return Look("bot01_sky_mower", sky.Shown + skyUp * 5f + Vector3.ProjectOnPlane(Vector3.right, skyUp).normalized * 9f, sky.Shown, 0.2f);
yield return Look("bot02_robot", robot.Shown + Planet.Up(robot.Shown) * 3f + Vector3.right * 4f, robot.Shown, 0.2f);
for (int k = 1; k <= 6; k++)
{
yield return new WaitForSeconds(15f);
Log($"t+{k * 15} s at {Mowbot.Haste:0}x: earned {Ts.Money.Value - money:0}, closed {Ts.Closed.Value}");
Log($" robot: {robot.Prompt}");
Log($" sky: {sky.Prompt} alt {Planet.Altitude(sky.ShownBody.position) - Planet.Altitude(sky.Shown):0.0} m");
Log($" pad: {pad.Prompt}, delivered {pad.Delivered}");
}
skyUp = Planet.Up(sky.Shown);
yield return Look("bot03_sky_late", sky.Shown + skyUp * 7f + Vector3.ProjectOnPlane(Vector3.forward, skyUp).normalized * -12f, sky.Shown, 0.2f);
yield return Look("bot04_pad", padAt + Planet.Up(padAt) * 6f + Vector3.right * 8f, padAt, 0.2f);
Mowbot.Haste = 1f;
Log("bots done");
Application.Quit();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 054f406d5f753b04ea40bd5f12cbd553

View File

@ -3003,6 +3003,11 @@ namespace GrassCutter
yield return Sizes();
yield break;
}
if (CommandLine.Has("-demobots"))
{
yield return Bots();
yield break;
}
if (CommandLine.Has("-demobelts"))
{
yield return Belts();

View File

@ -51,6 +51,7 @@ namespace GrassCutter
Cheats.Run("ship 60");
BuildRules.AnyGround = true;
yield return new WaitForSeconds(0.5f);
yield return StillKey();
yield return StillCrew();
yield return StillMachines();
yield return StillFactory();
@ -79,6 +80,55 @@ namespace GrassCutter
// ───────────────────────── by day ─────────────────────────
/// <summary>
/// `x_key`: the key art, from the game itself. The crew mows across the meadow in a staggered line, each trailing a
/// cut stripe, under the ringed giant. The camera looks the giant's way, so it hangs over the field; `-shotsize`
/// picks the frame (wide for the capsules and hero, upright for the library and vertical capsules), and the
/// lens widens on an upright frame so the giant and the crew both fit.
/// </summary>
IEnumerator StillKey()
{
if (!Wanted("x_key")) yield break;
Sky(0.55f, false);
bool tall = H > W;
// the spot and the lens can be tried from the command line without a new build
float x = Arg("-keyx", -80f), z = Arg("-keyz", 300f);
float dist = Arg("-keydist", tall ? 11f : 10f), aimUp = Arg("-keyaim", tall ? 10f : 9f), fov = Arg("-keyfov", tall ? 66f : 58f);
float spread = Arg("-keyspread", tall ? 2.4f : 3.6f);
// the giant hangs at (-0.55, 0.42, 0.72) in the sky above the base: look past it to the right, so it hangs
// over the left of the field and leaves the right for the logo
var giant = new Vector2(-0.55f, 0.72f).normalized;
var look = Rotate(giant, -Arg("-keyturn", tall ? 4f : 12f));
var right = new Vector2(look.y, -look.x);
var walk = (right * 0.55f - look * 0.85f).normalized; // toward us and a little across, faces showing
var abreast = new Vector2(walk.y, -walk.x); // across the frame
Vector3 At(Vector2 p, float h = 0f) => On(p.x, p.y, h);
var mid = new Vector2(x, z);
var who = new[] { 4, 1, 6, 2 };
var tools = new[] { ToolId.WideScythe, ToolId.LongScythe, ToolId.WideScythe, ToolId.Scythe };
for (int i = 0; i < who.Length; i++)
{
// a shallow V: the middle two lead, the outer two a step behind
var start = mid + abreast * ((i - 1.5f) * spread) - walk * (Mathf.Abs(i - 1.5f) * 1.4f);
MowMap.Cut(At(start - walk * 45f), At(start), 2.4f);
var s0 = start;
Actor(who[i], At(start), new Vector3(walk.x, 0f, walk.y), tools[i], true, s => At(s0 + walk * (s * 1.1f)));
}
var cam = mid - look * dist;
var aim = mid + look * 30f;
yield return Still("x_key", t => new Lens(At(cam, tall ? 2.6f : 2.8f), At(aim, aimUp), fov), 2f);
Strike();
}
static float Arg(string flag, float fallback) =>
float.TryParse(CommandLine.Get(flag), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float v) ? v : fallback;
static Vector2 Rotate(Vector2 v, float degrees)
{
float r = degrees * Mathf.Deg2Rad, c = Mathf.Cos(r), s = Mathf.Sin(r);
return new Vector2(v.x * c - v.y * s, v.x * s + v.y * c);
}
IEnumerator StillCrew()
{
if (!Wanted(X("x_crew"))) yield break;

View File

@ -117,7 +117,14 @@ namespace GrassCutter
[DefaultExecutionOrder(-2000)]
public partial class Trailer : MonoBehaviour
{
const int W = 2560, H = 1440;
/// <summary>The frame: 2560x1440 unless `-shotsize WxH` asks for another (key art is shot big, and upright too).</summary>
static readonly int W = ShotSize(0, 2560), H = ShotSize(1, 1440);
static int ShotSize(int i, int fallback)
{
var p = (CommandLine.Get("-shotsize") ?? "").Split('x');
return p.Length == 2 && int.TryParse(p[i], out int v) && v >= 64 && v <= 8192 ? v : fallback;
}
public string Folder;
Camera _cam;
RenderTexture _rt;

View File

@ -525,6 +525,33 @@ namespace GrassCutter
return false;
}
static readonly List<Port> s_belted = new List<Port>();
/// <summary>Does a belt leave any of this piece's hatches?</summary>
public static bool Belted(BuildPiece piece)
{
if (!piece) return false;
s_belted.Clear();
piece.Ports(s_belted);
foreach (var p in s_belted)
if (!p.input && Nearest(p.at, true, Joined, piece, out var next, out _, out _) && next.GetComponentInChildren<Conveyor>()) return true;
return false;
}
/// <summary>
/// Server: a silo with no belt out sends what it holds straight to Earth, a batch every few seconds (one payment
/// and one message per batch, not one per kilo). A belt is for more money (bales, bricks), never a must.
/// </summary>
public static void Ship(NetworkVariable<float> silo, Vector3 at, ref float next)
{
if (silo.Value < 1f || Time.time < next) return;
next = Time.time + 3f;
var ts = TeamState.Instance;
if (!ts) return;
ts.ServerDeposit(silo.Value, CargoKind.Grass, at);
silo.Value = 0f;
}
/// <summary>Does a belt already end here?</summary>
public static bool Taken(Vector3 at)
{

View File

@ -7,12 +7,14 @@ namespace GrassCutter
/// <summary>
/// A pad of fetching drones. Bundles of grass lying loose within <see cref="Range"/> of it (thrown down, dropped off the
/// end of a belt, flung by a twister) are flown in, one per drone per trip, and go into the pad's silo, which puts them
/// on the belts like any other silo. A trip is one synced value per drone (where to, when it left), and every peer flies
/// on the belts like any other silo, or with no belt out sends them straight to Earth: tie a bundle, drop it, the drones
/// do the walking. A trip is one synced value per drone (where to, when it left), and every peer flies
/// the drone along the same plan from it: up, across, down, grab, up, back, down onto the pad.
/// </summary>
public class DronePad : SiloPiece
{
public const float Range = 40f;
/// <summary>How far the drones go from a Mk I pad; every upgrade adds <see cref="RangePerTier"/>.</summary>
public const float Range = 70f, RangePerTier = 25f;
const float Room = 60f, Cruise = 7f, Climb = 3f, Speed = 6f, Hover = 1.35f, GrabTime = 0.8f, Carry = 1f, Look = 0.5f;
const int Most = 4;
/// <summary>A drone at rest on the pad.</summary>
@ -41,6 +43,8 @@ namespace GrassCutter
/// <summary>Two drones at Mk I, one more per upgrade, four at most.</summary>
int Count => Mathf.Min(Most, 2 + (Piece ? Piece.Tier.Value : 0));
float Fly => Speed * Mathf.Sqrt(Piece ? Piece.TierMul : 1f);
float Reach => Range + RangePerTier * (Piece ? Piece.Tier.Value : 0);
float _shipAt;
double Now => NetworkManager ? NetworkManager.ServerTime.Time : Time.timeAsDouble;
public override string Prompt
@ -49,7 +53,8 @@ namespace GrassCutter
{
int out_ = 0;
for (int i = 0; i < Count; i++) if (Trip(i).Value.w >= 0f) out_++;
return Loc.F("Drone Pad: {0} drones, {1} out · {2} of {3}", Count, out_, GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room));
return Loc.F("Drone Pad: {0} drones, {1} out · {2} of {3}", Count, out_, GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room))
+ " · " + (BeltNet.Belted(Piece) ? Loc.T("onto the belt") : Loc.F("straight to Earth, {0} m around", Mathf.RoundToInt(Reach)));
}
}
@ -159,8 +164,11 @@ namespace GrassCutter
protected override void Update()
{
if (Belted()) base.Update();
bool belted = Belted();
if (belted) base.Update();
if (!IsServer || !IsSpawned) return;
// no belt out: what the drones bring goes straight to Earth, so they never stand idle on a full silo
if (!belted) BeltNet.Ship(Silo, transform.position, ref _shipAt);
double now = Now;
bool look = Time.time >= _nextLook;
if (look) _nextLook = Time.time + Look;
@ -224,7 +232,7 @@ namespace GrassCutter
for (int k = 0; k < Most; k++) if (Trip(k).Value.w >= 0f) out_++;
if (Silo.Value + (out_ + 1) * GameDefs.BundleKg > Room) return;
Cargo best = null;
float bestD = Range * Range;
float bestD = Reach * Reach;
var here = transform.position;
foreach (var c in Cargo.All)
{

View File

@ -36,7 +36,7 @@ namespace GrassCutter
public enum PieceCat : byte { Services, Logistics, Production, Power, Structures, Decor, Count }
public enum PieceId : byte { Depot, Belt, Splitter, Merger, Square, Hex, Dryer, Press, SolarS, SolarM, SolarL, Garage, Binder, RobotI, RobotII, Reaper, Catcher, Pole, BatteryS, BatteryL, UnloadBay, DronePad, Intake,
Wall, WindowWall, DoorWall, Railing, Fence, Floor, FlatRoof, Roof, Stairs, Steps, Pillar, Planter, Lamppost, Bench, Crates, Flagpole, Count }
Wall, WindowWall, DoorWall, Railing, Fence, Floor, FlatRoof, Roof, Stairs, Steps, Pillar, Planter, Lamppost, Bench, Crates, Flagpole, SkyMower, Count }
/// <summary>How a structure finds its place: anywhere, on the edge of a deck, or on top of the walls (a storey up).</summary>
public enum Fit : byte { Free, Edge, Top }
@ -135,6 +135,8 @@ namespace GrassCutter
public string name { get => Loc.T(nameEn); set => nameEn = value; }
public int reach;
public float width, speed, hopper;
/// <summary>Flies this high over the grass (0: drives on it).</summary>
public float hover;
}
public class PanelDef
@ -311,9 +313,9 @@ namespace GrassCutter
new PieceDef { id = PieceId.Binder, cat = PieceCat.Logistics, name = Loc.N("Binder"), icon = "icon_piece_binder", model = "SM_Binder", prefab = "Piece_Binder", price = 100, sizeX = 2, sizeZ = 2,
desc = Loc.N("E hands it what's in your tool. It ties the grass into bundles and puts them on the belt at its front.") },
new PieceDef { id = PieceId.RobotI, cat = PieceCat.Services, name = Loc.N("Robot Mk I"), icon = "icon_piece_robot", model = "SM_RobotDock", prefab = "Piece_RobotI", price = 250, sizeX = 3, sizeZ = 3,
desc = Loc.N("Mows the 19 sectors around its dock. The dock ties what it brings into bundles for the belt.") },
desc = Loc.N("Mows the sectors around its dock, then further out once they are done. With a belt the dock sends bundles down it, without one it ships the grass to Earth itself.") },
new PieceDef { id = PieceId.RobotII, cat = PieceCat.Services, name = Loc.N("Robot Mk II"), icon = "icon_piece_robot2", model = "SM_RobotDock", prefab = "Piece_RobotII", price = 500, sizeX = 3, sizeZ = 3,
desc = Loc.N("37 sectors, a wider cut and a bigger hopper.") },
desc = Loc.N("Starts with 37 sectors, a wider cut and a bigger hopper.") },
new PieceDef { id = PieceId.Reaper, cat = PieceCat.Services, name = Loc.N("Reaper"), icon = "icon_piece_reaper", model = "SM_Reaper", prefab = "Piece_Reaper", price = 20000, sizeX = 3, sizeZ = 4,
desc = Loc.N("Goes from sector to sector on its own and shoots every bundle into a Bundle Catcher, from anywhere on the planet.") },
new PieceDef { id = PieceId.Catcher, cat = PieceCat.Services, name = Loc.N("Bundle Catcher"), icon = "icon_piece_catcher", model = "SM_BundleCatcher", prefab = "Piece_Catcher", price = 1500, sizeX = 3, sizeZ = 3,
@ -327,7 +329,7 @@ namespace GrassCutter
new PieceDef { id = PieceId.UnloadBay, cat = PieceCat.Logistics, name = Loc.N("Unload Bay"), icon = "icon_piece_unloadbay", model = "SM_UnloadBay", prefab = "Piece_UnloadBay", price = 150, sizeX = 4, sizeZ = 7,
desc = Loc.N("Drive a mower onto the grate and it empties into the bin. Two hatches at the back put it on belts as bundles.") },
new PieceDef { id = PieceId.DronePad, cat = PieceCat.Logistics, name = Loc.N("Drone Pad"), icon = "icon_piece_dronepad", model = "SM_DronePad", prefab = "Piece_DronePad", price = 600, sizeX = 3, sizeZ = 3, scale = 3.2f,
desc = Loc.N("Its drones fly out to bundles of grass lying loose within 40 m and bring them in. The front hatch puts them on a belt. Two drones, one more per upgrade.") },
desc = Loc.N("Its drones fly out to bundles of grass lying loose within 70 m (25 m more per upgrade) and bring them in. With a belt on the front hatch they go down it, without one straight to Earth. Two drones, one more per upgrade.") },
new PieceDef { id = PieceId.Intake, cat = PieceCat.Services, company = true, name = Loc.N("Base Intake"), icon = "icon_piece_hopper", model = "SM_BaseIntake", prefab = "Piece_Intake", sizeX = 3, sizeZ = 2,
desc = Loc.N("A low hopper against the side of the base: drop grass in or run a belt to it, and it's paid and on its way to Earth.") },
@ -364,6 +366,9 @@ namespace GrassCutter
desc = Loc.N("Company crates, stacked two high.") },
new PieceDef { id = PieceId.Flagpole, cat = PieceCat.Decor, name = Loc.N("Flagpole"), icon = "icon_piece_flagpole", model = "SM_Flagpole", prefab = "Piece_Flagpole", price = 5, sizeX = 1, sizeZ = 1,
desc = Loc.N("The crew's own flag, four metres up.") },
// (appended: the list follows PieceId, and saves keep the ids)
new PieceDef { id = PieceId.SkyMower, cat = PieceCat.Services, name = Loc.N("Sky Mower"), icon = "icon_piece_skymower", model = "SM_DronePad", prefab = "Piece_SkyMower", price = 4000, sizeX = 3, sizeZ = 3, scale = 3.2f,
desc = Loc.N("A big mowing drone. It flies over rocks and hills, works 91 sectors around its pad and goes further out once they are mown. No belt needed: the pad sends the grass to Earth.") },
};
public static PieceDef Piece(PieceId id) => Pieces[(int)id];
@ -379,7 +384,7 @@ namespace GrassCutter
{
case PieceId.Belt: case PieceId.Splitter: case PieceId.Merger: return UpgradeKind.Belt;
case PieceId.Dryer: case PieceId.Press: case PieceId.Binder: return UpgradeKind.Machine;
case PieceId.RobotI: case PieceId.RobotII: case PieceId.Reaper: return UpgradeKind.Robot;
case PieceId.RobotI: case PieceId.RobotII: case PieceId.Reaper: case PieceId.SkyMower: return UpgradeKind.Robot;
case PieceId.Garage: case PieceId.UnloadBay: case PieceId.Catcher: case PieceId.DronePad: return UpgradeKind.Silo;
default: return UpgradeKind.None;
}
@ -498,9 +503,10 @@ namespace GrassCutter
public static readonly RobotDef[] Robots =
{
new RobotDef { piece = PieceId.RobotI, name = Loc.N("Robot Mk I"), reach = 2, width = 0.9f, speed = 1.6f, hopper = 20f },
new RobotDef { piece = PieceId.RobotII, name = Loc.N("Robot Mk II"), reach = 3, width = 1.2f, speed = 2.2f, hopper = 50f },
new RobotDef { piece = PieceId.RobotI, name = Loc.N("Robot Mk I"), reach = 2, width = 0.9f, speed = 1.6f, hopper = 60f },
new RobotDef { piece = PieceId.RobotII, name = Loc.N("Robot Mk II"), reach = 3, width = 1.2f, speed = 2.2f, hopper = 150f },
new RobotDef { piece = PieceId.Reaper, name = Loc.N("Reaper"), width = 1.8f, speed = 3f, hopper = 40f },
new RobotDef { piece = PieceId.SkyMower, name = Loc.N("Sky Mower"), reach = 5, width = 2f, speed = 4f, hopper = 300f, hover = 2.4f },
};
public static RobotDef Robot(PieceId id)

View File

@ -16,7 +16,7 @@ namespace GrassCutter
/// <summary>The demo's fast forward, on the server.</summary>
public static float Haste = 1f;
const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f;
const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f, TravelMul = 2.5f;
const float EngineVolume = 0.16f;
const int SearchLimit = 4000;
@ -104,8 +104,9 @@ namespace GrassCutter
All.Add(this);
if (IsServer) Seat(Planet.Up(transform.position));
_shown = _from = _to = At.Value;
_bobPhase = Random.value * 6.28f;
At.OnValueChanged += Heard;
_engine = Sfx.Loop("robot_mower_loop", Body, 0f);
_engine = Sfx.Loop(Def.hover > 0f ? "drone_loop" : "robot_mower_loop", Body, 0f);
}
public override void OnNetworkDespawn()
@ -202,7 +203,14 @@ namespace GrassCutter
var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime));
// it glides: no shake, no bob, the moving parts do the living
bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f;
body.SetPositionAndRotation(_shown, turn);
// a flyer hangs over the grass, bobbing a little, and leans into the way it goes
var at = _shown;
if (Def.hover > 0f)
{
at += up * (Def.hover + Mathf.Sin(Time.time * 1.9f + _bobPhase) * 0.15f);
turn *= Quaternion.Euler((going ? 8f : 0f) * -nose, 0f, Mathf.Sin(Time.time * 1.3f + _bobPhase) * 2f);
}
body.SetPositionAndRotation(at, turn);
Animate(body, Vector3.SignedAngle(was * Vector3.forward, turn * Vector3.forward, up) / Mathf.Max(1e-3f, Time.deltaTime), going);
}
@ -218,6 +226,7 @@ namespace GrassCutter
float _roll, _level;
bool _parts;
float _spun, _nextBlink = 2f, _blinkAt = -1f, _swayX, _swayV, _wasGoing, _go;
float _bobPhase;
void Animate(Transform body, float turnRate, bool going)
{
@ -226,7 +235,7 @@ namespace GrassCutter
_parts = true;
foreach (var c in body.GetComponentsInChildren<Transform>(true))
{
if (c.name.StartsWith("Spin")) _spin.Add((c, BaseRot.LocalAxisFor(c, body.up)));
if (c.name.StartsWith("Spin") || c.name.StartsWith("Rotor")) _spin.Add((c, BaseRot.LocalAxisFor(c, body.up)));
else if (c.name.StartsWith("Blink")) _blink.Add((c, BaseRot.LocalAxisFor(c, body.up), c.localScale));
else if (c.name.StartsWith("Sway")) _sway.Add(c);
else if (c.name.StartsWith("Wheel_"))
@ -238,7 +247,8 @@ namespace GrassCutter
if (c != body) BaseRot.Of(c);
}
}
_spun += Time.deltaTime * (Mowing.Value ? 1400f : 0f);
// a flyer's rotors never stop: it would fall out of the sky
_spun += Time.deltaTime * (Def.hover > 0f ? 1900f : Mowing.Value ? 1400f : 0f);
foreach (var (t, axis) in _spin)
t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_spun, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward);
// the wheels roll with the ground going by, the clippings rise in the hopper
@ -291,7 +301,8 @@ namespace GrassCutter
var from = Planet.OnSurface(Dir);
// not RotateTowards: it calls anything under a tenth of a degree "there already", and that is 4 m on this ball
var gap = goal - Dir;
float step = Def.speed * Boost * dt / Planet.Radius;
// on the way somewhere (to a sector, home to unload) it goes faster than it mows
float step = Def.speed * Boost * (Homing || _travel ? TravelMul : 1f) * dt / Planet.Radius;
if (gap.magnitude > step) Dir = (Dir + gap.normalized * step).normalized;
else
{

View File

@ -4,7 +4,11 @@ using UnityEngine;
namespace GrassCutter
{
/// <summary>A robot mower and its dock: it works the rings of sectors around the dock, and the dock ties what it brings into bundles for the belt.</summary>
/// <summary>
/// A robot mower and its dock: it works the rings of sectors around the dock, and the dock ties what it brings into
/// bundles for the belt, or with no belt sends it straight to Earth. When everything in its rings is mown it takes the
/// next ring out, up to four times its first reach, so a dock keeps working for a long time without being moved.
/// </summary>
public class RobotDock : Mowbot, IPorts
{
const float SiloRoom = 100f, UnloadRate = 5f;
@ -13,12 +17,14 @@ namespace GrassCutter
public readonly NetworkVariable<float> Silo = new NetworkVariable<float>();
bool _unloading;
int _turn, _area;
int _turn, _area, _reach;
float _shipAt;
protected override Transform Body => bot;
protected override bool NoseOnBack => true;
protected override Vector3 Origin => transform.position;
protected override int Reach => Def.reach;
protected override int Reach => _reach > 0 ? _reach : Def.reach;
int MaxReach => Def.reach * 4;
protected override Vector3 HomeDir => Planet.Up(transform.position);
public override string Prompt
@ -26,17 +32,19 @@ namespace GrassCutter
get
{
if (_area == 0) _area = Area();
return Loc.F("{0}: {1}, {2} of {3}, {4} sectors, dock holds {5}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap), _area, GameDefs.Kilos(Silo.Value));
return Loc.F("{0}: {1}, {2} of {3}, {4} sectors, dock holds {5}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap), _area, GameDefs.Kilos(Silo.Value))
+ " · " + (BeltNet.Belted(GetComponent<BuildPiece>()) ? Loc.T("onto the belt") : Loc.T("straight to Earth"));
}
}
public override float[] State
{
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z, Silo.Value };
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z, Silo.Value, Reach };
set
{
base.State = value;
if (value != null && value.Length > 4) Silo.Value = value[4];
if (value != null && value.Length > 5) _reach = Mathf.Clamp((int)value[5], Def.reach, MaxReach);
}
}
@ -47,7 +55,9 @@ namespace GrassCutter
protected override bool Stay(float dt)
{
BeltNet.Drain(GetComponent<BuildPiece>(), Silo, ref _turn);
var piece = GetComponent<BuildPiece>();
if (BeltNet.Belted(piece)) BeltNet.Drain(piece, Silo, ref _turn);
else BeltNet.Ship(Silo, transform.position, ref _shipAt);
if (_unloading)
{
float give = Mathf.Min(Hopper.Value, UnloadRate * dt, SiloRoom - Silo.Value);
@ -58,7 +68,8 @@ namespace GrassCutter
}
if (Hopper.Value >= 0.01f)
{
Mood.Value = (byte)(give > 0f ? RobotMood.Unloading : RobotMood.Waiting);
// with no belt the dock ships every few seconds: that is unloading, not waiting for a belt
Mood.Value = (byte)(give > 0f || !BeltNet.Belted(piece) ? RobotMood.Unloading : RobotMood.Waiting);
return true;
}
Hopper.Value = 0f;
@ -72,8 +83,23 @@ namespace GrassCutter
protected override void NoWork()
{
// its rings are done: one more ring out, and look again
if (Reach < MaxReach)
{
_reach = Reach + 1;
_area = 0;
Mood.Value = (byte)RobotMood.Travelling;
return;
}
if (Vector3.Dot(Dir, HomeDir) < 0.9999999f || Hopper.Value > 0f) GoHome();
else Mood.Value = (byte)RobotMood.Finished;
}
public override void Moved(Vector3 at)
{
base.Moved(at);
_reach = Def.reach;
_area = 0;
}
}
}

View File

@ -79,7 +79,8 @@ namespace GrassCutter
public override void OnNetworkSpawn()
{
Instance = this;
Money.OnValueChanged += (a, b) => { MoneyChanged?.Invoke(a, b); Changed?.Invoke(); };
// the wallet has its own event: cards that rebuilt on every coin lost their scroll and their clicks
Money.OnValueChanged += (a, b) => MoneyChanged?.Invoke(a, b);
Perks.OnListChanged += _ => Changed?.Invoke();
Opened.OnListChanged += _ => Changed?.Invoke();
Tiles.OnListChanged += _ => { TilesChanged?.Invoke(); Changed?.Invoke(); };

View File

@ -341,7 +341,7 @@ namespace GrassCutter
if (overMeadow && !onDeck && Tank.Value < Capacity && driving)
{
mowing = true;
float kg = MowMap.Cut(_hasCut ? _lastCut : ip, ip, CutWidth) * GameDefs.GrassDensity;
float kg = MowMap.Cut(_hasCut ? _lastCut : ip, ip, CutWidth, blade: true) * GameDefs.GrassDensity;
Tank.Value = Mathf.Min(Capacity, Tank.Value + kg);
if (Tank.Value >= Capacity - 0.01f) { Sfx.Play("tank_full", 0.8f); Assistant.Say("asst_hopper"); Hud.Toast(Loc.F("{0} hopper full: unload at the base yard, a garage pad or an Unload Bay (follow the UNLOAD markers)", Def.name), Hud.ToastKind.Warn); }
_lastCut = ip;
@ -511,7 +511,7 @@ namespace GrassCutter
// someone else's machine: mow the same strip here
if (!IsOwner)
{
MowMap.Cut(_seenCut ? _seenAt : ip, ip, CutWidth);
MowMap.Cut(_seenCut ? _seenAt : ip, ip, CutWidth, blade: true);
_seenAt = ip;
_seenCut = true;
}

View File

@ -42,8 +42,9 @@ namespace GrassCutter
_grid = UIK.El("tree-graph supply-grid", body);
_detail = UIK.El("tree-detail", body);
// a machine or an upgrade arrives a moment after the server says so
// a machine or an upgrade arrives a moment after the server says so; the wallet only recolours the prices
Card.schedule.Execute(Refresh).Every(250);
UIK.FollowWallet(Card);
Refresh();
}
@ -53,14 +54,15 @@ namespace GrassCutter
var me = Me;
if (!ts || !me) return;
_money.text = UIK.Money(ts.Money.Value);
var key = $"{_selected} {Math.Floor(ts.Money.Value)}";
Status();
// rebuilt only when what you own changes: not for the money, not for the hopper
var key = $"{_selected}";
foreach (var d in GameDefs.Vehicles)
{
var v = Mine(d.kind);
key += v ? "1" : "0";
if (!v) continue;
for (int i = 0; i < v.Tuned.Count; i++) key += v.Tuned[i];
key += v.Tank.Value.ToString("0");
}
if (key == _shown) return;
bool first = _shown == null;
@ -82,7 +84,7 @@ namespace GrassCutter
UIK.Text(d.bed > 0 ? Loc.F("{0} bundles", d.bed) : Loc.F("{0:0.##} m · {1:0} kg", d.width, d.hopper), "supply-sub", e, false).pickingMode = PickingMode.Ignore;
var t = UIK.Text(v ? Loc.T("OWNED") : UIK.Money(d.price), "supply-tag", e, false);
t.pickingMode = PickingMode.Ignore;
t.EnableInClassList("supply-tag-afford", !v && Ts.Money.Value >= d.price);
if (!v) UIK.Costs(t, d.price, "supply-tag-afford", null);
e.RegisterCallback<ClickEvent>(_ => { _selected = d.kind; Sfx.Play("ui_click", 0.6f, 1.1f); Refresh(); });
e.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
if (animate) UIK.PopIn(e, 0.03f * index, 0.3f);
@ -93,31 +95,56 @@ namespace GrassCutter
var ts = Ts;
var d = GameDefs.Vehicle(_selected);
var v = Mine(_selected);
// the same machine again (an upgrade landed): stay where the list was scrolled to
var keep = _tunes != null && _tunesFor == _selected ? _tunes.scrollOffset : Vector2.zero;
_detail.Clear();
_tunes = null;
_status = null;
var top = UIK.El("detail-top", _detail);
top.style.backgroundColor = new Color(0.9f, 0.8f, 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);
UIK.Text(d.desc, "item-desc t-center", _detail, false).style.whiteSpace = WhiteSpace.Normal;
if (v) UIK.Text(d.bed > 0 ? Loc.F("Bed: {0} of {1}", v.Bed.Count, d.bed) : Loc.F("Strip {0:0.##} m · top speed {1:0} km/h · {2} of {3}", v.CutWidth, v.TopSpeed * 3.6f, GameDefs.Kilos(v.Tank.Value), GameDefs.Kilos(v.Capacity)), "t-small t-dark t-center", _detail, false).style.whiteSpace = WhiteSpace.Normal;
if (v)
{
_status = UIK.Text("", "t-small t-dark t-center", _detail, false);
_status.style.whiteSpace = WhiteSpace.Normal;
Status();
}
if (!v)
{
bool can = ts.Money.Value >= d.price;
var b = UIK.Btn(Loc.F("BUY {0}", UIK.Money(d.price)), () =>
{
if (!can) { Sfx.Play("error", 0.7f); Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn); return; }
if (!UIK.CanPay(d.price)) { Sfx.Play("error", 0.7f); Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn); return; }
ts.BuyVehicleRpc((byte)d.kind, _garage);
Sfx.Play("cash_register", 0.9f);
}, can ? "btn btn-green" : "btn btn-grey", _detail);
}, "btn", _detail);
UIK.Costs(b, d.price);
b.style.alignSelf = Align.Stretch;
return;
}
var call = UIK.Btn(Loc.T("CALL IT HERE"), () => { ts.CallVehicleRpc(v.NetworkObjectId, _garage); Sfx.Play("ui_click", 0.7f); }, "btn btn-green", _detail);
call.style.alignSelf = Align.Stretch;
var list = new ScrollView(ScrollViewMode.Vertical);
var list = _tunes = new ScrollView(ScrollViewMode.Vertical);
_tunesFor = _selected;
list.AddToClassList("tune-list");
_detail.Add(list);
for (int i = 0; i < (int)TuneId.Count; i++) Tune(list.contentContainer, v, (TuneId)i);
UIK.KeepScroll(list, keep);
}
ScrollView _tunes;
VehicleKind _tunesFor;
Label _status;
/// <summary>The machine's line of numbers, kept up to date in place (its hopper fills while the card is open).</summary>
void Status()
{
if (_status == null) return;
var d = GameDefs.Vehicle(_selected);
var v = Mine(_selected);
if (!v) return;
_status.text = d.bed > 0 ? Loc.F("Bed: {0} of {1}", v.Bed.Count, d.bed) : Loc.F("Strip {0:0.##} m · top speed {1:0} km/h · {2} of {3}", v.CutWidth, v.TopSpeed * 3.6f, GameDefs.Kilos(v.Tank.Value), GameDefs.Kilos(v.Capacity));
}
void Tune(VisualElement parent, Vehicle v, TuneId id)
@ -127,17 +154,17 @@ namespace GrassCutter
int level = v.Level(id);
bool max = level >= d.prices.Length;
double price = max ? 0d : GameDefs.TunePrice(v.kind, id, level);
bool can = !max && Ts.Money.Value >= price;
var row = UIK.El("tune-row", parent);
var names = UIK.El("tune-names", row);
UIK.Text($"{d.name} {level}/{d.prices.Length}", "t-small t-dark", names, false);
UIK.Text(max ? d.effect(level) : d.effect(level + 1), "tune-effect", names, false);
UIK.Btn(max ? Loc.T("MAX") : UIK.Money(price), () =>
var b = UIK.Btn(max ? Loc.T("MAX") : UIK.Money(price), () =>
{
if (!can) { Sfx.Play("error", 0.7f); return; }
if (max || !UIK.CanPay(price)) { Sfx.Play("error", 0.7f); return; }
Ts.TuneVehicleRpc(v.NetworkObjectId, (byte)id);
Sfx.Play("cash_register", 0.9f);
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", row);
}, max ? "btn btn-grey btn-small" : "btn btn-small", row);
if (!max) UIK.Costs(b, price);
}
}
}

View File

@ -86,10 +86,25 @@ namespace GrassCutter
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)
{
Toast(Loc.F("Sector {0:N0} mown clean! +{1}", id + 1, UIK.Money(pay)), ToastKind.Money);
Sfx.Play("perk_unlock", 0.7f);
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)
@ -222,17 +237,26 @@ namespace GrassCutter
if (Instance != null) Instance._toasts.Clear();
}
public static void Toast(string text, ToastKind kind = ToastKind.Info)
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)
{
var h = Instance;
if (h == null) return;
// don't stack the same message
foreach (var c in h._toasts.Children()) if (c is Label l && l.text == text) { UIK.Punch(l, 0.1f); return; }
var t = UIK.Text(text, "toast t-body", h._toasts, false);
// 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(300, 0), 0f, 0.4f);
Tween.Delay(t, 4f, () => UIK.Fade(t, 0f, 0.4f, () => t.RemoveFromHierarchy()));
while (h._toasts.childCount > 5) h._toasts.RemoveAt(0);
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)
@ -277,14 +301,33 @@ namespace GrassCutter
void OnDeposited(Vector3 at, double pay, double kg)
{
var ear = CameraFx.Cam ? CameraFx.Cam.transform.position : at;
if ((ear - at).sqrMagnitude < 30f * 30f) Sfx.PlayAt("cash_register", at, 0.2f, 1f, 0.08f, 0.35f);
FloatText(Loc.F("+{0} · {1} for Earth", UIK.Money(pay), GameDefs.Kilos(kg)), at + Planet.Up(at) * 0.8f, new Color(0.45f, 1f, 0.62f), 0.7f);
if (_local != null && (at - _local.transform.position).sqrMagnitude < 196f) Receipt(pay, kg);
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;
@ -433,7 +476,8 @@ namespace GrassCutter
double diff = _targetMoney - _shownMoney;
_shownMoney += diff * Mathf.Min(1f, Time.unscaledDeltaTime * 9f);
if (System.Math.Abs(_shownMoney - _targetMoney) < 0.02) _shownMoney = _targetMoney;
if (diff > 0 && Time.unscaledTime - _lastTick > 0.07f) { _lastTick = Time.unscaledTime; Sfx.Play("coin_tick", 0.09f, 1.2f, 0.1f); }
// 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);

View File

@ -6,23 +6,33 @@ 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.
/// M: the map of Herbaria-7. It opens close in on you, a few hundred metres across, where every sector is its own
/// hexagon; the wheel zooms out to the whole ball and back, dragging turns it, SPACE (or ME) brings you back to the
/// middle. Untouched sectors are the meadow, begun ones gold, finished ones the pale straw of mown ground.
///
/// The sectors go to the screen as one plain triangle mesh, not as painted paths: a few thousand hexagons cost next to
/// nothing that way, where tessellating them as shapes every repaint made the old globe stutter once much was mown.
/// </summary>
public class MapScreen
{
const float MaxZoom = 60f, HexZoom = 14f;
const int MaxHexes = 1400;
/// <summary>Closest in: the view this many metres across.</summary>
const float NearestMetres = 90f;
/// <summary>Where it opens: this many metres across.</summary>
const float OpenMetres = 650f;
/// <summary>Hexagons from this many pixels across; smaller and each worked sector is a speck.</summary>
const float HexPixels = 7f;
const int MaxHexes = 9000;
public VisualElement Card { get; }
readonly VisualElement _chart;
readonly Label _stats;
readonly VisualElement _chart, _scaleBar;
readonly Label _stats, _scaleText;
Quaternion _view;
float _zoom;
bool _dragging;
float _zoom = -1f;
bool _dragging, _follow = true;
Vector2 _last;
static readonly Color Meadow = new Color(0.27f, 0.47f, 0.17f);
static readonly Color Grid = new Color(0.19f, 0.34f, 0.12f);
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);
@ -32,53 +42,100 @@ namespace GrassCutter
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 Color Unload = new Color(0.98f, 0.55f, 0.2f);
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>();
readonly Dictionary<int, MowMap.Mask> _masks = new Dictionary<int, MowMap.Mask>();
readonly List<Vertex> _verts = new List<Vertex>();
readonly List<ushort> _tris = new List<ushort>();
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);
var tools = UIK.El("map-tools", header);
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("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;
_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<WheelEvent>(e => ZoomBy(e.delta.y > 0 ? 0.8f : 1.25f));
_chart.RegisterCallback<PointerDownEvent>(e => { _dragging = true; _follow = false; _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);
float k = 57.3f / (Radius * Zoom);
_view = Quaternion.Euler(d.y * k, d.x * k, 0f) * _view;
_chart.MarkDirtyRepaint();
});
_chart.schedule.Execute(() =>
{
var kb = UnityEngine.InputSystem.Keyboard.current;
if (kb != null && kb.spaceKey.wasPressedThisFrame) { _follow = true; Centre(); }
}).Every(0);
// the scale: a bar and what it measures, bottom left over the chart
var scale = UIK.El("map-scale", _chart);
_scaleBar = UIK.El("map-scale-bar", scale);
_scaleText = UIK.Text("", "t-small map-scale-text", scale, false);
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, Unload, Loc.T("Unload"));
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);
UIK.Text(Loc.T("DRAG move · WHEEL zoom · SPACE back to you · M close"), "t-small t-muted", legend, false);
Centre();
Refresh();
_chart.schedule.Execute(Refresh).Every(500);
}
/// <summary>The planet's radius on screen, against the chart's size, at this zoom.</summary>
float Zoom
{
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);
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;
void ZoomBy(float k)
{
_zoom = Mathf.Clamp(Zoom * k, 1f, MaxZoom);
_chart.MarkDirtyRepaint();
}
/// <summary>You in the middle, north up.</summary>
void Centre()
{
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);
_chart?.MarkDirtyRepaint();
}
void Refresh()
@ -86,6 +143,8 @@ namespace GrassCutter
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);
// keeps up with you as you go, until you drag it somewhere else
if (_follow) Centre();
_chart.MarkDirtyRepaint();
}
@ -109,7 +168,7 @@ namespace GrassCutter
{
var v = _view * d;
front = v.z > 0f;
return _chart.contentRect.center + new Vector2(v.x, -v.y) * Radius * _zoom;
return _chart.contentRect.center + new Vector2(v.x, -v.y) * Radius * Zoom;
}
/// <summary>A sector's corners, in order round its middle.</summary>
@ -127,15 +186,6 @@ namespace GrassCutter
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)
@ -143,23 +193,28 @@ namespace GrassCutter
var r = _chart.contentRect;
if (r.width < 4f) return;
var ts = TeamState.Instance;
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();
float size = Radius * _zoom;
p.fillColor = Meadow;
p.fillColor = hexPx >= HexPixels ? Grid : Meadow;
p.BeginPath(); p.Arc(r.center, size, 0f, 360f); p.Fill();
if (_zoom >= HexZoom) Hexes(p, r);
else Dots(p);
Lattice(p);
_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));
if (Zoom < 6f) 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);
foreach (var b in BuildPiece.All)
if (b && (b.piece == PieceId.UnloadBay || b.piece == PieceId.Intake)) Dot(p, Planet.Up(b.transform.position), 5f, Unload);
if (ts)
{
foreach (int id in ts.Found)
@ -173,6 +228,18 @@ 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);
}
/// <summary>A round number of metres about a fifth of the chart wide.</summary>
void Scale(float size)
{
float pxPerM = size / Planet.Radius;
float want = _chart.contentRect.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;
_scaleText.text = metres >= 1000f ? Loc.F("{0:0.0} km", metres / 1000f) : Loc.F("{0:0} m", metres);
}
void Dot(Painter2D p, Vector3 dir, float size, Color col)
@ -185,39 +252,51 @@ namespace GrassCutter
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)
// ───────────────────────── the sectors, as a mesh ─────────────────────────
void Flush(MeshGenerationContext ctx)
{
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();
}
if (_verts.Count == 0) return;
var mesh = ctx.Allocate(_verts.Count, _tris.Count);
mesh.SetAllVertices(_verts.ToArray());
mesh.SetAllIndices(_tris.ToArray());
_verts.Clear();
_tris.Clear();
}
/// <summary>Close up, every sector in view, walking out from the one in the middle.</summary>
void Hexes(Painter2D p, Rect r)
void Vert(Vector2 at, Color32 c) => _verts.Add(new Vertex { position = new Vector3(at.x, at.y, Vertex.nearZ), tint = c });
/// <summary>Far out each worked sector is a speck.</summary>
void Dots(MeshGenerationContext ctx, Rect r, float half)
{
var view = new Rect(r.x - half, r.y - half, r.width + half * 2f, r.height + half * 2f);
foreach (var m in _masks.Values)
{
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);
Color32 c = m.done ? Done : Begun;
int k = _verts.Count;
Vert(at + new Vector2(-half, -half), c);
Vert(at + new Vector2(half, -half), c);
Vert(at + new Vector2(half, half), c);
Vert(at + new Vector2(-half, half), c);
_tris.Add((ushort)k); _tris.Add((ushort)(k + 1)); _tris.Add((ushort)(k + 2));
_tris.Add((ushort)k); _tris.Add((ushort)(k + 2)); _tris.Add((ushort)(k + 3));
}
Flush(ctx);
}
/// <summary>Close up, every sector in view, walking out from the one in the middle; each a little smaller than it is, so the grid shows between.</summary>
void Hexes(MeshGenerationContext ctx, 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;
var view = new Rect(r.x - 60f, r.y - 60f, r.width + 120f, r.height + 120f);
int drawn = 0;
while (_queue.Count > 0 && drawn < MaxHexes)
{
@ -225,14 +304,23 @@ namespace GrassCutter
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();
_masks.TryGetValue(s.id, out var m);
Color32 col = Shade(m);
var c = Corners(s);
if (_verts.Count + c.Length + 1 > 65000) Flush(ctx);
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);
for (int i = 0; i < c.Length; i++)
{
_tris.Add((ushort)k);
_tris.Add((ushort)(k + 1 + i));
_tris.Add((ushort)(k + 1 + (i + 1) % c.Length));
}
foreach (int n in s.neighbours)
if (_seen.Add(n)) _queue.Enqueue(n);
}
Flush(ctx);
}
/// <summary>Latitude and longitude every 30°.</summary>

View File

@ -27,7 +27,7 @@ namespace GrassCutter
UIK.Btn("X", close, "btn btn-red btn-small", header);
_body = UIK.El(null, Card);
Refresh();
// the numbers follow the wallet and the piece while the card is up
// the card follows the piece while it is up; the wallet only recolours the price
int was = Stamp();
Card.schedule.Execute(() =>
{
@ -35,9 +35,10 @@ namespace GrassCutter
int now = Stamp();
if (now != was) { was = now; Refresh(); }
}).Every(200);
UIK.FollowWallet(Card);
}
int Stamp() => !_p ? 0 : _p.Setting * 31 + (TeamState.Instance ? (int)TeamState.Instance.Money.Value : 0);
int Stamp() => !_p ? 0 : _p.Setting;
void Refresh()
{
@ -56,17 +57,16 @@ namespace GrassCutter
if (tier < GameDefs.MaxTier)
{
double price = GameDefs.UpgradePrice(_p, tier);
bool can = ts.Money.Value >= price;
var up = UIK.El("tune-row", _body);
var upNames = UIK.El("tune-names", up);
UIK.Text(Loc.F("Upgrade to {0}", GameDefs.TierName(tier + 1)), "t-small t-dark", upNames, false);
UIK.Text(Loc.F("{0}.", Cap(GameDefs.TierEffect(kind, tier + 1))), "tune-effect", upNames, false);
UIK.Btn(UIK.Money(price), () =>
UIK.Costs(UIK.Btn(UIK.Money(price), () =>
{
if (!can) { Sfx.Play("error", 0.7f); return; }
if (!UIK.CanPay(price)) { Sfx.Play("error", 0.7f); return; }
_p.UpgradeRpc();
Sfx.Play("cash_register", 0.9f);
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", up);
}, "btn btn-small", up), price);
}
else UIK.Text(Loc.T("Fully upgraded."), "tune-effect", _body, false);
}

View File

@ -92,6 +92,9 @@ namespace GrassCutter
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);
// open on the first tree that has something affordable
// a single tree needs no tab row
if (TreeCount == 1) tabs.style.display = DisplayStyle.None;
@ -144,7 +147,7 @@ namespace GrassCutter
Vector2 NodeCenter(PerkDef d) => NodePos(d) + new Vector2(Node, Node) * 0.5f;
static Vector2 HubPos => new Vector2(CanvasW * 0.5f - Node * 0.5f, PadY);
void Rebuild(bool animate)
void Wallet()
{
var ts = Ts;
if (!ts) return;
@ -156,6 +159,13 @@ namespace GrassCutter
_tabBadges[i].text = n > 0 ? n.ToString() : "";
_tabBadges[i].style.display = n > 0 ? DisplayStyle.Flex : DisplayStyle.None;
}
}
void Rebuild(bool animate)
{
var ts = Ts;
if (!ts) return;
Wallet();
// nodes
foreach (var n in _nodes.Values) n.RemoveFromHierarchy();
@ -180,7 +190,8 @@ namespace GrassCutter
node.pickingMode = PickingMode.Position;
var pos = NodePos(d);
node.style.left = pos.x; node.style.top = pos.y;
node.AddToClassList(maxed ? "node-maxed" : lvl > 0 ? "node-owned" : !avail ? "node-locked" : afford ? "node-afford" : "node-available");
if (maxed || lvl > 0 || !avail) node.AddToClassList(maxed ? "node-maxed" : lvl > 0 ? "node-owned" : "node-locked");
else UIK.Costs(node, d.PriceFor(lvl), "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;
@ -261,7 +272,6 @@ namespace GrassCutter
bool maxed = lvl >= d.maxLevel;
bool avail = ts.PerkAvailable(d);
long price = d.PriceFor(lvl);
bool afford = ts.Money.Value >= price;
var top = UIK.El("detail-top", _detail);
top.style.backgroundColor = Color.Lerp(TreeColors[(int)_tree], Color.white, 0.55f);
@ -292,7 +302,8 @@ namespace GrassCutter
}
else
{
var b = UIK.Btn(lvl > 0 ? Loc.F("UPGRADE {0}", UIK.Money(price)) : Loc.F("UNLOCK {0}", UIK.Money(price)), () => Buy(d, afford), afford ? "btn btn-green" : "btn btn-grey", _detail);
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);

View File

@ -36,14 +36,15 @@ namespace GrassCutter
UIK.Text(Stations.Name(i), "t-small t-dark", names, false);
float metres = Mathf.Acos(Mathf.Clamp(Vector3.Dot(up, Stations.Dir(i)), -1f, 1f)) * Planet.Radius;
UIK.Text(Compass.Distance(metres), "tune-effect", names, false);
bool can = i != here && ts.Money.Value >= GameDefs.TravelPrice;
UIK.Btn(i == here ? Loc.T("HERE") : UIK.Money(GameDefs.TravelPrice), () =>
bool there = i == here;
var go = UIK.Btn(there ? Loc.T("HERE") : UIK.Money(GameDefs.TravelPrice), () =>
{
if (!can) { Sfx.Play("error", 0.7f); return; }
if (there || !UIK.CanPay(GameDefs.TravelPrice)) { Sfx.Play("error", 0.7f); return; }
ts.TravelRpc(id);
Sfx.Play("cash_register", 0.9f);
close();
}, (can ? "btn btn-green" : "btn btn-grey") + " btn-small", row);
}, there ? "btn btn-grey btn-small" : "btn btn-small", row);
if (!there) UIK.Costs(go, GameDefs.TravelPrice);
}
if (hidden > 0) UIK.Text(Loc.F("{0} more out there. Walk up to one and it opens.", hidden), "tune-effect", list.contentContainer, false);
}

View File

@ -55,6 +55,9 @@ namespace GrassCutter
foreach (var o in GameDefs.ToolOrder)
if (me && !me.Owns(o)) { _selected = (int)o; break; }
Rebuild(true);
// the wallet moves all the time: it recolours the prices and the pill, it doesn't rebuild the card
UIK.FollowWallet(Card);
Card.schedule.Execute(() => { if (Ts) _money.text = UIK.Money(Ts.Money.Value); }).Every(250);
}
void Refresh() => Rebuild(false);
@ -73,12 +76,12 @@ namespace GrassCutter
string sub = GameDefs.IsBlade(t) ? Loc.F("{0:0.#} cm · {1:0.##} kg", ts.ToolWidth(t) * 100f, ts.ToolCap(t)) : Loc.T("Build menu");
double price = ts.ToolPrice(d);
string tag = me.Owns(t) ? (me.Tools.Belt.Contains(t) ? Loc.T("ON BELT") : Loc.T("OWNED")) : price <= 0d ? Loc.T("FREE") : UIK.Money(price);
Item(i, d.icon, d.name, sub, tag, !me.Owns(t) && ts.Money.Value >= price, animate);
Item(i, d.icon, d.name, sub, tag, me.Owns(t) ? -1d : price, animate);
}
int slots = me.BeltSlots.Value;
bool maxed = slots >= GameDefs.MaxBeltSlots;
long slotPrice = GameDefs.BeltSlotPrice(slots);
Item(SlotItem, "icon_perk_release", Loc.T("Belt Slot"), Loc.F("{0} / {1} slots", slots, GameDefs.MaxBeltSlots), maxed ? Loc.T("MAXED") : UIK.Money(slotPrice), !maxed && ts.Money.Value >= slotPrice, animate);
Item(SlotItem, "icon_perk_release", Loc.T("Belt Slot"), Loc.F("{0} / {1} slots", slots, GameDefs.MaxBeltSlots), maxed ? Loc.T("MAXED") : UIK.Money(slotPrice), maxed ? -1d : slotPrice, animate);
Gear(JetItem, GearId.Jetpack, "icon_perk_jetpack", Loc.T("Jetpack"), Loc.T("Dash in the air"), animate);
Gear(BootItem, GearId.Boots, "icon_perk_boots", Loc.T("Gravity Boots"), Loc.T("G: Earth's pull"), animate);
Gear(NightItem, GearId.NightVision, "icon_perk_pure", Loc.T("Night Vision"), Loc.T("N: see in the dark"), animate);
@ -89,10 +92,10 @@ namespace GrassCutter
{
bool has = Me.HasGear(g);
long price = GameDefs.GearPrice(g);
Item(id, icon, name, sub, has ? Loc.T("OWNED") : UIK.Money(price), !has && Ts.Money.Value >= price, animate);
Item(id, icon, name, sub, has ? Loc.T("OWNED") : UIK.Money(price), has ? -1d : price, animate);
}
void Item(int id, string icon, string name, string sub, string tag, bool afford, bool animate)
void Item(int id, string icon, string name, string sub, string tag, double cost, bool animate)
{
var e = UIK.El("supply-item", _grid);
e.pickingMode = PickingMode.Position;
@ -102,7 +105,7 @@ namespace GrassCutter
UIK.Text(sub, "supply-sub", e, false).pickingMode = PickingMode.Ignore;
var t = UIK.Text(tag, "supply-tag", e, false);
t.pickingMode = PickingMode.Ignore;
t.EnableInClassList("supply-tag-afford", afford);
if (cost >= 0d) UIK.Costs(t, cost, "supply-tag-afford", null);
e.RegisterCallback<ClickEvent>(_ => { _selected = id; Sfx.Play("ui_click", 0.6f, 1.1f); Rebuild(false); });
e.RegisterCallback<MouseEnterEvent>(_ => Sfx.Play("ui_hover", 0.35f, 1.2f));
if (animate) UIK.PopIn(e, 0.03f * id, 0.3f);
@ -172,14 +175,14 @@ namespace GrassCutter
int slots = me.BeltSlots.Value;
if (slots >= GameDefs.MaxBeltSlots) { Done(Loc.T("MAXED OUT!")); return; }
long price = GameDefs.BeltSlotPrice(slots);
Buy(Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyBeltSlotRpc());
Buy(Loc.F("BUY {0}", UIK.Money(price)), price, () => ts.BuyBeltSlotRpc());
}
else if (_selected >= JetItem)
{
var g = _selected == JetItem ? GearId.Jetpack : _selected == BootItem ? GearId.Boots : GearId.NightVision;
if (me.HasGear(g)) { Done(Loc.T("OWNED")); return; }
long price = GameDefs.GearPrice(g);
Buy(Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyGearRpc((byte)g));
Buy(Loc.F("BUY {0}", UIK.Money(price)), price, () => ts.BuyGearRpc((byte)g));
}
else
{
@ -188,7 +191,7 @@ namespace GrassCutter
if (!me.Owns(t))
{
double price = ts.ToolPrice(GameDefs.Tool(t));
Buy(price <= 0d ? Loc.T("TAKE IT") : Loc.F("BUY {0}", UIK.Money(price)), ts.Money.Value >= price, () => ts.BuyToolRpc((byte)t));
Buy(price <= 0d ? Loc.T("TAKE IT") : Loc.F("BUY {0}", UIK.Money(price)), price, () => ts.BuyToolRpc((byte)t));
}
else if (tools.Current == t) Done(Loc.T("IN YOUR HANDS"));
else
@ -201,11 +204,11 @@ namespace GrassCutter
void Done(string text) => UIK.Text(text, "price t-green t-outline t-center", _detail);
void Buy(string label, bool afford, Action buy)
void Buy(string label, double cost, Action buy)
{
var b = UIK.Btn(label, () =>
{
if (!afford)
if (!UIK.CanPay(cost))
{
Sfx.Play("error", 0.7f);
Assistant.Say("asst_nocash"); Hud.Toast(Loc.T("Not enough cash: mow more!"), Hud.ToastKind.Warn);
@ -213,7 +216,8 @@ namespace GrassCutter
}
buy();
Sfx.Play("cash_register", 0.9f);
}, afford ? "btn btn-green" : "btn btn-grey", _detail);
}, "btn", _detail);
UIK.Costs(b, cost);
b.style.alignSelf = Align.Stretch;
}
}

View File

@ -48,6 +48,55 @@ namespace GrassCutter
return b;
}
// ───────────────────────── prices that follow the wallet ─────────────────────────
/// <summary>A price on something: the wallet only recolours it (<see cref="FollowWallet"/>), it never rebuilds the card.</summary>
sealed class Price { public double cost; public string yes, no; }
/// <summary>
/// Mark a button (green when you can pay, grey when you can't) or a tag (with <paramref name="yes"/> when you can) as
/// costing this much. The money changes every second once robots and belts run; rebuilding a card for that threw
/// away the scroll and the button under the cursor, so a click landed one time in two.
/// </summary>
public static T Costs<T>(T e, double cost, string yes = "btn-green", string no = "btn-grey") where T : VisualElement
{
e.AddToClassList("costs");
e.userData = new Price { cost = cost, yes = yes, no = no };
Tint(e, TeamState.Instance ? TeamState.Instance.Money.Value : 0d);
return e;
}
static void Tint(VisualElement e, double money)
{
if (!(e.userData is Price p)) return;
bool can = money >= p.cost;
if (!string.IsNullOrEmpty(p.yes)) e.EnableInClassList(p.yes, can);
if (!string.IsNullOrEmpty(p.no)) e.EnableInClassList(p.no, !can);
}
/// <summary>Recolour every price on the card a few times a second as the wallet moves.</summary>
public static void FollowWallet(VisualElement card, long everyMs = 250)
{
card.schedule.Execute(() =>
{
var ts = TeamState.Instance;
if (!ts) return;
double money = ts.Money.Value;
card.Query(className: "costs").ForEach(e => Tint(e, money));
}).Every(everyMs);
}
/// <summary>Can the team pay this right now (checked when the button is pressed, not when it was drawn).</summary>
public static bool CanPay(double cost) => TeamState.Instance && TeamState.Instance.Money.Value >= cost;
/// <summary>Rebuild what is inside a scroll view without it jumping back to the top.</summary>
public static void KeepScroll(ScrollView list, Vector2 offset)
{
if (list == null) return;
list.scrollOffset = offset;
list.schedule.Execute(() => list.scrollOffset = offset);
}
public static VisualElement Img(Texture2D tex, string classes = null, VisualElement parent = null)
{
var e = El(classes, parent);

View File

@ -264,7 +264,7 @@ namespace GrassCutter
/// standing counts, so the whole planet is worth exactly its area. minSweep lets a blade held still eat what is
/// under it, paint widens only what the eye sees, so that rows laid edge to edge show no seam.
/// </summary>
public static float Cut(Vector3 from, Vector3 to, float width, float minSweep = 0f, float paint = 0f)
public static float Cut(Vector3 from, Vector3 to, float width, float minSweep = 0f, float paint = 0f, bool blade = false)
{
var up = Planet.Up(to);
var flat = Vector3.ProjectOnPlane(to - from, up);
@ -296,9 +296,22 @@ namespace GrassCutter
if (cut <= 0f) return 0f;
Critters.Disturb(to, half, cut);
float r = half + paint;
int stamps = Mathf.Clamp(Mathf.CeilToInt(len / Mathf.Max(r, 0.25f)) + 1, 1, MaxStampsPerCut);
for (int i = 0; i < stamps; i++) Stamp(Vector3.Lerp(from, to, stamps > 1 ? (float)i / (stamps - 1) : 1f), r);
// a machine's header shows the strip it took and nothing ahead of it; a stroke shows round ends
if (blade)
{
if (len > 1e-3f)
foreach (int id in s_touched)
{
var m = Open(id);
if (m != null) PaintStrip(m, a, b, half);
}
}
else
{
float r = half + paint;
int stamps = Mathf.Clamp(Mathf.CeilToInt(len / Mathf.Max(r, 0.25f)) + 1, 1, MaxStampsPerCut);
for (int i = 0; i < stamps; i++) Stamp(Vector3.Lerp(from, to, stamps > 1 ? (float)i / (stamps - 1) : 1f), r);
}
return cut;
}
@ -411,6 +424,41 @@ namespace GrassCutter
if (-Vector3.Dot(d, s.borders[k]) < reach) Paint(HexGrid.Get(s.neighbours[k]), d, r);
}
/// <summary>
/// Show the strip a header swept from a to b: square across the line of travel, as wide as the cut, and only a
/// hand's breadth past either end so the next stroke joins on without a seam. A wide header shows a wide strip
/// behind it, not a disc eaten out in front of it.
/// </summary>
static void PaintStrip(Mask m, Vector3 a, Vector3 b, float half)
{
var s = m.s;
Flat(s, a, out float u0, out float v0);
Flat(s, b, out float u1, out float v1);
float du = u1 - u0, dv = v1 - v0, len = Mathf.Sqrt(du * du + dv * dv);
if (len < 1e-4f) return;
float ux = du / len, uv = dv / len;
const float cap = 0.3f;
float reach = half + PaintFeather + cap;
int x0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(u0, u1) - reach + s.half) / m.cell));
int x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(u0, u1) + reach + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(v0, v1) - reach + s.half) / m.cell));
int z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(v0, v1) + reach + s.half) / m.cell));
float wide = Mathf.Max(half, MinPaintRadius);
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
float cu = Cell(m, x) - u0, cv = Cell(m, z) - v0;
float across = Mathf.Abs(cv * ux - cu * uv);
float t = cu * ux + cv * uv;
float off = Mathf.Max(-t, t - len);
float f = Mathf.Clamp01((wide - across) / PaintFeather + 0.5f) * Mathf.Clamp01((cap - off) / PaintFeather + 0.5f);
if (f <= 0f) continue;
byte by = (byte)(f * 255f);
int i = (z * Res + x) * 2;
if (by > m.rg[i]) { m.rg[i] = by; m.show = m.dirty = m.keep = true; }
}
}
static void Paint(HexGrid.Sector s, Vector3 d, float r)
{
var m = Open(s.id);