Files
grass-cutters/Assets/Scripts/Gameplay/TeamState.Weather.cs
NiemandKG bbf73a6b96 Frame time on a big farm, round two: riding layer, instanced bundles
- Bundles on a belt move to a Riding layer that ignores the belts and the
  static world: every belt's catch trigger called OnTriggerStay (with a
  GetComponent) for each bundle riding it, every physics step.
- Bundles draw as instanced batches from CargoTick (their own renderers off,
  one in someone's hands draws itself), not as 2000 renderers to cull, sort
  and draw in the view and every shadow cascade.
- The main camera skips front-to-back sorting: the GPU has time to spare.
- BeltNet.Belted and DronePad.Belted are cached until the build changes;
  splitters on the host look only at their own items.

On the player's Mommy save, 2560x1440: base 14-15 ms -> 7.7 ms (~130 fps),
meadow 11.5-12 ms -> 6.8-7.5 ms (~135-145 fps).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:35:35 +06:00

277 lines
14 KiB
C#

using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
public enum WeatherKind : byte { Clear, Clouds, Rain, AcidRain, Wind, Storm, Meteors, Count }
/// <summary>
/// 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.
/// </summary>
public partial class TeamState
{
public readonly NetworkVariable<byte> Weather = new NetworkVariable<byte>();
/// <summary>A twister: where it set off, which way, and when (server time; 0 when there is none).</summary>
public readonly NetworkVariable<Vector3> TwisterFrom = new NetworkVariable<Vector3>(), TwisterDir = new NetworkVariable<Vector3>();
public readonly NetworkVariable<double> TwisterAt = new NetworkVariable<double>();
/// <summary>The saucer: the spot it comes down over and when it set off.</summary>
public readonly NetworkVariable<Vector3> UfoSpot = new NetworkVariable<Vector3>();
public readonly NetworkVariable<double> UfoAt = new NetworkVariable<double>();
public const float TwisterLife = 70f, TwisterSpeed = 3.6f, TwisterRadius = 3.2f;
/// <summary>Saucer timeline in seconds: coming down, drawing, leaving.</summary>
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;
/// <summary>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.</summary>
public static System.Func<double> 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;
/// <summary>Where the twister is at a moment: a wandering line across the meadow, the same on every machine.</summary>
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<Vector3> s_burns = new List<Vector3>();
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 ─────────────────────────
/// <summary>Server: a twister sets off toward the crew, from a spot ahead of someone (or where it's told).</summary>
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];
/// <summary>Server: loose bundles near the twister are lifted and spun out.</summary>
void ServerTwisterTick()
{
var at = TwisterPos(Now);
var up = Planet.Up(at);
int n = Physics.OverlapSphereNonAlloc(at + up * 2f, TwisterRadius + 2f, s_hits, Layers.CargoMask, 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 ─────────────────────────
/// <summary>Server: a saucer comes down over unmown meadow near someone.</summary>
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)));
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>Where the drawing has got to: the saucer drifts over it.</summary>
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<int, List<Stroke>> s_circles = new Dictionary<int, List<Stroke>>();
static List<Stroke> CircleStrokes(Vector3 centre, int seed)
{
if (s_circles.TryGetValue(seed, out var list)) return list;
list = new List<Stroke>();
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;
}
}
}