using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// A placed machine, belt or foundation. It stands wherever it was put on the ball; spawned, moved and removed by the server.
public class BuildPiece : NetworkBehaviour
{
public static readonly List All = new List();
public static event System.Action PiecesChanged;
/// Goes up whenever something is built, moved or removed: belts look up their links again.
public static int Version { get; private set; }
public PieceId piece;
/// Belts: where the run ends. It starts at the piece's own position.
public readonly NetworkVariable To = new NetworkVariable();
/// Starter kit: removing it refunds nothing.
public readonly NetworkVariable Free = new NetworkVariable();
/// The mode E switches a junction to, saved with the build. 0 if it has none.
public readonly NetworkVariable Mode = new NetworkVariable();
/// Upgrade level, 0 (Mk I) to .
public readonly NetworkVariable Tier = new NetworkVariable();
/// The on/off switch some pieces have: a belt stopped, a machine paused.
public readonly NetworkVariable Opt = new NetworkVariable();
BeltRun _run;
IPorts _ports;
public PieceDef Def => GameDefs.Piece(piece);
/// Stays where it was put: belts lie on top of the grass, a Reaper leaves.
bool Stands => !_run && !GetComponent();
public BeltRun Run => _run;
/// What it cost, which is what comes back when it's removed.
public double Price => _run ? GameDefs.BeltPrice(_run.Metres) : Def.price;
/// Mode, tier and option in one int for the save: the low byte is the mode, as saves from before tiers had it.
public int Setting
{
get => (Mode.Value & 0xFF) | (Tier.Value << 8) | (Opt.Value << 16);
set
{
Mode.Value = value & 0xFF;
Tier.Value = (byte)Mathf.Clamp((value >> 8) & 0xFF, 0, GameDefs.MaxTier);
Opt.Value = (byte)((value >> 16) & 0xFF);
}
}
public UpgradeKind Upgrades => GameDefs.UpgradeOf(piece);
/// What the tier does to this piece's pace: belts' speed, machines' work, robots' speed and hopper, silos' output.
public float TierMul => GameDefs.TierMul(Upgrades, Tier.Value);
public bool Switched => Opt.Value != 0;
[Rpc(SendTo.Server)]
public void UpgradeRpc(RpcParams rpc = default)
{
var ts = TeamState.Instance;
if (!ts || Upgrades == UpgradeKind.None || Tier.Value >= GameDefs.MaxTier) return;
double price = GameDefs.UpgradePrice(this, Tier.Value);
if (ts.Money.Value < price || Demo.Over) { ts.DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
ts.Money.Value -= price;
Tier.Value++;
UpgradedRpc();
}
[Rpc(SendTo.Everyone)]
void UpgradedRpc()
{
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
Sfx.PlayAt("perk_unlock", transform.position, 0.8f);
Tween.Scale(transform, new Vector3(1.12f, 0.85f, 1.12f), Vector3.one, 0.35f, Ease.OutBack, 0f, null);
}
[Rpc(SendTo.Server)]
public void SwitchRpc() => Opt.Value = (byte)(Opt.Value == 0 ? 1 : 0);
[Rpc(SendTo.Server)]
public void NextModeRpc(int count)
{
if (count > 0) Mode.Value = (Mode.Value + 1) % count;
}
public void Ports(List into)
{
if (_ports == null) _ports = GetComponentInChildren();
_ports?.Ports(into);
}
/// The grass was laid out afresh (the ball changed size): this piece keeps it off its spot again.
public void Reblock()
{
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
}
/// Everything looks at its neighbours again (belts fit their ends anew).
public static void Moved() => Version++;
public override void OnNetworkSpawn()
{
All.Add(this);
IdleMotion.Attach(gameObject);
_run = GetComponentInChildren();
if (_run) _run.Lay(transform.position, To.Value);
// grass doesn't grow through a machine
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
if (transform.childCount > 0 && Time.timeSinceLevelLoad > 3f)
{
// ports read while it bounced were off, so everything looks again once it has settled
Tween.Scale(transform, new Vector3(1.2f, 0.4f, 1.2f), Vector3.one, 0.4f, Ease.OutBack, 0f, Touched);
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
Sfx.PlayAt("build_place", transform.position, 0.9f);
}
Touched();
}
public override void OnNetworkDespawn()
{
All.Remove(this);
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
Sfx.PlayAt("build_remove", transform.position, 0.9f);
Touched();
}
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
[Rpc(SendTo.Everyone)]
public void MovedRpc(Vector3 at, Quaternion rot)
{
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);
Touched();
}
static void Touched()
{
Version++;
PiecesChanged?.Invoke();
}
}
/// What may stand where, shared by the ghost in the player's hands and the server.
public static class BuildRules
{
/// The console's `freebuild` and the test bots: standing grass stops nothing.
public static bool AnyGround;
public static string Uncut => Loc.T("Mow the grass here first");
// spots under a piece that must be cut, of the 25 looked at: a stray tuft doesn't count
const int Enough = 23;
static readonly Collider[] s_hits = new Collider[16];
static readonly List s_riders = new List();
/// Can something start from here, on cut ground?
public static bool CutUnder(Vector3 p) => AnyGround || MowMap.Clear(p);
public static Quaternion RunRotation(Vector3 a, Vector3 b) => Quaternion.LookRotation(b - a, Planet.Up((a + b) * 0.5f));
/// Pieces standing on a foundation: they go along when it moves and keep it from being removed. Belts stay where they are.
public static List Riders(BuildPiece foundation)
{
s_riders.Clear();
var t = foundation.transform;
foreach (var p in BuildPiece.All)
{
if (!p || p == foundation || p.Run || GameDefs.IsFoundation(p.piece)) continue;
// the position, not the bouncing scale: a piece just put down is still squashed
var l = Quaternion.Inverse(t.rotation) * (p.transform.position - t.position);
if (Mathf.Abs(l.x) < 2f && Mathf.Abs(l.z) < 2f && Mathf.Abs(l.y - Foundation.TopOf(foundation.piece)) < 0.4f) s_riders.Add(p);
}
return s_riders;
}
static bool Reserved(Vector3 p)
{
foreach (var b in GridBlocker.All) if (b.Covers(p)) return true;
return false;
}
static bool Clear(Vector3 center, Vector3 half, Quaternion rot, BuildPiece moving, out string reason)
{
const int Mask = (1 << Layers.Default) | (1 << Layers.Vehicle) | (1 << Layers.Build);
int n = Physics.OverlapBoxNonAlloc(center, half, s_hits, rot, Mask, QueryTriggerInteraction.Ignore);
for (int i = 0; i < n; i++)
{
if (s_hits[i].GetComponentInParent()) continue;
var p = s_hits[i].GetComponentInParent();
if (moving && p && (p == moving || Riders(moving).Contains(p))) continue;
reason = p ? Loc.F("{0} is in the way", p.Def.name) : s_hits[i].GetComponentInParent() ? Loc.T("A machine is parked here") : Loc.T("Something is in the way");
return false;
}
reason = null;
return true;
}
/// Can a piece stand here? A piece being moved doesn't get in its own way.
public static bool CanPlace(PieceDef d, Vector3 at, Quaternion rot, BuildPiece moving, out string reason)
{
float hx = d.sizeX * 0.5f, hz = d.sizeZ * 0.5f;
var r = rot * Vector3.right * hx;
var f = rot * Vector3.forward * hz;
if (Reserved(at) || Reserved(at + r + f) || Reserved(at + r - f) || Reserved(at - r + f) || Reserved(at - r - f))
{
reason = Loc.T("That's where a base building stands");
return false;
}
bool slab = GameDefs.IsFoundation(d.id);
// a hair more than half a wall's thickness: what fills a room (stairs end to end) may touch its walls
var half = new Vector3(hx - (slab ? 0.3f : 0.12f), slab ? 0.2f : 0.6f, hz - (slab ? 0.3f : 0.12f));
if (GameDefs.FitOf(d.id) == Fit.Edge) half = new Vector3(hx - 0.2f, 0.6f, 0.05f);
if (!Clear(at + rot * Vector3.up * (half.y + 0.12f), half, rot, moving, out reason)) return false;
// what stands on a foundation stands on what's under the foundation
if (AnyGround || Planet.Altitude(at) > 0.2f) return true;
int cut = 0;
for (int x = -2; x <= 2; x++)
for (int z = -2; z <= 2; z++)
if (MowMap.Clear(at + r * x * 0.45f + f * z * 0.45f)) cut++;
if (cut >= Enough) return true;
reason = Loc.F("Mow the grass here first: {0}% cut", cut * 4);
return false;
}
/// Can a belt run from A to B?
public static bool CanRun(Vector3 a, Vector3 b, out string reason)
{
float len = Vector3.Distance(a, b);
if (len < GameDefs.BeltShortest) { reason = Loc.T("Too short"); return false; }
if (len > GameDefs.BeltLongest) { reason = Loc.F("Too long: belts are up to {0:0} m", GameDefs.BeltLongest); return false; }
var dir = (b - a) / len;
var up = Planet.Up((a + b) * 0.5f);
if (Mathf.Abs(Vector3.Dot(dir, up)) > Mathf.Sin(GameDefs.BeltSteepest * Mathf.Deg2Rad)) { reason = Loc.T("Too steep"); return false; }
if (BeltNet.Taken(b)) { reason = Loc.T("A belt already ends here"); return false; }
int spots = 0, uncut = 0;
for (float z = 0f; z <= len; z += 1f)
{
var p = a + dir * z;
if (Reserved(p)) { reason = Loc.T("That's where a base building stands"); return false; }
if (Planet.Altitude(p) < 0.05f) { reason = Loc.T("The ground is in the way"); return false; }
spots++;
if (!MowMap.Clear(p)) uncut++;
}
if (!AnyGround && uncut * 6 > spots) { reason = Loc.T("Mow a path for the belt first"); return false; }
if (len < 1.3f) { reason = null; return true; }
// the ends may touch what they're joined to
return Clear((a + b) * 0.5f, new Vector3(0.42f, 0.2f, len * 0.5f - 0.6f), RunRotation(a, b), null, out reason);
}
}
}