using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using UnityEngine; namespace GrassCutter { /// /// 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. /// public static class MowMap { public const int Res = 128; /// The last scraps of a sector this nearly done go with the stroke that got it there. // the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent const float DoneAt = 0.93f; const int MaxStampsPerCut = 28, MaxOpen = 300; /// Trim waits for this many more open maps than it keeps, so it runs now and then, not at every sector. const int TrimSlack = 80; /// Less than this left in a cell is not worth a row of its own. 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; /// Its bytes, unsqueezed, while a worker packs them (null otherwise). public byte[] raw; 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 s_masks = new Dictionary(); static readonly Dictionary> s_blocks = new Dictionary>(); static readonly HashSet s_deck = new HashSet(); static readonly List s_walk = new List(); static readonly List s_touched = new List(); static Texture2D s_none, s_full; /// This peer has just mown a sector clean. public static event Action SectorDone; /// A sector is finished, by anyone, or by a save as it loads: the trees and bushes on it go too. public static event Action Bared; /// Everything is uncut again, so whatever went with a finished sector stands again. public static event Action Restarted; public static IEnumerable All => s_masks.Values; /// The map of a sector with nothing on it. public static Texture2D Blank => s_none; /// The look of a sector mown to the last blade (with no rock in it): nothing is left standing on it. public static Texture2D Full => s_full; public static int Started { get; private set; } public static int Finished { get; private set; } // ───────────────────────── sessions ───────────────────────── /// A new game: nothing is cut yet (the rocks and the base stay). 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 ───────────────────────── /// Nothing grows inside this rectangle of the base (axis-aligned, only near the pole). public static void Block(Vector3 center, Vector2 half) => Add(new Bare { center = center, half = half }, half.magnitude); /// Nothing grows under this rock. public static void BlockRound(Vector3 center, float radius) => Add(new Bare { round = true, center = center, dir = Planet.Up(center), radius = radius }, radius); /// The deck can only grow: new tiles join the blocks. public static void SetDeck(IEnumerable 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(); 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); } } /// The map was just made: a cell is the sector's exactly when it still has grass. /// Only the look: the counts came from a packed copy that already has the rock in it. static void Apply(Mask m, Bare b, bool fresh = false, bool look = false) { 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)); // plain numbers, not vectors: a big rock covers thousands of cells, and a fresh sector may have a dozen of them float rr = Planet.Radius * Planet.Radius, r2 = b.radius * b.radius; var c = s.c * Planet.Radius; var e1 = s.e1; var e2 = s.e2; var pc = Planet.Center; for (int z = z0; z <= z1; z++) { float v = Cell(m, z); float rx = c.x + e2.x * v, ry = c.y + e2.y * v, rz = c.z + e2.z * v; for (int x = x0; x <= x1; x++) { int i = z * Res + x; if (m.rg[i * 2 + 1] != 0) continue; float u = Cell(m, x); float fx = rx + e1.x * u, fy = ry + e1.y * u, fz = rz + e1.z * u; bool hit; if (b.round) { // a rock is measured along the ground: the frame is flat, the soil isn't float inv = 1f / Mathf.Sqrt(fx * fx + fy * fy + fz * fz); float dx = fx * inv - b.dir.x, dy = fy * inv - b.dir.y, dz = fz * inv - b.dir.z; hit = (dx * dx + dy * dy + dz * dz) * rr < r2; } else hit = Mathf.Abs(pc.x + fx - b.center.x) < b.half.x && Mathf.Abs(pc.z + fz - b.center.z) < b.half.y; if (!hit) continue; m.rg[i * 2 + 1] = 255; m.show = true; if (look) continue; // nobody can cut what stands under a rock: it isn't part of the sector's grass if (fresh ? m.left[i] != 0 : 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; /// The sector's map ready to read and write. Null when it is finished: nothing left to do there. 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; var s = m.s; var c = s.c * Planet.Radius; // the sector is a convex patch of the flat frame, so each row of it is one run of cells: the borders give its // ends, and only the cells at the ends are tested one by one (testing all 16k of them stalled the frame) for (int z = 0; z < Res; z++) { var row = c + s.e2 * Cell(m, z); float lo = float.NegativeInfinity, hi = float.PositiveInfinity; bool none = false; foreach (var b in s.borders) { float a = Vector3.Dot(row, b), k = Vector3.Dot(s.e1, b); if (Mathf.Abs(k) < 1e-6f) { if (a > 0f) none = true; continue; } if (k > 0f) hi = Mathf.Min(hi, -a / k); else lo = Mathf.Max(lo, -a / k); } if (none) continue; int xa = Mathf.CeilToInt(Mathf.Clamp((lo + s.half) / m.cell - 0.5f, -1f, Res)); int xb = Mathf.FloorToInt(Mathf.Clamp((hi + s.half) / m.cell - 0.5f, -1f, Res)); xa = Mathf.Clamp(xa, 0, Res - 1); xb = Mathf.Clamp(xb, 0, Res - 1); if (xa > xb) continue; while (xa <= xb && !Owned(s, xa, z, m)) xa++; while (xb >= xa && !Owned(s, xb, z, m)) xb--; if (xa > xb) continue; while (xa > 0 && Owned(s, xa - 1, z, m)) xa--; while (xb < Res - 1 && Owned(s, xb + 1, z, m)) xb++; for (int x = xa; x <= xb; x++) m.left[z * Res + x] = 65535; owned += xb - xa + 1; } 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, true); if (m.packed != null) m.total = kept; } } /// Just the look of a packed sector, for its texture: the grass counts stay packed. static void Look(Mask m) { var raw = m.raw; if (raw == null && m.packed != null) raw = Inflate(m.packed, s_inflate); if (raw == null) { Unpack(m); return; } m.rg = new byte[Res * Res * 2]; for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i]; m.show = true; MarkBare(m); } /// The packed copy keeps the grass, not where nothing grows: the blocks mark that again on a new look. static void MarkBare(Mask m) { if (!s_blocks.TryGetValue(m.s.id, out var list)) return; foreach (var b in list) Apply(m, b, false, true); } static void Unpack(Mask m) { // bytes being squeezed right now, or squeezed ones: no fresh start needed, they say everything var raw = m.raw; if (raw == null && m.packed != null) raw = Inflate(m.packed, s_inflate); if (raw == null) { Fresh(m); return; } m.left = new ushort[Res * Res]; bool had = m.rg != null && m.tex; bool fresh = m.rg == null; if (fresh) m.rg = new byte[Res * Res * 2]; 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]; if (fresh) MarkBare(m); if (!had) m.show = true; } static void Pack(Mask m) { m.packed = Deflate(Raw(m)); m.dirty = false; } static byte[] Raw(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]; return raw; } static byte[] Deflate(byte[] raw) { using (var mem = new MemoryStream()) { using (var z = new DeflateStream(mem, System.IO.Compression.CompressionLevel.Fastest, true)) z.Write(raw, 0, raw.Length); return mem.ToArray(); } } /// A sector packed off the main thread for a save: its bytes go back on the mask if nothing changed since. sealed class Packing { public Mask m; public byte[] raw, packed; } static readonly System.Collections.Concurrent.ConcurrentQueue s_packed = new System.Collections.Concurrent.ConcurrentQueue(); static void TakePacked() { while (s_packed.TryDequeue(out var p)) if (p.m.packed == null && !p.m.dirty && p.m.left != null) p.m.packed = p.packed; while (s_squeezed.TryDequeue(out var q)) { // the bytes it squeezed are still the sector's: they become its packed copy if (!ReferenceEquals(q.m.raw, q.raw)) continue; q.m.raw = null; if (q.m.packed == null && !q.m.dirty) q.m.packed = q.packed; } } sealed class Squeeze { public Mask m; public byte[] raw, packed; } static readonly System.Collections.Concurrent.ConcurrentQueue s_squeezed = new System.Collections.Concurrent.ConcurrentQueue(); /// Puts a sector's map away: its bytes go to a worker to be squeezed, the mask lets go of its grass counts. static void PutAway(Mask m) { if (m.dirty || (m.keep && m.packed == null && m.raw == null)) { var job = new Squeeze { m = m, raw = Raw(m) }; m.raw = job.raw; m.packed = null; m.dirty = false; System.Threading.Tasks.Task.Run(() => { job.packed = Deflate(job.raw); s_squeezed.Enqueue(job); }); } m.left = null; } /// The main thread's inflate buffer: what it holds is copied out at once. static readonly byte[] s_inflate = new byte[Res * Res * 3]; static byte[] Inflate(byte[] packed, byte[] into = null) { var raw = into ?? 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; } static readonly List s_trim = new List(); /// Too many maps in memory: squeeze the ones furthest from here. public static void Trim(Vector3 dir) { TakePacked(); int open = 0; foreach (var m in s_masks.Values) if (m.left != null) open++; if (open <= MaxOpen + TrimSlack) return; s_trim.Clear(); foreach (var m in s_masks.Values) if (m.left != null) s_trim.Add(m); s_trim.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude)); // 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 for (int i = 0; i < open - MaxOpen; i++) PutAway(s_trim[i]); s_trim.Clear(); } // ───────────────────────── cutting ───────────────────────── /// /// 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. /// public static float Cut(Vector3 from, Vector3 to, float width, float minSweep = 0f, float paint = 0f, bool blade = false) { 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); // a machine's header shows the strip it took and nothing ahead of it; a stroke shows round ends if (blade) { if (len > 1e-3f) foreach (int id in s_touched) { var m = Open(id); if (m != null) PaintStrip(m, a, b, half); } } else { 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; } /// /// 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. /// 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; } /// /// 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. /// public static void Rows(int id, float width, List 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])); } /// The direction of the fullest cell still standing in a sector, and how many cells have anything left (for the test bot). 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; } /// Where a direction falls in a sector's flat frame, in metres. 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); } /// Show a stroke on this sector and on any neighbour it spills onto. 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); } /// /// Show the strip a header swept from a to b: square across the line of travel, as wide as the cut, and only a /// hand's breadth past either end so the next stroke joins on without a seam. A wide header shows a wide strip /// behind it, not a disc eaten out in front of it. /// static void PaintStrip(Mask m, Vector3 a, Vector3 b, float half) { 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); if (len < 1e-4f) return; float ux = du / len, uv = dv / len; const float cap = 0.3f; float reach = half + PaintFeather + cap; 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 wide = Mathf.Max(half, MinPaintRadius); for (int z = z0; z <= z1; z++) for (int x = x0; x <= x1; x++) { float cu = Cell(m, x) - u0, cv = Cell(m, z) - v0; float across = Mathf.Abs(cv * ux - cu * uv); float t = cu * ux + cv * uv; float off = Mathf.Max(-t, t - len); float f = Mathf.Clamp01((wide - across) / PaintFeather + 0.5f) * Mathf.Clamp01((cap - off) / PaintFeather + 0.5f); if (f <= 0f) continue; byte by = (byte)(f * 255f); int i = (z * Res + x) * 2; if (by > m.rg[i]) { m.rg[i] = by; m.show = m.dirty = m.keep = true; } } } 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; } } } /// Is this sector as good as done? Then the last scraps go with this stroke. Returns their square metres. 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; } /// Host: this sector is done, whoever got there first. False when it has already been paid for. 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; } /// The host says this sector is done. 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; m.raw = 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); } /// Cheat: the whole sector goes at once. Returns the square metres that were still standing. 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 ───────────────────────── /// How much grass is left here: 1 = full meadow, 0 = mown (it never grows back). 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; } /// No grass standing here: it has been cut, or nothing ever grew. Things are only built on such ground. 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; /// How much of a sector is mown, 0..1. public static float Cleared(int id) => s_masks.TryGetValue(id, out var m) ? Cleared(m) : 0f; /// /// Sectors that still have grass standing, as of the last . The base, the rocks and a few sectors /// with no grass at all keep the mown area a little under the planet's (99.8% with everything cut), so "all of it" /// is this reaching 0, not the area reaching the planet's. /// public static int Left { get; private set; } = int.MaxValue; /// Square metres mown on the whole planet, as this peer knows it (and on the way). public static double MownArea() { double sum = 0d; int missing = HexGrid.Cells - s_masks.Count, left = missing; foreach (var m in s_masks.Values) { sum += m.mown; if (!m.done && m.total > 0f) left++; } // the last few sectors nobody has set foot in: open them to see whether there is any grass there at all if (missing > 0 && missing <= 64) { left -= missing; for (int id = 0; id < HexGrid.Cells; id++) if (!s_masks.ContainsKey(id) && Total(id) > 0f) left++; } Left = left; return sum; } /// Grass in a sector when nobody has touched it, in square metres. 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; } /// The map as the shaders read it (the blank one for an untouched sector with nothing in the way). static int s_texFrame, s_texMade; /// /// The map as the shaders read it. A sector coming into view far off may wait a frame or two for its texture /// (null), so that a drive across fresh meadow doesn't unpack and upload dozens in one frame; urgent ones (near the /// eye) always get theirs. /// public static Texture2D TextureFor(HexGrid.Sector s, bool urgent) { if (!urgent) { var had = Find(s.id); if (had != null && !had.tex && !(had.done && had.rg == null)) { if (s_texFrame != Time.frameCount) { s_texFrame = Time.frameCount; s_texMade = 0; } if (s_texMade >= 4) return null; s_texMade++; } } return TextureFor(s); } 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; } // the eye only needs the look: the grass counts stay packed (an open map counts against the ones kept open) if (m.rg == null) Look(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" /// Everything cut so far, as one block of bytes (the save file, and what a late joiner is sent). public static byte[] Serialize() => SerializeLater()(); /// /// The mow map as it stands now, put into bytes later, off the main thread if wanted: only the sectors cut since the /// last time are packed here, the ten-odd megabytes are laid out by the function it hands back. A packed array is /// only ever replaced, never written into, so holding on to them is safe. /// public static System.Func SerializeLater() { TakePacked(); var rows = new List<(int id, float total, float mown, bool done, byte[] packed, Packing job)>(s_masks.Count); foreach (var m in s_masks.Values) { if (!m.keep) continue; if (!m.done && (m.dirty || m.packed == null) && m.left != null) { // only the copy is made here, the squeezing happens with the rest of the save; till its bytes come // back the mask has none, so anything that needs them packs it again itself var job = new Packing { m = m, raw = Raw(m) }; m.packed = null; m.dirty = false; rows.Add((m.s.id, m.total, m.mown, false, null, job)); continue; } if (!m.done && m.packed == null && m.raw != null) { rows.Add((m.s.id, m.total, m.mown, false, null, new Packing { m = m, raw = m.raw })); continue; } rows.Add((m.s.id, m.total, m.mown, m.done, m.done ? null : m.packed, null)); } return () => { using (var mem = new MemoryStream()) using (var w = new BinaryWriter(mem)) { w.Write(Magic); w.Write(rows.Count); foreach (var (id, total, mown, done, had, job) in rows) { var packed = had; if (job != null) { packed = job.packed = Deflate(job.raw); job.raw = null; s_packed.Enqueue(job); } w.Write(id); w.Write(total); w.Write(mown); w.Write(done); int len = packed == null ? 0 : packed.Length; w.Write(len); if (len > 0) w.Write(packed); } w.Flush(); return mem.ToArray(); } }; } /// Take in a saved game. What this peer has cut in the meantime stays cut. 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(); } /// False when the file is there but can't be read. 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; } } } }