Files
NiemandKG 27d075103b Feedback round: bots that keep working, Sky Mower, calmer HUD, faster menus, new map
- Robot docks and drone pads with no belt ship straight to Earth; robots widen
  their rings up to 4x once everything in reach is mown, travel 2.5x faster
  empty, hoppers 60/150 kg. Drone reach 70 m + 25 m per upgrade.
- New Sky Mower: a big mowing drone on a pad, 91 sectors, flies over the grass.
- Cut paint follows the blade as a strip, no disc ahead of the machine.
- Sector toasts aggregate, chimes and till sounds throttled, toasts moved and
  narrowed.
- Menus no longer rebuild on every money change (price tint follows the
  wallet), scroll position kept.
- Map drawn as one mesh, opens near the player, ME / + / - / GLOBE, scale bar.
- Key-art still (x_key) and -shotsize for the store stills; -demobots test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 15:38:37 +06:00

396 lines
17 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
namespace GrassCutter
{
/// <summary>A body with nobody in it, for the trailer: walks a path, mows what's in front of it, looks like any player.</summary>
public class CineExtra : MonoBehaviour, ICrewPose
{
public ToolId Tool = ToolId.Scythe;
public Color Tint = Color.white;
public bool Cutting, Sitting, Phone, Laughing;
public float Pitch = 18f, Width = 1.3f, Sweep = 1f, Lag;
/// <summary>When it hits the ground, if it comes in from the sky.</summary>
public float DropAt = -1f;
/// <summary>Where it stands, by the seconds since it was made. Null stays put.</summary>
public Func<float, Vector3> Path;
public bool IsSwimming => false;
public bool IsDriving => Sitting;
public bool InCab { get; set; }
public bool HasPhoneOut => Phone;
public byte Held => (byte)Tool;
public float LookPitch => Laughing ? -6f + Mathf.Abs(Mathf.Sin(_t * 9f)) * 26f : Pitch;
public float TankKilos => 0f;
public Vector4 CutLine { get; private set; }
public Color Colour => Tint;
float _t;
void Update()
{
_t += Time.deltaTime;
if (Path != null)
{
var at = Path(_t);
var soil = Planet.Surface(at);
var way = Vector3.ProjectOnPlane(Path(_t + 0.2f) - at, Planet.Up(soil));
var up = Planet.Up(soil);
var turn = way.sqrMagnitude > 1e-4f ? Quaternion.LookRotation(way, up) : Quaternion.LookRotation(Vector3.ProjectOnPlane(transform.forward, up), up);
transform.SetPositionAndRotation(soil, Quaternion.Slerp(transform.rotation, turn, Time.deltaTime * 8f));
}
if (DropAt >= 0f)
{
float left = DropAt - _t;
var soil = Planet.Surface(transform.position);
transform.position = soil + Planet.Up(soil) * Mathf.Max(0f, left * left * 22f);
if (left <= 0f)
{
DropAt = -1f;
Fx.Slam(soil, Planet.Up(soil), 3f);
Fx.Dust(soil, 0.9f, 40);
}
}
if (Cutting)
{
float side = Mathf.Sin((Time.time + Lag) * PlayerTools.StrokesPerSecond(Tool) * Mathf.PI * 2f) * Sweep;
var blade = transform.position + transform.forward * 1.2f + transform.right * side + transform.up * 0.1f;
CutLine = new Vector4(blade.x, blade.y, blade.z, Width);
}
else CutLine = Vector4.zero;
}
}
/// <summary>Keeps a light where the shot needs it.</summary>
public class CineRig : MonoBehaviour
{
public Func<Vector3> Over, At;
void LateUpdate()
{
if (Over == null) return;
var from = Over();
transform.SetPositionAndRotation(from, Quaternion.LookRotation(At() - from, Planet.Up(from)));
}
}
/// <summary>Drives a real machine along a path, as the local player: it keeps its own suspension, wheels, strip and spray.</summary>
[DefaultExecutionOrder(100)]
public class CineDriver : MonoBehaviour
{
public Vehicle V;
public Func<float, Vector3> Path;
float _t;
void FixedUpdate()
{
if (!V || !V.IsSpawned) return;
_t += Time.fixedDeltaTime;
var at = Path(_t);
var up = Planet.Up(at);
var want = Vector3.ProjectOnPlane(Path(_t + 0.1f) - at, up) / 0.1f;
var pull = Vector3.ProjectOnPlane(at - V.transform.position, up);
var body = V.Body;
body.linearVelocity = want + pull * 3f + up * Vector3.Dot(body.linearVelocity, up);
if (want.sqrMagnitude > 0.1f)
{
// steer only: the heading turns about the machine's own up, and the springs keep it on the slope. Turning
// it to the planet's up held it level on a hillside, its downhill wheels in the air.
var own = body.rotation * Vector3.up;
var ahead = Vector3.ProjectOnPlane(want, own);
if (ahead.sqrMagnitude > 1e-4f)
body.MoveRotation(Quaternion.Slerp(body.rotation, Quaternion.LookRotation(ahead, own), Time.fixedDeltaTime * 4f));
}
V.Throttle.Value = 1f;
V.Tank.Value = 0f;
}
}
/// <summary>
/// `-demotrailer`: the film crew. A take runs the game one fixed step at a time and writes every frame, so it comes out
/// perfectly smooth at any speed, and a take at a high frame rate is true slow motion. No HUD: the world alone.
/// </summary>
[DefaultExecutionOrder(-2000)]
public partial class Trailer : MonoBehaviour
{
/// <summary>The frame: 2560x1440 unless `-shotsize WxH` asks for another (key art is shot big, and upright too).</summary>
static readonly int W = ShotSize(0, 2560), H = ShotSize(1, 1440);
static int ShotSize(int i, int fallback)
{
var p = (CommandLine.Get("-shotsize") ?? "").Split('x');
return p.Length == 2 && int.TryParse(p[i], out int v) && v >= 64 && v <= 8192 ? v : fallback;
}
public string Folder;
Camera _cam;
RenderTexture _rt;
Texture2D _read;
Func<float, Lens> _lens;
float _k;
readonly List<GameObject> _props = new List<GameObject>();
HashSet<string> _only;
public struct Lens
{
public Vector3 at, look;
public float fov, roll;
public Lens(Vector3 at, Vector3 look, float fov = 55f, float roll = 0f) { this.at = at; this.look = look; this.fov = fov; this.roll = roll; }
}
static PlayerAgent Me => PlayerAgent.Local;
static TeamState Ts => TeamState.Instance;
static void Log(string s) => Debug.Log("[Trailer] " + s);
// ───────────────────────── places ─────────────────────────
/// <summary>A point on the ground, in metres from the base.</summary>
protected static Vector3 On(float x, float z, float h = 0f)
{
var d = Planet.FromBase(x, z);
return Planet.OnSurface(d) + d * h;
}
// ───────────────────────── the camera ─────────────────────────
void Update()
{
if (_lens != null) Aim(_lens(_k));
}
void Aim(Lens l)
{
bool far = Planet.Altitude(l.at) > 700f;
_cam.farClipPlane = far ? 60000f : 14000f;
_cam.nearClipPlane = far ? 4f : 0.05f;
var up = Planet.Up(l.at);
var turn = Quaternion.LookRotation(l.look - l.at, up);
if (l.roll != 0f) turn *= Quaternion.AngleAxis(l.roll, Vector3.forward);
_cam.transform.SetPositionAndRotation(l.at, turn);
_cam.fieldOfView = l.fov;
}
/// <summary>Rolls: `seconds` of screen time at `fps`. Lead lets the machines get going before the first frame is kept.
/// With `hud` the game's own HUD goes over every frame.</summary>
protected IEnumerator Take(string name, float seconds, int fps, Func<float, Lens> lens, float lead = 0f, Action<float> every = null, bool hud = false)
{
if (!Wanted(name)) yield break;
var dir = Path.Combine(Folder, name);
Directory.CreateDirectory(dir);
_lens = lens;
_k = 0f;
Time.captureFramerate = fps;
Time.fixedDeltaTime = 1f / Mathf.Max(fps, 60);
_takeName = name;
Listen(name);
int skip = Mathf.RoundToInt(lead * fps) + 4;
for (int i = 0; i < skip; i++)
{
_frameNow = i - skip;
yield return null;
}
int frames = Mathf.RoundToInt(seconds * fps);
for (int f = 0; f < frames; f++)
{
_frameNow = f;
_k = frames > 1 ? f / (float)(frames - 1) : 0f;
every?.Invoke(_k);
yield return new WaitForEndOfFrame();
RollAlso(f);
if (_onlyAlso) continue;
_cam.targetTexture = _rt;
_cam.Render();
var was = RenderTexture.active;
RenderTexture.active = _rt;
_read.ReadPixels(new Rect(0, 0, W, H), 0, 0, false);
RenderTexture.active = was;
if (hud) Overlay();
File.WriteAllBytes(Path.Combine(dir, f.ToString("00000") + ".jpg"), _read.EncodeToJPG(96));
}
_lens = null;
Time.captureFramerate = 0;
StopListening();
Log($"{name}: {frames} frames");
}
protected bool Wanted(string name) => _only == null || _only.Any(o => name.StartsWith(o) || o.StartsWith(name));
// ───────────────────────── the cast ─────────────────────────
protected CineExtra Actor(int who, Vector3 at, Vector3 facing, ToolId tool = ToolId.Scythe, bool cut = false, Func<float, Vector3> path = null, int colour = -1)
{
var go = new GameObject("Extra" + who);
var soil = Planet.Surface(at);
go.transform.SetPositionAndRotation(soil, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, Planet.Up(soil)), Planet.Up(soil)));
var e = go.AddComponent<CineExtra>();
e.Tool = tool;
e.Cutting = cut;
e.Path = path;
// each its own moment in the stroke, the same every run
e.Lag = Mathf.Repeat(who * 0.37f + _props.Count * 0.61f, 1.9f);
e.Tint = PlayerAgent.Palette[(colour < 0 ? who : colour) % PlayerAgent.Palette.Length];
var body = new GameObject("Body");
body.transform.SetParent(go.transform, false);
body.AddComponent<CrewAvatar>().Setup(e, false, who);
_props.Add(go);
return e;
}
protected IEnumerator Machine(VehicleKind kind, Vector3 at, Vector3 facing, Func<float, Vector3> path, int driver, Action<Vehicle> done)
{
var up = Planet.Up(at);
Spawner.Instance.SpawnVehicle(kind, Me.SaveId, at + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, up), up));
yield return null;
var v = Vehicle.All.Last(x => x.kind == kind);
v.ServerPut(at + up * 1.2f, Quaternion.LookRotation(Vector3.ProjectOnPlane(facing, up), up));
v.Driver.Value = NetSession.Instance ? Me.OwnerClientId : 0UL;
var d = v.gameObject.AddComponent<CineDriver>();
d.V = v;
d.Path = path;
if (driver >= 0)
{
var e = Actor(driver, at, facing);
e.Sitting = true;
e.InCab = v.Def.seatDrop > 0f;
e.transform.SetParent(v.seat, false);
e.transform.localPosition = Vector3.zero;
e.transform.localRotation = Quaternion.identity;
}
_machines.Add(v);
done(v);
}
readonly List<Vehicle> _machines = new List<Vehicle>();
protected void Strike()
{
foreach (var g in _props) if (g) Destroy(g);
_props.Clear();
foreach (var v in _machines)
if (v)
{
Destroy(v.GetComponent<CineDriver>());
v.Driver.Value = Vehicle.Nobody;
v.NetworkObject.Despawn(true);
}
_machines.Clear();
}
/// <summary>Whose sky it is. The sun is lower or higher a kilometre from the base.</summary>
protected Vector2 SkyAt;
/// <summary>A light on a pole above a spot, aimed at the ground ahead of it. Only one can burn at a time.</summary>
protected Transform WorkLight(Func<Vector3> over, Func<Vector3> at)
{
var go = new GameObject("WorkLight");
var rig = go.AddComponent<CineRig>();
rig.Over = over;
rig.At = at;
_props.Add(go);
DayNight.Rig = go.transform;
DayNight.SetView(DayNight.Lamp);
return go.transform;
}
/// <summary>The middle of the biggest grove within reach of the base.</summary>
protected Vector2 Grove(float reach)
{
var ground = Ground.Instance;
var names = ground.trees.Where(t => t).Select(t => t.name).ToArray();
var spots = ground.GetComponentsInChildren<Transform>(true).Where(t => names.Any(n => t.name.StartsWith(n))).Select(t => t.position).Where(p => p.y > Planet.NorthCapY && new Vector2(p.x, p.z).magnitude < reach).ToList();
var best = Vector3.zero;
int most = -1;
foreach (var a in spots)
{
int n = spots.Count(b => (a - b).sqrMagnitude < 40f * 40f);
if (n > most) { most = n; best = a; }
}
var flat = new Vector2(best.x, best.z);
Log($"grove of {most} of {spots.Count} at {flat}");
return flat;
}
/// <summary>Bare earth around a spot, so a low camera doesn't look at the backs of blades.</summary>
protected void Clear(float x, float z, float r)
{
for (float d = -r; d <= r; d += 1.5f) MowMap.Cut(On(x - r, z + d), On(x + r, z + d), 2f);
}
/// <summary>The time of day with the sun this high over the base, in the morning or the evening.</summary>
protected float PhaseFor(float height, bool evening)
{
float was = Sun.Pinned, best = 0f, gap = 9f, noon = 0f, top = -2f;
var up = Planet.Up(On(SkyAt.x, SkyAt.y));
for (int i = 0; i < 1440; i++)
{
Sun.Pinned = i / 1440f;
Sun.Tick();
float h = Sun.Height(up);
if (h > top) { top = h; noon = Sun.Pinned; }
}
for (int i = 0; i < 720; i++)
{
Sun.Pinned = Mathf.Repeat(noon + (evening ? i : -i) / 1440f, 1f);
Sun.Tick();
float g = Mathf.Abs(Sun.Height(up) - height);
if (g < gap) { gap = g; best = Sun.Pinned; }
}
Sun.Pinned = was;
return best;
}
protected void Sky(float height, bool evening = true) => Sun.Pinned = PhaseFor(height, evening);
/// <summary>The sky runs from one height of the sun to another. The clock only ever goes forward.</summary>
protected Action<float> SkyRun(float fromHeight, bool fromEvening, float toHeight, bool toEvening)
{
float a = PhaseFor(fromHeight, fromEvening), b = PhaseFor(toHeight, toEvening);
if (b < a) b += 1f;
return k => Sun.Pinned = Mathf.Repeat(Mathf.Lerp(a, b, k), 1f);
}
// ───────────────────────── rolling ─────────────────────────
public IEnumerator Shoot(string folder)
{
Folder = folder;
if (CommandLine.Get("-shots") is string s) _only = new HashSet<string>(s.Split(','));
TeamState.DeleteSave();
yield return new WaitForSeconds(2f);
NetSession.Instance.HostLocal();
while (!Me || !Ts) yield return null;
yield return new WaitForSeconds(2f);
// the world keeps the time of the frames from here on, not of the wall
double netAt = Ts.Now, gameAt = Time.timeAsDouble;
TeamState.ClockOverride = () => netAt + (Time.timeAsDouble - gameAt);
DirectorCall.Quiet = true;
Cheats.Run("tool all");
Cheats.Run("money set 90000000");
_cam = CameraFx.Cam;
_rt = new RenderTexture(W, H, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "Trailer", antiAliasing = 4 };
_rt.Create();
_read = new Texture2D(W, H, TextureFormat.RGB24, false, false);
// the camera comes off the player's head, and the player off the set
var fx = _cam.GetComponent<CameraFx>();
_cam.transform.SetParent(null, true);
if (fx) fx.enabled = false;
ViewModel.Hidden = true;
DayNight.SetView(DayNight.Off);
var body = Me.GetComponentInChildren<CrewAvatar>();
if (body) body.gameObject.SetActive(false);
Application.runInBackground = true;
// the hemp stays out of the picture, the store page sells a lawn
var grass = FindAnyObjectByType<GrassField>();
if (grass) grass.hempMat = null;
yield return new WaitForSeconds(1.5f);
yield return CommandLine.Has("-stills") ? Stills() : Script();
Time.captureFramerate = 0;
Log("wrap");
Application.Quit();
}
}
}