- 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>
425 lines
20 KiB
C#
425 lines
20 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Unity.Collections;
|
|
using Unity.Netcode;
|
|
using UnityEngine;
|
|
|
|
namespace GrassCutter
|
|
{
|
|
/// <summary>
|
|
/// Shared, server-owned crew progress: wallet, kilos shipped to Earth (= how much of Herbaria-7 is mown), the upgrade
|
|
/// matrix, deck tiles and the save game. Tools, belt slots and gear are personal, and the host's save remembers them.
|
|
/// </summary>
|
|
public partial class TeamState : NetworkBehaviour
|
|
{
|
|
public static TeamState Instance { get; private set; }
|
|
|
|
public readonly NetworkVariable<double> Money = new NetworkVariable<double>();
|
|
public readonly NetworkVariable<double> Shipped = new NetworkVariable<double>();
|
|
/// <summary>Square metres mown, as the host counts them.</summary>
|
|
public readonly NetworkVariable<double> Mown = new NetworkVariable<double>();
|
|
/// <summary>Sectors mown clean.</summary>
|
|
public readonly NetworkVariable<int> Closed = new NetworkVariable<int>();
|
|
public NetworkList<byte> Perks;
|
|
public NetworkList<int> Tiles;
|
|
/// <summary>Stakes and survey points the crew has done.</summary>
|
|
public NetworkList<int> Found;
|
|
|
|
public static event Action<double, double> MoneyChanged;
|
|
public static event Action<string, string> Purchased; // who, what
|
|
/// <summary>Added to the server clock to give the time of day.</summary>
|
|
public readonly NetworkVariable<float> DayOffset = new NetworkVariable<float>();
|
|
/// <summary>How big the ball is (<see cref="Difficulty"/>): the host's save says, everyone builds on the same one.</summary>
|
|
public readonly NetworkVariable<byte> Size = new NetworkVariable<byte>();
|
|
public static event Action<string> Announcement;
|
|
public static event Action<Vector3, double, double> Deposited; // where, money, kilos
|
|
public static event Action Changed;
|
|
public static event Action TilesChanged;
|
|
|
|
[Serializable] class PieceSave { public int id, cfg; public bool free; public Vector3 at, to; public Quaternion turn; public float[] state; }
|
|
[Serializable] class CrewSave { public string key; public int owned, slots, current = 255; public int[] belt; public float[] bins; }
|
|
[Serializable] class CargoSave { public int kind; public float kg; public Vector3 at; }
|
|
[Serializable]
|
|
class SaveData
|
|
{
|
|
/// <summary>0: pieces stood on the old 1 m grid.</summary>
|
|
public int ver;
|
|
/// <summary>How big the ball is: 0 the whole planet (every save from before there was a choice), 1 half, 2 a third.</summary>
|
|
public int level;
|
|
public double money, shipped, mown;
|
|
/// <summary>Time of day: the first morning begins here.</summary>
|
|
public float day = 0.75f;
|
|
public int[] perks;
|
|
public int[] tiles;
|
|
public int[] found;
|
|
public int[] stations;
|
|
public List<string> banned = new List<string>();
|
|
public List<PieceSave> pieces = new List<PieceSave>();
|
|
public List<CrewSave> crew = new List<CrewSave>();
|
|
public List<CargoSave> cargo = new List<CargoSave>();
|
|
public List<VehicleSave> vehicles = new List<VehicleSave>();
|
|
}
|
|
|
|
static readonly long[][] OldFleet = { new long[] { 1000 }, new long[] { 6000 }, new long[] { 250, 600, 1500 }, new long[] { 200, 500, 1200 }, new long[] { 150, 400 } };
|
|
|
|
/// <summary>A crew that leaves more lying around than this loses the rest on a restart.</summary>
|
|
const int MaxSavedBundles = 4000;
|
|
|
|
List<CrewSave> _crew = new List<CrewSave>();
|
|
|
|
void Awake()
|
|
{
|
|
Instance = this;
|
|
Perks = new NetworkList<byte>();
|
|
Tiles = new NetworkList<int>();
|
|
Found = new NetworkList<int>();
|
|
Opened = new NetworkList<byte>();
|
|
}
|
|
|
|
public override void OnNetworkSpawn()
|
|
{
|
|
Instance = this;
|
|
// 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(); };
|
|
if (!IsServer)
|
|
{
|
|
Difficulties.Apply((Difficulty)Size.Value);
|
|
MowMap.Reset(); // the host sends what has been cut
|
|
}
|
|
WatchSectors();
|
|
if (IsServer)
|
|
{
|
|
for (int i = 0; i < (int)PerkId.Count; i++) Perks.Add(0);
|
|
Load();
|
|
}
|
|
TilesChanged?.Invoke();
|
|
Changed?.Invoke();
|
|
}
|
|
|
|
public override void OnNetworkDespawn()
|
|
{
|
|
if (Instance == this) Instance = null;
|
|
UnwatchSectors();
|
|
}
|
|
|
|
// ───────────────────────── queries ─────────────────────────
|
|
|
|
public int Level(PerkId id) => Perks != null && (int)id < Perks.Count ? Perks[(int)id] : 0;
|
|
public bool Has(PerkId id) => Level(id) > 0;
|
|
|
|
public bool PerkAvailable(PerkDef d)
|
|
{
|
|
foreach (var r in d.requires) if (Level(r) < d.requireLevel) return false;
|
|
return true;
|
|
}
|
|
|
|
/// <summary>Matrix installs so far, out of <see cref="TotalInstalls"/>; the uplink in the middle comes free.</summary>
|
|
public int Installs
|
|
{
|
|
get { int n = 1; foreach (var d in GameDefs.Perks) n += Level(d.id); return n; }
|
|
}
|
|
|
|
public static int TotalInstalls
|
|
{
|
|
get { int n = 1; foreach (var d in GameDefs.Perks) n += d.maxLevel; return n; }
|
|
}
|
|
|
|
public double Mown01 => Mown.Value / GameDefs.PlanetArea;
|
|
|
|
public float ToolCap(ToolId t) => GameDefs.IsBlade(t) ? GameDefs.ToolCap(t, GameDefs.HasBinPerk(t) ? Level(GameDefs.BinPerk(t)) : 0, Level(PerkId.Compactor)) : 0f;
|
|
|
|
/// <summary>The strip this tool cuts right now, in metres.</summary>
|
|
public float ToolWidth(ToolId t) => GameDefs.Tool(t).width * (1f + GameDefs.WidthBonus(Level(PerkId.WiderBlades))) * (1f + Level(PerkId.DeepSwath) * 0.06f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
|
|
|
|
public float ToolDepthMul => (1f + Level(PerkId.DeepSwath) * 0.12f) * (Has(PerkId.WhetSteel) ? 1.1f : 1f);
|
|
|
|
public float ToolReach => GameDefs.ToolReach + Level(PerkId.LongHandles) * 0.75f + (Has(PerkId.WhetSteel) ? 0.5f : 0f);
|
|
|
|
public float BundleSeconds => GameDefs.BundleSeconds(Level(PerkId.QuickTwine), Level(PerkId.ExpressDepot));
|
|
|
|
public float PayoutMul => GameDefs.PayoutMul(Level(PerkId.EarthPrices), Level(PerkId.GreenExchange));
|
|
|
|
public double ToolPrice(ToolDef d) => d.id == ToolId.Hammer ? d.price : Math.Round(d.price * (double)GameDefs.ToolPriceMul(Level(PerkId.SupplyDeals)), 2);
|
|
|
|
public bool HasTile(int tx, int tz) => Tiles != null && Tiles.Contains(PackTile(tx, tz));
|
|
public bool OnDeck(Vector3 world) => Planet.InNorthCap(world) && HasTile(TileOf(world.x), TileOf(world.z));
|
|
|
|
public static int TileOf(float w) => Mathf.FloorToInt((w + GameDefs.TileSize * 0.5f) / GameDefs.TileSize);
|
|
public static int PackTile(int tx, int tz) => ((tx + 512) << 10) | (tz + 512);
|
|
public static Vector2Int UnpackTile(int p) => new Vector2Int((p >> 10) - 512, (p & 1023) - 512);
|
|
public static Vector3 TileCenter(int tx, int tz) => new Vector3(tx * GameDefs.TileSize, 0f, tz * GameDefs.TileSize);
|
|
|
|
// ───────────────────────── server: grass & money ─────────────────────────
|
|
|
|
/// <summary>Server: this much grass reached a depot. Pays at once and it is on its way to Earth.</summary>
|
|
public double ServerDeposit(float kg, CargoKind kind, Vector3 at)
|
|
{
|
|
if (!IsServer || kg <= 0f) return 0d;
|
|
double pay = kg * GameDefs.PerKg(kind) * PayoutMul;
|
|
Money.Value += pay;
|
|
Shipped.Value += kg;
|
|
DepositedRpc(at, pay, kg);
|
|
return pay;
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void DepositRpc(float kg, byte kind, Vector3 at, RpcParams rpc = default)
|
|
{
|
|
if (kind > (byte)CargoKind.Brick) return;
|
|
ServerDeposit(Mathf.Clamp(kg, 0f, 50000f), (CargoKind)kind, at);
|
|
}
|
|
|
|
[Rpc(SendTo.Everyone)]
|
|
void DepositedRpc(Vector3 at, double pay, double kg) => Deposited?.Invoke(at, pay, kg);
|
|
|
|
/// <summary>Tie grass from a tool into a bundle at this spot.</summary>
|
|
[Rpc(SendTo.Server)]
|
|
public void BundleRpc(float kg, Vector3 at, Vector3 velocity, RpcParams rpc = default)
|
|
{
|
|
if (Spawner.Instance) Spawner.Instance.SpawnCargo(CargoKind.Grass, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), velocity, Mathf.Clamp(kg, 0.01f, GameDefs.BundleKg));
|
|
}
|
|
|
|
// ───────────────────────── matrix ─────────────────────────
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void BuyPerkRpc(int perk, RpcParams rpc = default)
|
|
{
|
|
if (perk < 0 || perk >= (int)PerkId.Count) return;
|
|
var def = GameDefs.Perk((PerkId)perk);
|
|
int lvl = Level(def.id);
|
|
if (lvl >= def.maxLevel || !PerkAvailable(def) || Money.Value < def.PriceFor(lvl)) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
|
Money.Value -= def.PriceFor(lvl);
|
|
Perks[perk] = (byte)(lvl + 1);
|
|
PurchasedRpc(PlayerName(rpc.Receive.SenderClientId), def.maxLevel > 1 ? Loc.Key(def.nameEn, GameDefs.ToRoman(lvl + 1)) : Loc.Key(def.nameEn));
|
|
Save();
|
|
}
|
|
|
|
[Rpc(SendTo.SpecifiedInParams)]
|
|
public void DeniedRpc(RpcParams p = default) { Sfx.Play("error"); }
|
|
|
|
[Rpc(SendTo.Everyone)]
|
|
void PurchasedRpc(FixedString64Bytes who, FixedString64Bytes what) => Purchased?.Invoke(who.ToString(), what.ToString());
|
|
|
|
public string PlayerName(ulong client)
|
|
{
|
|
var p = PlayerOf(client);
|
|
return p ? p.DisplayName : Loc.N("Someone");
|
|
}
|
|
|
|
public static PlayerAgent PlayerOf(ulong client)
|
|
{
|
|
foreach (var p in PlayerAgent.All) if (p.OwnerClientId == client) return p;
|
|
return null;
|
|
}
|
|
|
|
// ───────────────────────── supply wall (personal) ─────────────────────────
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void BuyToolRpc(byte tool, RpcParams rpc = default)
|
|
{
|
|
var who = PlayerOf(rpc.Receive.SenderClientId);
|
|
if (!who || tool >= GameDefs.ToolCount) return;
|
|
var d = GameDefs.Tool((ToolId)tool);
|
|
double price = ToolPrice(d);
|
|
if (who.Owns((ToolId)tool) || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
|
Money.Value -= price;
|
|
who.Owned.Value |= (ushort)(1 << tool);
|
|
SaveCrew(who);
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void BuyBeltSlotRpc(RpcParams rpc = default)
|
|
{
|
|
var who = PlayerOf(rpc.Receive.SenderClientId);
|
|
if (!who) return;
|
|
long price = GameDefs.BeltSlotPrice(who.BeltSlots.Value);
|
|
if (who.BeltSlots.Value >= GameDefs.MaxBeltSlots || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
|
Money.Value -= price;
|
|
who.BeltSlots.Value++;
|
|
SaveCrew(who);
|
|
}
|
|
|
|
[Rpc(SendTo.Server)]
|
|
public void BuyGearRpc(byte gear, RpcParams rpc = default)
|
|
{
|
|
var who = PlayerOf(rpc.Receive.SenderClientId);
|
|
if (!who || gear < (byte)GearId.Jetpack || gear > (byte)GearId.NightVision) return;
|
|
long price = GameDefs.GearPrice((GearId)gear);
|
|
if (who.HasGear((GearId)gear) || Money.Value < price) { DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
|
Money.Value -= price;
|
|
who.Owned.Value |= (ushort)(1 << gear);
|
|
SaveCrew(who);
|
|
}
|
|
|
|
/// <summary>Server: someone joined: give them back their tools, or nothing at all on the first day.</summary>
|
|
public void ServerRestoreCrew(PlayerAgent p)
|
|
{
|
|
foreach (var c in _crew)
|
|
if (c.key == p.SaveId)
|
|
{
|
|
p.Owned.Value = (ushort)c.owned;
|
|
p.BeltSlots.Value = (byte)Mathf.Clamp(c.slots, 1, GameDefs.MaxBeltSlots);
|
|
if (c.owned != 0 && c.belt != null && c.bins != null) p.RestoreToolsRpc(c.owned, c.bins, c.belt, c.current);
|
|
return;
|
|
}
|
|
}
|
|
|
|
CrewSave CrewOf(PlayerAgent p)
|
|
{
|
|
var c = _crew.Find(x => x.key == p.SaveId);
|
|
if (c == null) { c = new CrewSave { key = p.SaveId }; _crew.Add(c); }
|
|
c.owned = p.Owned.Value;
|
|
c.slots = p.BeltSlots.Value;
|
|
return c;
|
|
}
|
|
|
|
void SaveCrew(PlayerAgent p)
|
|
{
|
|
CrewOf(p);
|
|
Save();
|
|
}
|
|
|
|
/// <summary>Server: what this player's tools hold, for the next save.</summary>
|
|
public void ServerStoreTools(PlayerAgent p, float[] bins, int[] belt, int current)
|
|
{
|
|
if (!p.ClaimedSave) return;
|
|
var c = CrewOf(p);
|
|
c.bins = bins;
|
|
c.belt = belt;
|
|
c.current = current;
|
|
}
|
|
|
|
// ───────────────────────── tick ─────────────────────────
|
|
|
|
float _saveTimer, _backupAt = 60f;
|
|
|
|
float _powerTimer;
|
|
|
|
public void ServerSetPhase(float phase) => DayOffset.Value = Sun.OffsetFor(phase);
|
|
|
|
void Update()
|
|
{
|
|
if (!IsServer || !IsSpawned) return;
|
|
TickSectors();
|
|
TickWeather();
|
|
_powerTimer += Time.deltaTime;
|
|
if (_powerTimer > 0.25f) { PowerGrid.Tick(_powerTimer); _powerTimer = 0f; }
|
|
_saveTimer += Time.deltaTime;
|
|
if (_saveTimer > 30f) { _saveTimer = 0f; Save(); }
|
|
if (Time.time > _backupAt)
|
|
{
|
|
_backupAt = Time.time + 1800f;
|
|
Save();
|
|
SaveSlots.Backup();
|
|
}
|
|
}
|
|
|
|
[Rpc(SendTo.Everyone)]
|
|
public void AnnounceRpc(FixedString128Bytes text) => Announcement?.Invoke(text.ToString());
|
|
|
|
// ───────────────────────── persistence (host) ─────────────────────────
|
|
|
|
public void Save()
|
|
{
|
|
if (!IsServer) return;
|
|
var d = new SaveData { ver = 6, level = Size.Value, money = Money.Value, shipped = Shipped.Value, mown = Mown.Value, crew = _crew, day = Sun.Phase, vehicles = PackVehicles(), banned = _banned };
|
|
d.perks = new int[Perks.Count];
|
|
for (int i = 0; i < Perks.Count; i++) d.perks[i] = Perks[i];
|
|
d.tiles = new int[Tiles.Count];
|
|
for (int i = 0; i < Tiles.Count; i++) d.tiles[i] = Tiles[i];
|
|
d.found = new int[Found.Count];
|
|
for (int i = 0; i < Found.Count; i++) d.found[i] = Found[i];
|
|
d.stations = new int[Opened.Count];
|
|
for (int i = 0; i < Opened.Count; i++) d.stations[i] = Opened[i];
|
|
foreach (var p in BuildPiece.All)
|
|
if (p && p.IsSpawned) d.pieces.Add(new PieceSave { id = (int)p.piece, at = p.transform.position, turn = p.transform.rotation, to = p.To.Value, cfg = p.Setting, free = p.Free.Value, state = p.GetComponent<IPieceState>()?.State });
|
|
foreach (var c in Cargo.All)
|
|
if (c && c.IsSpawned && !c.Grab.Consumed && d.cargo.Count < MaxSavedBundles)
|
|
d.cargo.Add(new CargoSave { kind = (int)c.kind, kg = c.Kg.Value, at = c.transform.position });
|
|
SaveSlots.Write(JsonUtility.ToJson(d), MowMap.Serialize());
|
|
}
|
|
|
|
void Load()
|
|
{
|
|
var json = SaveSlots.Read();
|
|
SaveData d = null;
|
|
if (!string.IsNullOrEmpty(json))
|
|
{
|
|
try { d = JsonUtility.FromJson<SaveData>(json); }
|
|
catch (Exception e) { Debug.LogWarning("[Save] corrupt save, starting fresh: " + e.Message); }
|
|
}
|
|
bool fresh = d == null || d.tiles == null || d.tiles.Length == 0;
|
|
if (d == null) d = new SaveData();
|
|
// the ball first: the mow map, the stakes and every piece go down on it
|
|
var level = fresh ? Difficulties.Chosen : (Difficulty)d.level;
|
|
if (fresh && CommandLine.Get("-difficulty") is string forced && byte.TryParse(forced, out byte f)) level = (Difficulty)f;
|
|
Difficulties.Apply(level);
|
|
Size.Value = (byte)Difficulties.Current;
|
|
MowMap.Reset();
|
|
if (!fresh) LoadMow();
|
|
Money.Value = d.money;
|
|
Shipped.Value = d.shipped;
|
|
ServerSetPhase(d.day);
|
|
Mown.Value = MowMap.MownArea();
|
|
MowMap.Count();
|
|
Closed.Value = MowMap.Finished;
|
|
if (d.found != null) foreach (int id in d.found) Found.Add(id);
|
|
if (d.stations != null) foreach (int id in d.stations) Opened.Add((byte)id);
|
|
_banned = d.banned ?? new List<string>();
|
|
_crew = d.crew ?? new List<CrewSave>();
|
|
if (d.perks != null) for (int i = 0; i < d.perks.Length && i < Perks.Count; i++) Perks[i] = (byte)d.perks[i];
|
|
// machines used to be crew upgrades after the last perk: what was paid for them comes back
|
|
if (d.perks != null && d.ver < 2)
|
|
for (int i = Perks.Count; i < d.perks.Length && i - Perks.Count < OldFleet.Length; i++)
|
|
for (int l = 0; l < d.perks[i] && l < OldFleet[i - Perks.Count].Length; l++) Money.Value += OldFleet[i - Perks.Count][l];
|
|
if (fresh)
|
|
{
|
|
for (int x = -1; x <= 1; x++) for (int z = -1; z <= 1; z++) Tiles.Add(PackTile(x, z));
|
|
TilesChanged?.Invoke();
|
|
Spawner.Instance?.ServerSpawnStarter();
|
|
}
|
|
else
|
|
{
|
|
foreach (var t in d.tiles) Tiles.Add(t);
|
|
TilesChanged?.Invoke();
|
|
if (d.ver < 1)
|
|
{
|
|
// what stood on the old grid can't be placed any more: the crew gets its money back
|
|
if (d.pieces != null) foreach (var p in d.pieces) if (!p.free) Money.Value += p.id == 4 ? 5d : 0.5d;
|
|
Spawner.Instance?.ServerSpawnStarter();
|
|
}
|
|
else if (d.pieces != null)
|
|
foreach (var p in d.pieces)
|
|
if (p.id >= 0 && p.id < GameDefs.Pieces.Length) ServerSpawnPiece((PieceId)p.id, p.at, p.turn, p.to, p.cfg, p.free, p.state);
|
|
// bundles lie where they were left; those on a belt climb back on by themselves
|
|
if (d.cargo != null && Spawner.Instance)
|
|
foreach (var c in d.cargo)
|
|
if (c.kind >= 0 && c.kind <= (int)CargoKind.Brick && c.kg > 0f) Spawner.Instance.SpawnCargo((CargoKind)c.kind, c.at, Quaternion.identity, Vector3.zero, c.kg);
|
|
}
|
|
if (d.ver < 3) ServerSpawnStations();
|
|
if (d.ver < 4) ServerSpawnIntakes();
|
|
else if (d.ver < 5) ServerSwapIntakes();
|
|
else if (d.ver < 6) ServerRespawnIntakes();
|
|
if (!fresh) UnpackVehicles(d.vehicles);
|
|
foreach (var p in PlayerAgent.All) if (p.ClaimedSave) ServerRestoreCrew(p);
|
|
}
|
|
|
|
/// <summary>The slot's own map, or the newest backup that can still be read.</summary>
|
|
static void LoadMow()
|
|
{
|
|
if (MowMap.LoadFile(SaveSlots.MapPath)) return;
|
|
foreach (var path in SaveSlots.OlderMaps())
|
|
{
|
|
MowMap.Reset();
|
|
if (MowMap.LoadFile(path)) return;
|
|
}
|
|
MowMap.Reset();
|
|
}
|
|
|
|
public static void DeleteSave() => SaveSlots.Delete(SaveSlots.Current);
|
|
}
|
|
}
|