Smoother drives across the meadow: no more hitches opening sectors
- Sector maps are put away on a worker thread, and trimmed in batches - A far sector's texture only needs its look; at most four new ones a frame - Fresh maps fill rows between their borders instead of testing every cell - Rocks are marked with plain numbers; marks come back on unpacked maps - Worked-overlay sort uses float keys; idle belts look on staggered steps - Chase camera cast no longer allocates; perf demo drives and runs too Drive phase on a late save: p99 33 -> 16 ms, frames over 20 ms 242 -> 7. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -16,6 +16,44 @@ namespace GrassCutter
|
|||||||
/// every profiler marker (a development build has one per script Update), the slow frames and what was busy in them.
|
/// every profiler marker (a development build has one per script Update), the slow frames and what was busy in them.
|
||||||
/// Writes perf.txt beside the shots. Needs a development build for the per-script markers.
|
/// Writes perf.txt beside the shots. Needs a development build for the per-script markers.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
IEnumerator Phase(StringBuilder outp, List<(string name, ProfilerRecorder rec)> recs, ProfilerRecorder loop, string label, float seconds, System.Action begin, System.Action<int> each)
|
||||||
|
{
|
||||||
|
var total = new Dictionary<string, double>();
|
||||||
|
var spikes = new List<(int frame, float at, double ms, string top)>();
|
||||||
|
var frames = new List<double>();
|
||||||
|
begin();
|
||||||
|
float t0 = Time.realtimeSinceStartup, until = t0 + seconds;
|
||||||
|
int f = 0;
|
||||||
|
while (Time.realtimeSinceStartup < until)
|
||||||
|
{
|
||||||
|
yield return null;
|
||||||
|
f++;
|
||||||
|
each(f);
|
||||||
|
double frameMs = loop.Valid ? loop.LastValue / 1e6 : Time.unscaledDeltaTime * 1000.0;
|
||||||
|
frames.Add(frameMs);
|
||||||
|
var busy = new List<(string, double)>();
|
||||||
|
foreach (var (name, rec) in recs)
|
||||||
|
{
|
||||||
|
if (!rec.Valid) continue;
|
||||||
|
double ms = rec.LastValue / 1e6;
|
||||||
|
if (ms <= 0 || ms > 1000) continue;
|
||||||
|
total[name] = (total.TryGetValue(name, out var t) ? t : 0) + ms;
|
||||||
|
if (frameMs > 20 && ms > 1 && name != "PlayerLoop") busy.Add((name, ms));
|
||||||
|
}
|
||||||
|
if (frameMs > 20)
|
||||||
|
spikes.Add((f, Time.realtimeSinceStartup - t0, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(14).Select(b => $"{b.Item1} {b.Item2:0.0}"))));
|
||||||
|
}
|
||||||
|
frames.Sort();
|
||||||
|
double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)];
|
||||||
|
outp.AppendLine();
|
||||||
|
outp.AppendLine($"=== {label}: {f} frames, mean {frames.Average():0.0} ms, median {Pct(0.5):0.0}, p95 {Pct(0.95):0.0}, p99 {Pct(0.99):0.0}, max {frames.LastOrDefault():0.0}; {spikes.Count} over 20 ms, {spikes.Count(s => s.ms > 50)} over 50 ms");
|
||||||
|
foreach (var kv in total.Where(kv => kv.Key.StartsWith("GC:") || kv.Key.StartsWith("GC.") || kv.Key.StartsWith("Physics") || kv.Key.StartsWith("Gfx.") || kv.Key.StartsWith("Loading") || kv.Key.Contains("Upload")).OrderByDescending(kv => kv.Value).Take(40))
|
||||||
|
outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}");
|
||||||
|
outp.AppendLine("— slow frames —");
|
||||||
|
foreach (var s in spikes.OrderByDescending(s => s.ms).Take(20))
|
||||||
|
outp.AppendLine($"#{s.frame} t{s.at:0.0} {s.ms:0.0} ms: {s.top}");
|
||||||
|
}
|
||||||
|
|
||||||
IEnumerator Perf(int slot)
|
IEnumerator Perf(int slot)
|
||||||
{
|
{
|
||||||
SaveSlots.Current = slot - 1;
|
SaveSlots.Current = slot - 1;
|
||||||
@ -54,44 +92,35 @@ namespace GrassCutter
|
|||||||
var loop = recs.FirstOrDefault(r => r.name == "PlayerLoop").rec;
|
var loop = recs.FirstOrDefault(r => r.name == "PlayerLoop").rec;
|
||||||
outp.AppendLine($"recording {recs.Count} markers, PlayerLoop {(loop.Valid ? "ok" : "MISSING")}");
|
outp.AppendLine($"recording {recs.Count} markers, PlayerLoop {(loop.Valid ? "ok" : "MISSING")}");
|
||||||
|
|
||||||
var total = new Dictionary<string, double>();
|
// three things a player does: walk about the base, drive a mower across fresh meadow, run through the meadow
|
||||||
var spikes = new List<(int frame, double ms, string top)>();
|
yield return Phase(outp, recs, loop, "walk at the base", 25f, () => Ctl.BotMove = new Vector2(0.3f, 1f), f => { if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y); });
|
||||||
var frames = new List<double>();
|
|
||||||
float until = Time.realtimeSinceStartup + 40f;
|
|
||||||
int f = 0;
|
|
||||||
// walk around a little, as a player would
|
|
||||||
Ctl.BotMove = new Vector2(0.3f, 1f);
|
|
||||||
while (Time.realtimeSinceStartup < until)
|
|
||||||
{
|
|
||||||
yield return null;
|
|
||||||
f++;
|
|
||||||
if (f % 120 == 0) Ctl.BotMove = new Vector2(-Ctl.BotMove.x, Ctl.BotMove.y);
|
|
||||||
double frameMs = loop.Valid ? loop.LastValue / 1e6 : Time.unscaledDeltaTime * 1000.0;
|
|
||||||
frames.Add(frameMs);
|
|
||||||
var busy = new List<(string, double)>();
|
|
||||||
foreach (var (name, rec) in recs)
|
|
||||||
{
|
|
||||||
if (!rec.Valid) continue;
|
|
||||||
double ms = rec.LastValue / 1e6;
|
|
||||||
if (ms <= 0 || ms > 1000) continue;
|
|
||||||
total[name] = (total.TryGetValue(name, out var t) ? t : 0) + ms;
|
|
||||||
if (frameMs > 25 && ms > 1 && ms < 1000 && (name.StartsWith("GC:") || name.StartsWith("Physics.Simulate") || name.StartsWith("Semaphore") || name.StartsWith("GC.") || name.StartsWith("Gfx."))) busy.Add((name, ms));
|
|
||||||
}
|
|
||||||
if (frameMs > 25)
|
|
||||||
spikes.Add((f, frameMs, string.Join(", ", busy.OrderByDescending(b => b.Item2).Take(10).Select(b => $"{b.Item1} {b.Item2:0.0}"))));
|
|
||||||
}
|
|
||||||
Ctl.BotMove = Vector2.zero;
|
Ctl.BotMove = Vector2.zero;
|
||||||
|
var ride = Vehicle.All.Where(v => v && v.Def.width > 0f).OrderByDescending(v => v.Def.width).FirstOrDefault();
|
||||||
|
if (ride)
|
||||||
|
{
|
||||||
|
var far = Planet.FromBase(90f, 160f);
|
||||||
|
var up = far;
|
||||||
|
ride.ServerPut(Planet.OnSurface(far) + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, up), up));
|
||||||
|
yield return new WaitForSeconds(1f);
|
||||||
|
Me.Teleport(ride.transform.position + ride.transform.right * 3f);
|
||||||
|
yield return new WaitForSeconds(0.5f);
|
||||||
|
ride.Interact();
|
||||||
|
yield return new WaitForSeconds(1.5f);
|
||||||
|
ride.Tank.Value = 0f;
|
||||||
|
yield return Phase(outp, recs, loop, $"drive the {ride.kind} through the meadow", 40f, () => Ctl.BotMove = new Vector2(0.15f, 1f), f => { });
|
||||||
|
Ctl.BotMove = Vector2.zero;
|
||||||
|
ride.RequestExit();
|
||||||
|
yield return new WaitForSeconds(1.5f);
|
||||||
|
}
|
||||||
|
else outp.AppendLine("no mower to drive");
|
||||||
|
var run = Planet.FromBase(-150f, 120f);
|
||||||
|
Me.Teleport(Planet.OnSurface(run) + run * 0.3f);
|
||||||
|
yield return new WaitForSeconds(1f);
|
||||||
|
yield return Phase(outp, recs, loop, "run through the meadow", 25f, () => { Ctl.BotMove = new Vector2(0f, 1f); Ctl.BotSprint = true; }, f => { if (f % 200 == 0) Ctl.BotMove = new Vector2(Ctl.BotMove.x > 0 ? -0.4f : 0.4f, 1f); });
|
||||||
|
Ctl.BotMove = Vector2.zero;
|
||||||
|
Ctl.BotSprint = false;
|
||||||
foreach (var (_, rec) in recs) rec.Dispose();
|
foreach (var (_, rec) in recs) rec.Dispose();
|
||||||
|
|
||||||
frames.Sort();
|
|
||||||
double Pct(double p) => frames.Count == 0 ? 0 : frames[Mathf.Clamp((int)(frames.Count * p), 0, frames.Count - 1)];
|
|
||||||
outp.AppendLine($"{f} frames: mean {frames.Average():0.0} ms, median {Pct(0.5):0.0}, p95 {Pct(0.95):0.0}, p99 {Pct(0.99):0.0}, max {frames.LastOrDefault():0.0}; {spikes.Count} over 25 ms");
|
|
||||||
outp.AppendLine("— mean ms a frame, top markers —");
|
|
||||||
foreach (var kv in total.OrderByDescending(kv => kv.Value).Take(70))
|
|
||||||
outp.AppendLine($"{kv.Value / f,8:0.000} {kv.Key}");
|
|
||||||
outp.AppendLine("— slow frames —");
|
|
||||||
foreach (var s in spikes.OrderByDescending(s => s.ms).Take(25))
|
|
||||||
outp.AppendLine($"#{s.frame} {s.ms:0.0} ms: {s.top}");
|
|
||||||
float render = 0f;
|
float render = 0f;
|
||||||
yield return BotCapture.FrameCost(40, v => render = v);
|
yield return BotCapture.FrameCost(40, v => render = v);
|
||||||
outp.AppendLine($"render (camera at the base, GPU waited for): {render:0.0} ms");
|
outp.AppendLine($"render (camera at the base, GPU waited for): {render:0.0} ms");
|
||||||
|
|||||||
@ -339,7 +339,9 @@ namespace GrassCutter
|
|||||||
{
|
{
|
||||||
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
|
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
|
||||||
// a line that hasn't moved for a while only looks again every few steps whether the front can go on
|
// a line that hasn't moved for a while only looks again every few steps whether the front can go on
|
||||||
if (_idle > 40 && ++_idleSkip % 6 != 0) return;
|
// (each line at its own step of the six: a loaded base has hundreds, and all of them looking on the same step
|
||||||
|
// stalled that frame)
|
||||||
|
if (_idle > 40 && (++_idleSkip + _phase) % 6 != 0) return;
|
||||||
bool moved = false;
|
bool moved = false;
|
||||||
float dt = Time.fixedDeltaTime * (_idle > 40 ? 6f : 1f);
|
float dt = Time.fixedDeltaTime * (_idle > 40 ? 6f : 1f);
|
||||||
float step = Speed * dt;
|
float step = Speed * dt;
|
||||||
@ -372,6 +374,8 @@ namespace GrassCutter
|
|||||||
}
|
}
|
||||||
|
|
||||||
int _idle, _idleSkip;
|
int _idle, _idleSkip;
|
||||||
|
static int s_lines;
|
||||||
|
readonly int _phase = s_lines++ % 6;
|
||||||
|
|
||||||
/// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary>
|
/// <summary>How far an item can go: to the turn until it has chosen, then the end of its route, and never into the one ahead.</summary>
|
||||||
float Room(int i, ref float L)
|
float Room(int i, ref float L)
|
||||||
|
|||||||
@ -14,6 +14,8 @@ namespace GrassCutter
|
|||||||
/// <summary>Dev bots hold / tap the use buttons through these (they bypass focus checks).</summary>
|
/// <summary>Dev bots hold / tap the use buttons through these (they bypass focus checks).</summary>
|
||||||
public static bool BotUseHeld, BotUsePressed, BotAltHeld, BotAltPressed;
|
public static bool BotUseHeld, BotUsePressed, BotAltHeld, BotAltPressed;
|
||||||
public static Vector2 BotMove;
|
public static Vector2 BotMove;
|
||||||
|
/// <summary>The test bots run.</summary>
|
||||||
|
public static bool BotSprint;
|
||||||
public static bool BotJumpPressed;
|
public static bool BotJumpPressed;
|
||||||
/// <summary>The opening film is running: nobody moves.</summary>
|
/// <summary>The opening film is running: nobody moves.</summary>
|
||||||
public static bool Cinematic;
|
public static bool Cinematic;
|
||||||
@ -63,6 +65,7 @@ namespace GrassCutter
|
|||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (Blocked) { s_sprintOn = false; return false; }
|
if (Blocked) { s_sprintOn = false; return false; }
|
||||||
|
if (BotSprint) return true;
|
||||||
if (G != null && G.leftStickButton.isPressed) return true;
|
if (G != null && G.leftStickButton.isPressed) return true;
|
||||||
if (!SprintToggle) return Binds.Held(Act.Sprint);
|
if (!SprintToggle) return Binds.Held(Act.Sprint);
|
||||||
if (s_sprintFrame != Time.frameCount)
|
if (s_sprintFrame != Time.frameCount)
|
||||||
|
|||||||
@ -676,9 +676,12 @@ namespace GrassCutter
|
|||||||
var dir = (back + up * 0.25f).normalized;
|
var dir = (back + up * 0.25f).normalized;
|
||||||
float want = _chaseDist;
|
float want = _chaseDist;
|
||||||
float reach = want;
|
float reach = want;
|
||||||
var hits = Physics.SphereCastAll(target, 0.35f, dir, want, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore);
|
int count = Physics.SphereCastNonAlloc(target, 0.35f, dir, s_boomHits, want, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Vehicle), QueryTriggerInteraction.Ignore);
|
||||||
foreach (var h in hits)
|
for (int i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
var h = s_boomHits[i];
|
||||||
if (h.distance > 0f && !h.collider.transform.IsChildOf(v.transform)) reach = Mathf.Min(reach, h.distance - 0.2f);
|
if (h.distance > 0f && !h.collider.transform.IsChildOf(v.transform)) reach = Mathf.Min(reach, h.distance - 0.2f);
|
||||||
|
}
|
||||||
reach = Mathf.Max(1.5f, reach);
|
reach = Mathf.Max(1.5f, reach);
|
||||||
// closing in is instant (walls), backing off again is gentle
|
// closing in is instant (walls), backing off again is gentle
|
||||||
_chaseShown = _chaseShown <= 0f || reach < _chaseShown ? reach : Mathf.Lerp(_chaseShown, reach, Time.deltaTime * 4f);
|
_chaseShown = _chaseShown <= 0f || reach < _chaseShown ? reach : Mathf.Lerp(_chaseShown, reach, Time.deltaTime * 4f);
|
||||||
@ -689,6 +692,8 @@ namespace GrassCutter
|
|||||||
_boom.rotation = Quaternion.LookRotation(target - pos, up);
|
_boom.rotation = Quaternion.LookRotation(target - pos, up);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static readonly RaycastHit[] s_boomHits = new RaycastHit[32];
|
||||||
|
|
||||||
void EnterVehicle(Vehicle v)
|
void EnterVehicle(Vehicle v)
|
||||||
{
|
{
|
||||||
SetFlying(false);
|
SetFlying(false);
|
||||||
|
|||||||
@ -95,6 +95,8 @@ namespace GrassCutter
|
|||||||
readonly List<MaterialPropertyBlock> _mpbs = new List<MaterialPropertyBlock>();
|
readonly List<MaterialPropertyBlock> _mpbs = new List<MaterialPropertyBlock>();
|
||||||
readonly List<HexGrid.Sector> _near = new List<HexGrid.Sector>();
|
readonly List<HexGrid.Sector> _near = new List<HexGrid.Sector>();
|
||||||
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
|
readonly List<HexGrid.Sector> _worked = new List<HexGrid.Sector>();
|
||||||
|
float[] _workedKey = new float[256];
|
||||||
|
HexGrid.Sector[] _workedBy = new HexGrid.Sector[256];
|
||||||
readonly Plane[] _frustum = new Plane[6];
|
readonly Plane[] _frustum = new Plane[6];
|
||||||
int _mpbUsed, _here = -1;
|
int _mpbUsed, _here = -1;
|
||||||
/// <summary>Grass draws issued last frame (for -demogpu).</summary>
|
/// <summary>Grass draws issued last frame (for -demogpu).</summary>
|
||||||
@ -269,7 +271,8 @@ namespace GrassCutter
|
|||||||
if (!GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) continue;
|
if (!GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) continue;
|
||||||
float arc = (s.c - dir).magnitude * Planet.Radius;
|
float arc = (s.c - dir).magnitude * Planet.Radius;
|
||||||
float reachable = Mathf.Max(arc - s.radius, alt);
|
float reachable = Mathf.Max(arc - s.radius, alt);
|
||||||
var mask = MowMap.TextureFor(s);
|
var mask = MowMap.TextureFor(s, arc - s.radius < 45f);
|
||||||
|
if (!mask) continue;
|
||||||
// mown to the last blade: only the floor shows (the pile's shells and every plant are cut away in the
|
// mown to the last blade: only the floor shows (the pile's shells and every plant are cut away in the
|
||||||
// shader anyway), one draw instead of up to six. Near the base that is most of what is in view.
|
// shader anyway), one draw instead of up to six. Near the base that is most of what is in view.
|
||||||
if (mask == MowMap.Full && mask)
|
if (mask == MowMap.Full && mask)
|
||||||
@ -303,20 +306,24 @@ namespace GrassCutter
|
|||||||
}
|
}
|
||||||
if (furMat)
|
if (furMat)
|
||||||
foreach (var s in _worked)
|
foreach (var s in _worked)
|
||||||
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds)) DrawPile(FurFloor, s, MowMap.TextureFor(s), true);
|
if (GeometryUtility.TestPlanesAABB(_frustum, s.bounds) && MowMap.TextureFor(s, false) is Texture2D worked && worked) DrawPile(FurFloor, s, worked, true);
|
||||||
DrawBatches();
|
DrawBatches();
|
||||||
Draws = _mpbUsed + _drawn;
|
Draws = _mpbUsed + _drawn;
|
||||||
}
|
}
|
||||||
|
|
||||||
int _drawn;
|
int _drawn;
|
||||||
|
|
||||||
|
readonly HashSet<int> _seen = new HashSet<int>();
|
||||||
|
|
||||||
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
|
/// <summary>Every sector the rings can reach from here, the one underfoot first, and the worked ones further out.</summary>
|
||||||
void GatherNear(int here)
|
void GatherNear(int here)
|
||||||
{
|
{
|
||||||
_near.Clear();
|
_near.Clear();
|
||||||
var from = HexGrid.Get(here);
|
var from = HexGrid.Get(here);
|
||||||
_near.Add(from);
|
_near.Add(from);
|
||||||
var seen = new HashSet<int> { here };
|
var seen = _seen;
|
||||||
|
seen.Clear();
|
||||||
|
seen.Add(here);
|
||||||
float reach = Mathf.Max(Hemp.fadeB, FurFar.outer) + 40f;
|
float reach = Mathf.Max(Hemp.fadeB, FurFar.outer) + 40f;
|
||||||
for (int i = 0; i < _near.Count; i++)
|
for (int i = 0; i < _near.Count; i++)
|
||||||
foreach (int n in _near[i].neighbours)
|
foreach (int n in _near[i].neighbours)
|
||||||
@ -327,13 +334,27 @@ namespace GrassCutter
|
|||||||
}
|
}
|
||||||
MowMap.Trim(from.c);
|
MowMap.Trim(from.c);
|
||||||
_worked.Clear();
|
_worked.Clear();
|
||||||
|
// a well-worked planet has thousands of these: they are sorted by a plain number, not by a comparison that
|
||||||
|
// works out two distances every time (that took 4 ms at every step into a new sector)
|
||||||
|
float far = OverlayReach / Planet.Radius;
|
||||||
|
far *= far;
|
||||||
|
int count = 0;
|
||||||
foreach (var m in MowMap.All)
|
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));
|
if (!m.keep || seen.Contains(m.s.id)) continue;
|
||||||
_worked.RemoveRange(OverlayMax, _worked.Count - OverlayMax);
|
float d = (m.s.c - from.c).sqrMagnitude;
|
||||||
|
if (d >= far) continue;
|
||||||
|
if (count == _workedKey.Length)
|
||||||
|
{
|
||||||
|
System.Array.Resize(ref _workedKey, count * 2);
|
||||||
|
System.Array.Resize(ref _workedBy, count * 2);
|
||||||
|
}
|
||||||
|
_workedKey[count] = d;
|
||||||
|
_workedBy[count++] = m.s;
|
||||||
}
|
}
|
||||||
|
if (count > OverlayMax) System.Array.Sort(_workedKey, _workedBy, 0, count);
|
||||||
|
for (int i = 0; i < count && i < OverlayMax; i++) _worked.Add(_workedBy[i]);
|
||||||
|
System.Array.Clear(_workedBy, 0, count);
|
||||||
}
|
}
|
||||||
|
|
||||||
static void Flat(HexGrid.Sector s, Vector3 dir, out float u, out float v) => MowMap.Flat(s, dir, out u, out v);
|
static void Flat(HexGrid.Sector s, Vector3 dir, out float u, out float v) => MowMap.Flat(s, dir, out u, out v);
|
||||||
|
|||||||
@ -20,6 +20,8 @@ namespace GrassCutter
|
|||||||
// the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent
|
// the last few scraps (behind rocks, along the seams) go by themselves: no hunting for the final percent
|
||||||
const float DoneAt = 0.93f;
|
const float DoneAt = 0.93f;
|
||||||
const int MaxStampsPerCut = 28, MaxOpen = 300;
|
const int MaxStampsPerCut = 28, MaxOpen = 300;
|
||||||
|
/// <summary>Trim waits for this many more open maps than it keeps, so it runs now and then, not at every sector.</summary>
|
||||||
|
const int TrimSlack = 80;
|
||||||
/// <summary>Less than this left in a cell is not worth a row of its own.</summary>
|
/// <summary>Less than this left in a cell is not worth a row of its own.</summary>
|
||||||
const ushort Scrap = 120;
|
const ushort Scrap = 120;
|
||||||
const float MinPaintRadius = 0.15f;
|
const float MinPaintRadius = 0.15f;
|
||||||
@ -32,6 +34,8 @@ namespace GrassCutter
|
|||||||
public ushort[] left; // 65535 = untouched, null while packed
|
public ushort[] left; // 65535 = untouched, null while packed
|
||||||
public byte[] rg; // r, g per cell
|
public byte[] rg; // r, g per cell
|
||||||
public byte[] packed;
|
public byte[] packed;
|
||||||
|
/// <summary>Its bytes, unsqueezed, while a worker packs them (null otherwise).</summary>
|
||||||
|
public byte[] raw;
|
||||||
public float total, mown; // square metres
|
public float total, mown; // square metres
|
||||||
public bool done;
|
public bool done;
|
||||||
public bool paid; // the host has paid out for it
|
public bool paid; // the host has paid out for it
|
||||||
@ -127,7 +131,9 @@ namespace GrassCutter
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void Apply(Mask m, Bare b)
|
/// <param name="fresh">The map was just made: a cell is the sector's exactly when it still has grass.</param>
|
||||||
|
/// <param name="look">Only the look: the counts came from a packed copy that already has the rock in it.</param>
|
||||||
|
static void Apply(Mask m, Bare b, bool fresh = false, bool look = false)
|
||||||
{
|
{
|
||||||
var s = m.s;
|
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
|
// only the cells the block can reach: a base is hundreds of tiles, and a sector 16k cells, so looking at all of
|
||||||
@ -136,24 +142,41 @@ namespace GrassCutter
|
|||||||
float reach = (b.round ? b.radius : b.half.magnitude) * 1.5f + m.cell * 2f;
|
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 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));
|
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++)
|
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++)
|
for (int x = x0; x <= x1; x++)
|
||||||
{
|
{
|
||||||
int i = z * Res + x;
|
int i = z * Res + x;
|
||||||
if (m.rg[i * 2 + 1] != 0) continue;
|
if (m.rg[i * 2 + 1] != 0) continue;
|
||||||
var flat = s.c * Planet.Radius + s.e1 * Cell(m, x) + s.e2 * Cell(m, z);
|
float u = Cell(m, x);
|
||||||
var p = Planet.Center + flat;
|
float fx = rx + e1.x * u, fy = ry + e1.y * u, fz = rz + e1.z * u;
|
||||||
// a rock is measured along the ground: the frame is flat, the soil isn't
|
bool hit;
|
||||||
bool hit = b.round
|
if (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;
|
// 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;
|
if (!hit) continue;
|
||||||
m.rg[i * 2 + 1] = 255;
|
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
|
// 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);
|
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.left[i] = 0;
|
||||||
m.show = true;
|
m.show = true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static float Cell(Mask m, int i) => (i + 0.5f) * m.cell - m.s.half;
|
static float Cell(Mask m, int i) => (i + 0.5f) * m.cell - m.s.half;
|
||||||
@ -191,9 +214,36 @@ namespace GrassCutter
|
|||||||
m.left = new ushort[Res * Res];
|
m.left = new ushort[Res * Res];
|
||||||
m.rg = new byte[Res * Res * 2];
|
m.rg = new byte[Res * Res * 2];
|
||||||
int owned = 0;
|
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++)
|
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++; }
|
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;
|
float total = owned * m.area;
|
||||||
if (m.total <= 0f) m.total = total;
|
if (m.total <= 0f) m.total = total;
|
||||||
m.show = true;
|
m.show = true;
|
||||||
@ -201,19 +251,44 @@ namespace GrassCutter
|
|||||||
{
|
{
|
||||||
float kept = m.total;
|
float kept = m.total;
|
||||||
m.total = total;
|
m.total = total;
|
||||||
foreach (var b in list) Apply(m, b);
|
foreach (var b in list) Apply(m, b, true);
|
||||||
if (m.packed != null) m.total = kept;
|
if (m.packed != null) m.total = kept;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void Unpack(Mask m)
|
/// <summary>Just the look of a packed sector, for its texture: the grass counts stay packed.</summary>
|
||||||
|
static void Look(Mask m)
|
||||||
{
|
{
|
||||||
Fresh(m);
|
var raw = m.raw;
|
||||||
if (m.packed == null) return;
|
if (raw == null && m.packed != null) raw = Inflate(m.packed, s_inflate);
|
||||||
var raw = Inflate(m.packed);
|
if (raw == null) { Unpack(m); return; }
|
||||||
System.Buffer.BlockCopy(raw, 0, m.left, 0, Res * Res * 2);
|
m.rg = new byte[Res * Res * 2];
|
||||||
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i];
|
for (int i = 0; i < Res * Res; i++) m.rg[i * 2] = raw[Res * Res * 2 + i];
|
||||||
m.show = true;
|
m.show = true;
|
||||||
|
MarkBare(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The packed copy keeps the grass, not where nothing grows: the blocks mark that again on a new look.</summary>
|
||||||
|
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)
|
static void Pack(Mask m)
|
||||||
@ -247,11 +322,42 @@ namespace GrassCutter
|
|||||||
{
|
{
|
||||||
while (s_packed.TryDequeue(out var p))
|
while (s_packed.TryDequeue(out var p))
|
||||||
if (p.m.packed == null && !p.m.dirty && p.m.left != null) p.m.packed = p.packed;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static byte[] Inflate(byte[] packed)
|
sealed class Squeeze { public Mask m; public byte[] raw, packed; }
|
||||||
|
static readonly System.Collections.Concurrent.ConcurrentQueue<Squeeze> s_squeezed = new System.Collections.Concurrent.ConcurrentQueue<Squeeze>();
|
||||||
|
|
||||||
|
/// <summary>Puts a sector's map away: its bytes go to a worker to be squeezed, the mask lets go of its grass counts.</summary>
|
||||||
|
static void PutAway(Mask m)
|
||||||
{
|
{
|
||||||
var raw = new byte[Res * Res * 3];
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The main thread's inflate buffer: what it holds is copied out at once.</summary>
|
||||||
|
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))
|
using (var z = new DeflateStream(new MemoryStream(packed), CompressionMode.Decompress))
|
||||||
{
|
{
|
||||||
int at = 0, n;
|
int at = 0, n;
|
||||||
@ -260,24 +366,22 @@ namespace GrassCutter
|
|||||||
return raw;
|
return raw;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static readonly List<Mask> s_trim = new List<Mask>();
|
||||||
|
|
||||||
/// <summary>Too many maps in memory: squeeze the ones furthest from here.</summary>
|
/// <summary>Too many maps in memory: squeeze the ones furthest from here.</summary>
|
||||||
public static void Trim(Vector3 dir)
|
public static void Trim(Vector3 dir)
|
||||||
{
|
{
|
||||||
TakePacked();
|
TakePacked();
|
||||||
int open = 0;
|
int open = 0;
|
||||||
foreach (var m in s_masks.Values) if (m.left != null) open++;
|
foreach (var m in s_masks.Values) if (m.left != null) open++;
|
||||||
if (open <= MaxOpen) return;
|
if (open <= MaxOpen + TrimSlack) return;
|
||||||
var list = new List<Mask>();
|
s_trim.Clear();
|
||||||
foreach (var m in s_masks.Values) if (m.left != null) list.Add(m);
|
foreach (var m in s_masks.Values) if (m.left != null) s_trim.Add(m);
|
||||||
list.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude));
|
s_trim.Sort((a, b) => (b.s.c - dir).sqrMagnitude.CompareTo((a.s.c - dir).sqrMagnitude));
|
||||||
for (int i = 0; i < open - MaxOpen; i++)
|
// 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
|
||||||
var m = list[i];
|
for (int i = 0; i < open - MaxOpen; i++) PutAway(s_trim[i]);
|
||||||
if (m.dirty || (m.keep && m.packed == null)) Pack(m);
|
s_trim.Clear();
|
||||||
// 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 ─────────────────────────
|
// ───────────────────────── cutting ─────────────────────────
|
||||||
@ -536,6 +640,7 @@ namespace GrassCutter
|
|||||||
m.mown = m.total;
|
m.mown = m.total;
|
||||||
m.left = null;
|
m.left = null;
|
||||||
m.packed = null;
|
m.packed = null;
|
||||||
|
m.raw = null;
|
||||||
if (s_blocks.ContainsKey(m.s.id) && m.rg != null)
|
if (s_blocks.ContainsKey(m.s.id) && m.rg != null)
|
||||||
{
|
{
|
||||||
// the rock keeps its bare patch
|
// the rock keeps its bare patch
|
||||||
@ -612,6 +717,28 @@ namespace GrassCutter
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The map as the shaders read it (the blank one for an untouched sector with nothing in the way).</summary>
|
/// <summary>The map as the shaders read it (the blank one for an untouched sector with nothing in the way).</summary>
|
||||||
|
static int s_texFrame, s_texMade;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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)
|
public static Texture2D TextureFor(HexGrid.Sector s)
|
||||||
{
|
{
|
||||||
if (!s_none) s_none = Single(new Color32(0, 0, 0, 255));
|
if (!s_none) s_none = Single(new Color32(0, 0, 0, 255));
|
||||||
@ -630,7 +757,8 @@ namespace GrassCutter
|
|||||||
m.left = null;
|
m.left = null;
|
||||||
m.show = true;
|
m.show = true;
|
||||||
}
|
}
|
||||||
if (m.rg == null) Unpack(m);
|
// 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)
|
if (!m.tex)
|
||||||
{
|
{
|
||||||
// the mips are the soft edge of a cut: the grass beside it reads them to stand lower
|
// the mips are the soft edge of a cut: the grass beside it reads them to stand lower
|
||||||
@ -693,6 +821,11 @@ namespace GrassCutter
|
|||||||
rows.Add((m.s.id, m.total, m.mown, false, null, job));
|
rows.Add((m.s.id, m.total, m.mown, false, null, job));
|
||||||
continue;
|
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));
|
rows.Add((m.s.id, m.total, m.mown, m.done, m.done ? null : m.packed, null));
|
||||||
}
|
}
|
||||||
return () =>
|
return () =>
|
||||||
|
|||||||
Reference in New Issue
Block a user