using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
public enum WeatherKind : byte { Clear, Clouds, Rain, AcidRain, Wind, Storm, Meteors, Count }
///
/// Herbaria-7's weather, decided by the host and the same for everyone. Spells of a few minutes each: clear, cloud, rain, acid
/// rain (it scorches a little of the meadow, which is gone for good and pays nothing), wind with twisters that tear up the
/// grass in a line and throw the crew about, thunderstorms, and on clear nights a meteor shower. Now and then a flying saucer
/// comes down, draws a crop circle in the meadow and leaves the crew a tip for it.
///
public partial class TeamState
{
public readonly NetworkVariable Weather = new NetworkVariable();
/// A twister: where it set off, which way, and when (server time; 0 when there is none).
public readonly NetworkVariable TwisterFrom = new NetworkVariable(), TwisterDir = new NetworkVariable();
public readonly NetworkVariable TwisterAt = new NetworkVariable();
/// The saucer: the spot it comes down over and when it set off.
public readonly NetworkVariable UfoSpot = new NetworkVariable();
public readonly NetworkVariable UfoAt = new NetworkVariable();
public const float TwisterLife = 70f, TwisterSpeed = 3.6f, TwisterRadius = 3.2f;
/// Saucer timeline in seconds: coming down, drawing, leaving.
public const float UfoArrive = 7f, UfoDraw = 22f, UfoLeave = 6f;
public WeatherKind WeatherNow => (WeatherKind)Weather.Value;
public double Now => ClockOverride != null ? ClockOverride() : NetworkManager ? NetworkManager.ServerTime.Time : 0d;
/// The trailer's clock: the time of the frames it writes, not of the wall, so a twister or a saucer moves
/// at its own pace however long each frame takes to render.
public static System.Func ClockOverride;
public bool TwisterOn => TwisterAt.Value > 0d && Now - TwisterAt.Value < TwisterLife;
public bool UfoOn => UfoAt.Value > 0d && Now - UfoAt.Value < UfoArrive + UfoDraw + UfoLeave;
double _weatherUntil, _nextBurn, _nextUfoRoll, _ufoCooldown;
bool _ufoPaid;
/// Where the twister is at a moment: a wandering line across the meadow, the same on every machine.
public Vector3 TwisterPos(double t)
{
float s = (float)(t - TwisterAt.Value);
var from = TwisterFrom.Value;
var up = Planet.Up(from);
var dir = TwisterDir.Value;
var side = Vector3.Cross(up, dir).normalized;
var p = from + dir * (s * TwisterSpeed) + side * (Mathf.Sin(s * 0.21f) * 9f + Mathf.Sin(s * 0.53f) * 3f);
return Planet.Surface(p);
}
static readonly WeatherKind[] Bag = { WeatherKind.Clear, WeatherKind.Clear, WeatherKind.Clear, WeatherKind.Clouds, WeatherKind.Clouds, WeatherKind.Rain, WeatherKind.Rain, WeatherKind.Wind, WeatherKind.AcidRain, WeatherKind.Storm };
void TickWeather()
{
double now = Now;
if (now >= _weatherUntil)
{
var next = Bag[Random.Range(0, Bag.Length)];
// a clear night is a meteor night half the time
if (next == WeatherKind.Clear && Sun.Height(Planet.Up(Spawner.Instance ? Spawner.Instance.transform.position : Vector3.up)) < -0.1f && Random.value < 0.5f) next = WeatherKind.Meteors;
// the first minutes of a new game are always fine
if (Time.timeSinceLevelLoad < 240f) next = WeatherKind.Clear;
ServerSetWeather(next, Random.Range(180f, 360f));
}
var kind = WeatherNow;
if ((kind == WeatherKind.Wind || kind == WeatherKind.Storm) && !TwisterOn && Random.value < Time.deltaTime / 40f) ServerTwister(null);
if (kind == WeatherKind.AcidRain && now >= _nextBurn) { _nextBurn = now + 1.5d; ServerBurn(); }
if (TwisterOn) ServerTwisterTick();
if (UfoOn) ServerUfoTick();
else if (now >= _nextUfoRoll && now >= _ufoCooldown && Time.timeSinceLevelLoad > 300f)
{
_nextUfoRoll = now + 60d;
bool night = DayNight.Dark > 0.5f;
if (Random.value < (night ? 0.08f : 0.03f)) ServerUfo(null);
}
}
public void ServerSetWeather(WeatherKind k, float seconds)
{
if (!IsServer) return;
Weather.Value = (byte)k;
_weatherUntil = Now + seconds;
if (k != WeatherKind.Clear && k != WeatherKind.Clouds) WeatherNewsRpc((byte)k);
}
[Rpc(SendTo.Everyone)]
void WeatherNewsRpc(byte kind)
{
switch ((WeatherKind)kind)
{
case WeatherKind.Rain: Assistant.Say("asst_rain"); Hud.Toast(Loc.T("Rain. The solar panels give less while it lasts."), Hud.ToastKind.Info); break;
case WeatherKind.AcidRain: Assistant.Say("asst_acid"); Hud.Toast(Loc.T("Acid rain! It scorches the meadow here and there: that grass is gone and pays nothing."), Hud.ToastKind.Warn); break;
case WeatherKind.Wind: Assistant.Say("asst_wind"); Hud.Toast(Loc.T("The wind is getting up. Watch out for twisters."), Hud.ToastKind.Warn); break;
case WeatherKind.Storm: Assistant.Say("asst_storm"); Hud.Toast(Loc.T("Thunderstorm! Dark skies, weak sun, twisters about."), Hud.ToastKind.Warn); break;
case WeatherKind.Meteors: Assistant.Say("asst_meteors"); Hud.Toast(Loc.T("A meteor shower tonight. Look up!"), Hud.ToastKind.Info); break;
}
}
// ───────────────────────── acid rain ─────────────────────────
static readonly List s_burns = new List();
void ServerBurn()
{
s_burns.Clear();
foreach (var p in PlayerAgent.All)
{
if (!p) continue;
for (int i = 0; i < 2; i++)
{
var at = Planet.Surface(p.transform.position + Random.insideUnitSphere * 26f);
if (OnDeck(at) || MowMap.Yield(at) < 0.2f) continue;
s_burns.Add(at);
}
}
if (s_burns.Count > 0) BurnRpc(s_burns.ToArray());
}
[Rpc(SendTo.Everyone)]
void BurnRpc(Vector3[] spots)
{
foreach (var at in spots)
{
var up = Planet.Up(at);
var side = Vector3.Cross(up, Vector3.forward).normalized * 0.4f;
MowMap.Cut(at - side, at + side, 1.1f);
Fx.Smoke(at + up * 0.3f, 0.5f);
WeatherFx.Sizzle(at);
}
}
// ───────────────────────── twisters ─────────────────────────
/// Server: a twister sets off toward the crew, from a spot ahead of someone (or where it's told).
public void ServerTwister(Vector3? at)
{
if (!IsServer || PlayerAgent.All.Count == 0) return;
var who = PlayerAgent.All[Random.Range(0, PlayerAgent.All.Count)];
var target = at ?? who.transform.position;
var up = Planet.Up(target);
var away = Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized;
var from = Planet.Surface(target + away * (at.HasValue ? 0f : 60f));
TwisterFrom.Value = from;
TwisterDir.Value = at.HasValue ? Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized : -away;
TwisterAt.Value = Now;
TwisterNewsRpc();
}
[Rpc(SendTo.Everyone)]
void TwisterNewsRpc() { Assistant.Say("asst_twister"); Hud.Toast(Loc.T("A twister is coming! It rips up the grass in its path and throws you about."), Hud.ToastKind.Warn); }
static readonly Collider[] s_hits = new Collider[32];
/// Server: loose bundles near the twister are lifted and spun out.
void ServerTwisterTick()
{
var at = TwisterPos(Now);
var up = Planet.Up(at);
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
for (int i = 0; i < n; i++)
{
var rb = s_hits[i].attachedRigidbody;
if (!rb || rb.isKinematic) continue;
var off = Vector3.ProjectOnPlane(rb.position - at, up);
var swirl = Vector3.Cross(up, off.normalized) * 9f;
rb.AddForce((swirl + up * 14f - off * 1.5f) * rb.mass, ForceMode.Force);
}
}
// ───────────────────────── the saucer ─────────────────────────
/// Server: a saucer comes down over unmown meadow near someone.
public void ServerUfo(Vector3? at)
{
if (!IsServer || PlayerAgent.All.Count == 0) return;
Vector3 spot = default;
bool found = false;
if (at.HasValue) { spot = Planet.Surface(at.Value); found = true; }
for (int tries = 0; tries < 30 && !found; tries++)
{
var who = PlayerAgent.All[Random.Range(0, PlayerAgent.All.Count)];
var up = Planet.Up(who.transform.position);
var p = Planet.Surface(who.transform.position + Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized * Random.Range(25f, 50f));
if (OnDeck(p) || MowMap.Yield(p) < 0.6f) continue;
spot = p; found = true;
}
if (!found) return;
UfoSpot.Value = spot;
UfoAt.Value = Now;
_ufoPaid = false;
_ufoCooldown = Now + 900d;
UfoNewsRpc();
}
[Rpc(SendTo.Everyone)]
void UfoNewsRpc() { Assistant.Say("asst_ufo"); Hud.Toast(Loc.T("Something is coming down out of the sky…"), Hud.ToastKind.Warn); }
void ServerUfoTick()
{
if (_ufoPaid || Now - UfoAt.Value < UfoArrive + UfoDraw) return;
_ufoPaid = true;
double tip = System.Math.Round(System.Math.Max(150d, Shipped.Value * 0.03d));
Money.Value += tip;
AnnounceRpc(Loc.Pack("The visitors liked the meadow: they left {0} by their crop circle.", UIK.Money(tip)));
}
///
/// The crop circle: rings and spokes in the saucer's own frame, as strokes from the centre outward. Every peer cuts the
/// part of it that the drawing time has reached, so it appears line by line under the beam.
///
public static void CropCircle(Vector3 centre, int seed, float upTo, ref int done)
{
var strokes = CircleStrokes(centre, seed);
int last = Mathf.Min(strokes.Count, Mathf.CeilToInt(upTo * strokes.Count));
for (; done < last; done++)
{
var s = strokes[done];
MowMap.Cut(s.a, s.b, s.w);
}
}
/// Where the drawing has got to: the saucer drifts over it.
public static Vector3 CircleAt(Vector3 centre, int seed, float upTo)
{
var strokes = CircleStrokes(centre, seed);
int i = Mathf.Clamp(Mathf.CeilToInt(upTo * strokes.Count) - 1, 0, strokes.Count - 1);
return (strokes[i].a + strokes[i].b) * 0.5f;
}
public struct Stroke { public Vector3 a, b; public float w; }
static readonly Dictionary> s_circles = new Dictionary>();
static List CircleStrokes(Vector3 centre, int seed)
{
if (s_circles.TryGetValue(seed, out var list)) return list;
list = new List();
var rng = new System.Random(seed);
var up = Planet.Up(centre);
var x = Vector3.ProjectOnPlane(Vector3.forward, up).normalized;
if (x.sqrMagnitude < 0.1f) x = Vector3.ProjectOnPlane(Vector3.right, up).normalized;
var z = Vector3.Cross(x, up);
Vector3 At(float r, float a) => Planet.Surface(centre + (x * Mathf.Cos(a) + z * Mathf.Sin(a)) * r);
// the middle: a filled disc as a tight spiral
for (float a = 0f, r = 0.3f; r < 2.4f; a += 0.5f, r += 0.06f) list.Add(new Stroke { a = At(r, a), b = At(r + 0.06f, a + 0.5f), w = 0.9f });
int spokes = 4 + rng.Next(5);
float[] rings = { 4f + (float)rng.NextDouble(), 7f + (float)rng.NextDouble() * 1.5f, 10f + (float)rng.NextDouble() * 2f };
foreach (float r in rings)
{
int segs = Mathf.CeilToInt(r * 6f);
for (int i = 0; i < segs; i++) list.Add(new Stroke { a = At(r, i * Mathf.PI * 2f / segs), b = At(r, (i + 1) * Mathf.PI * 2f / segs), w = 0.9f });
}
for (int s = 0; s < spokes; s++)
{
float a = s * Mathf.PI * 2f / spokes;
for (float r = 2.4f; r < rings[2]; r += 1f) list.Add(new Stroke { a = At(r, a), b = At(Mathf.Min(rings[2], r + 1f), a), w = 0.7f });
// a little satellite circle at the end of every other spoke
if (s % 2 == 0)
{
var c = rings[2] + 2.2f;
for (int i = 0; i < 10; i++)
{
float b0 = i * Mathf.PI * 0.2f, b1 = (i + 1) * Mathf.PI * 0.2f;
var cc = At(c, a);
var cu = Planet.Up(cc);
var cx = Vector3.ProjectOnPlane(x, cu).normalized;
var cz = Vector3.Cross(cx, cu);
list.Add(new Stroke { a = Planet.Surface(cc + (cx * Mathf.Cos(b0) + cz * Mathf.Sin(b0)) * 1.4f), b = Planet.Surface(cc + (cx * Mathf.Cos(b1) + cz * Mathf.Sin(b1)) * 1.4f), w = 0.8f });
}
}
}
s_circles[seed] = list;
return list;
}
}
}