using System.Collections.Generic; using UnityEngine; namespace GrassCutter { /// /// 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 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. /// [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; /// More than trees and spires: field stones, slabs and crystals (they stay), and mushrooms, a stump and /// bulb plants (they come down with the trees when their sector is mown clean). public GameObject[] stones = new GameObject[0], growths = new GameObject[0]; 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 _rocks = new List(); /// The trees and bushes standing in each sector, by index into the rocks: they go when it's mown clean. readonly Dictionary> _plants = new Dictionary>(); /// A plant this close to the camera falls over when its sector is finished; further off it just isn't there any more. const float FellSeen = 260f; Transform _root, _skin; /// /// A film looking at the ball from far off (the ending's rise and orbit): the skin is an even mesh fixed to the ball /// instead of the rings gathered under the lens, whose coarse far rings swim over the hills as the lens moves round. /// public static bool FarSkin; MeshFilter _skinMf; Mesh _nearSkin, _farSkin; 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(); gameObject.AddComponent(); } void OnDestroy() { MowMap.Bared -= Clear; MowMap.Restarted -= Regrow; Planet.Rescaled -= Rebuild; } /// 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. 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(); 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(); } /// A sector has been mown clean: the trees and bushes on it come down. 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); } } /// The tree or bush still standing nearest a point, and the sector it's in (for the test bot). Zero if none. 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; } /// A new game on a new planet: everything stands again. 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(true)) c.enabled = true; r.go.SetActive(false); } } /// It leans, goes over faster and faster, and is gone in a puff of dust where it lands. System.Collections.IEnumerator Fell(GameObject go, Vector3 foot, float radius) { go.SetActive(true); foreach (var c in go.GetComponentsInChildren()) 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); if (_skinMf) { if (FarSkin && !_farSkin) _farSkin = BuildEvenSkin(); var want = FarSkin ? _farSkin : _nearSkin; if (_skinMf.sharedMesh != want) _skinMf.sharedMesh = want; } _skin.rotation = FarSkin ? Quaternion.identity : 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); } /// A slice of the rocks each frame: only the ones nearby are drawn at all. 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 { 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(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; _skinMf = go.AddComponent(); _skinMf.sharedMesh = m; _nearSkin = m; var mr = go.AddComponent(); mr.sharedMaterial = soil; mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; _skin = go.transform; } /// The ball's skin with every vertex about the same distance apart (a cube blown up into a sphere), facing out. static Mesh BuildEvenSkin() { const int N = 160; var verts = new List(6 * (N + 1) * (N + 1)); var tris = new List(6 * N * N * 6); Vector3[] fwd = { Vector3.up, Vector3.down, Vector3.left, Vector3.right, Vector3.forward, Vector3.back }; foreach (var f in fwd) { var a = Mathf.Abs(f.y) > 0.5f ? Vector3.right : Vector3.up; var b = Vector3.Cross(f, a); int o = verts.Count; for (int y = 0; y <= N; y++) for (int x = 0; x <= N; x++) { // tangent spacing evens the cells out towards the cube's edges float u = Mathf.Tan((x / (float)N * 2f - 1f) * Mathf.PI * 0.25f); float v = Mathf.Tan((y / (float)N * 2f - 1f) * Mathf.PI * 0.25f); verts.Add((f + a * u + b * v).normalized); } for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) { int i0 = o + y * (N + 1) + x, i1 = i0 + 1, i2 = i0 + N + 1, i3 = i2 + 1; AddOut(verts, tris, i0, i2, i1); AddOut(verts, tris, i1, i2, i3); } } var m = new Mesh { name = "PlanetSkinEven", indexFormat = UnityEngine.Rendering.IndexFormat.UInt32 }; m.SetVertices(verts); m.SetTriangles(tris, 0); m.bounds = new Bounds(Vector3.zero, Vector3.one * Planet.Radius * 3f); return m; } static void AddOut(List v, List t, int a, int b, int c) { // Unity's front face: the side the clockwise normal points to; it must point out of the ball if (Vector3.Dot(Vector3.Cross(v[b] - v[a], v[c] - v[a]), v[a]) < 0f) { int s = b; b = c; c = s; } t.Add(a); t.Add(b); t.Add(c); } 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); } } Scatter(); } /// Stones and odd growths over the meadow: a few round the clearing, the rest anywhere on the ball. A separate /// sequence of its own, so the spires and the trees stand where they always have. void Scatter() { var rng = new System.Random(9311); float R(float a, float b) => a + (float)rng.NextDouble() * (b - a); bool any = false; foreach (var g in stones) any |= g; foreach (var g in growths) any |= g; if (!any) return; GameObject Pick(GameObject[] set) => set.Length > 0 ? set[rng.Next(set.Length)] : null; // close by, where the crew sees them from the first minute for (int i = 0; i < 26; i++) { float a = R(0f, Mathf.PI * 2f), d = R(55f, 150f); var dir = Planet.FromBase(Mathf.Cos(a) * d, Mathf.Sin(a) * d); bool stone = rng.NextDouble() < 0.5; var p = Pick(stone ? stones : growths); if (!p) continue; // the bulb plants are walked through; everything else is solid Place(p, dir, R(0f, 360f), stone ? R(0.8f, 1.6f) : R(0.9f, 1.5f), p.name != "SM_BulbPlants", !stone); } int far = Mathf.Max(40, Mathf.RoundToInt(420 * Planet.Scale * Planet.Scale)); for (int i = 0; i < far; i++) { var dir = new Vector3(R(-1f, 1f), R(-1f, 1f), R(-1f, 1f)).normalized; if (dir.y > 0.985f) continue; bool stone = rng.NextDouble() < 0.55; var p = Pick(stone ? stones : growths); if (!p) continue; // they come in little clusters of two or three var e1 = Vector3.Cross(dir, Vector3.right).normalized; var e2 = Vector3.Cross(dir, e1); int n = rng.Next(1, 4); for (int k = 0; k < n; k++) { var at = (dir + (e1 * R(-9f, 9f) + e2 * R(-9f, 9f)) / Planet.Radius).normalized; Place(p, at, R(0f, 360f), stone ? R(0.7f, 2.2f) : R(0.8f, 1.7f), p.name != "SM_BulbPlants", !stone); } } } /// 70 m round each far station, on any ball. 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(); 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()) mf.gameObject.AddComponent().sharedMesh = mf.sharedMesh; if (plant) { int sector = HexGrid.SectorAt(dir); if (!_plants.TryGetValue(sector, out var list)) _plants[sector] = list = new List(); 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; } /// Is a rock standing on this spot? 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; } } }