using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// A built thing that remembers more than where it stands: what's inside, how full its battery is.
public interface IPieceState
{
float[] State { get; set; }
}
///
/// The dryer and the brick press: cargo comes in by belt or by hand and turns into the product all the time, not in
/// batches, at the speed the power allows: 100% power is full speed, 30% is a third of it. What's made goes onto the belt at
/// the front, or onto the ground if there's none.
///
public class Machine : NetworkBehaviour, ICargoSink, IPorts, IInteractable, IPieceState
{
public static readonly List All = new List();
/// A hopper holds this many kilos of each thing.
const float Hold = 10f;
const float PortOut = 1.05f;
public readonly NetworkVariable Grass = new NetworkVariable();
public readonly NetworkVariable Hay = new NetworkVariable();
/// Kilos made and waiting to leave.
public readonly NetworkVariable Made = new NetworkVariable();
/// Share of the power it asks for that it's getting, 0..1: that's how fast it runs.
public readonly NetworkVariable Power = new NetworkVariable();
public Renderer lamp;
public Transform spin;
BuildPiece _piece;
float _done, _nextEject, _pace, _spun, _nextThump;
bool _short;
int _spinAxis = -1;
AudioSource _hum;
MaterialPropertyBlock _mpb;
static readonly int Emission = Shader.PropertyToID("_EmissionColor");
readonly List _ports = new List();
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent());
RecipeDef Recipe => GameDefs.Recipe(Piece.piece);
public float Kw => Piece.Def.kw * GameDefs.TierPower(Piece.Tier.Value);
const float Crumb = 0.001f;
bool Stocked => Grass.Value > Crumb && (Recipe.hay <= 0f || Hay.Value > Crumb);
/// Does it want power right now?
public bool Busy => Stocked && Made.Value < Hold;
/// Kilos a minute it's turning out right now.
public float PerMinute => Busy ? 60f * Recipe.makes / Recipe.seconds * Power.Value : 0f;
public override void OnNetworkSpawn()
{
All.Add(this);
_mpb = new MaterialPropertyBlock();
_hum = Sfx.Loop("machine_hum_loop", transform, 0f);
}
public override void OnNetworkDespawn()
{
All.Remove(this);
if (_hum) Destroy(_hum.gameObject);
}
public override void OnDestroy()
{
All.Remove(this);
base.OnDestroy();
}
public float[] State
{
get => new[] { Grass.Value, Hay.Value, Made.Value };
set
{
if (value == null || value.Length < 3) return;
Grass.Value = value[0];
Hay.Value = value[1];
Made.Value = value[2];
}
}
/// In at the back, out at the front. The press has two ways in and either takes either.
public void Ports(List into)
{
var f = transform.forward;
var r = transform.right;
var at = transform.position + transform.up * GameDefs.BeltLowest;
if (Recipe.hay > 0f)
{
into.Add(new Port { at = at - f * PortOut - r * 0.5f, dir = f, input = true });
into.Add(new Port { at = at - f * PortOut + r * 0.5f, dir = f, input = true });
}
else into.Add(new Port { at = at - f * PortOut, dir = f, input = true });
into.Add(new Port { at = at + f * PortOut, dir = f });
}
public string Prompt
{
get
{
var r = Recipe;
string have = r.hay > 0f ? Loc.F("{0} grass, {1} hay", GameDefs.Kilos(Grass.Value), GameDefs.Kilos(Hay.Value)) : Loc.F("{0} grass", GameDefs.Kilos(Grass.Value));
string state = !Busy ? (Made.Value >= Hold ? Loc.T("the way out is blocked") : Loc.T("waiting for grass")) : Power.Value <= 0f ? Loc.T("no power") : Loc.F("running at {0:0}% speed, {1:0.#} kg a minute", Power.Value * 100f, PerMinute);
return Loc.F("{0}: {1}, {2}", Piece.Def.name, have, state);
}
}
public bool CanInteract => false;
public void Interact() { }
public bool ServerAccept(Cargo c, Vector3 from, Vector3 dir)
{
if (!c || !c.IsSpawned) return false;
float kg = c.Kg.Value;
var r = Recipe;
if (c.kind == CargoKind.Grass && r.grass > 0f && Grass.Value + kg <= Hold) Grass.Value += kg;
else if (c.kind == CargoKind.Hay && r.hay > 0f && Hay.Value + kg <= Hold) Hay.Value += kg;
else return false;
c.Grab.Consumed = true;
c.NetworkObject.Despawn(true);
return true;
}
void Update()
{
if (!IsSpawned) return;
Visuals();
if (!IsServer) return;
Eject();
if (!Busy) return;
var r = Recipe;
// it adds up for a moment so the network isn't written to every frame
if (Piece.Switched) return;
_done += Time.deltaTime * Power.Value * Piece.TierMul / r.seconds;
if (_done < 0.02f) return;
float take = Mathf.Min(_done, Grass.Value / r.grass, (Hold - Made.Value) / r.makes);
if (r.hay > 0f) take = Mathf.Min(take, Hay.Value / r.hay);
_done = 0f;
Grass.Value = Mathf.Max(0f, Grass.Value - r.grass * take);
Hay.Value = Mathf.Max(0f, Hay.Value - r.hay * take);
Made.Value += r.makes * take;
}
/// On every peer: the lamp, the moving part and the sound all follow the speed it's running at.
void Visuals()
{
_pace = Mathf.MoveTowards(_pace, Busy ? Power.Value : 0f, Time.deltaTime * 1.5f);
if (_hum)
{
_hum.volume = _pace * 0.32f * Sfx.SfxVolume;
_hum.pitch = Mathf.Lerp(0.6f, 1.1f, _pace);
}
// the press comes down slower the less power it gets
if (Piece.piece == PieceId.Press && _pace > 0.05f && Time.time >= _nextThump)
{
_nextThump = Time.time + 2.2f / _pace;
Sfx.PlayAt("press_thump", transform.position + transform.up, 0.45f);
}
bool slow = Busy && Power.Value < 0.5f;
if (slow && !_short) Sfx.PlayAt("power_low", transform.position + transform.up, 0.4f, 1f, 0f, 20f);
_short = slow;
if (spin)
{
if (_spinAxis < 0) _spinAxis = BaseRot.LocalAxisFor(spin, transform.forward);
float idle = Piece.piece == PieceId.Dryer ? 18f + WeatherFx.Wind * 140f : 10f;
_spun += (_pace * 300f + idle * (1f - Mathf.Clamp01(_pace * 4f))) * Time.deltaTime;
var axis = _spinAxis == 0 ? Vector3.right : _spinAxis == 1 ? Vector3.up : Vector3.forward;
spin.localRotation = BaseRot.Of(spin) * Quaternion.Euler(axis * _spun);
}
if (lamp)
{
var c = !Busy ? new Color(0.12f, 0.2f, 0.12f) : Power.Value <= 0f ? new Color(1f, 0.1f, 0.08f) : Power.Value < 0.99f ? new Color(1f, 0.7f, 0.1f) : new Color(0.2f, 1f, 0.3f);
lamp.GetPropertyBlock(_mpb);
_mpb.SetColor(Emission, c * 2.2f);
lamp.SetPropertyBlock(_mpb);
}
}
/// One kilo at a time through the front, onto whatever takes it.
void Eject()
{
if (Made.Value < 1f || Time.time < _nextEject) return;
_nextEject = Time.time + 0.3f;
_ports.Clear();
Ports(_ports);
if (BeltNet.Send(Piece, _ports[_ports.Count - 1], Recipe.product)) Made.Value -= 1f;
}
}
}