using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
namespace GrassCutter
{
///
/// 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.
///
[DefaultExecutionOrder(-60)]
public class GrassField : MonoBehaviour
{
public static GrassField Instance { get; private set; }
public Material furMat, strandMat, hempMat, flowerMat;
public Mesh hempMesh, flowerMesh;
/// By : the plant up close and the same plant further off.
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 };
/// 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.
public static float FurReach = 1f;
/// The share of blades drawn (graphics settings: grass).
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;
/// The floor under the strands is seen up close: a finer grid, so no bump of the ground between its corners shows through.
const int FloorSide = 37;
const float SeamBand = 5f;
/// Mown ground stays visible this far, on this many of the nearest sectors.
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; }
/// The strand texture tiles every this many metres (256 px, a strand every ~3 px: ~1200 strands per m²).
const float FurTile = 2.5f;
/// The pile never grows taller than this (just under the crew's eyes).
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 _mpbs = new List();
readonly List _near = new List();
readonly List _worked = new List();
readonly Plane[] _frustum = new Plane[6];
int _mpbUsed, _here = -1;
int _deckHash;
/// The grass's blocks were cleared (the ball changed size): the deck goes back in next frame.
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);
}
/// Meadow height in metres.
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);
}
/// Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.
void GatherNear(int here)
{
_near.Clear();
var from = HexGrid.Get(here);
_near.Add(from);
var seen = new HashSet { 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++];
}
/// The strand texture lies on the cube face under the camera: no seam for as far as the pile reaches.
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);
}
/// The pile over a whole sector. onlyWorked: past the grass, just the floor where something was cut.
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);
}
/// The window of a sector's cells that the camera's ring can touch. False when there is none.
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 ─────────────────────────
/// 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).
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;
}
/// One strand: a ribbon with a row of two vertices per entry; x = side (-1..1), y = along the strand.
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;
}
///
/// 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.
///
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;
}
}
}