Grass Cutters Together: the project as of moon-sweepers f3666f0

A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and
Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date.
Images, audio, models and binaries go through Git LFS (.gitattributes).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NiemandKG
2026-11-06 18:44:40 +06:00
parent 0f0467cd0c
commit d1c3761e58
4190 changed files with 270757 additions and 1 deletions

View File

@ -0,0 +1,42 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>One sound for all the belts: it stands on the nearest belt with something riding on it.</summary>
public class BeltSound : MonoBehaviour
{
const float Hear = 14f, Every = 0.25f, Loud = 0.3f;
AudioSource _loop;
float _next, _want;
void Update()
{
if (!_loop)
{
if (!AssetBank.I) return;
_loop = Sfx.Loop("conveyor_loop", transform, 0f);
if (!_loop) { enabled = false; return; }
}
if (Time.time >= _next)
{
_next = Time.time + Every;
var cam = CameraFx.Cam;
float best = Hear * Hear;
_want = 0f;
if (cam)
foreach (var c in Conveyor.All)
{
if (!c || c.Count == 0) continue;
var p = c.NearestPoint(cam.transform.position);
float d = (p - cam.transform.position).sqrMagnitude;
if (d >= best) continue;
best = d;
transform.position = p;
_want = Loud;
}
}
_loop.volume = Mathf.MoveTowards(_loop.volume, _want * Sfx.SfxVolume, Time.deltaTime * 0.8f);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 52554946721108b4cb69379bbe1ad4f5

View File

@ -0,0 +1,63 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The dark where a machine stands: a soft patch under each wheel and a wider one under the body, on the soil and the
/// grass (Planet.hlsl, GcContact). The sun's own shadow falls wherever the sun puts it, often well off to one side, and
/// a machine with lit ground right under its tyres reads as floating, most of all from a low camera.
/// </summary>
public static class ContactShade
{
public const int Max = 24; // matches _GcContacts in Planet.hlsl
const float Near = 90f; // machines further off than this get none
const int Machines = 5;
static readonly Vector4[] s_pts = new Vector4[Max];
static readonly List<Vehicle> s_near = new List<Vehicle>();
static readonly int PtsId = Shader.PropertyToID("_GcContacts"), CountId = Shader.PropertyToID("_GcContactCount");
/// <summary>Once a frame, after the camera has moved.</summary>
public static void Publish(Vector3 cam)
{
s_near.Clear();
foreach (var v in Vehicle.All)
if (v && v.isActiveAndEnabled && v.wheels != null && v.wheels.Length > 0 && (v.transform.position - cam).sqrMagnitude < Near * Near)
s_near.Add(v);
s_near.Sort((a, b) => (a.transform.position - cam).sqrMagnitude.CompareTo((b.transform.position - cam).sqrMagnitude));
int n = 0;
for (int m = 0; m < s_near.Count && m < Machines; m++)
{
var v = s_near[m];
Vector3 sum = Vector3.zero;
int on = 0, start = n;
for (int k = 0; k < v.wheels.Length; k++)
{
var w = v.wheels[k];
if (!w || n >= Max - 1) continue;
float radius = v.WheelRadius != null && k < v.WheelRadius.Length && v.WheelRadius[k] > 0f ? v.WheelRadius[k] : Vehicle.TyreRadius(w);
var up = Planet.Up(w.position);
var ground = Planet.OnSurface(up);
// lifts off the ground (a jump, a tip): the patch thins out and is gone a metre up
float lift = Planet.Altitude(w.position) - radius;
float fade = 1f - Mathf.Clamp01((lift - 0.15f) / 0.9f);
if (fade <= 0f) continue;
s_pts[n++] = new Vector4(ground.x, ground.y, ground.z, radius * 1.3f * fade);
sum += ground;
on++;
}
if (on < 2 || n >= Max) continue;
// the body: one wide, soft patch over the wheelbase
var mid = sum / on;
float reach = 0f;
for (int i = start; i < n; i++) reach = Mathf.Max(reach, Vector3.Distance(mid, s_pts[i]));
s_pts[n++] = new Vector4(mid.x, mid.y, mid.z, reach * 1.15f);
}
for (int i = n; i < Max; i++) s_pts[i] = Vector4.zero;
Shader.SetGlobalVectorArray(PtsId, s_pts);
Shader.SetGlobalFloat(CountId, n);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ff7330de78bfd0b4f91cec11c202ec24

View File

@ -0,0 +1,167 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Now and then a cut turns up the little life under the grass: beetles that scurry off and grasshoppers that hop away,
/// each gone back into the standing grass a moment later. Only seen near the camera, and only by whoever sees it.
/// </summary>
public class Critters : MonoBehaviour
{
const int Max = 36;
const float Reach = 28f;
class Bug
{
public Transform t;
public bool hopper, live;
public Vector3 at, vel, up;
public float life, age, hopIn, size;
}
static Critters _i;
/// <summary>How many are out right now (for the dev bot).</summary>
public static int Alive { get { int n = 0; if (_i) foreach (var b in _i._bugs) if (b.live) n++; return n; } }
readonly List<Bug> _bugs = new List<Bug>();
float _stirred, _nextSound;
bool _warned;
/// <summary>Families that ran out so far (for the dev bot).</summary>
public static int Families;
static Critters I
{
get
{
if (!_i && Application.isPlaying)
{
var go = new GameObject("[Critters]");
_i = go.AddComponent<Critters>();
}
return _i;
}
}
/// <summary>Grass was just cut here (square metres of it): maybe something runs out.</summary>
public static void Disturb(Vector3 at, float half, float area)
{
var cam = CameraFx.Cam;
if (!cam || (cam.transform.position - at).sqrMagnitude > Reach * Reach) return;
var i = I;
if (!i) return;
i._stirred += area;
// roughly one family per 9 m² of meadow cut, a little luck either way
if (i._stirred < 9f) return;
i._stirred = Random.Range(-3f, 2f);
if (Random.value > 0.55f) return;
Families++;
int n = Random.Range(2, 6);
bool hoppers = Random.value < 0.45f;
var up = Planet.Up(at);
for (int k = 0; k < n; k++)
{
var off = Random.insideUnitCircle * Mathf.Max(0.3f, half);
var p = Planet.Surface(at + Planet.Frame * new Vector3(off.x, 0f, off.y));
i.Spawn(p, up, hoppers ? Random.value < 0.8f : Random.value < 0.15f);
}
if (Time.time > i._nextSound)
{
i._nextSound = Time.time + 1.2f;
Sfx.PlayAt(Random.value < 0.5f ? "bug_scatter_1" : "bug_scatter_2", at, 0.35f, 1f, 0.12f);
}
}
void Spawn(Vector3 at, Vector3 up, bool hopper)
{
Bug b = null;
foreach (var x in _bugs) if (!x.live && x.hopper == hopper) { b = x; break; }
if (b == null)
{
if (_bugs.Count >= Max) return;
var model = AssetBank.I.Model(hopper ? "SM_Grasshopper" : "SM_Bug");
if (!model) { if (!_warned) { _warned = true; Debug.LogWarning("[Critters] no model " + (hopper ? "SM_Grasshopper" : "SM_Bug")); } return; }
var go = Instantiate(model, transform);
foreach (var c in go.GetComponentsInChildren<Collider>(true)) Destroy(c);
foreach (var r in go.GetComponentsInChildren<Renderer>(true)) { r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; r.receiveShadows = false; }
b = new Bug { t = go.transform, hopper = hopper };
_bugs.Add(b);
}
var flat = Random.insideUnitCircle.normalized;
var away = Vector3.ProjectOnPlane(Planet.Frame * new Vector3(flat.x, 0f, flat.y), up).normalized;
b.live = true;
b.at = at;
b.up = up;
b.age = 0f;
b.size = Random.Range(2.4f, 3.2f); // cartoon-sized, so they read from standing height
if (hopper)
{
b.life = Random.Range(1.4f, 2.4f);
b.vel = Vector3.zero;
b.hopIn = Random.Range(0.02f, 0.2f);
}
else
{
b.life = Random.Range(0.8f, 1.5f);
b.vel = away * Random.Range(1.2f, 2.4f);
}
b.t.gameObject.SetActive(true);
b.t.localScale = Vector3.one * b.size;
Face(b, away);
}
void Update()
{
float dt = Time.deltaTime;
foreach (var b in _bugs)
{
if (!b.live) continue;
b.age += dt;
if (b.age >= b.life) { b.live = false; b.t.gameObject.SetActive(false); continue; }
var up = Planet.Up(b.at);
if (b.hopper)
{
b.hopIn -= dt;
// on the ground it waits a beat, then springs off in a new direction
if (b.hopIn <= 0f && b.vel == Vector3.zero)
{
var flat = Random.insideUnitCircle.normalized;
var dir = Vector3.ProjectOnPlane(Planet.Frame * new Vector3(flat.x, 0f, flat.y), up).normalized;
b.vel = dir * Random.Range(1.4f, 2.6f) + up * Random.Range(2.2f, 3.4f);
Face(b, dir);
}
if (b.vel != Vector3.zero)
{
b.vel -= up * 12f * dt;
b.at += b.vel * dt;
var ground = Planet.Surface(b.at);
if (Vector3.Dot(b.at - ground, up) <= 0f && Vector3.Dot(b.vel, up) < 0f)
{
b.at = ground;
b.vel = Vector3.zero;
b.hopIn = Random.Range(0.12f, 0.35f);
}
}
}
else
{
// a beetle zigzags a little as it runs
var side = Vector3.Cross(up, b.vel).normalized;
b.at = Planet.Surface(b.at + (b.vel + side * Mathf.Sin(b.age * 18f) * 0.4f) * dt);
}
// the last moment it dives back into the grass
float k = Mathf.Clamp01((b.life - b.age) / 0.25f);
b.t.position = b.at;
b.t.localScale = Vector3.one * b.size * k;
if (!b.hopper) Face(b, b.vel);
}
}
static void Face(Bug b, Vector3 dir)
{
var up = Planet.Up(b.at);
var f = Vector3.ProjectOnPlane(dir, up);
if (f.sqrMagnitude < 1e-5f) return;
b.t.rotation = Quaternion.LookRotation(f, up);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 39cb1fa12a457b44bbb40ff8218e09f2

View File

@ -0,0 +1,77 @@
using UnityEngine;
namespace GrassCutter
{
public enum Crop : byte { Grass, Wheat, Oats, Corn, Sunflowers }
/// <summary>
/// Most of Herbaria-7 is grass, but wild stands of wheat, oats, corn and sunflowers grow up through it. The grass under
/// them is the same grass as everywhere. They cut and count like grass, and a field sector pays more when it's mown clean. Which sector grows what follows from where it
/// is, so every peer sees the same fields and nothing has to be saved. Four fields stand near the base.
/// </summary>
public static class Crops
{
const float FieldSize = 190f, Rare = 0.69f, BaseClear = 115f, FirstRadius = 48f, StationClear = 0.99985f;
static readonly (Crop crop, float x, float z)[] First =
{
(Crop.Wheat, 165f, 40f), (Crop.Sunflowers, -150f, 105f), (Crop.Oats, 40f, -180f), (Crop.Corn, -125f, -150f),
};
public static Crop At(int id) => At(HexGrid.Get(id));
public static Crop At(HexGrid.Sector s)
{
if (s.crop < 0) s.crop = (sbyte)Grows(s.c);
return (Crop)s.crop;
}
/// <summary>The middle of the first field of this kind, near the base.</summary>
public static Vector3 FirstField(Crop crop)
{
foreach (var f in First) if (f.crop == crop) return Planet.FromBase(f.x, f.z);
return Planet.FromBase(0f, 0f);
}
public static string Name(Crop crop) => crop switch
{
Crop.Wheat => Loc.T("Wheat"), Crop.Oats => Loc.T("Oats"), Crop.Corn => Loc.T("Corn"), Crop.Sunflowers => Loc.T("Sunflowers"), _ => Loc.T("Sector"),
};
/// <summary>The sector bonus is worth this many times more.</summary>
public static double Pays(Crop crop) => crop == Crop.Sunflowers ? 3d : crop == Crop.Corn ? 2d : crop == Crop.Grass ? 1d : 1.5d;
static Crop Grows(Vector3 dir)
{
foreach (var f in First)
if ((dir - Planet.FromBase(f.x, f.z)).magnitude * Planet.Radius < FirstRadius) return f.crop;
if ((dir - Planet.FromBase(0f, 0f)).magnitude * Planet.Radius < BaseClear) return Crop.Grass;
for (int i = 1; i < Stations.Count; i++) if (Vector3.Dot(dir, Stations.Dir(i)) > StationClear) return Crop.Grass;
var at = dir * (Planet.Radius / FieldSize);
if (Noise(at) < Rare) return Crop.Grass;
float kind = Noise(at * 0.37f + new Vector3(41f, 7f, 23f));
return kind < 0.42f ? Crop.Wheat : kind < 0.5f ? Crop.Oats : kind < 0.58f ? Crop.Corn : Crop.Sunflowers;
}
static float Noise(Vector3 p)
{
int x = Mathf.FloorToInt(p.x), y = Mathf.FloorToInt(p.y), z = Mathf.FloorToInt(p.z);
float fx = Smooth(p.x - x), fy = Smooth(p.y - y), fz = Smooth(p.z - z);
float a = Mathf.Lerp(Mathf.Lerp(Hash(x, y, z), Hash(x + 1, y, z), fx), Mathf.Lerp(Hash(x, y + 1, z), Hash(x + 1, y + 1, z), fx), fy);
float b = Mathf.Lerp(Mathf.Lerp(Hash(x, y, z + 1), Hash(x + 1, y, z + 1), fx), Mathf.Lerp(Hash(x, y + 1, z + 1), Hash(x + 1, y + 1, z + 1), fx), fy);
return Mathf.Lerp(a, b, fz);
}
static float Smooth(float t) => t * t * (3f - 2f * t);
static float Hash(int x, int y, int z)
{
unchecked
{
uint h = (uint)x * 374761393u + (uint)y * 668265263u + (uint)z * 2147483647u;
h = (h ^ (h >> 13)) * 1274126177u;
return (h ^ (h >> 16)) / (float)uint.MaxValue;
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fc32d72c42c0bd142a2680eb4af0197e

View File

@ -0,0 +1,174 @@
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace GrassCutter
{
/// <summary>
/// The sun goes round the ball, the same for everyone: it stands overhead at the base at phase 0 and its path leans toward
/// the north, so the day at the base runs a little longer than the night. Each place has its own time of day.
/// </summary>
public static class Sun
{
const float Lean = 25f * Mathf.Deg2Rad;
/// <summary>The time of day before the crew has one: the morning light of the main menu.</summary>
const float MenuPhase = 0.9f;
public static float Phase { get; private set; } = MenuPhase;
/// <summary>Which way the sun is, from anywhere.</summary>
public static Vector3 Dir { get; private set; } = Vector3.up;
/// <summary>Test bots hold the sun still so their pictures compare. Below 0: it moves.</summary>
public static float Pinned = -1f;
/// <summary>1 with the sun overhead, 0 on the horizon, below that it's night.</summary>
public static float Height(Vector3 up) => Vector3.Dot(up, Dir);
public static void Tick()
{
var ts = TeamState.Instance;
var net = NetworkManager.Singleton;
if (Pinned >= 0f) Phase = Pinned;
else if (ts && ts.IsSpawned && net) Phase = Mathf.Repeat(ts.DayOffset.Value + (float)(net.ServerTime.Time / GameDefs.DayLength % 1.0), 1f);
else Phase = MenuPhase;
var a = new Vector3(Mathf.Cos(Lean), Mathf.Sin(Lean), 0f);
var b = new Vector3(-Mathf.Sin(Lean), Mathf.Cos(Lean), 0f);
float t = Phase * Mathf.PI * 2f;
Dir = (Mathf.Cos(Lean) * (Mathf.Cos(t) * b + Mathf.Sin(t) * Vector3.forward) + Mathf.Sin(Lean) * a).normalized;
}
/// <summary>What the time of day has to be for the given offset of the clock to read this phase.</summary>
public static float OffsetFor(float phase)
{
var net = NetworkManager.Singleton;
return Mathf.Repeat(phase - (net ? (float)(net.ServerTime.Time / GameDefs.DayLength % 1.0) : 0f), 1f);
}
}
/// <summary>
/// Sets the light from the sun's height over the camera, carries the headlamp, and turns the night vision on. Grass and soil
/// have shaders of their own that only know the sun, so the lamp is also handed to them directly.
/// </summary>
public class DayNight : MonoBehaviour
{
public const int Off = 0, Lamp = 1, NightVision = 2;
const float LampRange = 42f;
public static int View { get; private set; } = Lamp;
/// <summary>0 in daylight, 1 in the dark, where the camera is.</summary>
public static float Dark { get; private set; }
/// <summary>1 at sunrise and sunset, when the sun sits on the horizon; 0 the rest of the time.</summary>
public static float Dusk { get; private set; }
static readonly int DuskId = Shader.PropertyToID("_GcDusk");
static readonly Color DuskFog = new Color(0.98f, 0.6f, 0.42f), DuskSky = new Color(1f, 0.62f, 0.5f);
static readonly int NightId = Shader.PropertyToID("_GcNight"), LampPosId = Shader.PropertyToID("_GcLampPos"), LampDirId = Shader.PropertyToID("_GcLampDir"), SunId = Shader.PropertyToID("_SunDir"), CloudId = Shader.PropertyToID("_GcCloudShade");
const float CloudShade = 0.5f;
static readonly Color NightFog = new Color(0.05f, 0.07f, 0.12f);
static readonly Color DuskSun = new Color(1f, 0.5f, 0.24f);
const float MoonPower = 0.55f;
static readonly Color Moon = new Color(0.56f, 0.68f, 1f);
static readonly Color NightSky = new Color(0.13f, 0.17f, 0.3f), NightMid = new Color(0.09f, 0.12f, 0.21f), NightLow = new Color(0.05f, 0.07f, 0.11f);
Light _sun, _lamp;
float _sunPower;
Color _sunColor, _fog, _sky, _mid, _low;
ColorAdjustments _grade;
float _exposure;
void Start()
{
_sun = RenderSettings.sun;
if (_sun) { _sunPower = _sun.intensity; _sunColor = _sun.color; }
_fog = RenderSettings.fogColor;
_sky = RenderSettings.ambientSkyColor;
_mid = RenderSettings.ambientEquatorColor;
_low = RenderSettings.ambientGroundColor;
var volume = FindAnyObjectByType<Volume>();
if (volume && volume.profile.TryGet(out _grade)) _exposure = _grade.postExposure.value;
if (!GetComponent<WeatherFx>()) gameObject.AddComponent<WeatherFx>();
}
public static void SetView(int view) => View = view;
/// <summary>The trailer's work light: the lamp hangs from this instead of the camera.</summary>
public static Transform Rig;
void LateUpdate()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
Sun.Tick();
float h = Sun.Height(Planet.LocalUp);
float day = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(-0.08f, 0.16f, h));
Dark = 1f - day;
float dusk = Mathf.Clamp01(1f - Mathf.Abs(h - 0.03f) / 0.2f);
Dusk = dusk * dusk * (3f - 2f * dusk);
float clear = 1f - WeatherFx.Storm * 0.75f - WeatherFx.Rain * 0.25f;
Shader.SetGlobalFloat(DuskId, Dusk * Mathf.Clamp01(clear));
float gloom = 1f - WeatherFx.Storm * 0.4f - WeatherFx.Rain * 0.15f;
if (_sun)
{
// after dark the same light is the moon, opposite the sun: it comes up once the sun has gone out
float moon = Mathf.InverseLerp(-0.1f, -0.32f, h);
var from = h < -0.09f ? -Sun.Dir : Sun.Dir;
_sun.transform.rotation = Quaternion.LookRotation(-from, Mathf.Abs(from.y) > 0.99f ? Vector3.forward : Vector3.up);
_sun.intensity = Mathf.Max(_sunPower * day * WeatherFx.SunMul, MoonPower * moon * WeatherFx.SunMul) + WeatherFx.Flash * 2.2f;
_sun.color = moon > 0f ? Moon : Color.Lerp(DuskSun, _sunColor, Mathf.InverseLerp(0f, 0.32f, h));
}
var flash = new Color(0.55f, 0.6f, 0.75f) * WeatherFx.Flash;
var warm = Color.Lerp(Color.white, DuskSky, Dusk * day * 0.6f);
RenderSettings.ambientSkyColor = Color.Lerp(NightSky, _sky * warm, day) * gloom + flash;
RenderSettings.ambientEquatorColor = Color.Lerp(NightMid, _mid * warm, day) * gloom + flash;
RenderSettings.ambientGroundColor = Color.Lerp(NightLow, _low, day) * gloom;
var air = Color.Lerp(Color.Lerp(_fog, DuskFog, Dusk * day * 0.5f), WeatherFx.FogTint, WeatherFx.Murk * 0.8f);
RenderSettings.fogColor = Color.Lerp(air, NightFog, Dark);
Shader.SetGlobalFloat(NightId, Dark);
Shader.SetGlobalFloat(CloudId, CloudShade * day * (1f - WeatherFx.Storm * 0.6f));
Fx.Motes(cam.transform.position, Dark);
var sky = RenderSettings.skybox;
if (sky) sky.SetVector(SunId, Quaternion.Inverse(Planet.Frame) * Sun.Dir);
TickLamp(cam);
}
void TickLamp(Camera cam)
{
var me = PlayerAgent.Local;
if (Ctl.LampPressed && me)
{
View = View == Lamp && me.HasGear(GearId.NightVision) ? NightVision : View == Off ? Lamp : Off;
Sfx.Play("ui_click", 0.6f, 1.2f);
Hud.Toast(View == NightVision ? Loc.T("Night vision on") : View == Lamp ? Loc.T("Headlamp on") : Loc.T("Headlamp off"), Hud.ToastKind.Info);
}
if (!me && View == NightVision) View = Lamp;
if (!_lamp)
{
_lamp = new GameObject("Headlamp").AddComponent<Light>();
_lamp.type = LightType.Spot;
_lamp.spotAngle = 62f;
_lamp.innerSpotAngle = 34f;
_lamp.range = LampRange;
_lamp.color = new Color(1f, 0.95f, 0.85f);
_lamp.shadows = LightShadows.None;
}
var from = Rig ? Rig : cam.transform;
_lamp.transform.SetParent(from, false);
// a machine's floodlights join in while you drive it
float flood = me && me.Vehicle ? 1f + me.Vehicle.Level(TuneId.Lights) * 0.6f : 1f;
float power = View == Lamp && me ? Dark * flood : 0f;
float reach = LampRange * Mathf.Sqrt(flood);
_lamp.intensity = power * 9f;
_lamp.range = reach;
var t = from;
Shader.SetGlobalVector(LampPosId, new Vector4(t.position.x, t.position.y, t.position.z, reach));
Shader.SetGlobalVector(LampDirId, new Vector4(t.forward.x, t.forward.y, t.forward.z, power));
if (_grade)
{
bool green = View == NightVision;
_grade.colorFilter.Override(green ? new Color(0.45f, 1f, 0.5f) : Color.white);
_grade.postExposure.Override(_exposure + GameSettings.Brightness + (green ? 3.2f * Dark : 0f));
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 37a200da8250c0a469be9776a71e5e6b

View File

@ -0,0 +1,176 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Builds and updates the base's deck from the synced tile list; new tiles drop onto their stilts with a thump.</summary>
public class DeckManager : MonoBehaviour
{
public static DeckManager Instance { get; private set; }
public GameObject tileModel, ladderModel;
/// <summary>Deck-edge points that must stay open (the dock): the railing on that side of the tile is left out.</summary>
public Vector3[] gaps;
readonly Dictionary<int, DeckTileView> _views = new Dictionary<int, DeckTileView>();
/// <summary>Packed tile keys currently shown (the menu rig included): the grass never grows under them.</summary>
public IEnumerable<int> TileKeys => _views.Keys;
void Awake()
{
Instance = this;
TeamState.TilesChanged += Rebuild;
}
void OnDestroy() { TeamState.TilesChanged -= Rebuild; }
void Update()
{
// the session ended: clear the deck so the menu shows the bare starter base in the meadow
if (!TeamState.Instance && _views.Count > 0 && !(NetSession.Instance && NetSession.Instance.Current == NetSession.State.InGame)) Clear();
if (!TeamState.Instance && _views.Count == 0) ShowMenuRig();
}
bool _menuRig;
/// <summary>Main menu backdrop: the 3x3 starter deck without anything on it.</summary>
void ShowMenuRig()
{
if (_menuRig) return;
_menuRig = true;
for (int x = -1; x <= 1; x++)
for (int z = -1; z <= 1; z++)
Make(TeamState.PackTile(x, z), false);
RefreshEdges(p => Mathf.Abs(TeamState.UnpackTile(p).x) <= 1 && Mathf.Abs(TeamState.UnpackTile(p).y) <= 1);
}
void Clear()
{
foreach (var v in _views.Values) if (v) Destroy(v.gameObject);
_views.Clear();
_menuRig = false;
}
void Rebuild()
{
var ts = TeamState.Instance;
if (!ts || ts.Tiles == null) return;
if (_menuRig) { Clear(); }
var want = new HashSet<int>();
foreach (var t in ts.Tiles) want.Add(t);
var dead = new List<int>();
foreach (var k in _views.Keys) if (!want.Contains(k)) dead.Add(k);
foreach (var k in dead) { if (_views[k]) Destroy(_views[k].gameObject); _views.Remove(k); }
bool animate = Time.timeSinceLevelLoad > 3f && _views.Count > 0;
foreach (var t in want) if (!_views.ContainsKey(t)) Make(t, animate);
RefreshEdges(p => want.Contains(p));
}
void RefreshEdges(System.Func<int, bool> has)
{
foreach (var kv in _views)
{
var c = TeamState.UnpackTile(kv.Key);
var ctr = TeamState.TileCenter(c.x, c.y);
float h = GameDefs.TileSize * 0.5f;
kv.Value.SetEdges(
!has(TeamState.PackTile(c.x, c.y + 1)) && !Gap(ctr + new Vector3(0f, 0f, h)),
!has(TeamState.PackTile(c.x, c.y - 1)) && !Gap(ctr + new Vector3(0f, 0f, -h)),
!has(TeamState.PackTile(c.x + 1, c.y)) && !Gap(ctr + new Vector3(h, 0f, 0f)),
!has(TeamState.PackTile(c.x - 1, c.y)) && !Gap(ctr + new Vector3(-h, 0f, 0f)));
}
}
bool Gap(Vector3 edgeMid)
{
if (gaps == null) return false;
foreach (var g in gaps) if (new Vector2(g.x - edgeMid.x, g.z - edgeMid.z).sqrMagnitude < 1f) return true;
return false;
}
void Make(int packed, bool animate)
{
var c = TeamState.UnpackTile(packed);
var go = new GameObject($"Deck_{c.x}_{c.y}");
go.transform.SetParent(transform, false);
go.transform.position = TeamState.TileCenter(c.x, c.y);
var v = go.AddComponent<DeckTileView>();
v.tile = c;
float S = GameDefs.TileSize;
if (tileModel)
{
var m = Instantiate(tileModel, go.transform);
m.transform.localPosition = Vector3.zero;
foreach (var t in m.GetComponentsInChildren<Transform>(true))
{
if (t.name == "Rail_N") v.railN = t.gameObject;
else if (t.name == "Rail_S") v.railS = t.gameObject;
else if (t.name == "Rail_E") v.railE = t.gameObject;
else if (t.name == "Rail_W") v.railW = t.gameObject;
}
}
else
{
var p = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy(p.GetComponent<Collider>());
p.transform.SetParent(go.transform, false);
p.transform.localPosition = new Vector3(0, -0.22f, 0);
p.transform.localScale = new Vector3(S, 0.45f, S);
}
var slab = go.AddComponent<BoxCollider>();
slab.center = new Vector3(0f, -0.23f, 0f);
slab.size = new Vector3(S, 0.46f, S);
BoxCollider Rail(string n, Vector3 center, Vector3 size)
{
// Ignore Raycast: the rail still stops bodies but never blocks aiming the suction over it
var r = new GameObject(n) { layer = Physics.IgnoreRaycastLayer };
r.transform.SetParent(go.transform, false);
r.transform.localPosition = center;
var bc = r.AddComponent<BoxCollider>();
bc.size = size;
return bc;
}
float h = 1.0f, e = S * 0.5f - 0.12f;
v.colN = Rail("RailN", new Vector3(0, h * 0.5f, e), new Vector3(S, h, 0.1f));
v.colS = Rail("RailS", new Vector3(0, h * 0.5f, -e), new Vector3(S, h, 0.1f));
v.colE = Rail("RailE", new Vector3(e, h * 0.5f, 0), new Vector3(0.1f, h, S));
v.colW = Rail("RailW", new Vector3(-e, h * 0.5f, 0), new Vector3(0.1f, h, S));
// ladders down to the meadow on every open edge (shown by SetEdges)
if (ladderModel)
{
var lr = new GameObject("Ladders").transform;
lr.SetParent(go.transform, false);
v.ladderRoot = lr;
void L(Vector3 pos, float yaw)
{
var l = Instantiate(ladderModel, lr);
l.transform.localPosition = pos;
l.transform.localRotation = Quaternion.Euler(0, yaw, 0) * ladderModel.transform.localRotation;
}
// front of the ladder model hangs toward -Y Blender = +Z Unity (yaw 0 → toward +Z)
L(new Vector3(-1.5f, 0f, S * 0.5f), 0f);
L(new Vector3(1.5f, 0f, -S * 0.5f), 180f);
L(new Vector3(S * 0.5f, 0f, 1.5f), 90f);
L(new Vector3(-S * 0.5f, 0f, -1.5f), 270f);
}
foreach (var t in go.GetComponentsInChildren<Transform>(true)) t.gameObject.isStatic = false;
_views[packed] = v;
if (animate)
{
var start = go.transform.position + Vector3.up * 6f;
var end = go.transform.position;
go.transform.position = start;
Tween.Run(go, 0.9f, k => { if (go) go.transform.position = Vector3.LerpUnclamped(start, end, k); }, Ease.OutBack);
Fx.Splash(end + Vector3.down * 1.1f, 2.2f);
Fx.Dust(end + Vector3.down * 1f, 1.2f, 18);
Sfx.PlayAt("splash_big", end, 1f, 0.8f);
Sfx.PlayAt("build_place", end, 1f, 0.7f);
CameraFx.Shake(0.2f);
}
}
public DeckTileView ViewAt(Vector3 world)
{
_views.TryGetValue(TeamState.PackTile(TeamState.TileOf(world.x), TeamState.TileOf(world.z)), out var v);
return v;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1e4a2173e2ceb44458e88e624b13ac6d

View File

@ -0,0 +1,27 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>One floating 6x6 deck tile (client-side visual + colliders, built from TeamState.Tiles).</summary>
public class DeckTileView : MonoBehaviour
{
public Vector2Int tile;
public GameObject railN, railS, railE, railW;
public BoxCollider colN, colS, colE, colW;
public Transform ladderRoot;
public void SetEdges(bool n, bool s, bool e, bool w)
{
void Set(GameObject rail, BoxCollider col, bool open)
{
if (rail) rail.SetActive(open);
if (col) col.enabled = open;
}
Set(railN, colN, n); Set(railS, colS, s); Set(railE, colE, e); Set(railW, colW, w);
if (ladderRoot)
for (int i = 0; i < ladderRoot.childCount && i < 4; i++)
ladderRoot.GetChild(i).gameObject.SetActive(i == 0 ? n : i == 1 ? s : i == 2 ? e : w);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 44464ba80dbb1794c8e3657ba3e75a7c

View File

@ -0,0 +1,43 @@
namespace GrassCutter
{
/// <summary>
/// How big Herbaria-7 is. The ball keeps its 163 830 sectors whatever its size, so a smaller ball has smaller sectors
/// too: less grass all round and every sector done sooner. The host picks it for a new save, it stays with the save,
/// and everyone who joins gets the host's ball. 0 is the whole planet, as every save from before there was a choice.
/// </summary>
public enum Difficulty : byte { Hazard = 0, HoldMyBeer = 1, Mommy = 2 }
public static class Difficulties
{
/// <summary>Easiest first, the way the choice is offered.</summary>
public static readonly Difficulty[] Order = { Difficulty.Mommy, Difficulty.HoldMyBeer, Difficulty.Hazard };
public static string Name(Difficulty d) =>
d == Difficulty.Mommy ? "Mommy, I'm Scared!" : d == Difficulty.HoldMyBeer ? "Hold My Beer!" : "I AM THE FUCKING HAZARD!";
public static string Tag(Difficulty d) => Loc.T(d == Difficulty.Mommy ? Loc.N("EASY") : d == Difficulty.HoldMyBeer ? Loc.N("NORMAL") : Loc.N("EXTRA HARD"));
public static string Blurb(Difficulty d) => Loc.T(
d == Difficulty.Mommy ? Loc.N("A planet a third the size, with sectors to match. Earth can wait a little.")
: d == Difficulty.HoldMyBeer ? Loc.N("Half the planet, half-size sectors. Still a lot of lawn.")
: Loc.N("The whole of Herbaria-7, full-size sectors, every blade of it."));
/// <summary>The planet's radius against the whole one.</summary>
public static float Scale(Difficulty d) => d == Difficulty.Mommy ? 1f / 3f : d == Difficulty.HoldMyBeer ? 0.5f : 1f;
/// <summary>What the next new save starts on: set by the menu (and `-difficulty 0..2` for the dev bots).</summary>
public static Difficulty Chosen = Difficulty.Hazard;
/// <summary>The ball the world is built on right now.</summary>
public static Difficulty Current { get; private set; } = Difficulty.Hazard;
/// <summary>Builds the world on the ball for this difficulty, if it isn't on it already.</summary>
public static void Apply(Difficulty d)
{
if (d != Difficulty.Mommy && d != Difficulty.HoldMyBeer) d = Difficulty.Hazard;
if (d == Current) return;
Current = d;
Planet.Rescale(GameDefs.PlanetRadius * Scale(d));
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 57b65a3d102c655488af6e832158f7c5

View File

@ -0,0 +1,40 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Keeps the meadow from growing through fixed ground furniture (the loading ramp, the unloading yard): registers an
/// axis-aligned rectangle with <see cref="MowMap.Block"/>. <see cref="halfSize"/> is local (x, z); a quarter-turned
/// placement swaps the axes.
/// </summary>
public class GrassBlocker : MonoBehaviour
{
public Vector3 center;
public Vector2 halfSize = Vector2.one;
static readonly List<GrassBlocker> s_all = new List<GrassBlocker>();
void Start()
{
s_all.Add(this);
Block();
}
void OnDestroy() => s_all.Remove(this);
void Block()
{
var c = transform.TransformPoint(center);
bool turned = Mathf.Abs(Vector3.Dot(transform.right, Vector3.forward)) > 0.7f;
MowMap.Block(c, turned ? new Vector2(halfSize.y, halfSize.x) : halfSize);
}
/// <summary>The ball has changed size and the blocks were wiped with it: the ramp and the yard keep their spot
/// (without this a smaller planet grew grass over them).</summary>
public static void ReblockAll()
{
foreach (var b in s_all) if (b) b.Block();
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d6e42234b919eb94994d42050a3d056b

View File

@ -0,0 +1,431 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace GrassCutter
{
/// <summary>
/// Draws Herbaria-7's grass and hemp around the camera straight from the GPU, one draw per sector in view so every
/// strand keeps its place on the ball and reads that sector's mow map: up close the meadow is a pile of real strands,
/// long round "sausages" over a dark floor (GrassStrand.shader: one ribbon per cell of the sector's flat frame, placed
/// from the instance id, a fine ring and a coarser one); out to the horizon, where strands would be under a pixel, it
/// turns into shells (GrassFur.shader). Hemp plants poke out of it (Grass.shader). Further out still, only the floor of
/// the sectors the crew has worked on is drawn, so a mown region stays visible from a long way off.
/// </summary>
[DefaultExecutionOrder(-60)]
public class GrassField : MonoBehaviour
{
public static GrassField Instance { get; private set; }
public Material furMat, strandMat, hempMat, flowerMat;
public Mesh hempMesh, flowerMesh;
/// <summary>By <see cref="Crop"/>: the plant up close and the same plant further off.</summary>
public CropLook[] crops;
[System.Serializable]
public class CropLook { public Material mat; public Mesh near, far; }
// hemp: cell size, fade start / end, inner skip radius, density
static readonly Ring Hemp = new Ring { cell = 2.4f, fadeA = 62f, fadeB = 88f, inner = 0f, density = 0.34f };
struct Ring { public float cell, fadeA, fadeB, inner, density; }
static readonly Ring Flowers = new Ring { cell = 1.05f, fadeA = 54f, fadeB = 76f, inner = 0f, density = 0.7f };
// a stand of plants: thick to 30 m, then cheap ones to the edge of the strands. By crop.
static readonly Ring[] CropNear =
{
default,
new Ring { cell = 0.46f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.92f },
new Ring { cell = 0.46f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.92f },
new Ring { cell = 0.82f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.95f },
new Ring { cell = 0.85f, fadeA = 25f, fadeB = 35f, inner = 0f, density = 0.95f },
};
static readonly Ring[] CropFar =
{
default,
new Ring { cell = 0.72f, fadeA = 64f, fadeB = 88f, inner = 30f, density = 0.92f },
new Ring { cell = 0.72f, fadeA = 64f, fadeB = 88f, inner = 30f, density = 0.92f },
new Ring { cell = 0.95f, fadeA = 72f, fadeB = 100f, inner = 30f, density = 0.95f },
new Ring { cell = 0.95f, fadeA = 72f, fadeB = 100f, inner = 30f, density = 0.95f },
};
// fur: shells, drawn between inner..outer metres (handing over through a dithered band), sinks into the ground
// fadeA..fadeB. Both share one grid laid over the sector.
static readonly Pile FurFloor = new Pile { shells = 1, inner = 0f, outer = StrandEnd, fadeA = 900f, fadeB = 1000f };
static readonly Pile FurFarBase = new Pile { shells = 8, inner = StrandEnd, outer = 158f, fadeA = 118f, fadeB = 158f };
/// <summary>How far the pile reaches, as a multiple of its usual 158 m: the opening film pushes it out so the shots from the air stay furry.</summary>
public static float FurReach = 1f;
/// <summary>The share of blades drawn (graphics settings: grass).</summary>
public static float Detail = 1f;
static Pile FurFar => FurReach == 1f ? FurFarBase : new Pile { shells = FurFarBase.shells, inner = FurFarBase.inner, outer = FurFarBase.outer * FurReach, fadeA = FurFarBase.fadeA * FurReach, fadeB = FurFarBase.fadeB * FurReach };
float _gatheredReach = 1f;
struct Pile { public float inner, outer, fadeA, fadeB; public int shells; }
const int GridSide = 13;
/// <summary>The floor under the strands is seen up close: a finer grid, so no bump of the ground between its corners shows through.</summary>
const int FloorSide = 37;
const float SeamBand = 5f;
/// <summary>Mown ground stays visible this far, on this many of the nearest sectors.</summary>
const float OverlayReach = 1500f;
const int OverlayMax = 400;
// strands: cell (one strand each), ribbon rows, drawn between inner..outer metres, width in metres
const float StrandEnd = 46f;
static readonly Tuft StrandNear = new Tuft { cell = 0.055f, rows = new[] { 0f, 0.3f, 0.6f, 0.8f, 0.92f, 1f }, inner = 0f, outer = 12f, width = 0.05f };
static readonly Tuft StrandMid = new Tuft { cell = 0.13f, rows = new[] { 0f, 0.6f, 1f }, inner = 12f, outer = StrandEnd, width = 0.115f };
struct Tuft { public float cell, inner, outer, width; public float[] rows; }
/// <summary>The strand texture tiles every this many metres (256 px, a strand every ~3 px: ~1200 strands per m²).</summary>
const float FurTile = 2.5f;
/// <summary>The pile never grows taller than this (just under the crew's eyes).</summary>
public const float FurMax = 1.02f;
static readonly int HeightId = Shader.PropertyToID("_GcHeight"), CamId = Shader.PropertyToID("_GcCam");
static readonly int GridId = Shader.PropertyToID("_GcGrid"), FadeId = Shader.PropertyToID("_GcFade");
static readonly int PushersId = Shader.PropertyToID("_GcPushers"), PusherCountId = Shader.PropertyToID("_GcPusherCount");
static readonly int ShellsId = Shader.PropertyToID("_GcShells"), FurTexId = Shader.PropertyToID("_GcFurTex"), FurScaleId = Shader.PropertyToID("_GcFurScale");
static readonly int FurMaxId = Shader.PropertyToID("_GcFurMax"), CamUpId = Shader.PropertyToID("_GcCamUp");
static readonly int SectorCId = Shader.PropertyToID("_GcC"), SectorE1Id = Shader.PropertyToID("_GcE1"), SectorE2Id = Shader.PropertyToID("_GcE2");
static readonly int SaltId = Shader.PropertyToID("_GcSalt"), BordersId = Shader.PropertyToID("_GcBorders"), MaskTexId = Shader.PropertyToID("_GcMaskTex");
static readonly int FurNId = Shader.PropertyToID("_GcFurN"), FurUId = Shader.PropertyToID("_GcFurU"), FurVId = Shader.PropertyToID("_GcFurV");
static readonly int StrandId = Shader.PropertyToID("_GcStrand"), CamFwdId = Shader.PropertyToID("_GcCamFwd");
const int MaxPushers = 8;
readonly Vector4[] _pushers = new Vector4[MaxPushers];
Mesh _grid, _floorGrid, _strandNear, _strandMid;
Texture2D _furTex;
readonly List<MaterialPropertyBlock> _mpbs = new List<MaterialPropertyBlock>();
readonly List<HexGrid.Sector> _near = new List<HexGrid.Sector>();
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1;
int _deckHash;
/// <summary>The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.</summary>
public void Redeck() => _deckHash = int.MinValue;
void Awake()
{
Instance = this;
_grid = BuildGrid(GridSide);
_floorGrid = BuildGrid(FloorSide);
_strandNear = BuildRibbon(StrandNear.rows);
_strandMid = BuildRibbon(StrandMid.rows);
_furTex = BuildStrands(256, 3, 7);
Shader.SetGlobalTexture(FurTexId, _furTex);
Shader.SetGlobalFloat(FurScaleId, 1f / FurTile);
Shader.SetGlobalFloat(FurMaxId, FurMax);
Shader.SetGlobalVectorArray(PushersId, _pushers);
}
void OnDestroy()
{
if (_furTex) Destroy(_furTex);
}
/// <summary>Meadow height in metres.</summary>
public static float CurrentHeight => GameDefs.GrassHeight;
// ───────────────────────── update ─────────────────────────
void LateUpdate()
{
Shader.SetGlobalFloat(HeightId, GameDefs.GrassHeight);
WatchDeck();
UpdatePushers();
Draw();
}
void WatchDeck()
{
var dm = DeckManager.Instance;
if (!dm) return;
int hash = 17;
foreach (var t in dm.TileKeys) hash = hash * 31 + t;
if (hash != _deckHash) { _deckHash = hash; MowMap.SetDeck(dm.TileKeys); }
}
void UpdatePushers()
{
int n = 0;
foreach (var p in PlayerAgent.All)
{
if (!p || n >= MaxPushers) continue;
var pos = p.transform.position;
_pushers[n++] = new Vector4(pos.x, pos.y, pos.z, p.Driving.Value ? 0f : 1.15f);
}
foreach (var v in Vehicle.All)
{
if (!v || n >= MaxPushers) continue;
var pos = v.transform.position;
_pushers[n++] = new Vector4(pos.x, pos.y, pos.z, v.length * 0.55f);
}
for (int i = n; i < MaxPushers; i++) _pushers[i] = Vector4.zero;
Shader.SetGlobalVectorArray(PushersId, _pushers);
Shader.SetGlobalFloat(PusherCountId, n);
}
void Draw()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var cp = cam.transform.position;
Shader.SetGlobalVector(CamId, new Vector4(cp.x, cp.y, cp.z, 0f));
Shader.SetGlobalVector(CamFwdId, cam.transform.forward);
Shader.SetGlobalVector(CamUpId, Planet.LocalUp);
var dir = Planet.LocalUp;
int here = HexGrid.SectorAt(dir);
if (here != _here || _gatheredReach != FurReach) { _here = here; _gatheredReach = FurReach; GatherNear(here); }
_mpbUsed = 0;
PublishFurAxes(dir);
GeometryUtility.CalculateFrustumPlanes(cam, _frustum);
float alt = Planet.Altitude(cp);
foreach (var s in _near)
{
if (!GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) continue;
float arc = (s.c - dir).magnitude * Planet.Radius;
float reachable = Mathf.Max(arc - s.radius, alt);
var mask = MowMap.TextureFor(s);
if (furMat)
{
var far = FurFar;
if (reachable < FurFloor.outer + SeamBand) DrawPile(FurFloor, s, mask, false);
if (reachable < far.outer && arc + s.radius > far.inner - SeamBand) DrawPile(far, s, mask, false);
else if (reachable >= far.outer && mask != MowMap.Blank) DrawPile(FurFloor, s, mask, true);
}
if (alt > FurFarBase.outer) continue;
Flat(s, dir, out float u, out float v);
if (strandMat)
{
if (arc < StrandNear.outer + s.radius) DrawTuft(_strandNear, StrandNear, s, mask, u, v);
if (arc < StrandMid.outer + s.radius) DrawTuft(_strandMid, StrandMid, s, mask, u, v);
}
var crop = (int)Crops.At(s);
if (crop > 0 && crops != null && crop < crops.Length && crops[crop].mat)
{
if (arc < CropNear[crop].fadeB + s.radius) DrawRing(crops[crop].mat, crops[crop].near, CropNear[crop], s, mask, u, v);
if (arc < CropFar[crop].fadeB + s.radius) DrawRing(crops[crop].mat, crops[crop].far, CropFar[crop], s, mask, u, v);
continue;
}
if (hempMat && hempMesh && arc < Hemp.fadeB + s.radius) DrawRing(hempMat, hempMesh, Hemp, s, mask, u, v);
if (flowerMat && flowerMesh && arc < Flowers.fadeB + s.radius) DrawRing(flowerMat, flowerMesh, Flowers, s, mask, u, v);
}
if (furMat)
foreach (var s in _worked)
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true);
}
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
void GatherNear(int here)
{
_near.Clear();
var from = HexGrid.Get(here);
_near.Add(from);
var seen = new HashSet<int> { here };
float reach = Mathf.Max(Hemp.fadeB, FurFar.outer) + 40f;
for (int i = 0; i < _near.Count; i++)
foreach (int n in _near[i].neighbours)
{
if (!seen.Add(n)) continue;
var s = HexGrid.Get(n);
if ((s.c - from.c).magnitude * Planet.Radius < reach) _near.Add(s);
}
MowMap.Trim(from.c);
_worked.Clear();
foreach (var m in MowMap.All)
if (m.keep && !seen.Contains(m.s.id) && (m.s.c - from.c).magnitude * Planet.Radius < OverlayReach) _worked.Add(m.s);
if (_worked.Count > OverlayMax)
{
_worked.Sort((a, b) => (a.c - from.c).sqrMagnitude.CompareTo((b.c - from.c).sqrMagnitude));
_worked.RemoveRange(OverlayMax, _worked.Count - OverlayMax);
}
}
static void Flat(HexGrid.Sector s, Vector3 dir, out float u, out float v) => MowMap.Flat(s, dir, out u, out v);
static void SetSector(MaterialPropertyBlock mpb, HexGrid.Sector s, Texture2D mask)
{
mpb.SetVector(SectorCId, s.c);
mpb.SetVector(SectorE1Id, s.e1);
mpb.SetVector(SectorE2Id, s.e2);
mpb.SetVector(SaltId, s.salt);
mpb.SetVectorArray(BordersId, s.borders);
mpb.SetTexture(MaskTexId, mask);
}
MaterialPropertyBlock NextMpb()
{
if (_mpbUsed == _mpbs.Count) _mpbs.Add(new MaterialPropertyBlock());
return _mpbs[_mpbUsed++];
}
/// <summary>The strand texture lies on the cube face under the camera: no seam for as far as the pile reaches.</summary>
static void PublishFurAxes(Vector3 d)
{
float x = Mathf.Abs(d.x), y = Mathf.Abs(d.y), z = Mathf.Abs(d.z);
Vector3 n, u, v;
if (x >= y && x >= z) { n = new Vector3(Mathf.Sign(d.x), 0f, 0f); u = Vector3.forward; v = Vector3.up; }
else if (y >= z) { n = new Vector3(0f, Mathf.Sign(d.y), 0f); u = Vector3.right; v = Vector3.forward; }
else { n = new Vector3(0f, 0f, Mathf.Sign(d.z)); u = Vector3.right; v = Vector3.up; }
Shader.SetGlobalVector(FurNId, n);
Shader.SetGlobalVector(FurUId, u);
Shader.SetGlobalVector(FurVId, v);
}
/// <summary>The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.</summary>
void DrawPile(Pile p, HexGrid.Sector s, Texture2D mask, bool onlyWorked)
{
var mpb = NextMpb();
SetSector(mpb, s, mask);
bool floor = p.shells == 1;
mpb.SetVector(GridId, new Vector4(s.half, s.half * 2f / ((floor ? FloorSide : GridSide) - 1), 0f, 0f));
mpb.SetVector(ShellsId, new Vector4(p.shells, onlyWorked ? 0f : p.inner, onlyWorked ? 1e6f : p.outer, SeamBand));
mpb.SetVector(FadeId, new Vector4(p.fadeA, onlyWorked ? 1e6f : p.fadeB, onlyWorked ? 1f : 0f, 0f));
var rp = new RenderParams(furMat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, floor ? _floorGrid : _grid, 0, p.shells);
}
/// <summary>The window of a sector's cells that the camera's ring can touch. False when there is none.</summary>
static bool Window(HexGrid.Sector s, float u, float v, float reach, float cell, out int x0, out int z0, out int w, out int h)
{
x0 = Mathf.FloorToInt(Mathf.Max(u - reach, -s.halfU) / cell);
z0 = Mathf.FloorToInt(Mathf.Max(v - reach, -s.halfV) / cell);
w = Mathf.CeilToInt(Mathf.Min(u + reach, s.halfU) / cell) - x0 + 1;
h = Mathf.CeilToInt(Mathf.Min(v + reach, s.halfV) / cell) - z0 + 1;
return w > 0 && h > 0;
}
void DrawTuft(Mesh mesh, Tuft t, HexGrid.Sector s, Texture2D mask, float u, float v)
{
if (!Window(s, u, v, t.outer + SeamBand, t.cell, out int x0, out int z0, out int w, out int h)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
mpb.SetVector(GridId, new Vector4(x0, z0, t.cell, w));
mpb.SetVector(StrandId, new Vector4(t.inner, t.outer, SeamBand, t.width));
var rp = new RenderParams(strandMat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, mesh, 0, w * h);
}
void DrawRing(Material mat, Mesh mesh, Ring r, HexGrid.Sector s, Texture2D mask, float u, float v)
{
if (!Window(s, u, v, r.fadeB, r.cell, out int x0, out int z0, out int w, out int h)) return;
var mpb = NextMpb();
SetSector(mpb, s, mask);
mpb.SetVector(GridId, new Vector4(x0, z0, r.cell, w));
mpb.SetVector(FadeId, new Vector4(r.fadeA, r.fadeB, r.inner, r.density * Detail));
var rp = new RenderParams(mat)
{
worldBounds = s.bounds,
matProps = mpb,
shadowCastingMode = ShadowCastingMode.Off,
receiveShadows = true,
layer = 0,
};
Graphics.RenderMeshPrimitives(rp, mesh, 0, w * h);
}
// ───────────────────────── meshes ─────────────────────────
/// <summary>A flat grid of n×n vertices over -1..1 in local x/z (the sector scales it, the shells are the shader's job).</summary>
static Mesh BuildGrid(int n)
{
var v = new Vector3[n * n];
for (int z = 0; z < n; z++)
for (int x = 0; x < n; x++)
v[z * n + x] = new Vector3(x * 2f / (n - 1) - 1f, 0f, z * 2f / (n - 1) - 1f);
var t = new int[(n - 1) * (n - 1) * 6];
int k = 0;
for (int z = 0; z < n - 1; z++)
for (int x = 0; x < n - 1; x++)
{
int i = z * n + x;
t[k++] = i; t[k++] = i + n; t[k++] = i + 1;
t[k++] = i + 1; t[k++] = i + n; t[k++] = i + n + 1;
}
var m = new Mesh { name = "FurGrid" };
m.SetVertices(v);
m.SetTriangles(t, 0);
return m;
}
/// <summary>One strand: a ribbon with a row of two vertices per entry; x = side (-1..1), y = along the strand.</summary>
static Mesh BuildRibbon(float[] rows)
{
var v = new Vector3[rows.Length * 2];
for (int i = 0; i < rows.Length; i++)
{
v[i * 2] = new Vector3(-1f, rows[i], 0f);
v[i * 2 + 1] = new Vector3(1f, rows[i], 0f);
}
var t = new int[(rows.Length - 1) * 6];
for (int i = 0, k = 0; i < rows.Length - 1; i++)
{
int a = i * 2;
t[k++] = a; t[k++] = a + 2; t[k++] = a + 1;
t[k++] = a + 1; t[k++] = a + 2; t[k++] = a + 3;
}
var m = new Mesh { name = "Strand" };
m.SetVertices(v);
m.SetTriangles(t, 0);
m.bounds = new Bounds(Vector3.up * 0.5f, new Vector3(2f, 2f, 2f));
return m;
}
/// <summary>
/// The strand texture: one strand per jittered spacing×spacing cell, r = its height tapering to 0 at the rim (so a
/// shell cuts it as a cone), g = its tint. Tiles seamlessly; the mips average the strands for distant shells.
/// </summary>
static Texture2D BuildStrands(int res, int spacing, int seed)
{
var rng = new System.Random(seed);
float Rnd() => (float)rng.NextDouble();
var px = new Color32[res * res];
int cells = res / spacing;
float span = cells * spacing;
for (int cz = 0; cz < cells; cz++)
for (int cx = 0; cx < cells; cx++)
{
// full-cell jitter: a regular strand grid beats against the shell spacing into rings (moiré)
float sx = (cx + Rnd()) * spacing * res / span, sz = (cz + Rnd()) * spacing * res / span;
float h = Mathf.Lerp(0.55f, 1f, Mathf.Sqrt(Rnd()));
float rad = spacing * Mathf.Lerp(0.6f, 0.85f, Rnd());
byte tint = (byte)(Rnd() * 255f);
int r = Mathf.CeilToInt(rad);
for (int dz = -r; dz <= r; dz++)
for (int dx = -r; dx <= r; dx++)
{
int x = Mathf.FloorToInt(sx) + dx, z = Mathf.FloorToInt(sz) + dz;
float d = new Vector2(x + 0.5f - sx, z + 0.5f - sz).magnitude / rad;
if (d >= 1f) continue;
x = (x % res + res) % res;
z = (z % res + res) % res;
byte val = (byte)(h * (1f - d * d) * 255f);
int i = z * res + x;
if (val > px[i].r) px[i] = new Color32(val, tint, 0, 255);
}
}
var tex = new Texture2D(res, res, TextureFormat.RGBA32, true, true)
{
name = "FurStrands", wrapMode = TextureWrapMode.Repeat, filterMode = FilterMode.Trilinear, anisoLevel = 8,
};
tex.SetPixels32(px);
tex.Apply(true, true);
return tex;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0a96668323f671a439e9aeab51f4e5d7

View File

@ -0,0 +1,25 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Fixed rig buildings (terminal, crew cabin, harbour) keep the ground under them to themselves, so nothing can be
/// built into them. Footprint = a local rectangle around <see cref="center"/>.
/// </summary>
public class GridBlocker : MonoBehaviour
{
public Vector3 center;
public Vector2 size = Vector2.one;
public static readonly System.Collections.Generic.List<GridBlocker> All = new System.Collections.Generic.List<GridBlocker>();
void OnEnable() => All.Add(this);
void OnDisable() => All.Remove(this);
public bool Covers(Vector3 p)
{
var d = p - transform.TransformPoint(center);
return Mathf.Abs(Vector3.Dot(d, transform.right)) < size.x * 0.5f && Mathf.Abs(Vector3.Dot(d, transform.forward)) < size.y * 0.5f;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ed6dc2a031dd5a542a7d5c79722f4240

View File

@ -0,0 +1,346 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The soil of Herbaria-7, seen. One polar mesh wraps the whole ball, its fine middle always under the camera; the
/// shader lifts every vertex to the soil from the heights <see cref="Planet.Bake"/> published. Nobody has lived here: rock
/// mesas, trees and bushes are all that stands on it. Everything is deterministic, so every peer sees the same world.
/// Also carries the sky along with the camera.
/// </summary>
[DefaultExecutionOrder(-70)]
public class Ground : MonoBehaviour
{
public static Ground Instance { get; private set; }
public Material soil;
public GameObject[] spires = new GameObject[3];
public GameObject[] trees = new GameObject[3];
public GameObject bush;
const int Rings = 112, Spokes = 192, WildRocks = 800, Groves = 110;
const float FirstRing = 1f, RingGrowth = 1.06f, RockDraw = 1800f;
struct Rock { public GameObject go; public Vector3 pos; public float radius; public bool gone; public Vector3 size; public Quaternion turn; }
readonly List<Rock> _rocks = new List<Rock>();
/// <summary>The trees and bushes standing in each sector, by index into the rocks: they go when it's mown clean.</summary>
readonly Dictionary<int, List<int>> _plants = new Dictionary<int, List<int>>();
/// <summary>A plant this close to the camera falls over when its sector is finished; further off it just isn't there any more.</summary>
const float FellSeen = 260f;
Transform _root, _skin;
int _rockAt;
static readonly int SkyRotId = Shader.PropertyToID("_GcSkyRot"), SkyOnId = Shader.PropertyToID("_GcSkyOn");
void Awake()
{
Instance = this;
_root = new GameObject("GroundRoot").transform;
_root.SetParent(transform, false);
Planet.Bake();
HexGrid.Publish();
MowMap.ResetBlocks();
BuildSkin();
Populate();
MowMap.Bared += Clear;
MowMap.Restarted += Regrow;
Planet.Rescaled += Rebuild;
foreach (var m in MowMap.All) if (m.done) Clear(m.s.id);
gameObject.AddComponent<Landmarks>();
gameObject.AddComponent<DayNight>();
}
void OnDestroy()
{
MowMap.Bared -= Clear;
MowMap.Restarted -= Regrow;
Planet.Rescaled -= Rebuild;
}
/// <summary>The ball has changed size: the soil, the rocks and the trees go down again on the new one, and so do the
/// stakes, the far stations and whatever keeps the grass off its spot.</summary>
void Rebuild()
{
if (_root) Destroy(_root.gameObject);
_rocks.Clear();
_plants.Clear();
_rockAt = 0;
_root = new GameObject("GroundRoot").transform;
_root.SetParent(transform, false);
HexGrid.Publish();
MowMap.ResetBlocks();
BuildSkin();
Populate();
var marks = GetComponent<Landmarks>();
if (marks) marks.Replace();
if (Stations.Instance) Stations.Instance.Replace();
if (GrassField.Instance) GrassField.Instance.Redeck();
foreach (var p in BuildPiece.All) if (p) p.Reblock();
GrassBlocker.ReblockAll();
BuildPiece.Moved();
}
/// <summary>A sector has been mown clean: the trees and bushes on it come down.</summary>
void Clear(int sector)
{
if (!_plants.TryGetValue(sector, out var list)) return;
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
foreach (int i in list)
{
var r = _rocks[i];
if (r.gone) continue;
r.gone = true;
_rocks[i] = r;
bool seen = cam && Time.timeSinceLevelLoad > 3f && (r.pos - cam.transform.position).sqrMagnitude < FellSeen * FellSeen;
if (seen) StartCoroutine(Fell(r.go, r.pos, r.radius));
else r.go.SetActive(false);
}
}
/// <summary>The tree or bush still standing nearest a point, and the sector it's in (for the test bot). Zero if none.</summary>
public Vector3 NearestPlant(Vector3 from, out int sector)
{
sector = -1;
var best = Vector3.zero;
float d = float.MaxValue;
foreach (var kv in _plants)
foreach (int i in kv.Value)
{
var r = _rocks[i];
float m = (r.pos - from).sqrMagnitude;
if (r.gone || m > d) continue;
d = m; best = r.pos; sector = kv.Key;
}
return best;
}
/// <summary>A new game on a new planet: everything stands again.</summary>
void Regrow()
{
StopAllCoroutines();
for (int i = 0; i < _rocks.Count; i++)
{
var r = _rocks[i];
if (!r.gone) continue;
r.gone = false;
_rocks[i] = r;
r.go.transform.SetPositionAndRotation(r.pos, r.turn);
r.go.transform.localScale = r.size;
foreach (var c in r.go.GetComponentsInChildren<Collider>(true)) c.enabled = true;
r.go.SetActive(false);
}
}
/// <summary>It leans, goes over faster and faster, and is gone in a puff of dust where it lands.</summary>
System.Collections.IEnumerator Fell(GameObject go, Vector3 foot, float radius)
{
go.SetActive(true);
foreach (var c in go.GetComponentsInChildren<Collider>()) c.enabled = false;
var up = Planet.Up(foot);
var side = Vector3.Cross(up, Random.onUnitSphere).normalized;
var start = go.transform.rotation;
var size = go.transform.localScale;
yield return new WaitForSeconds(Random.Range(0f, 0.5f));
Sfx.PlayAt("giant_roll_creak", foot, 0.7f, 1.3f);
for (float t = 0f; t < 1f; t += Time.deltaTime / 1.1f)
{
go.transform.rotation = Quaternion.AngleAxis(88f * t * t, side) * start;
yield return null;
}
var down = foot + Vector3.Cross(side, up) * radius * 2.2f;
Sfx.PlayAt("cardboard_thud_" + Random.Range(1, 4), foot, 0.9f, 0.7f);
for (int k = 0; k < 5; k++) Fx.Dust(Vector3.Lerp(foot, down, k / 4f), 0.6f + radius * 0.15f, 4);
for (float t = 0f; t < 1f; t += Time.deltaTime / 0.35f)
{
go.transform.localScale = size * (1f - t * t);
yield return null;
}
Fx.Smoke(down, 1.2f + radius * 0.3f);
go.SetActive(false);
}
void OnEnable()
{
Planet.Bake();
HexGrid.Publish();
}
void LateUpdate()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var p = cam.transform.position;
Planet.SetFrame(p);
_skin.rotation = Quaternion.FromToRotation(Vector3.up, Planet.LocalUp);
Shader.SetGlobalMatrix(SkyRotId, Matrix4x4.Rotate(Quaternion.Inverse(Planet.Frame)));
Shader.SetGlobalFloat(SkyOnId, 1f);
// climb and the haze lets go of the planet
float alt = Mathf.Max(0f, Planet.Altitude(p));
RenderSettings.fogStartDistance = (180f + alt * 2f) * WeatherFx.FogMul;
RenderSettings.fogEndDistance = (1900f + alt * 3.2f) * WeatherFx.FogMul;
WakeRocks(p);
ContactShade.Publish(p);
}
/// <summary>A slice of the rocks each frame: only the ones nearby are drawn at all.</summary>
void WakeRocks(Vector3 p)
{
for (int i = 0; i < 40 && _rocks.Count > 0; i++)
{
_rockAt = (_rockAt + 1) % _rocks.Count;
var r = _rocks[_rockAt];
if (r.gone) continue;
bool on = (r.pos - p).sqrMagnitude < RockDraw * RockDraw;
if (r.go.activeSelf != on) r.go.SetActive(on);
}
}
// ───────────────────────── terrain ─────────────────────────
void BuildSkin()
{
// rings of unit directions around +Y, each a little wider apart than the last, right round to -Y
var angle = new List<float> { 0f };
float step = FirstRing, s = 0f;
for (int i = 0; i < Rings && s < Mathf.PI * Planet.Radius; i++)
{
s += step;
step *= RingGrowth;
angle.Add(Mathf.Min(s / Planet.Radius, Mathf.PI));
}
int rings = angle.Count;
var verts = new Vector3[1 + (rings - 1) * Spokes];
verts[0] = Vector3.up;
for (int r = 1; r < rings; r++)
for (int j = 0; j < Spokes; j++)
{
float a = j * Mathf.PI * 2f / Spokes;
verts[1 + (r - 1) * Spokes + j] = new Vector3(Mathf.Sin(angle[r]) * Mathf.Sin(a), Mathf.Cos(angle[r]), Mathf.Sin(angle[r]) * Mathf.Cos(a));
}
var tris = new List<int>(verts.Length * 6);
for (int j = 0; j < Spokes; j++) { tris.Add(0); tris.Add(1 + j); tris.Add(1 + (j + 1) % Spokes); }
for (int r = 1; r < rings - 1; r++)
for (int j = 0; j < Spokes; j++)
{
int a = 1 + (r - 1) * Spokes + j, b = 1 + (r - 1) * Spokes + (j + 1) % Spokes;
int c = a + Spokes, d = b + Spokes;
tris.Add(a); tris.Add(c); tris.Add(b);
tris.Add(b); tris.Add(c); tris.Add(d);
}
var m = new Mesh { name = "PlanetSkin", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 };
m.vertices = verts;
m.SetTriangles(tris, 0);
m.bounds = new Bounds(Vector3.zero, Vector3.one * Planet.Radius * 3f);
var go = new GameObject("Terrain");
go.transform.SetParent(_root, false);
go.transform.position = Planet.Center;
go.AddComponent<MeshFilter>().sharedMesh = m;
var mr = go.AddComponent<MeshRenderer>();
mr.sharedMaterial = soil;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_skin = go.transform;
}
void Populate()
{
var rng = new System.Random(7177);
float R(float a, float b) => a + (float)rng.NextDouble() * (b - a);
// giant far mesas on the hills
for (int i = 0; i < 9; i++)
{
float a = i / 9f * Mathf.PI * 2f + R(-0.2f, 0.2f);
float d = R(320f, 620f);
Place(spires[i % 3], Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d), R(0f, 360f), R(1.8f, 2.8f), true);
}
// closer boulders poking out of the grass
for (int i = 0; i < 22; i++)
{
float a = R(0f, Mathf.PI * 2f);
float d = R(95f, 300f);
Place(spires[rng.Next(3)], Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d), R(0f, 360f), R(0.35f, 0.8f), true);
}
// the rest of the planet
// fewer on a smaller ball, so the land isn't crowded
int wild = Mathf.Max(60, Mathf.RoundToInt(WildRocks * Planet.Scale * Planet.Scale));
for (int i = 0; i < wild; i++)
{
var dir = new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f)).normalized;
if (dir.y > 0.94f) continue;
bool giant = rng.NextDouble() < 0.2;
Place(spires[rng.Next(3)], dir, R(0f, 360f), giant ? R(1.6f, 2.8f) : R(0.35f, 0.9f), true);
}
// a loose ring of trees and bushes around the clearing, and groves all over the ball
if (trees == null || !trees[0]) return;
for (int i = 0; i < 34; i++)
{
float a = i / 34f * Mathf.PI * 2f + R(-0.05f, 0.05f);
float d = R(84f, 112f);
var dir = Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d);
if (i % 3 == 2) Place(bush, dir, R(0f, 360f), R(1f, 1.5f), false, true);
else Place(trees[rng.Next(3)], dir, R(0f, 360f), R(1.3f, 2.1f), true, true);
}
int groves = Mathf.Max(14, Mathf.RoundToInt(Groves * Planet.Scale * Planet.Scale));
for (int i = 0; i < groves; i++)
{
var dir = new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f)).normalized;
if (dir.y > 0.94f) continue;
var e1 = Vector3.Cross(dir, Vector3.right).normalized;
var e2 = Vector3.Cross(dir, e1);
int count = rng.Next(4, 9);
for (int k = 0; k < count; k++)
{
var at = (dir + (e1 * R(-18f, 18f) + e2 * R(-18f, 18f)) / Planet.Radius).normalized;
Place(trees[rng.Next(3)], at, R(0f, 360f), R(1.2f, 2.2f), true, true);
}
}
}
/// <summary>70 m round each far station, on any ball.</summary>
static float StationClear => Mathf.Cos(70f / Planet.Radius);
GameObject Place(GameObject prefab, Vector3 dir, float yaw, float scale, bool collide, bool plant = false)
{
if (!prefab) return null;
// nothing stands on a station's clearing
float clear = StationClear;
for (int i = 1; i < Stations.Count; i++) if (Vector3.Dot(dir, Stations.Dir(i)) > clear) return null;
var pos = Planet.OnSurface(dir) - dir * 0.4f * scale;
var go = Instantiate(prefab, _root);
go.transform.localScale = prefab.transform.localScale * scale;
go.transform.SetPositionAndRotation(pos, Quaternion.Euler(0f, yaw, 0f) * prefab.transform.localRotation);
float radius = 4f;
var rs = go.GetComponentsInChildren<Renderer>();
if (rs.Length > 0)
{
var b = rs[0].bounds;
foreach (var r in rs) b.Encapsulate(r.bounds);
radius = Mathf.Max(b.extents.x, b.extents.z);
}
// measured standing up, then stood on its spot of the ball
go.transform.rotation = Quaternion.FromToRotation(Vector3.up, dir) * go.transform.rotation;
if (collide)
foreach (var mf in go.GetComponentsInChildren<MeshFilter>())
mf.gameObject.AddComponent<MeshCollider>().sharedMesh = mf.sharedMesh;
if (plant)
{
int sector = HexGrid.SectorAt(dir);
if (!_plants.TryGetValue(sector, out var list)) _plants[sector] = list = new List<int>();
list.Add(_rocks.Count);
}
_rocks.Add(new Rock { go = go, pos = pos, radius = radius * 0.8f, size = go.transform.localScale, turn = go.transform.rotation });
MowMap.BlockRound(pos, radius * 0.7f);
go.SetActive(false);
return go;
}
/// <summary>Is a rock standing on this spot?</summary>
public bool RockAt(Vector3 p)
{
foreach (var r in _rocks)
if (!r.gone && (r.pos - p).sqrMagnitude < r.radius * r.radius) return true;
return false;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1697d48ae2d4c8842a62bbabd4e6d841

View File

@ -0,0 +1,265 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The sectors of Herbaria-7: an icosahedron with every face cut into a 128-to-a-side triangular lattice and blown out
/// onto the ball. Each lattice point owns the cell around it: 163 830 hexagons and 12 pentagons at the corners, the
/// first of them right under the base. Ids are worked out on the fly, so nothing here costs memory until a sector
/// comes near the camera (<see cref="Get"/>).
/// </summary>
public static class HexGrid
{
public const int N = 128;
public const int Cells = 10 * N * N + 2;
const int EdgePoints = N - 1, Inner = (N - 1) * (N - 2) / 2;
/// <summary>One sector: its centre, a flat frame through it, and its neighbours as planes that fence it in.</summary>
public class Sector
{
public int id;
public Vector3 c, e1, e2;
/// <summary>Metres-per-unit-direction normal of the border toward each neighbour (a pentagon repeats its last).</summary>
public readonly Vector4[] borders = new Vector4[6];
public readonly List<int> neighbours = new List<int>(6);
/// <summary>Half size of the sector in its own frame, and the corner farthest from the centre.</summary>
public float halfU, halfV, radius;
/// <summary>The square its mow map covers: half a side, in metres.</summary>
public float half;
public Vector4 salt;
public Bounds bounds;
/// <summary>What grows here, worked out the first time it's asked: see <see cref="Crops"/>.</summary>
public sbyte crop = -1;
}
static readonly Vector3[] Corner = new Vector3[12];
static readonly int[,] Face = new int[20, 3];
static readonly int[,] EdgeOf = new int[12, 12];
static readonly Vector4[] Normal = new Vector4[20], Row0 = new Vector4[20], Row1 = new Vector4[20], Row2 = new Vector4[20];
static readonly Dictionary<int, Sector> s_cache = new Dictionary<int, Sector>();
static HexGrid()
{
float lat = Mathf.Atan(0.5f);
Corner[0] = Vector3.up;
Corner[11] = Vector3.down;
for (int i = 0; i < 5; i++)
{
float a = i * 72f * Mathf.Deg2Rad, b = (i + 0.5f) * 72f * Mathf.Deg2Rad;
Corner[1 + i] = new Vector3(Mathf.Cos(lat) * Mathf.Sin(a), Mathf.Sin(lat), Mathf.Cos(lat) * Mathf.Cos(a));
Corner[6 + i] = new Vector3(Mathf.Cos(lat) * Mathf.Sin(b), -Mathf.Sin(lat), Mathf.Cos(lat) * Mathf.Cos(b));
}
for (int i = 0; i < 5; i++)
{
int u0 = 1 + i, u1 = 1 + (i + 1) % 5, d0 = 6 + i, d1 = 6 + (i + 1) % 5;
SetFace(i * 4, 0, u0, u1);
SetFace(i * 4 + 1, u0, d0, u1);
SetFace(i * 4 + 2, u1, d0, d1);
SetFace(i * 4 + 3, 11, d1, d0);
}
int edges = 0;
for (int a = 0; a < 12; a++) for (int b = 0; b < 12; b++) EdgeOf[a, b] = -1;
for (int f = 0; f < 20; f++)
for (int k = 0; k < 3; k++)
{
int a = Face[f, k], b = Face[f, (k + 1) % 3];
if (a > b) (a, b) = (b, a);
if (EdgeOf[a, b] < 0) EdgeOf[a, b] = edges++;
}
for (int f = 0; f < 20; f++)
{
Vector3 a = Corner[Face[f, 0]], b = Corner[Face[f, 1]], c = Corner[Face[f, 2]];
Normal[f] = (a + b + c).normalized;
float det = Vector3.Dot(a, Vector3.Cross(b, c));
Row0[f] = Vector3.Cross(b, c) / det;
Row1[f] = Vector3.Cross(c, a) / det;
Row2[f] = Vector3.Cross(a, b) / det;
}
}
static void SetFace(int f, int a, int b, int c) { Face[f, 0] = a; Face[f, 1] = b; Face[f, 2] = c; }
/// <summary>The Ground shader draws the same lattice.</summary>
/// <summary>The ball changed size: every sector is cut again when it's next asked for.</summary>
public static void Forget() => s_cache.Clear();
public static void Publish()
{
Shader.SetGlobalVectorArray("_GcIcoN", Normal);
Shader.SetGlobalVectorArray("_GcIcoR0", Row0);
Shader.SetGlobalVectorArray("_GcIcoR1", Row1);
Shader.SetGlobalVectorArray("_GcIcoR2", Row2);
}
// ───────────────────────── ids ─────────────────────────
/// <summary>Which sector a direction falls in.</summary>
public static int SectorAt(Vector3 d)
{
int f = 0;
float best = -2f;
for (int i = 0; i < 20; i++)
{
float dot = Normal[i].x * d.x + Normal[i].y * d.y + Normal[i].z * d.z;
if (dot > best) { best = dot; f = i; }
}
float w0 = Dot(Row0[f], d), w1 = Dot(Row1[f], d), w2 = Dot(Row2[f], d);
float sum = N / (w0 + w1 + w2);
float x = w0 * sum, y = w1 * sum, z = w2 * sum;
int rx = Mathf.RoundToInt(x), ry = Mathf.RoundToInt(y), rz = Mathf.RoundToInt(z);
float ex = Mathf.Abs(rx - x), ey = Mathf.Abs(ry - y), ez = Mathf.Abs(rz - z);
if (ex > ey && ex > ez) rx = N - ry - rz;
else if (ey > ez) ry = N - rx - rz;
else rz = N - rx - ry;
return Id(f, Mathf.Clamp(ry, 0, N), Mathf.Clamp(rz, 0, N));
}
static float Dot(Vector4 a, Vector3 b) => a.x * b.x + a.y * b.y + a.z * b.z;
/// <summary>Lattice point (i toward corner 1, j toward corner 2) of a face to its one id across the shared edges.</summary>
static int Id(int f, int i, int j)
{
int k = N - i - j;
if (k < 0) { j += k; k = 0; }
int a = Face[f, 0], b = Face[f, 1], c = Face[f, 2];
if (k == N) return a;
if (i == N) return b;
if (j == N) return c;
if (j == 0) return OnEdge(a, b, i);
if (i == 0) return OnEdge(a, c, j);
if (k == 0) return OnEdge(b, c, j);
return 12 + 30 * EdgePoints + f * Inner + (i - 1) * (2 * N - 2 - i) / 2 + j - 1;
}
static int OnEdge(int a, int b, int t)
{
if (a > b) { (a, b) = (b, a); t = N - t; }
return 12 + EdgeOf[a, b] * EdgePoints + t - 1;
}
/// <summary>Unit direction of a sector's centre.</summary>
public static Vector3 Centre(int id)
{
if (id < 12) return Corner[id];
int e = id - 12;
if (e < 30 * EdgePoints)
{
int edge = e / EdgePoints, t = e % EdgePoints + 1;
for (int a = 0; a < 12; a++)
for (int b = a + 1; b < 12; b++)
if (EdgeOf[a, b] == edge) return (Corner[a] * (N - t) + Corner[b] * t).normalized;
}
e -= 30 * EdgePoints;
int f = e / Inner, tri = e % Inner, row = 1;
while (tri >= N - 1 - row) { tri -= N - 1 - row; row++; }
int j = tri + 1, k = N - row - j;
return (Corner[Face[f, 0]] * k + Corner[Face[f, 1]] * row + Corner[Face[f, 2]] * j).normalized;
}
// ───────────────────────── sectors ─────────────────────────
public static Sector Get(int id)
{
if (s_cache.TryGetValue(id, out var s)) return s;
s = Build(id);
s_cache[id] = s;
return s;
}
static Sector Build(int id)
{
var c = Centre(id);
var s = new Sector { id = id, c = c };
var side = Vector3.Cross(c, Mathf.Abs(c.y) < 0.9f ? Vector3.up : Vector3.right).normalized;
var fwd = Vector3.Cross(c, side);
FindNeighbours(id, c, side, fwd, s.neighbours);
s.neighbours.Sort((p, q) => Bearing(c, side, fwd, p).CompareTo(Bearing(c, side, fwd, q)));
for (int k = 0; k < 6; k++)
{
var d = Centre(s.neighbours[Mathf.Min(k, s.neighbours.Count - 1)]) - c;
s.borders[k] = d.normalized * Planet.Radius;
}
s.e1 = Vector3.ProjectOnPlane(Centre(s.neighbours[0]) - c, c).normalized;
s.e2 = Vector3.Cross(c, s.e1);
// the cell's corners: where three neighbours meet
float u = 0f, v = 0f, far = 0f;
int count = s.neighbours.Count;
for (int k = 0; k < count; k++)
{
var a = Centre(s.neighbours[k]);
var b = Centre(s.neighbours[(k + 1) % count]);
// the true Voronoi vertex, projected onto the sector's plane: around the
// pentagons it sits well past the centroid, and the grass square left holes
var vx = Vector3.Cross(a - c, b - c).normalized;
if (Vector3.Dot(vx, c) < 0f) vx = -vx;
for (int pass = 0; pass < 2; pass++)
{
var corner = (pass == 0 ? vx / Vector3.Dot(vx, c) - c : (c + a + b) / 3f - c) * Planet.Radius;
u = Mathf.Max(u, Mathf.Abs(Vector3.Dot(corner, s.e1)));
v = Mathf.Max(v, Mathf.Abs(Vector3.Dot(corner, s.e2)));
far = Mathf.Max(far, corner.magnitude);
}
}
s.halfU = u * 1.04f; s.halfV = v * 1.04f; s.radius = far * 1.04f;
s.half = Mathf.Max(s.halfU, s.halfV);
s.salt = new Vector4(id % 991 * 17.3f, id % 613 * 29.1f, 0.5f / s.half, 0f);
float size = s.radius * 2.2f;
s.bounds = new Bounds(Planet.OnSurface(c), new Vector3(size, size, size));
return s;
}
/// <summary>
/// Twelve looks around the centre, reaching further until all of them have left the cell. Lattice steps differ by
/// half across a face, so no fixed reach works; just past the cell's corners each neighbour owns a 60 degree slice.
/// </summary>
static void FindNeighbours(int id, Vector3 c, Vector3 side, Vector3 fwd, List<int> into)
{
for (float reach = 12f / GameDefs.PlanetRadius; ; reach *= 1.1f) // an angle: the lattice is the same on any ball
{
into.Clear();
bool left = true;
for (int k = 0; k < 12 && left; k++)
{
float a = k * 30f * Mathf.Deg2Rad;
int n = SectorAt((c + (side * Mathf.Cos(a) + fwd * Mathf.Sin(a)) * reach).normalized);
if (n == id) left = false;
else if (!into.Contains(n)) into.Add(n);
}
if (left) return;
}
}
static float Bearing(Vector3 c, Vector3 side, Vector3 fwd, int n)
{
var d = Centre(n) - c;
return Mathf.Atan2(Vector3.Dot(d, fwd), Vector3.Dot(d, side));
}
/// <summary>Walk every id both ways and count the shapes: what the demo reports.</summary>
public static string SelfTest()
{
int bad = 0, hex = 0, pent = 0, odd = 0;
float min = float.MaxValue, max = 0f;
var seen = new List<int>(6);
for (int id = 0; id < Cells; id++)
{
var c = Centre(id);
if (SectorAt(c) != id) bad++;
var side = Vector3.Cross(c, Mathf.Abs(c.y) < 0.9f ? Vector3.up : Vector3.right).normalized;
FindNeighbours(id, c, side, Vector3.Cross(c, side), seen);
if (seen.Count == 6) hex++;
else if (seen.Count == 5) pent++;
else odd++;
foreach (int n in seen)
{
float d = (Centre(n) - c).magnitude * Planet.Radius;
min = Mathf.Min(min, d);
max = Mathf.Max(max, d);
}
}
float area = 4f * Mathf.PI * Planet.Radius * Planet.Radius / Cells;
return $"hex grid: {Cells} cells, {hex} hexagons, {pent} pentagons, odd {odd}, ids that fail the round trip {bad}, mean area {area:0} m², across {min:0.0}-{max:0.0} m";
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 53718d9c5490f714d8b93750b806125f

View File

@ -0,0 +1,201 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Things to find on Herbaria-7: 195 survey stakes the wind has tangled and 26 survey points. Hold E at one and the crew
/// is paid for it, once. They stand in the same places on every peer, spread evenly over the ball, and only the ones
/// nearby are switched on.
/// </summary>
public class Landmarks : MonoBehaviour
{
public static Landmarks Instance { get; private set; }
public const int Stakes = 195, Points = 26, Count = Stakes + Points;
const float StakeHold = 1.6f, PointHold = 3f, DrawDistance = 900f, Bare = 1.3f;
static readonly Vector3[] s_spots = new Vector3[Count];
readonly Landmark[] _all = new Landmark[Count];
Landmark _busy;
float _held;
int _wake;
Material _wait, _done;
public static bool IsPoint(int id) => id >= Stakes;
public static double Pay(int id) => IsPoint(id) ? GameDefs.PointPay : GameDefs.StakePay;
/// <summary>Where it stands on the ground.</summary>
public static Vector3 Spot(int id) => s_spots[id];
/// <summary>How far along the one in your sights is, 0..1.</summary>
public float Held(Landmark l) => l == _busy ? Mathf.Clamp01(_held / HoldFor(l.id)) : 0f;
static float HoldFor(int id) => IsPoint(id) ? PointHold : StakeHold;
void Awake() => Instance = this;
void Start()
{
_wait = Paint("M_LightAmber", new Color(1f, 0.7f, 0.15f));
_done = Paint("M_LightGreen", new Color(0.3f, 1f, 0.4f));
for (int i = 0; i < Count; i++)
{
s_spots[i] = Planet.OnSurface(Place(i));
_all[i] = Build(i);
MowMap.BlockRound(s_spots[i], Bare);
}
}
/// <summary>The ball changed size: the stakes and points stand again where they belong on it.</summary>
public void Replace()
{
foreach (var l in _all) if (l) Destroy(l.gameObject);
Start();
}
static Material Paint(string name, Color fallback)
{
var m = AssetBank.I ? AssetBank.I.Mat(name) : null;
return m ? m : new Material(Shader.Find("Universal Render Pipeline/Lit")) { color = fallback };
}
/// <summary>Spirals down the ball so they spread evenly, nudged off the regular pattern and out of the rocks.</summary>
static Vector3 Place(int id)
{
bool point = IsPoint(id);
int n = point ? Points : Stakes, i = point ? id - Stakes : id;
float z = 1f - (i + 0.5f) * 2f / n, a = i * 2.39996f + (point ? 1.1f : 0.3f), r = Mathf.Sqrt(1f - z * z);
var d = new Vector3(r * Mathf.Cos(a), z, r * Mathf.Sin(a));
var rng = new System.Random(id * 7919 + 13);
float R() => (float)rng.NextDouble() * 2f - 1f;
d = (d + new Vector3(R(), R(), R()) * Mathf.Sqrt(4f / n) * 0.25f).normalized;
for (int tries = 0; tries < 12 && Ground.Instance && Ground.Instance.RockAt(Planet.OnSurface(d)); tries++)
d = (d + new Vector3(R(), R(), R()) * 8f / Planet.Radius).normalized;
return d;
}
Landmark Build(int id)
{
var go = new GameObject((IsPoint(id) ? "Point " : "Stake ") + id);
go.transform.SetParent(transform, false);
var up = Planet.Up(s_spots[id]);
go.transform.SetPositionAndRotation(s_spots[id], Quaternion.FromToRotation(Vector3.up, up));
var l = go.AddComponent<Landmark>();
l.id = id;
var col = go.AddComponent<CapsuleCollider>();
col.height = 2.6f;
col.radius = 0.45f;
col.center = Vector3.up * 1.3f;
var model = AssetBank.I ? AssetBank.I.Model(IsPoint(id) ? "SM_SurveyPoint" : "SM_SurveyStake") : null;
if (model)
foreach (var t in Instantiate(model, go.transform).GetComponentsInChildren<Transform>(true))
{
if (t.name == "Lamp") l.lamp = t;
else if (t.name == "Post") { l.post = t; l.upright = t.localRotation; }
else if (t.name == "ClothKnot") l.knot = t.gameObject;
else if (t.name == "ClothFlag") l.flag = t.gameObject;
}
go.SetActive(false);
l.Show(false);
return l;
}
/// <summary>The crew's list changed: each one shows whether it has been done.</summary>
public void Refresh()
{
var ts = TeamState.Instance;
if (!ts) return;
foreach (var l in _all) l.Show(ts.Found.Contains(l.id));
}
public void SetLamp(Landmark l, bool done)
{
var r = l.lamp ? l.lamp.GetComponent<Renderer>() : null;
var mat = done ? _done : _wait;
if (r && mat) r.sharedMaterial = mat;
}
/// <summary>The nearest one nobody has done yet, -1 when they all are.</summary>
public int Nearest(Vector3 from, bool points)
{
var ts = TeamState.Instance;
int best = -1;
float d = float.MaxValue;
for (int i = 0; i < Count; i++)
{
if (IsPoint(i) != points || (ts && ts.Found.Contains(i))) continue;
float m = (s_spots[i] - from).sqrMagnitude;
if (m < d) { d = m; best = i; }
}
return best;
}
public void Begin(Landmark l)
{
_busy = l;
_held = 0f;
}
void Update()
{
var cam = CameraFx.Cam;
if (cam)
for (int i = 0; i < 16; i++)
{
_wake = (_wake + 1) % Count;
bool on = (s_spots[_wake] - cam.transform.position).sqrMagnitude < DrawDistance * DrawDistance;
if (_all[_wake].gameObject.activeSelf != on) _all[_wake].gameObject.SetActive(on);
}
if (!_busy) return;
var me = PlayerAgent.Local;
var ts = TeamState.Instance;
if (!me || !ts || !Ctl.InteractHeld || me.AimInteractable as Landmark != _busy) { _busy = null; return; }
_held += Time.deltaTime;
if (_held < HoldFor(_busy.id)) return;
ts.ClaimMarkRpc(_busy.id);
Sfx.Play("build_place", 0.7f, 1.2f);
_busy = null;
}
}
/// <summary>One stake or survey point.</summary>
public class Landmark : MonoBehaviour, IInteractable
{
public int id;
public Transform post, lamp;
public GameObject knot, flag;
public Quaternion upright = Quaternion.identity;
bool Done => TeamState.Instance && TeamState.Instance.Found.Contains(id);
public string Prompt
{
get
{
if (Done) return Landmarks.IsPoint(id) ? Loc.T("Survey point: already read") : Loc.T("Stake: straight and tidy");
float held = Landmarks.Instance.Held(this);
bool point = Landmarks.IsPoint(id);
if (held > 0f) return point ? Loc.F("Read the survey point: {0:0}%", held * 100f) : Loc.F("Untangle the stake: {0:0}%", held * 100f);
string pay = UIK.Money(Landmarks.Pay(id));
return point ? Loc.F("Hold: Read the survey point ({0})", pay) : Loc.F("Hold: Untangle the stake ({0})", pay);
}
}
public bool CanInteract => TeamState.Instance && !Done;
public void Interact()
{
if (CanInteract) Landmarks.Instance.Begin(this);
}
/// <summary>Knotted round a leaning post until somebody sorts it out.</summary>
public void Show(bool done)
{
if (post)
{
post.localRotation = (done ? Quaternion.identity : Quaternion.Euler(16f, 0f, 9f)) * upright;
if (knot) knot.SetActive(!done);
if (flag) flag.SetActive(done);
}
if (lamp) Landmarks.Instance.SetLamp(this, done);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d2b9a29678a50d84e89dceccf4fa366d

View File

@ -0,0 +1,101 @@
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The overgrown surface of Herbaria-7. Owns the shared clock and the mowing spots: every blade and mower registers a
/// spot each frame and the grass bends toward it.
/// </summary>
[DefaultExecutionOrder(-50)]
public class Meadow : MonoBehaviour
{
public static Meadow Instance { get; private set; }
public const int MaxVortex = 12;
static readonly Vector4[] s_vortex = new Vector4[MaxVortex]; // where, strength
static readonly float[] s_reach = new float[MaxVortex];
static int s_vortexCount;
static readonly int VortexId = Shader.PropertyToID("_GcVortex"), VortexCountId = Shader.PropertyToID("_GcVortexCount");
static readonly int ReachId = Shader.PropertyToID("_GcVortexReach"), TimeId = Shader.PropertyToID("_GcTime");
/// <summary>Shared clock (server time when networked, so everyone sees the same wind and spurts).</summary>
public static float T
{
get
{
if (TeamState.ClockOverride != null) return (float)(TeamState.ClockOverride() % 100000d);
var nm = NetworkManager.Singleton;
return nm && nm.IsListening ? (float)(nm.ServerTime.Time % 100000d) : Time.time;
}
}
void Awake()
{
Instance = this;
Shader.SetGlobalVectorArray(VortexId, s_vortex);
Shader.SetGlobalFloatArray(ReachId, s_reach);
}
void LateUpdate()
{
Shader.SetGlobalFloat(TimeId, T);
Shader.SetGlobalVectorArray(VortexId, s_vortex);
Shader.SetGlobalFloatArray(ReachId, s_reach);
Shader.SetGlobalFloat(VortexCountId, s_vortexCount);
// mowing spots are re-registered every frame by whoever is cutting
for (int i = 0; i < MaxVortex; i++) s_vortex[i].w *= 0.82f;
s_vortexCount = 0;
for (int i = 0; i < MaxVortex; i++) if (s_vortex[i].w > 0.02f) s_vortexCount = i + 1;
}
/// <summary>Register a mowing spot for this frame (blades, mowers). strength 0..1, radius in metres.</summary>
public static void Vortex(Vector3 at, float strength, float radius)
{
// reuse the nearest slot so one cutter doesn't hog many
int best = -1;
float bestD = 4f;
for (int i = 0; i < MaxVortex; i++)
{
if (s_vortex[i].w <= 0.02f) continue;
float d = ((Vector3)s_vortex[i] - at).sqrMagnitude;
if (d < bestD) { bestD = d; best = i; }
}
if (best < 0)
{
float weakest = 9f;
for (int i = 0; i < MaxVortex; i++) if (s_vortex[i].w < weakest) { weakest = s_vortex[i].w; best = i; }
}
s_vortex[best] = new Vector4(at.x, at.y, at.z, Mathf.Max(s_vortex[best].w, Mathf.Clamp01(strength)));
s_reach[best] = radius;
s_vortexCount = Mathf.Max(s_vortexCount, best + 1);
}
/// <summary>Where a ray first meets the ground. False if it never does within range.</summary>
public static bool Raycast(Ray ray, float maxDist, out Vector3 hit)
{
hit = default;
float prev = 0f;
float step = 0.25f;
for (float d = 0f; d <= maxDist; d += step)
{
var p = ray.origin + ray.direction * d;
if (Planet.Altitude(p) <= 0f)
{
float a = prev, b = d;
for (int i = 0; i < 6; i++)
{
float m = (a + b) * 0.5f;
var q = ray.origin + ray.direction * m;
if (Planet.Altitude(q) <= 0f) b = m; else a = m;
}
hit = ray.origin + ray.direction * b;
return true;
}
prev = d;
step = Mathf.Min(0.6f, step * 1.15f);
}
return false;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 66d7f7d005e4419498dde2b0d96b6cde

View File

@ -0,0 +1,691 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// What has been cut on Herbaria-7, sector by sector. A sector nobody has touched costs nothing; a touched one keeps a
/// 128² map in its own flat frame: how much grass is left in each cell (what a blade sweeps is exactly what lands in
/// its container) and how it looks (red: cut, green: nothing grows, under the deck and rocks). A finished sector shrinks
/// to a single flag, one far away to a compressed block. The host writes it all to disk; a late joiner gets it over the
/// wire. Every peer cuts for itself from the same strokes.
/// </summary>
public static class MowMap
{
public const int Res = 128;
/// <summary>The last scraps of a sector this nearly done go with the stroke that got it there.</summary>
// the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent
const float DoneAt = 0.97f;
const int MaxStampsPerCut = 28, MaxOpen = 300;
/// <summary>Less than this left in a cell is not worth a row of its own.</summary>
const ushort Scrap = 120;
const float MinPaintRadius = 0.15f;
public const float PaintFeather = 0.25f;
public class Mask
{
public HexGrid.Sector s;
public float cell, area; // one cell: its side, its square metres
public ushort[] left; // 65535 = untouched, null while packed
public byte[] rg; // r, g per cell
public byte[] packed;
public float total, mown; // square metres
public bool done;
public bool paid; // the host has paid out for it
public bool keep; // somebody cut here: it goes in the save
public bool dirty; // changed since it was last packed
public bool show; // the texture is out of date
public Texture2D tex;
}
class Bare { public bool round; public Vector3 center, dir; public float radius; public Vector2 half; }
static readonly Dictionary<int, Mask> s_masks = new Dictionary<int, Mask>();
static readonly Dictionary<int, List<Bare>> s_blocks = new Dictionary<int, List<Bare>>();
static readonly HashSet<int> s_deck = new HashSet<int>();
static readonly List<int> s_walk = new List<int>();
static readonly List<int> s_touched = new List<int>();
static Texture2D s_none, s_full;
/// <summary>This peer has just mown a sector clean.</summary>
public static event Action<int> SectorDone;
/// <summary>A sector is finished, by anyone, or by a save as it loads: the trees and bushes on it go too.</summary>
public static event Action<int> Bared;
/// <summary>Everything is uncut again, so whatever went with a finished sector stands again.</summary>
public static event Action Restarted;
public static IEnumerable<Mask> All => s_masks.Values;
/// <summary>The map of a sector with nothing on it.</summary>
public static Texture2D Blank => s_none;
public static int Started { get; private set; }
public static int Finished { get; private set; }
// ───────────────────────── sessions ─────────────────────────
/// <summary>A new game: nothing is cut yet (the rocks and the base stay).</summary>
public static void Reset()
{
foreach (var m in s_masks.Values) Drop(m);
s_masks.Clear();
Started = Finished = 0;
Restarted?.Invoke();
}
public static void ResetBlocks()
{
s_blocks.Clear();
s_deck.Clear();
}
static void Drop(Mask m)
{
if (m.tex) UnityEngine.Object.Destroy(m.tex);
m.tex = null;
}
// ───────────────────────── nothing grows here ─────────────────────────
/// <summary>Nothing grows inside this rectangle of the base (axis-aligned, only near the pole).</summary>
public static void Block(Vector3 center, Vector2 half) => Add(new Bare { center = center, half = half }, half.magnitude);
/// <summary>Nothing grows under this rock.</summary>
public static void BlockRound(Vector3 center, float radius) => Add(new Bare { round = true, center = center, dir = Planet.Up(center), radius = radius }, radius);
/// <summary>The deck can only grow: new tiles join the blocks.</summary>
public static void SetDeck(IEnumerable<int> tiles)
{
float h = GameDefs.TileSize * 0.5f + 0.15f;
foreach (int t in tiles)
if (s_deck.Add(t))
{
var c = TeamState.UnpackTile(t);
var ctr = TeamState.TileCenter(c.x, c.y);
Add(new Bare { center = ctr, half = new Vector2(h, h) }, h * 1.5f);
}
}
static void Add(Bare b, float reach)
{
// every sector it can touch, walking out from the one it stands in
s_walk.Clear();
int first = HexGrid.SectorAt(Planet.Up(b.center));
s_walk.Add(first);
var dir = Planet.Up(b.center);
for (int i = 0; i < s_walk.Count; i++)
{
var s = HexGrid.Get(s_walk[i]);
if ((s.c - dir).magnitude * Planet.Radius > reach + s.radius) continue;
if (!s_blocks.TryGetValue(s.id, out var list)) s_blocks[s.id] = list = new List<Bare>();
list.Add(b);
if (s_masks.TryGetValue(s.id, out var m) && m.left != null) Apply(m, b);
foreach (int n in s.neighbours) if (!s_walk.Contains(n)) s_walk.Add(n);
}
}
static void Apply(Mask m, Bare b)
{
var s = m.s;
// only the cells the block can reach: a base is hundreds of tiles, and a sector 16k cells, so looking at all of
// them for every tile stalled the frame each time a sector near the base was opened
Flat(s, Planet.Up(b.center), out float bu, out float bv);
float reach = (b.round ? b.radius : b.half.magnitude) * 1.5f + m.cell * 2f;
int x0 = Mathf.Max(0, Mathf.FloorToInt((bu - reach + s.half) / m.cell)), x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((bu + reach + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((bv - reach + s.half) / m.cell)), z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((bv + reach + s.half) / m.cell));
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
int i = z * Res + x;
if (m.rg[i * 2 + 1] != 0) continue;
var flat = s.c * Planet.Radius + s.e1 * Cell(m, x) + s.e2 * Cell(m, z);
var p = Planet.Center + flat;
// a rock is measured along the ground: the frame is flat, the soil isn't
bool hit = b.round
? (flat.normalized - b.dir).sqrMagnitude * Planet.Radius * Planet.Radius < b.radius * b.radius
: Mathf.Abs(p.x - b.center.x) < b.half.x && Mathf.Abs(p.z - b.center.z) < b.half.y;
if (!hit) continue;
m.rg[i * 2 + 1] = 255;
// nobody can cut what stands under a rock: it isn't part of the sector's grass
if (Owned(s, x, z, m)) m.total = Mathf.Max(0f, m.total - m.area);
m.left[i] = 0;
m.show = true;
}
}
static float Cell(Mask m, int i) => (i + 0.5f) * m.cell - m.s.half;
static bool Owned(HexGrid.Sector s, int x, int z, Mask m)
{
var p = s.c * Planet.Radius + s.e1 * Cell(m, x) + s.e2 * Cell(m, z);
foreach (var b in s.borders)
if (p.x * b.x + p.y * b.y + p.z * b.z > 0f) return false;
return true;
}
// ───────────────────────── opening a sector ─────────────────────────
static Mask Find(int id) => s_masks.TryGetValue(id, out var m) ? m : null;
/// <summary>The sector's map ready to read and write. Null when it is finished: nothing left to do there.</summary>
static Mask Open(int id)
{
var m = Find(id);
if (m == null)
{
var s = HexGrid.Get(id);
m = new Mask { s = s, cell = s.half * 2f / Res };
m.area = m.cell * m.cell;
s_masks[id] = m;
}
if (m.done) return null;
if (m.left == null) Unpack(m);
return m;
}
static void Fresh(Mask m)
{
m.left = new ushort[Res * Res];
m.rg = new byte[Res * Res * 2];
int owned = 0;
for (int z = 0; z < Res; z++)
for (int x = 0; x < Res; x++)
if (Owned(m.s, x, z, m)) { m.left[z * Res + x] = 65535; owned++; }
float total = owned * m.area;
if (m.total <= 0f) m.total = total;
m.show = true;
if (s_blocks.TryGetValue(m.s.id, out var list))
{
float kept = m.total;
m.total = total;
foreach (var b in list) Apply(m, b);
if (m.packed != null) m.total = kept;
}
}
static void Unpack(Mask m)
{
Fresh(m);
if (m.packed == null) return;
var raw = Inflate(m.packed);
System.Buffer.BlockCopy(raw, 0, m.left, 0, Res * Res * 2);
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i];
m.show = true;
}
static void Pack(Mask m)
{
var raw = new byte[Res * Res * 3];
System.Buffer.BlockCopy(m.left, 0, raw, 0, Res * Res * 2);
for (int i = 0; i < Res * Res; i++) raw[Res * Res * 2 + i] = m.rg[i * 2];
using (var mem = new MemoryStream())
{
using (var z = new DeflateStream(mem, System.IO.Compression.CompressionLevel.Fastest, true)) z.Write(raw, 0, raw.Length);
m.packed = mem.ToArray();
}
m.dirty = false;
}
static byte[] Inflate(byte[] packed)
{
var raw = new byte[Res * Res * 3];
using (var z = new DeflateStream(new MemoryStream(packed), CompressionMode.Decompress))
{
int at = 0, n;
while (at < raw.Length && (n = z.Read(raw, at, raw.Length - at)) > 0) at += n;
}
return raw;
}
/// <summary>Too many maps in memory: squeeze the ones furthest from here.</summary>
public static void Trim(Vector3 dir)
{
int open = 0;
foreach (var m in s_masks.Values) if (m.left != null) open++;
if (open <= MaxOpen) return;
var list = new List<Mask>();
foreach (var m in s_masks.Values) if (m.left != null) list.Add(m);
list.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude));
for (int i = 0; i < open - MaxOpen; i++)
{
var m = list[i];
if (m.dirty || (m.keep && m.packed == null)) Pack(m);
// only the grass counts go: the look (and its texture) stays, because the overlay of worked ground still
// draws these sectors, and taking it away had every one of them unpacked again the very next frame
m.left = null;
}
}
// ───────────────────────── cutting ─────────────────────────
/// <summary>
/// Sweep a blade from one point to another. Returns the square metres of grass it actually cut: only what is still
/// standing counts, so the whole planet is worth exactly its area. minSweep lets a blade held still eat what is
/// under it, paint widens only what the eye sees, so that rows laid edge to edge show no seam.
/// </summary>
public static float Cut(Vector3 from, Vector3 to, float width, float minSweep = 0f, float paint = 0f)
{
var up = Planet.Up(to);
var flat = Vector3.ProjectOnPlane(to - from, up);
float len = flat.magnitude;
float sweep = Mathf.Max(len, minSweep);
float half = width * 0.5f;
float cut = 0f;
// every sector the stroke touches, each for the part of it that lies there
s_touched.Clear();
int points = Mathf.CeilToInt(len / 8f) + 1;
for (int i = 0; i < points; i++)
{
var d = Planet.Up(Vector3.Lerp(from, to, points > 1 ? (float)i / (points - 1) : 1f));
var s = HexGrid.Get(HexGrid.SectorAt(d));
if (!s_touched.Contains(s.id)) s_touched.Add(s.id);
for (int k = 0; k < s.neighbours.Count; k++)
if (-Vector3.Dot(d, s.borders[k]) < half + 0.5f && !s_touched.Contains(s.neighbours[k])) s_touched.Add(s.neighbours[k]);
}
var a = Planet.Up(from);
var b = Planet.Up(to);
foreach (int id in s_touched)
{
var m = Open(id);
if (m == null) continue;
cut += Sweep(m, a, b, half, sweep);
cut += Settle(m);
}
if (cut <= 0f) return 0f;
Critters.Disturb(to, half, cut);
float r = half + paint;
int stamps = Mathf.Clamp(Mathf.CeilToInt(len / Mathf.Max(r, 0.25f)) + 1, 1, MaxStampsPerCut);
for (int i = 0; i < stamps; i++) Stamp(Vector3.Lerp(from, to, stamps > 1 ? (float)i / (stamps - 1) : 1f), r);
return cut;
}
/// <summary>
/// Take what the strip covers out of each cell under it: the share of the cell across the strip times the share
/// along this stroke, so one full pass leaves nothing and strokes laid edge to edge leave no gap. Returns square metres.
/// </summary>
static float Sweep(Mask m, Vector3 a, Vector3 b, float half, float sweep)
{
var s = m.s;
Flat(s, a, out float u0, out float v0);
Flat(s, b, out float u1, out float v1);
float du = u1 - u0, dv = v1 - v0, len = Mathf.Sqrt(du * du + dv * dv);
float ux = len > 1e-4f ? du / len : 1f, uv = len > 1e-4f ? dv / len : 0f;
float extra = Mathf.Max(0f, sweep - len) * 0.5f;
float h = m.cell * 0.5f * (Mathf.Abs(ux) + Mathf.Abs(uv));
float reach = half + h + extra;
int x0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(u0, u1) - reach + s.half) / m.cell));
int x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(u0, u1) + reach + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((Mathf.Min(v0, v1) - reach + s.half) / m.cell));
int z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((Mathf.Max(v0, v1) + reach + s.half) / m.cell));
float top = Mathf.Min(half / h, 1f), slope = 1f / (2f * Mathf.Min(half, h));
float got = 0f;
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
int k = z * Res + x;
ushort has = m.left[k];
if (has == 0) continue;
float cu = Cell(m, x) - u0, cv = Cell(m, z) - v0;
float across = Mathf.Clamp01((half + h - Mathf.Abs(cv * ux - cu * uv)) * slope) * top;
if (across <= 0f) continue;
float t = cu * ux + cv * uv;
float along = (Mathf.Min(t + h, len + extra) - Mathf.Max(t - h, -extra)) / (2f * h);
if (along <= 0f) continue;
int take = Mathf.Min(has, Mathf.CeilToInt(across * Mathf.Min(along, 1f) * 65535f));
m.left[k] = (ushort)(has - take);
float area = take / 65535f * m.area;
m.mown += area;
got += area;
}
if (got > 0f) m.dirty = m.keep = true;
return got;
}
/// <summary>
/// Rows that would take all that still stands in a sector, laid edge to edge along its flat frame: x is where the row
/// lies across, y and z where it starts and ends, in metres. None when nothing is left.
/// </summary>
public static void Rows(int id, float width, List<Vector3> into)
{
into.Clear();
var m = Open(id);
if (m == null) return;
int bands = Mathf.CeilToInt(m.s.half * 2f / width);
var lo = new float[bands];
var hi = new float[bands];
for (int b = 0; b < bands; b++) { lo[b] = float.MaxValue; hi[b] = float.MinValue; }
for (int z = 0; z < Res; z++)
{
int band = Mathf.Min(bands - 1, (int)((Cell(m, z) + m.s.half) / width));
for (int x = 0; x < Res; x++)
{
if (m.left[z * Res + x] <= Scrap) continue;
float u = Cell(m, x);
lo[band] = Mathf.Min(lo[band], u);
hi[band] = Mathf.Max(hi[band], u);
}
}
for (int b = 0; b < bands; b++)
if (lo[b] <= hi[b]) into.Add(new Vector3((b + 0.5f) * width - m.s.half, lo[b], hi[b]));
}
/// <summary>The direction of the fullest cell still standing in a sector, and how many cells have anything left (for the test bot).</summary>
public static int Leftover(int id, out Vector3 dir)
{
dir = HexGrid.Get(id).c;
var m = Open(id);
if (m == null) return 0;
int count = 0, best = 0;
for (int z = 0; z < Res; z++)
for (int x = 0; x < Res; x++)
{
int left = m.left[z * Res + x];
if (left == 0 || !Owned(m.s, x, z, m)) continue;
count++;
if (left <= best) continue;
best = left;
dir = (m.s.c * Planet.Radius + m.s.e1 * Cell(m, x) + m.s.e2 * Cell(m, z)).normalized;
}
return count;
}
/// <summary>Where a direction falls in a sector's flat frame, in metres.</summary>
public static void Flat(HexGrid.Sector s, Vector3 d, out float u, out float v)
{
var p = d * (Planet.Radius / Mathf.Max(0.5f, Vector3.Dot(d, s.c))) - s.c * Planet.Radius;
u = Vector3.Dot(p, s.e1);
v = Vector3.Dot(p, s.e2);
}
/// <summary>Show a stroke on this sector and on any neighbour it spills onto.</summary>
static void Stamp(Vector3 at, float r)
{
var d = Planet.Up(at);
var s = HexGrid.Get(HexGrid.SectorAt(d));
Paint(s, d, r);
float reach = Mathf.Max(r, MinPaintRadius) + PaintFeather + 0.3f;
for (int k = 0; k < s.neighbours.Count; k++)
if (-Vector3.Dot(d, s.borders[k]) < reach) Paint(HexGrid.Get(s.neighbours[k]), d, r);
}
static void Paint(HexGrid.Sector s, Vector3 d, float r)
{
var m = Open(s.id);
if (m == null) return;
Flat(s, d, out float u, out float v);
float size = Mathf.Max(r, MinPaintRadius) + PaintFeather;
int x0 = Mathf.Max(0, Mathf.FloorToInt((u - size + s.half) / m.cell)), x1 = Mathf.Min(Res - 1, Mathf.CeilToInt((u + size + s.half) / m.cell));
int z0 = Mathf.Max(0, Mathf.FloorToInt((v - size + s.half) / m.cell)), z1 = Mathf.Min(Res - 1, Mathf.CeilToInt((v + size + s.half) / m.cell));
float reach = Mathf.Max(r, MinPaintRadius);
for (int z = z0; z <= z1; z++)
for (int x = x0; x <= x1; x++)
{
float dx = Cell(m, x) - u, dz = Cell(m, z) - v;
float f = Mathf.Clamp01((reach - Mathf.Sqrt(dx * dx + dz * dz)) / PaintFeather + 0.5f);
byte b = (byte)(f * 255f);
int i = (z * Res + x) * 2;
if (b > m.rg[i]) { m.rg[i] = b; m.show = m.dirty = m.keep = true; }
}
}
/// <summary>Is this sector as good as done? Then the last scraps go with this stroke. Returns their square metres.</summary>
static float Settle(Mask m)
{
if (m.done || m.total <= 0f || m.mown < m.total * DoneAt) return 0f;
float rest = m.total - m.mown;
Finish(m);
SectorDone?.Invoke(m.s.id);
return rest;
}
/// <summary>Host: this sector is done, whoever got there first. False when it has already been paid for.</summary>
public static bool Claim(int id)
{
var m = Open(id) ?? Find(id);
if (m.paid) return false;
if (!m.done) Finish(m);
m.paid = true;
return true;
}
/// <summary>The host says this sector is done.</summary>
public static void Close(int id)
{
var m = Open(id);
if (m != null) Finish(m);
}
static void Finish(Mask m)
{
m.done = m.keep = true;
m.dirty = false;
m.mown = m.total;
m.left = null;
m.packed = null;
if (s_blocks.ContainsKey(m.s.id) && m.rg != null)
{
// the rock keeps its bare patch
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = 255;
m.show = true;
}
else
{
m.rg = null;
Drop(m);
}
Bared?.Invoke(m.s.id);
}
/// <summary>Cheat: the whole sector goes at once. Returns the square metres that were still standing.</summary>
public static float CutSector(int id)
{
var m = Open(id);
if (m == null) return 0f;
float rest = m.total - m.mown;
Finish(m);
SectorDone?.Invoke(id);
return rest;
}
// ───────────────────────── reading ─────────────────────────
/// <summary>How much grass is left here: 1 = full meadow, 0 = mown (it never grows back).</summary>
public static float Yield(Vector3 at)
{
var d = Planet.Up(at);
var m = Find(HexGrid.SectorAt(d));
if (m == null) return 1f;
if (m.done) return 0f;
if (m.left == null) Unpack(m);
Flat(m.s, d, out float u, out float v);
int x = Mathf.FloorToInt((u + m.s.half) / m.cell), z = Mathf.FloorToInt((v + m.s.half) / m.cell);
if (x < 0 || z < 0 || x >= Res || z >= Res) return 1f;
return m.left[z * Res + x] / 65535f;
}
/// <summary>No grass standing here: it has been cut, or nothing ever grew. Things are only built on such ground.</summary>
public static bool Clear(Vector3 at)
{
var d = Planet.Up(at);
int id = HexGrid.SectorAt(d);
if (Find(id) == null && !s_blocks.ContainsKey(id)) return false;
var m = Open(id);
if (m == null) return true;
Flat(m.s, d, out float u, out float v);
int x = Mathf.FloorToInt((u + m.s.half) / m.cell), z = Mathf.FloorToInt((v + m.s.half) / m.cell);
return x >= 0 && z >= 0 && x < Res && z < Res && m.left[z * Res + x] < 16384;
}
static float Cleared(Mask m) => m.done ? 1f : m.total > 0f ? Mathf.Clamp01(m.mown / m.total) : 0f;
/// <summary>How much of a sector is mown, 0..1.</summary>
public static float Cleared(int id) => s_masks.TryGetValue(id, out var m) ? Cleared(m) : 0f;
/// <summary>Square metres mown on the whole planet, as this peer knows it.</summary>
public static float MownArea()
{
float sum = 0f;
foreach (var m in s_masks.Values) sum += m.mown;
return sum;
}
/// <summary>Grass in a sector when nobody has touched it, in square metres.</summary>
public static float Total(int id)
{
var m = Find(id);
if (m == null || m.total <= 0f) m = Open(id);
return m != null ? m.total : 0f;
}
/// <summary>The map as the shaders read it (the blank one for an untouched sector with nothing in the way).</summary>
public static Texture2D TextureFor(HexGrid.Sector s)
{
if (!s_none) s_none = Single(new Color32(0, 0, 0, 255));
if (!s_full) s_full = Single(new Color32(255, 0, 0, 255));
var m = Find(s.id);
if (m == null)
{
if (!s_blocks.ContainsKey(s.id)) return s_none;
m = Open(s.id);
}
if (m.done && m.rg == null)
{
if (!s_blocks.ContainsKey(s.id)) return s_full;
Fresh(m);
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = 255;
m.left = null;
m.show = true;
}
if (m.rg == null) Unpack(m);
if (!m.tex)
{
// the mips are the soft edge of a cut: the grass beside it reads them to stand lower
m.tex = new Texture2D(Res, Res, TextureFormat.RG16, true, true) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear };
m.show = true;
}
if (m.show)
{
m.tex.SetPixelData(m.rg, 0);
m.tex.Apply(true, false);
m.show = false;
}
return m.tex;
}
static Texture2D Single(Color32 c)
{
var t = new Texture2D(1, 1, TextureFormat.RG16, false, true) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Point };
t.SetPixelData(new[] { c.r, c.g }, 0);
t.Apply(false, true);
return t;
}
public static void Count()
{
Started = Finished = 0;
foreach (var m in s_masks.Values)
{
if (m.done) Finished++;
else if (m.keep) Started++;
}
}
// ───────────────────────── saving ─────────────────────────
const int Magic = 0x314D4347; // "GCM1"
/// <summary>Everything cut so far, as one block of bytes (the save file, and what a late joiner is sent).</summary>
public static byte[] Serialize()
{
using (var mem = new MemoryStream())
using (var w = new BinaryWriter(mem))
{
int count = 0;
foreach (var m in s_masks.Values) if (m.keep) count++;
w.Write(Magic);
w.Write(count);
foreach (var m in s_masks.Values)
{
if (!m.keep) continue;
if (!m.done && (m.dirty || m.packed == null) && m.left != null) Pack(m);
w.Write(m.s.id);
w.Write(m.total);
w.Write(m.mown);
w.Write(m.done);
int len = m.done || m.packed == null ? 0 : m.packed.Length;
w.Write(len);
if (len > 0) w.Write(m.packed);
}
w.Flush();
return mem.ToArray();
}
}
/// <summary>Take in a saved game. What this peer has cut in the meantime stays cut.</summary>
public static void Merge(byte[] data)
{
if (data == null || data.Length < 8) return;
using (var r = new BinaryReader(new MemoryStream(data)))
{
if (r.ReadInt32() != Magic) { Debug.LogWarning("[MowMap] not a mow map, ignored"); return; }
int count = r.ReadInt32();
for (int i = 0; i < count; i++)
{
int id = r.ReadInt32();
float total = r.ReadSingle(), mown = r.ReadSingle();
bool done = r.ReadBoolean();
int len = r.ReadInt32();
var packed = len > 0 ? r.ReadBytes(len) : null;
var had = Find(id);
if (had != null && had.done) continue;
var s = HexGrid.Get(id);
if (had == null)
{
had = new Mask { s = s, cell = s.half * 2f / Res };
had.area = had.cell * had.cell;
s_masks[id] = had;
}
had.keep = true;
if (done) { Finish(had); had.total = total; had.mown = total; had.paid = true; continue; }
if (had.left == null)
{
had.total = total;
had.mown = mown;
had.packed = packed;
had.rg = null; // a squeezed sector keeps its look: this one is out of date now
continue;
}
if (packed == null) continue;
var raw = Inflate(packed);
float left = 0f;
for (int k = 0; k < Res * Res; k++)
{
int theirs = raw[k * 2] | raw[k * 2 + 1] << 8;
if (theirs < had.left[k]) had.left[k] = (ushort)theirs;
left += had.left[k] / 65535f;
byte b = raw[Res * Res * 2 + k];
if (b > had.rg[k * 2]) had.rg[k * 2] = b;
}
had.mown = Mathf.Max(0f, had.total - left * had.area);
had.show = had.dirty = true;
}
}
Count();
}
/// <summary>False when the file is there but can't be read.</summary>
public static bool LoadFile(string path)
{
if (!File.Exists(path)) return true;
try { Merge(File.ReadAllBytes(path)); return true; }
catch (Exception e) when (e is IOException || e is InvalidDataException || e is IndexOutOfRangeException || e is ArgumentException)
{
Debug.LogWarning("[MowMap] can't read the save: " + e.Message);
return false;
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 75b5a04fd24582e4fbd0fd2afde54812

View File

@ -0,0 +1,282 @@
using System.Threading.Tasks;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Herbaria-7 is a real ball. Its centre sits straight under the base, so the base keeps its plain coordinates on the
/// north pole and "up" anywhere is simply away from the centre. The soil is a pure function of direction: hills and
/// craters on the ball, a flat clearing around the base, the same on every peer. Nothing walks on a collider: the crew,
/// machines and bundles all ask <see cref="Altitude"/>.
/// </summary>
public static class Planet
{
/// <summary>How big the ball is: the whole planet, or a half or a third of it (<see cref="Difficulties"/>).</summary>
public static float Radius { get; private set; } = GameDefs.PlanetRadius;
/// <summary>The ball against the whole planet.</summary>
public static float Scale => Radius / GameDefs.PlanetRadius;
public const float G = 9.81f;
/// <summary>Straight under the base, whatever the size: the base keeps its coordinates on the pole.</summary>
public static Vector3 Center { get; private set; } = new Vector3(0f, GameDefs.WaterY - GameDefs.PlanetRadius, 0f);
/// <summary>The ball has changed size: whatever was laid out on it lays itself out again.</summary>
public static event System.Action Rescaled;
/// <summary>Below this the base's flat maps (mow mask, deck grid) stop meaning anything: the far side shares their x, z.</summary>
public static float NorthCapY => -300f * Scale;
// the clearing around the base, then the blend out into open country (metres from the pole)
const float ClearA = 150f, ClearB = 420f;
const float CraterCell = 460f;
// the same around each of the eleven far stations, at the height the land has there
const float StationA = 45f, StationB = 140f;
const int FarStations = 11;
static readonly Vector3[] s_stations = new Vector3[FarStations];
static readonly float[] s_level = new float[FarStations];
static float s_stationReach = Mathf.Cos(StationB / GameDefs.PlanetRadius);
static Planet() => Levels();
static void Levels()
{
for (int i = 0; i < FarStations; i++)
{
s_stations[i] = HexGrid.Centre(i + 1);
s_level[i] = Terrain(s_stations[i]);
}
s_stationReach = Mathf.Cos(StationB / Radius);
}
/// <summary>
/// The ball at another size: the soil is worked out afresh (the same hills, in metres, on a smaller ball), the sectors
/// are cut again from the same lattice, and everything laid out on the ball hears <see cref="Rescaled"/>.
/// </summary>
public static void Rescale(float radius)
{
if (Mathf.Approximately(radius, Radius)) return;
Radius = radius;
Center = new Vector3(0f, GameDefs.WaterY - radius, 0f);
Levels();
HexGrid.Forget();
if (s_heights) Object.Destroy(s_heights);
s_heights = null;
Bake();
Rescaled?.Invoke();
}
/// <summary>Up at the camera, and the turn that brings the base's frame there: the sky, sun and particles live in it.</summary>
public static Vector3 LocalUp { get; private set; } = Vector3.up;
public static Quaternion Frame { get; private set; } = Quaternion.identity;
public static Vector3 Up(Vector3 p) => (p - Center).normalized;
public static Vector3 OnSurface(Vector3 dir) => Center + dir * (Radius + HeightAt(dir));
public static Vector3 Surface(Vector3 p) => OnSurface(Up(p));
public static bool InNorthCap(Vector3 p) => p.y > NorthCapY;
/// <summary>Metres above the soil straight below (negative: under it).</summary>
public static float Altitude(Vector3 p)
{
var d = p - Center;
float r = d.magnitude;
return r - Radius - HeightAt(d / r);
}
/// <summary>Where a ray first meets the soil. There is no collider to hit, so it walks.</summary>
public static bool Cast(Vector3 from, Vector3 dir, float max, out Vector3 hit)
{
const float Step = 0.2f;
float clear = 0f;
for (float t = Step; t <= max + Step; t += Step)
{
if (Altitude(from + dir * t) >= 0f) { clear = t; continue; }
float hi = t;
for (int i = 0; i < 6; i++)
{
float mid = (clear + hi) * 0.5f;
if (Altitude(from + dir * mid) < 0f) hi = mid; else clear = mid;
}
hit = from + dir * hi;
return hi <= max;
}
hit = default;
return false;
}
/// <summary>Direction of a spot x, z metres from the base along the ground.</summary>
public static Vector3 FromBase(float x, float z)
{
float s = Mathf.Sqrt(x * x + z * z);
if (s < 1e-3f) return Vector3.up;
float a = s / Radius, k = Mathf.Sin(a) / s;
return new Vector3(x * k, Mathf.Cos(a), z * k);
}
public static Vector3 FromLatLon(float lat, float lon)
{
float a = lat * Mathf.Deg2Rad, b = lon * Mathf.Deg2Rad;
return new Vector3(Mathf.Cos(a) * Mathf.Sin(b), Mathf.Sin(a), Mathf.Cos(a) * Mathf.Cos(b));
}
public static void SetFrame(Vector3 camera)
{
LocalUp = Up(camera);
// carried along rather than recomputed: the sky never spins when you walk over the south pole
Frame = Quaternion.FromToRotation(Frame * Vector3.up, LocalUp) * Frame;
Physics.gravity = -LocalUp * G; // only particles use it: bodies fall toward the centre on their own
}
// ───────────────────────── soil ─────────────────────────
/// <summary>Height of the soil above the bare ball along a direction.</summary>
public static float HeightAt(Vector3 dir)
{
float s = Mathf.Sqrt(Mathf.Max(0f, 2f - 2f * dir.y)) * Radius;
if (s <= ClearA) return Radius / dir.y - Radius; // the plane the base stands on
float open = StationGround(dir, Terrain(dir));
if (s >= ClearB) return open;
float k = Mathf.SmoothStep(0f, 1f, (s - ClearA) / (ClearB - ClearA));
return Mathf.Lerp(Radius / dir.y - Radius, open, k);
}
static float StationGround(Vector3 dir, float open)
{
for (int i = 0; i < FarStations; i++)
{
float dot = Vector3.Dot(dir, s_stations[i]);
if (dot < s_stationReach) continue;
float gap = Mathf.Sqrt(Mathf.Max(0f, 2f - 2f * dot)) * Radius;
float flat = s_level[i] + Radius / dot - Radius;
return gap <= StationA ? flat : Mathf.Lerp(flat, open, Mathf.SmoothStep(0f, 1f, (gap - StationA) / (StationB - StationA)));
}
return open;
}
static float Terrain(Vector3 dir)
{
float x = dir.x * Radius, y = dir.y * Radius, z = dir.z * Radius;
return (Noise(x * 0.0011f + 31.7f, y * 0.0011f + 12.1f, z * 0.0011f + 5.3f) - 0.5f) * 70f
+ (Noise(x * 0.0037f + 3.3f, y * 0.0037f + 7.7f, z * 0.0037f + 1.1f) - 0.5f) * 26f
+ (Noise(x * 0.012f + 9.1f, y * 0.012f + 1.9f, z * 0.012f + 4.2f) - 0.5f) * 6f
+ Craters(x, y, z);
}
/// <summary>A few bowls with raised rims, one possible per 460 m cell, none near the base.</summary>
static float Craters(float x, float y, float z)
{
int cx = Mathf.FloorToInt(x / CraterCell), cy = Mathf.FloorToInt(y / CraterCell), cz = Mathf.FloorToInt(z / CraterCell);
float h = 0f;
for (int k = -1; k <= 1; k++)
for (int j = -1; j <= 1; j++)
for (int i = -1; i <= 1; i++)
{
int ix = cx + i, iy = cy + j, iz = cz + k;
if (Hash(ix, iy, iz) > 0.42f) continue;
float px = (ix + Hash(iz, ix, iy)) * CraterCell, py = (iy + Hash(iy, iz, ix)) * CraterCell, pz = (iz + Hash(ix + 7, iy, iz)) * CraterCell;
float len = Mathf.Sqrt(px * px + py * py + pz * pz);
if (len < 1f) continue;
float s = Radius / len;
px *= s; py *= s; pz *= s;
// the middle of the crater must lie well away from the base
float bx = px, by = py - Radius, bz = pz;
if (bx * bx + by * by + bz * bz < 620f * 620f) continue;
float size = Hash(iy + 3, iz, ix);
float r = Mathf.Lerp(35f, 120f, size * size);
float dx = x - px, dy = y - py, dz = z - pz;
float d2 = dx * dx + dy * dy + dz * dz;
if (d2 > r * r * 2.6f) continue;
float t = Mathf.Sqrt(d2) / r;
if (t < 1f) h -= r * 0.2f * (1f - t * t);
float rim = (t - 1f) / 0.22f;
h += r * 0.06f * Mathf.Exp(-rim * rim);
}
return h;
}
static float Hash(int x, int y, int z)
{
uint h = (uint)x * 374761393u + (uint)y * 668265263u + (uint)z * 2246822519u;
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
return h / 4294967296f;
}
static float Noise(float x, float y, float z)
{
int ix = Mathf.FloorToInt(x), iy = Mathf.FloorToInt(y), iz = Mathf.FloorToInt(z);
float fx = x - ix, fy = y - iy, fz = z - iz;
fx = fx * fx * (3f - 2f * fx); fy = fy * fy * (3f - 2f * fy); fz = fz * fz * (3f - 2f * fz);
float a = Mathf.LerpUnclamped(Hash(ix, iy, iz), Hash(ix + 1, iy, iz), fx);
float b = Mathf.LerpUnclamped(Hash(ix, iy + 1, iz), Hash(ix + 1, iy + 1, iz), fx);
float c = Mathf.LerpUnclamped(Hash(ix, iy, iz + 1), Hash(ix + 1, iy, iz + 1), fx);
float d = Mathf.LerpUnclamped(Hash(ix, iy + 1, iz + 1), Hash(ix + 1, iy + 1, iz + 1), fx);
return Mathf.LerpUnclamped(Mathf.LerpUnclamped(a, b, fy), Mathf.LerpUnclamped(c, d, fy), fz);
}
// ───────────────────────── the GPU's copy ─────────────────────────
const int HeightRes = 1024, NoiseRes = 64;
static readonly int HeightsId = Shader.PropertyToID("_GcHeights"), HeightResId = Shader.PropertyToID("_GcHeightRes");
static readonly int PlanetId = Shader.PropertyToID("_GcPlanet"), NoiseId = Shader.PropertyToID("_GcNoise3");
static Texture2DArray s_heights;
static Texture3D s_noise;
/// <summary>Publish the soil to the shaders: six cube faces of heights (Planet.hlsl reads them) and a tiling 3D noise.</summary>
public static void Bake()
{
if (!s_heights)
{
s_heights = new Texture2DArray(HeightRes, HeightRes, 6, TextureFormat.RFloat, false, true)
{
name = "PlanetHeights", wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear,
};
for (int f = 0; f < 6; f++)
{
var data = new float[HeightRes * HeightRes];
int face = f;
Parallel.For(0, HeightRes, j =>
{
for (int i = 0; i < HeightRes; i++)
data[j * HeightRes + i] = HeightAt(FaceDir(face, i / (HeightRes - 1f) * 2f - 1f, j / (HeightRes - 1f) * 2f - 1f));
});
s_heights.SetPixelData(data, 0, f);
}
s_heights.Apply(false, true);
var rng = new System.Random(4177);
var px = new Color32[NoiseRes * NoiseRes * NoiseRes];
var bytes = new byte[4];
for (int i = 0; i < px.Length; i++)
{
rng.NextBytes(bytes);
px[i] = new Color32(bytes[0], bytes[1], bytes[2], bytes[3]);
}
s_noise = new Texture3D(NoiseRes, NoiseRes, NoiseRes, TextureFormat.RGBA32, true)
{
name = "PlanetNoise", wrapMode = TextureWrapMode.Repeat, filterMode = FilterMode.Bilinear,
};
s_noise.SetPixels32(px);
s_noise.Apply(true, true);
}
Shader.SetGlobalTexture(HeightsId, s_heights);
Shader.SetGlobalTexture(NoiseId, s_noise);
Shader.SetGlobalFloat(HeightResId, HeightRes);
Shader.SetGlobalVector(PlanetId, new Vector4(Center.x, Center.y, Center.z, Radius));
}
/// <summary>Same face layout as GcHeight in Planet.hlsl. u, v run -1..1 and both faces of an edge share its texels.</summary>
static Vector3 FaceDir(int f, float u, float v)
{
Vector3 d;
switch (f)
{
case 0: d = new Vector3(1f, v, u); break;
case 1: d = new Vector3(-1f, v, u); break;
case 2: d = new Vector3(u, 1f, v); break;
case 3: d = new Vector3(u, -1f, v); break;
case 4: d = new Vector3(u, v, 1f); break;
default: d = new Vector3(u, v, -1f); break;
}
return d.normalized;
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 87fdd89fe40fa2d4e942db2592e41bc8

View File

@ -0,0 +1,92 @@
using System.Collections.Generic;
using UnityEngine;
namespace GrassCutter
{
/// <summary>Everyone sees the same wires: a sagging line from each pole to what it feeds. They're for show, the network doesn't need them.</summary>
public class PowerWires : MonoBehaviour
{
const int Points = 9, MostPerPole = 6;
const float Sag = 0.05f;
readonly List<LineRenderer> _lines = new List<LineRenderer>();
readonly List<(float dist, Vector3 at, Transform pole)> _ends = new List<(float, Vector3, Transform)>();
readonly Vector3[] _curve = new Vector3[Points];
Material _mat;
bool _dirty = true;
void OnEnable() => BuildPiece.PiecesChanged += Dirty;
void OnDisable() => BuildPiece.PiecesChanged -= Dirty;
void Dirty() => _dirty = true;
void LateUpdate()
{
if (!_dirty || !AssetBank.I) return;
_dirty = false;
if (!_mat) _mat = AssetBank.I.Mat("M_Rubber");
int used = 0;
foreach (var n in PowerNode.All)
{
if (!(n is PowerPole)) continue;
_ends.Clear();
var from = Tie(n.transform, n.WireHeight);
foreach (var o in PowerNode.All)
{
if (!o || o == n || !PowerGrid.Joined(n, o)) continue;
// two poles share one wire: the first of them draws it
if (o is PowerPole && PowerNode.All.IndexOf(o) < PowerNode.All.IndexOf(n)) continue;
_ends.Add((Vector3.Distance(from, o.transform.position), Tie(o.transform, o.WireHeight), o is PowerPole ? o.transform : null));
}
foreach (var m in Machine.All)
if (m && PowerGrid.Reaches(n, m.transform.position)) _ends.Add((Vector3.Distance(from, m.transform.position), Tie(m.transform, 1.5f), null));
_ends.Sort((a, b) => a.dist.CompareTo(b.dist));
for (int i = 0; i < _ends.Count && i < MostPerPole; i++)
{
var far = _ends[i];
if (!far.pole) { Hang(used++, from, far.at); continue; }
// pole to pole: a pair of conductors, one off each end of the crossarm
var across = Vector3.Cross(Planet.Up(from), far.at - from);
var here = Arm(n.transform, across);
var there = Arm(far.pole, across);
Hang(used++, from + here, far.at + there);
Hang(used++, from - here, far.at - there);
}
}
for (int i = used; i < _lines.Count; i++) _lines[i].enabled = false;
}
static Vector3 Tie(Transform t, float height) => t.position + t.up * height;
static Vector3 Arm(Transform pole, Vector3 across)
{
var arm = pole.right * GameDefs.PoleArm;
return Vector3.Dot(arm, across) < 0f ? -arm : arm;
}
void Hang(int i, Vector3 a, Vector3 b)
{
if (i >= _lines.Count)
{
var go = new GameObject("Wire");
go.transform.SetParent(transform, false);
var made = go.AddComponent<LineRenderer>();
made.sharedMaterial = _mat;
made.widthMultiplier = 0.035f;
made.positionCount = Points;
made.numCapVertices = 0;
made.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
_lines.Add(made);
}
var line = _lines[i];
line.enabled = true;
float sag = Vector3.Distance(a, b) * Sag;
var up = Planet.Up(a);
for (int k = 0; k < Points; k++)
{
float t = k / (Points - 1f);
_curve[k] = Vector3.Lerp(a, b, t) - up * (sag * 4f * t * (1f - t));
}
line.SetPositions(_curve);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8f74edc6e7e5d6b4dbeb2bda14c29c94

View File

@ -0,0 +1,51 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// Wind by day and crickets by night where the camera is, and music that follows them: five tunes in turn by day, two quiet
/// ones in the dark, and a tense one while a storm is on.
/// </summary>
public class Soundscape : MonoBehaviour
{
const float Loud = 0.32f, TuneLength = 200f, Every = 2f;
AudioSource _wind, _crickets;
float _next, _tuneEnds;
bool _night;
int _day, _dark;
static readonly string[] Days = { "music_game_loop", "music_game3_loop", "music_game2_loop", "music_game4_loop", "music_game5_loop" };
static readonly string[] Nights = { "music_night_loop", "music_night2_loop" };
AudioSource Make(string clip)
{
var s = Sfx.Loop(clip, transform, 0f);
if (s) s.spatialBlend = 0f;
return s;
}
void Update()
{
if (!_wind)
{
if (!AssetBank.I) return;
_wind = Make("wind_meadow_loop");
_crickets = Make("night_crickets_loop");
if (!_wind) { enabled = false; return; }
}
float dark = DayNight.Dark;
_wind.volume = Loud * (1f - dark) * Sfx.SfxVolume;
if (_crickets) _crickets.volume = Loud * dark * Sfx.SfxVolume;
if (Time.time < _next || !UIRoot.I || !UIRoot.I.InGame) return;
_next = Time.time + Every;
if (_night ? dark < 0.3f : dark > 0.7f) _night = !_night;
if (Time.time >= _tuneEnds)
{
_tuneEnds = Time.time + TuneLength;
if (_night) _dark = (_dark + 1) % Nights.Length;
else _day = (_day + 1) % Days.Length;
}
Sfx.Music(WeatherFx.Storm > 0.5f ? "music_storm_loop" : _night ? Nights[_dark] : Days[_day], 4f);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a2848242811d1274bb5e9cd0caee1c31

View File

@ -0,0 +1,22 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>Endless spin about a local axis for windmill sails, weather vanes and other set dressing, with an optional 3D loop sound.</summary>
public class Spin : MonoBehaviour
{
public Vector3 axis = Vector3.up;
public float degreesPerSecond = 60f;
public string loopClip;
public float loopVolume = 0.25f;
void Start()
{
// desync identical pieces
transform.Rotate(axis, Random.Range(0f, 360f), Space.Self);
if (!string.IsNullOrEmpty(loopClip) && !Application.isBatchMode) Sfx.Loop(loopClip, transform, loopVolume);
}
void Update() => transform.Rotate(axis, degreesPerSecond * Time.deltaTime, Space.Self);
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: cd1cfbaadc6aeb94893cebdc4b233c1b

View File

@ -0,0 +1,84 @@
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// The twelve stations, one on each corner of the sector lattice, the base being the first. The other eleven are found by
/// walking up to them: each has a depot (a build piece the server spawns), a supply wall, a console and a travel terminal.
/// They stand in the same places on every peer and only the ones nearby are switched on.
/// </summary>
public class Stations : MonoBehaviour
{
public static Stations Instance { get; private set; }
public const int Count = 12;
const float DrawDistance = 900f, Found = 45f, Bare = 11f;
public static readonly string[] Names = { "Base", "Fescue", "Clover", "Rye", "Timothy", "Bentgrass", "Sedge", "Vetch", "Yarrow", "Sorrel", "Tansy", "Thistle" };
/// <summary>As shown: the base is a word in the player's language, the eleven others are names.</summary>
public static string Name(int i) => i == 0 ? Loc.T("Base") : Names[i];
public GameObject rig;
readonly GameObject[] _rigs = new GameObject[Count];
readonly Vector3[] _spots = new Vector3[Count];
float _next;
public static Vector3 Dir(int i) => HexGrid.Centre(i);
public static Vector3 Spot(int i) => Planet.OnSurface(Dir(i));
public static Quaternion Turn(int i)
{
var up = Dir(i);
return Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, up), up);
}
/// <summary>Where a traveller steps out.</summary>
public static Vector3 Arrival(int i) => i == 0 ? new Vector3(0f, 0.15f, -5.5f) : Spot(i) + Turn(i) * new Vector3(0f, 0.2f, -5f);
/// <summary>The station nearest a spot on the ball.</summary>
public static int Nearest(Vector3 p)
{
var up = Planet.Up(p);
int best = 0;
for (int i = 1; i < Count; i++) if (Vector3.Dot(up, Dir(i)) > Vector3.Dot(up, Dir(best))) best = i;
return best;
}
void Awake() => Instance = this;
void Start()
{
for (int i = 1; i < Count; i++)
{
_spots[i] = Spot(i);
MowMap.BlockRound(_spots[i], Bare);
_rigs[i] = Instantiate(rig, _spots[i], Turn(i), transform);
_rigs[i].SetActive(false);
}
}
/// <summary>The ball changed size: the far stations stand again where they belong on it.</summary>
public void Replace()
{
foreach (var r in _rigs) if (r) Destroy(r);
Start();
}
void Update()
{
if (Time.time < _next) return;
_next = Time.time + 0.5f;
var me = PlayerAgent.Local;
var ts = TeamState.Instance;
if (!me || !ts) return;
var at = me.transform.position;
for (int i = 1; i < Count; i++)
{
float far = Vector3.Distance(_spots[i], at);
_rigs[i].SetActive(far < DrawDistance);
if (far < Found && !ts.StationOpen(i)) ts.OpenStationRpc(i);
}
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d77aaacf0f2c85943a5a691f1007a879

View File

@ -0,0 +1,637 @@
using Unity.Netcode;
using UnityEngine;
namespace GrassCutter
{
/// <summary>
/// What the weather looks and sounds like where the camera is. The host decides the weather (<see cref="TeamState"/>); this
/// eases into it and draws it: rain and acid rain around the camera, the sky clouding over, the fog closing in, a gale in
/// the grass, lightning and thunder, shooting stars, the twister and the saucer. The twister's and the saucer's paths are
/// worked out from server time, so every machine sees them in the same place and cuts the same grass.
/// </summary>
public class WeatherFx : MonoBehaviour
{
/// <summary>Eased weather, 0..1: rain falling (acid or not), how much of it is acid, wind, storm.</summary>
public static float Rain, Acid, Wind, Storm;
/// <summary>How much the weather thickens the air (0 clear), and the fog's colour then.</summary>
public static float Murk;
public static Color FogTint = new Color(0.55f, 0.6f, 0.66f);
/// <summary>What's left of the sunlight; a lightning flash, 0..1.</summary>
public static float SunMul = 1f, Flash;
public static float FogMul => Mathf.Lerp(1f, 0.25f, Murk);
static readonly int CoverId = Shader.PropertyToID("_GcCoverAdd"), StormId = Shader.PropertyToID("_GcStorm"), FlashId = Shader.PropertyToID("_GcFlash"),
AcidId = Shader.PropertyToID("_GcAcid"), GustId = Shader.PropertyToID("_GcGust");
/// <summary>The share of sunshine the solar panels get in each weather (the host's own figure, not eased).</summary>
public static float SolarOf(WeatherKind k)
{
switch (k)
{
case WeatherKind.Clouds: return 0.75f;
case WeatherKind.Rain: return 0.55f;
case WeatherKind.AcidRain: return 0.5f;
case WeatherKind.Wind: return 0.9f;
case WeatherKind.Storm: return 0.35f;
default: return 1f;
}
}
float _cover;
ParticleSystem _drops, _splash, _funnel, _debris, _meteor, _beam;
AudioSource _rainLoop, _windLoop, _twisterLoop, _ufoHum, _ufoBeam;
Transform _twister, _ufo;
Light _ufoLight;
Renderer[] _ufoLights;
Material _ufoGlow;
float _rainDue, _splashDue, _windDue, _funnelDue, _beamDue, _nextFlash = 8f, _thunderAt = -1f, _thunderVol, _nextMeteor, _flingAt;
Vector3 _lastTwister;
bool _twisterWas;
double _circleOf;
int _circleDone;
Vector3 _ufoAt;
void Start()
{
var fx = Fx.I;
var bank = AssetBank.I;
var soft = bank.Mat("FX_Soft");
var spark = bank.Mat("FX_Sparkle") ?? soft;
_drops = fx.Make("rain", soft, 0.9f, 0.03f, 0f, false);
var dr = _drops.GetComponent<ParticleSystemRenderer>();
dr.renderMode = ParticleSystemRenderMode.Stretch;
dr.velocityScale = 0.05f;
dr.lengthScale = 1f;
_splash = fx.Make("rain_splash", soft, 0.25f, 0.12f, 0f, false);
Fx.SetSizeCurve(_splash, 0.3f, 1.2f);
Fx.SetFade(_splash, 0.6f);
_funnel = fx.Make("twister", soft, 2.6f, 1.2f, 0f, true);
Fx.SetSizeCurve(_funnel, 0.5f, 2.2f);
Fx.SetFade(_funnel, 0.55f);
var fm = _funnel.main; fm.simulationSpace = ParticleSystemSimulationSpace.Local; fm.maxParticles = 1500;
var orbit = _funnel.velocityOverLifetime;
orbit.enabled = true;
orbit.space = ParticleSystemSimulationSpace.Local;
orbit.x = orbit.y = orbit.z = new ParticleSystem.MinMaxCurve(0f);
orbit.orbitalX = orbit.orbitalZ = new ParticleSystem.MinMaxCurve(0f);
orbit.orbitalY = new ParticleSystem.MinMaxCurve(5.5f);
orbit.radial = new ParticleSystem.MinMaxCurve(1.7f);
_twister = _funnel.transform;
_twister.SetParent(transform, false);
_debris = fx.Make("twister_debris", bank.Mat("FX_Leaf") ?? soft, 2.2f, 0.12f, 0f, true);
var dm = _debris.main; dm.simulationSpace = ParticleSystemSimulationSpace.Local;
var dorbit = _debris.velocityOverLifetime;
dorbit.enabled = true;
dorbit.space = ParticleSystemSimulationSpace.Local;
dorbit.x = dorbit.y = dorbit.z = new ParticleSystem.MinMaxCurve(0f);
dorbit.orbitalX = dorbit.orbitalZ = new ParticleSystem.MinMaxCurve(0f);
dorbit.orbitalY = new ParticleSystem.MinMaxCurve(7f);
dorbit.radial = new ParticleSystem.MinMaxCurve(1.6f);
_debris.transform.SetParent(_twister, false);
_meteor = fx.Make("meteors", spark, 0.9f, 0.6f, 0f, false);
var mr = _meteor.GetComponent<ParticleSystemRenderer>();
mr.renderMode = ParticleSystemRenderMode.Stretch;
mr.velocityScale = 0.18f;
mr.lengthScale = 2f;
Fx.SetFade(_meteor, 1f);
_beam = fx.Make("ufo_beam", soft, 0.9f, 1.4f, 0f, false);
Fx.SetSizeCurve(_beam, 0.6f, 1.4f);
Fx.SetFade(_beam, 0.5f);
}
void OnDestroy()
{
foreach (var ps in new[] { _drops, _splash, _meteor, _beam })
if (ps) Destroy(ps.gameObject);
}
void OnDisable()
{
Rain = Acid = Wind = Storm = Murk = Flash = 0f;
SunMul = 1f;
}
void Update()
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (!cam) return;
var ts = TeamState.Instance;
var kind = ts && ts.IsSpawned ? ts.WeatherNow : WeatherKind.Clear;
float dt = Time.deltaTime;
Ease(kind, dt);
var eye = cam.transform.position;
var up = Planet.Up(eye);
var windDir = Vector3.ProjectOnPlane(new Vector3(0.87f, 0.11f, 0.48f), up).normalized;
Shader.SetGlobalFloat(CoverId, _cover);
// rain greys the sky too, a storm most of all
Shader.SetGlobalFloat(StormId, Mathf.Clamp01(Storm + Rain * 0.45f));
Shader.SetGlobalFloat(AcidId, Acid * Mathf.Clamp01(Rain * 1.6f));
Shader.SetGlobalFloat(GustId, Wind * 2.2f + Storm * 0.8f);
TickRain(eye, up, windDir, dt);
TickWind(eye, up, windDir, dt);
TickLightning(eye, dt);
TickMeteors(eye, up, kind, dt);
TickTwister(ts, eye);
TickUfo(ts, eye);
}
void Ease(WeatherKind k, float dt)
{
float rain = 0f, acid = Acid, wind = 0f, storm = 0f, cover = -0.15f, murk = 0f, sun = SolarOf(k);
switch (k)
{
case WeatherKind.Clouds: cover = 0.35f; murk = 0.12f; break;
case WeatherKind.Rain: rain = 0.75f; acid = 0f; cover = 0.5f; murk = 0.45f; break;
case WeatherKind.AcidRain: rain = 0.7f; acid = 1f; cover = 0.5f; murk = 0.5f; break;
case WeatherKind.Wind: wind = 1f; cover = 0.1f; murk = 0.15f; break;
case WeatherKind.Storm: rain = 1f; acid = 0f; wind = 0.7f; storm = 1f; cover = 0.65f; murk = 0.75f; break;
case WeatherKind.Meteors: cover = -0.35f; break;
}
float step = dt / 9f;
Rain = Mathf.MoveTowards(Rain, rain, step);
// the acid share only flips while nothing is falling, so a shower never changes colour in mid-air
if (Rain < 0.02f || rain > 0f) Acid = Mathf.MoveTowards(Acid, acid, step * 3f);
Wind = Mathf.MoveTowards(Wind, wind, step);
Storm = Mathf.MoveTowards(Storm, storm, step);
_cover = Mathf.MoveTowards(_cover, cover, step);
Murk = Mathf.MoveTowards(Murk, murk, step);
SunMul = Mathf.MoveTowards(SunMul, Mathf.Lerp(1f, sun, 0.8f), step);
FogTint = Color.Lerp(new Color(0.55f, 0.6f, 0.66f), new Color(0.66f, 0.74f, 0.3f), Acid);
}
// ───────────────────────── rain ─────────────────────────
void TickRain(Vector3 eye, Vector3 up, Vector3 windDir, float dt)
{
float r = Rain;
if (r > 0.01f)
{
var tint = Color.Lerp(new Color(0.82f, 0.88f, 1f, 0.7f), new Color(0.78f, 1f, 0.3f, 0.8f), Acid);
var fall = -up * 24f + windDir * (Wind * 7f + 1.5f);
_rainDue += dt * 2600f * r;
int n = Mathf.Min((int)_rainDue, 200);
_rainDue -= (int)_rainDue;
var ground = Planet.Surface(eye);
float lift = Mathf.Max(14f, Vector3.Dot(eye - ground, up) + 10f);
for (int i = 0; i < n; i++)
{
var o = Random.insideUnitCircle * 24f;
var at = ground + Planet.Frame * new Vector3(o.x, 0f, o.y) + up * (lift + Random.Range(0f, 6f)) - windDir * 4f;
Fx.Emit(_drops, at, fall * Random.Range(0.9f, 1.1f), Random.Range(0.045f, 0.07f), tint, (lift + 3f) / 24f);
}
_splashDue += dt * 70f * r;
for (; _splashDue >= 1f; _splashDue -= 1f)
{
var o = Random.insideUnitCircle * 12f;
var at = Planet.Surface(eye + Planet.Frame * new Vector3(o.x, 0f, o.y));
if (Vector3.Dot(eye - at, up) > 25f) break;
Fx.Emit(_splash, at + up * 0.05f, up * 0.4f, Random.Range(0.08f, 0.16f), new Color(tint.r, tint.g, tint.b, 0.5f));
}
}
Volume(ref _rainLoop, "rain_loop", r * (0.55f + Storm * 0.25f));
}
void TickWind(Vector3 eye, Vector3 up, Vector3 windDir, float dt)
{
float w = Mathf.Max(Wind, Storm * 0.6f);
Volume(ref _windLoop, "wind_loop", w * 0.5f);
if (w < 0.05f) return;
// clippings and dust streaming past low over the meadow
_windDue += dt * 30f * w;
for (; _windDue >= 1f; _windDue -= 1f)
{
var at = Planet.Surface(eye - windDir * 12f + Random.insideUnitSphere * 14f) + up * Random.Range(0.2f, 2.5f);
Fx.Emit(_splash, at, windDir * Random.Range(8f, 14f) * w + up * Random.Range(-0.3f, 0.6f), Random.Range(0.12f, 0.3f), new Color(0.85f, 0.85f, 0.75f, 0.25f), 1.2f);
}
}
// ───────────────────────── storm ─────────────────────────
void TickLightning(Vector3 eye, float dt)
{
Flash = Mathf.MoveTowards(Flash, 0f, dt * 3.5f);
// a flicker: the flash dips and comes back once before it goes
float shown = Flash * (Flash > 0.55f && Flash < 0.75f ? 0.35f : 1f);
Shader.SetGlobalFloat(FlashId, shown);
if (_thunderAt > 0f && Time.time >= _thunderAt)
{
_thunderAt = -1f;
Sfx.Play("thunder", _thunderVol, Random.Range(0.85f, 1.1f));
if (_thunderVol > 0.7f) CameraFx.Shake(0.15f);
}
if (Storm < 0.6f) { _nextFlash = Time.time + Random.Range(4f, 10f); return; }
if (Time.time < _nextFlash) return;
_nextFlash = Time.time + Random.Range(5f, 16f);
float near = Random.value;
Flash = Mathf.Lerp(0.5f, 1f, near);
_thunderAt = Time.time + Mathf.Lerp(3f, 0.3f, near);
_thunderVol = Mathf.Lerp(0.45f, 1f, near);
}
void TickMeteors(Vector3 eye, Vector3 up, WeatherKind kind, float dt)
{
if (kind != WeatherKind.Meteors || DayNight.Dark < 0.4f || Time.time < _nextMeteor) return;
_nextMeteor = Time.time + Random.Range(0.1f, 0.7f);
var side = Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized;
var at = eye + (up * Random.Range(0.45f, 1f) + side).normalized * 320f;
var dir = (Vector3.ProjectOnPlane(Random.onUnitSphere, up).normalized - up * 0.35f).normalized;
var c = Color.Lerp(new Color(1.6f, 1.5f, 1.2f), new Color(0.9f, 1.4f, 1.8f), Random.value);
Fx.Emit(_meteor, at, dir * Random.Range(120f, 200f), Random.Range(2.2f, 3.6f), c * 1.6f, Random.Range(0.6f, 1.1f));
if (Random.value < 0.08f) Sfx.Play("meteor_whoosh", 0.25f, Random.Range(0.8f, 1.2f), 0.1f, 2f);
}
// ───────────────────────── twister ─────────────────────────
void TickTwister(TeamState ts, Vector3 eye)
{
bool on = ts && ts.IsSpawned && ts.TwisterOn;
if (!on)
{
if (_twisterWas) { _twisterWas = false; Volume(ref _twisterLoop, "twister_loop", 0f); }
return;
}
double now = ts.Now;
var at = ts.TwisterPos(now);
var up = Planet.Up(at);
float age = (float)(now - ts.TwisterAt.Value);
// it spins up and dies away again
float life = Mathf.Clamp01(age / 4f) * Mathf.Clamp01((TeamState.TwisterLife - age) / 6f);
_twister.position = at;
_twister.rotation = Quaternion.FromToRotation(Vector3.up, up);
if (!_twisterWas) { _twisterWas = true; _lastTwister = at; }
_funnelDue += Time.deltaTime * 420f * life;
for (; _funnelDue >= 1f; _funnelDue -= 1f)
{
float h = Random.Range(0f, 1f);
float a = Random.Range(0f, Mathf.PI * 2f);
float r = Mathf.Lerp(0.6f, 2.2f, h) * Random.Range(0.8f, 1.2f);
var local = new Vector3(Mathf.Cos(a) * r, h * 3f, Mathf.Sin(a) * r);
var col = Color.Lerp(new Color(0.5f, 0.52f, 0.44f, 0.75f), new Color(0.72f, 0.74f, 0.7f, 0.55f), h);
Fx.Emit(_funnel, local, Vector3.up * Random.Range(5f, 7f), Random.Range(1.3f, 2.4f), col);
if (Random.value < 0.35f)
Fx.Emit(_debris, new Vector3(Mathf.Cos(a), 0.2f, Mathf.Sin(a)) * 1.2f, Vector3.up * Random.Range(3f, 9f), Random.Range(0.06f, 0.14f), Fx.Clip());
}
Meadow.Vortex(at, life, TeamState.TwisterRadius * 1.6f);
// the grass in its path is torn out: gone, and nobody is paid for it
if (life > 0.3f && (at - _lastTwister).sqrMagnitude > 0.25f)
{
MowMap.Cut(_lastTwister, at, TeamState.TwisterRadius * 1.1f);
_lastTwister = at;
}
else if (life <= 0.3f) _lastTwister = at;
if (!_twisterLoop) { Volume(ref _twisterLoop, "twister_loop", 0f); if (_twisterLoop) { _twisterLoop.transform.SetParent(_twister, false); _twisterLoop.spatialBlend = 0.95f; _twisterLoop.maxDistance = 110f; _twisterLoop.minDistance = 6f; } }
if (_twisterLoop) _twisterLoop.volume = life * 0.9f * Sfx.SfxVolume;
var me = PlayerAgent.Local;
if (me && !me.Vehicle && Time.time >= _flingAt)
{
var off = Vector3.ProjectOnPlane(me.transform.position - at, up);
if (off.magnitude < TeamState.TwisterRadius + 0.8f && life > 0.5f)
{
_flingAt = Time.time + 3f;
var swirl = Vector3.Cross(up, off.normalized);
me.Fling(up * 13f + swirl * 9f + off.normalized * 6f);
Sfx.Play("throw_whoosh", 0.9f, 0.7f);
Assistant.Say("asst_thrown"); Hud.Toast(Loc.T("Whoa! The twister threw you."), Hud.ToastKind.Warn);
}
}
else if (me && me.Vehicle && Vector3.Distance(me.transform.position, at) < TeamState.TwisterRadius + 3f) CameraFx.Shake(0.05f);
}
// ───────────────────────── the saucer ─────────────────────────
// the saucer: the model's parts, its glow, its beam
Transform _ufoRing, _beamCone;
Quaternion _ringRest;
Material _bulbMat, _domeMat, _emitMat, _beamMat;
Vector3 _ufoVel, _ufoLast;
float _ufoYaw, _ringSpin;
bool _ufoLanded, _ufoGone;
const float Hover = 21f;
void TickUfo(TeamState ts, Vector3 eye)
{
bool on = ts && ts.IsSpawned && ts.UfoOn;
if (!on)
{
if (_ufo && _ufo.gameObject.activeSelf)
{
_ufo.gameObject.SetActive(false);
Volume(ref _ufoHum, "ufo_hum_loop", 0f);
Volume(ref _ufoBeam, "ufo_beam_loop", 0f);
}
return;
}
if (!_ufo) BuildSaucer();
if (!_ufo.gameObject.activeSelf) { _ufo.gameObject.SetActive(true); _ufoLanded = _ufoGone = false; _ufoVel = Vector3.zero; }
double now = ts.Now;
float t = (float)(now - ts.UfoAt.Value);
var spot = ts.UfoSpot.Value;
var up = Planet.Up(spot);
int seed = (int)(ts.UfoAt.Value * 997d) ^ 0x5F3759;
if (_circleOf != ts.UfoAt.Value)
{
_circleOf = ts.UfoAt.Value; _circleDone = 0; _ufoAt = spot;
_ufoLanded = _ufoGone = false;
Sfx.PlayAt("meteor_whoosh", spot + up * 120f, 0.8f, 0.55f, 0.05f);
}
float dt = Mathf.Max(1e-4f, Time.deltaTime);
Vector3 pos;
float beam = 0f, stretch = 0f;
const float A = TeamState.UfoArrive, D = TeamState.UfoDraw;
var side = Vector3.Cross(up, Vector3.forward).normalized;
var fwd = Vector3.Cross(side, up);
if (t < A)
{
// swoops in on a curve, brakes hard and bobs to a stop over the field
float k = Mathf.Clamp01(t / A);
float e = 1f - Mathf.Pow(1f - k, 3.2f);
var p0 = spot + up * 260f + side * 340f + fwd * 160f;
var p1 = spot + up * 70f + side * 60f - fwd * 30f;
var p2 = spot + up * Hover;
pos = (1 - e) * (1 - e) * p0 + 2f * (1 - e) * e * p1 + e * e * p2;
// the last moment: a little overshoot down and back
if (k > 0.82f) pos += up * Mathf.Sin((k - 0.82f) / 0.18f * Mathf.PI) * -1.6f;
}
else if (t < A + D)
{
if (!_ufoLanded)
{
_ufoLanded = true;
var g = Planet.Surface(spot);
Fx.Slam(g, Planet.Up(g), 9f);
Fx.Dust(g, 1.2f, 30);
}
float f = (t - A) / D;
TeamState.CropCircle(spot, seed, f, ref _circleDone);
// glides over the line it is drawing, on a soft spring rather than a lerp
var target = TeamState.CircleAt(spot, seed, f);
_ufoAt = Vector3.SmoothDamp(_ufoAt, target, ref _ufoVel, 0.55f, 40f, dt);
pos = _ufoAt + Planet.Up(_ufoAt) * (Hover + Mathf.Sin(t * 1.7f) * 0.7f + Mathf.Sin(t * 0.63f) * 0.4f);
beam = Mathf.Clamp01((t - A) * 1.5f) * Mathf.Clamp01((A + D - t) * 1.5f);
}
else
{
TeamState.CropCircle(spot, seed, 1f, ref _circleDone);
float k = (t - A - D) / TeamState.UfoLeave;
var hold = _ufoAt + Planet.Up(_ufoAt) * Hover;
if (k < 0.18f)
{
// crouches before the jump
pos = hold - Planet.Up(_ufoAt) * Mathf.Sin(k / 0.18f * Mathf.PI * 0.5f) * 2.2f;
}
else
{
if (!_ufoGone)
{
_ufoGone = true;
Sfx.PlayAt("meteor_whoosh", hold, 1f, 1.35f, 0.05f);
Fx.Sparkles(hold - Planet.Up(_ufoAt) * 2f, 40, new Color(0.5f, 1f, 0.85f));
}
float j = (k - 0.18f) / 0.82f;
pos = hold - Planet.Up(_ufoAt) * 2.2f + Planet.Up(_ufoAt) * (j * j * j * 900f) + side * j * j * 80f;
stretch = Mathf.Clamp01(j * 3f) * Mathf.Clamp01((1f - j) * 4f + 0.4f);
}
}
// banks into where it's going, turns slowly, wobbles
var vel = (pos - _ufoLast) / dt;
_ufoLast = pos;
var pu = Planet.Up(pos);
var flatVel = Vector3.ProjectOnPlane(vel, pu);
float bank = Mathf.Clamp(flatVel.magnitude * 0.35f, 0f, 22f);
var bankAxis = flatVel.sqrMagnitude > 1e-3f ? Vector3.Cross(pu, flatVel.normalized) : side;
_ufoYaw += dt * (25f + beam * 45f);
var level = Quaternion.FromToRotation(Vector3.up, pu);
var wobble = Quaternion.Euler(Mathf.Sin(t * 0.9f) * 3f, 0f, Mathf.Cos(t * 1.1f) * 3f);
_ufo.SetPositionAndRotation(pos, Quaternion.AngleAxis(bank, bankAxis) * level * wobble * Quaternion.AngleAxis(_ufoYaw, Vector3.up));
_ufo.localScale = new Vector3(1f - stretch * 0.35f, 1f + stretch * 1.6f, 1f - stretch * 0.35f);
// the rim spins up while it works; the bulbs breathe and flash in turn; the belly glows with the beam
_ringSpin += dt * (90f + beam * 260f);
if (_ufoRing)
{
// round the saucer's own up, whatever the import did to the ring's axes
var axis = _ufoRing.parent ? _ufoRing.parent.InverseTransformDirection(_ufo.up).normalized : Vector3.up;
_ufoRing.localRotation = Quaternion.AngleAxis(_ringSpin, axis) * _ringRest;
}
float pulse = 0.6f + 0.4f * Mathf.Sin(t * 6f);
if (_bulbMat) _bulbMat.SetColor("_EmissionColor", Color.Lerp(new Color(1f, 0.6f, 0.2f), new Color(0.4f, 1f, 0.8f), 0.5f + 0.5f * Mathf.Sin(t * 1.3f)) * (2.5f + pulse * 4f));
if (_domeMat) _domeMat.SetColor("_EmissionColor", new Color(0.2f, 0.9f, 0.7f) * (0.8f + pulse * 0.8f));
if (_emitMat) _emitMat.SetColor("_EmissionColor", new Color(0.4f, 1f, 0.55f) * (0.6f + beam * 7f));
if (_ufoLights != null)
for (int i = 0; i < _ufoLights.Length; i++)
{
float lit = Mathf.Repeat(t * 3f - i / (float)_ufoLights.Length, 1f) < 0.3f ? 1f : 0.25f;
_ufoLights[i].transform.localScale = Vector3.one * (0.35f + lit * 0.25f);
}
_ufoLight.intensity = beam * 80f;
// the beam: a cone of light down to the meadow, and the grass swirling up inside it
float drop = Mathf.Max(1f, Vector3.Dot(pos - Planet.Surface(pos), pu) - 1.2f);
if (_beamCone)
{
_beamCone.gameObject.SetActive(beam > 0.01f);
_beamCone.localScale = new Vector3(1f, drop / Mathf.Max(0.2f, _ufo.localScale.y), 1f);
if (_beamMat) _beamMat.SetFloat("_Power", beam);
}
if (beam > 0.05f)
{
var down = -pu;
_beamDue += dt * 260f * beam;
for (; _beamDue >= 1f; _beamDue -= 1f)
{
float along = Random.value;
var at = pos + down * (1.2f + along * drop) + Random.insideUnitSphere * Mathf.Lerp(1.5f, 5f, along);
Fx.Emit(_beam, at, -down * Random.Range(2f, 5f), Random.Range(1.4f, 2.8f), new Color(0.6f, 1.6f, 1.4f, 0.35f));
}
if (Random.value < dt * 30f * beam)
{
var g = Planet.Surface(pos + Random.insideUnitSphere.Flat() * 4f);
Fx.Droplets(g + Planet.Up(g) * 0.2f, Planet.Up(g) * 2f, 4);
}
}
Volume(ref _ufoHum, "ufo_hum_loop", 0f);
if (_ufoHum && _ufoHum.transform.parent != _ufo) { _ufoHum.transform.SetParent(_ufo, false); _ufoHum.spatialBlend = 0.95f; _ufoHum.maxDistance = 220f; _ufoHum.minDistance = 10f; }
if (_ufoHum) { _ufoHum.volume = 0.85f * Sfx.SfxVolume; _ufoHum.pitch = 0.9f + Mathf.Clamp01(vel.magnitude / 60f) * 0.5f + beam * 0.1f; }
Volume(ref _ufoBeam, "ufo_beam_loop", 0f);
if (_ufoBeam && _ufoBeam.transform.parent != _ufo) { _ufoBeam.transform.SetParent(_ufo, false); _ufoBeam.spatialBlend = 0.95f; _ufoBeam.maxDistance = 120f; _ufoBeam.minDistance = 8f; }
if (_ufoBeam) _ufoBeam.volume = beam * 0.75f * Sfx.SfxVolume;
}
/// <summary>The saucer from its model: the rim (it spins), the bulbs, the glass dome and the belly emitter glow.</summary>
void BuildSaucer()
{
var model = AssetBank.I.Model("SM_Ufo");
if (!model) { BuildPrimitiveSaucer(); return; }
_ufo = new GameObject("Saucer").transform;
_ufo.SetParent(transform, false);
var go = Instantiate(model, _ufo);
go.transform.localPosition = Vector3.zero;
foreach (var c in go.GetComponentsInChildren<Collider>(true)) Destroy(c);
var lit = Shader.Find("Universal Render Pipeline/Lit");
_bulbMat = new Material(lit) { color = new Color(1f, 0.8f, 0.45f) };
_bulbMat.EnableKeyword("_EMISSION");
_domeMat = new Material(lit) { color = new Color(0.32f, 0.92f, 0.82f) };
_domeMat.SetFloat("_Smoothness", 0.95f);
_domeMat.EnableKeyword("_EMISSION");
_emitMat = new Material(lit) { color = new Color(0.45f, 1f, 0.55f) };
_emitMat.EnableKeyword("_EMISSION");
foreach (var tr in go.GetComponentsInChildren<Transform>(true))
{
var r = tr.GetComponent<Renderer>();
switch (tr.name)
{
case "Ring": _ufoRing = tr; _ringRest = tr.localRotation; break;
case "Bulbs": if (r) r.sharedMaterial = _bulbMat; break;
case "Dome": if (r) r.sharedMaterial = _domeMat; break;
case "Emitter": if (r) r.sharedMaterial = _emitMat; break;
}
if (r) r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
}
_ufoLights = new Renderer[0];
// the cone: 2.4 m across at the ship, 7 m on the ground, one metre tall (stretched to the drop)
var cone = new GameObject("BeamCone");
cone.transform.SetParent(_ufo, false);
cone.transform.localPosition = new Vector3(0f, -1.3f, 0f);
cone.AddComponent<MeshFilter>().sharedMesh = Cone(1.2f, 3.5f, 40);
var mr = cone.AddComponent<MeshRenderer>();
var bm = AssetBank.I.Mat("M_UfoBeam");
_beamMat = bm ? new Material(bm) : null;
if (_beamMat) _beamMat.SetColor("_BaseColor", new Color(0.45f, 1f, 0.8f, 0.32f));
mr.sharedMaterial = _beamMat;
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
mr.receiveShadows = false;
_beamCone = cone.transform;
cone.SetActive(false);
_ufoLight = new GameObject("Beam").AddComponent<Light>();
_ufoLight.transform.SetParent(_ufo, false);
_ufoLight.transform.localPosition = new Vector3(0f, -1.6f, 0f);
_ufoLight.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
_ufoLight.type = LightType.Spot;
_ufoLight.spotAngle = 32f;
_ufoLight.range = 60f;
_ufoLight.color = new Color(0.5f, 1f, 0.85f);
_ufoLight.shadows = LightShadows.None;
}
/// <summary>An open cone hanging down from y 0 (radius top) to y -1 (radius bottom); uv.y is 0 at the ground.</summary>
static Mesh Cone(float top, float bottom, int n)
{
var v = new Vector3[(n + 1) * 2];
var nm = new Vector3[v.Length];
var uv = new Vector2[v.Length];
var tri = new int[n * 6];
for (int i = 0; i <= n; i++)
{
float a = i * Mathf.PI * 2f / n;
var d = new Vector3(Mathf.Cos(a), 0f, Mathf.Sin(a));
v[i * 2] = d * top;
v[i * 2 + 1] = d * bottom + Vector3.down;
var slope = new Vector3(d.x, (bottom - top), d.z).normalized;
nm[i * 2] = nm[i * 2 + 1] = slope;
uv[i * 2] = new Vector2(i / (float)n, 1f);
uv[i * 2 + 1] = new Vector2(i / (float)n, 0f);
}
for (int i = 0; i < n; i++)
{
int k = i * 6, a0 = i * 2;
tri[k] = a0; tri[k + 1] = a0 + 2; tri[k + 2] = a0 + 1;
tri[k + 3] = a0 + 1; tri[k + 4] = a0 + 2; tri[k + 5] = a0 + 3;
}
var m = new Mesh { name = "BeamCone", vertices = v, normals = nm, uv = uv, triangles = tri };
m.bounds = new Bounds(new Vector3(0f, -0.5f, 0f), new Vector3(bottom * 2f, 1f, bottom * 2f));
return m;
}
void BuildPrimitiveSaucer()
{
_ufo = new GameObject("Saucer").transform;
_ufo.SetParent(transform, false);
var shader = Shader.Find("Universal Render Pipeline/Lit");
var hull = new Material(shader) { color = new Color(0.62f, 0.66f, 0.7f) };
hull.SetFloat("_Metallic", 0.85f);
hull.SetFloat("_Smoothness", 0.75f);
var glass = new Material(shader) { color = new Color(0.3f, 0.95f, 0.8f) };
glass.SetFloat("_Smoothness", 0.95f);
glass.EnableKeyword("_EMISSION");
glass.SetColor("_EmissionColor", new Color(0.2f, 0.9f, 0.7f) * 1.5f);
_ufoGlow = new Material(shader) { color = new Color(1f, 0.85f, 0.3f) };
_ufoGlow.EnableKeyword("_EMISSION");
_ufoGlow.SetColor("_EmissionColor", new Color(1f, 0.8f, 0.25f) * 4f);
Part(PrimitiveType.Sphere, new Vector3(0f, 0f, 0f), new Vector3(10f, 1.3f, 10f), hull);
Part(PrimitiveType.Cylinder, new Vector3(0f, -0.15f, 0f), new Vector3(10.6f, 0.12f, 10.6f), hull);
Part(PrimitiveType.Sphere, new Vector3(0f, 0.7f, 0f), new Vector3(4.2f, 2.6f, 4.2f), glass);
Part(PrimitiveType.Cylinder, new Vector3(0f, -0.65f, 0f), new Vector3(3f, 0.25f, 3f), glass);
const int n = 14;
_ufoLights = new Renderer[n];
for (int i = 0; i < n; i++)
{
float a = i * Mathf.PI * 2f / n;
_ufoLights[i] = Part(PrimitiveType.Sphere, new Vector3(Mathf.Cos(a) * 5.05f, -0.15f, Mathf.Sin(a) * 5.05f), Vector3.one * 0.45f, _ufoGlow);
}
_ufoLight = new GameObject("Beam").AddComponent<Light>();
_ufoLight.transform.SetParent(_ufo, false);
_ufoLight.transform.localPosition = new Vector3(0f, -0.8f, 0f);
_ufoLight.transform.localRotation = Quaternion.Euler(90f, 0f, 0f);
_ufoLight.type = LightType.Spot;
_ufoLight.spotAngle = 38f;
_ufoLight.range = 40f;
_ufoLight.color = new Color(0.5f, 1f, 0.85f);
_ufoLight.shadows = LightShadows.None;
}
Renderer Part(PrimitiveType type, Vector3 at, Vector3 size, Material mat)
{
var go = GameObject.CreatePrimitive(type);
Destroy(go.GetComponent<Collider>());
go.transform.SetParent(_ufo, false);
go.transform.localPosition = at;
go.transform.localScale = size;
var r = go.GetComponent<Renderer>();
r.sharedMaterial = mat;
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
return r;
}
// ───────────────────────── sound ─────────────────────────
static bool s_missing(string clip) => !AssetBank.I || !AssetBank.I.Clip(clip);
/// <summary>A flat (not placed) weather loop at a volume: started the first time it's wanted, left playing silent after.</summary>
void Volume(ref AudioSource s, string clip, float vol)
{
if (!s)
{
if (vol <= 0.001f && clip != "twister_loop" && clip != "ufo_hum_loop" && clip != "ufo_beam_loop") return;
if (s_missing(clip)) return;
s = Sfx.Loop(clip, transform, 0f);
if (!s) return;
s.spatialBlend = 0f;
}
s.volume = vol * Sfx.SfxVolume;
}
/// <summary>Acid rain scorching a patch: a hiss and a puff of yellow-green steam.</summary>
public static void Sizzle(Vector3 at)
{
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam && (cam.transform.position - at).sqrMagnitude > 60f * 60f) return;
Sfx.PlayAt("acid_sizzle", at, 0.45f, 1f, 0.15f, 0.25f);
Fx.Steam(at, 0.6f);
}
}
}

View File

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1a5772efaa1fe2540869ea508f74941a