using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEngine; namespace GrassCutter { /// A body with nobody in it, for the trailer: walks a path, mows what's in front of it, looks like any player. 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; /// When it hits the ground, if it comes in from the sky. public float DropAt = -1f; /// Where it stands, by the seconds since it was made. Null stays put. public Func 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; } } /// Keeps a light where the shot needs it. public class CineRig : MonoBehaviour { public Func Over, At; void LateUpdate() { if (Over == null) return; var from = Over(); transform.SetPositionAndRotation(from, Quaternion.LookRotation(At() - from, Planet.Up(from))); } } /// Drives a real machine along a path, as the local player: it keeps its own suspension, wheels, strip and spray. [DefaultExecutionOrder(100)] public class CineDriver : MonoBehaviour { public Vehicle V; public Func 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; } } /// /// `-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. /// [DefaultExecutionOrder(-2000)] public partial class Trailer : MonoBehaviour { const int W = 2560, H = 1440; public string Folder; Camera _cam; RenderTexture _rt; Texture2D _read; Func _lens; float _k; readonly List _props = new List(); HashSet _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 ───────────────────────── /// A point on the ground, in metres from the base. 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; } /// 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. protected IEnumerator Take(string name, float seconds, int fps, Func lens, float lead = 0f, Action 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 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(); 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().Setup(e, false, who); _props.Add(go); return e; } protected IEnumerator Machine(VehicleKind kind, Vector3 at, Vector3 facing, Func path, int driver, Action 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(); 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 _machines = new List(); protected void Strike() { foreach (var g in _props) if (g) Destroy(g); _props.Clear(); foreach (var v in _machines) if (v) { Destroy(v.GetComponent()); v.Driver.Value = Vehicle.Nobody; v.NetworkObject.Despawn(true); } _machines.Clear(); } /// Whose sky it is. The sun is lower or higher a kilometre from the base. protected Vector2 SkyAt; /// A light on a pole above a spot, aimed at the ground ahead of it. Only one can burn at a time. protected Transform WorkLight(Func over, Func at) { var go = new GameObject("WorkLight"); var rig = go.AddComponent(); rig.Over = over; rig.At = at; _props.Add(go); DayNight.Rig = go.transform; DayNight.SetView(DayNight.Lamp); return go.transform; } /// The middle of the biggest grove within reach of the base. 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(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; } /// Bare earth around a spot, so a low camera doesn't look at the backs of blades. 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); } /// The time of day with the sun this high over the base, in the morning or the evening. 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); /// The sky runs from one height of the sun to another. The clock only ever goes forward. protected Action 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(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(); _cam.transform.SetParent(null, true); if (fx) fx.enabled = false; ViewModel.Hidden = true; DayNight.SetView(DayNight.Off); var body = Me.GetComponentInChildren(); 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(); 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(); } } }