using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; using UnityEngine.UIElements; namespace GrassCutter { /// /// The end of the game: the last blade on Herbaria-7 is down. A beat, the phone rings, and the Director, voice breaking, /// tells the crew they did it. The phone goes down and the cuts climb away from the bare ground, slower than the opening /// film's, until the planet hangs in space, mown bald. Over it: the title, a line, what the crew did. Then a jump across space /// to where the grass went: Earth, scorched and dried out. A rocket from Herbaria-7 comes past the lens and down onto it, the /// green spreads from where it lands over the whole ball, and the credits roll up past it, THE END… and a card to go on /// mowing, leave a review or go back to the menu. Space, Enter or /// Esc jumps to that card. Every player in the session sees it at once on their own screen; it plays once per world, when /// the planet goes past while you are in it (the cheat "ending" plays it again). /// [DefaultExecutionOrder(10000)] public class EndingCinematic : MonoBehaviour { const string SeenKey = "gc_ending_seen"; /// The planet counts as mown from here, the same line as the Director's last milestone. public const double Done = 0.99999d; public const string ReviewUrl = "https://store.steampowered.com/recommended/recommendgame/5551720"; /// This computer has watched the ending at least once. public static bool Seen => PlayerPrefs.GetInt(SeenKey, 0) == 1; public static bool Running { get; private set; } /// The cheat and the dev bot: play it now, whatever the planet says. public static bool Force; /// Where the film is, for the dev bot's pictures. public static string Stage => Running ? I._phase.ToString() : ""; static EndingCinematic I; // who made it: roles and names, in the order they roll (roles go through Loc, names never do) static readonly (string role, string[] names)[] Credits = { (Loc.N("A game by"), new[] { "Exbyte Studios" }), (Loc.N("Publisher"), new[] { "PlayWay" }), (Loc.N("Art"), new[] { "POLYGON art by Synty Studios" }), (Loc.N("Fonts"), new[] { "Lilita One by Juan Montoreano", "Nunito by the Nunito Project Authors", "Noto Sans CJK by Google and Adobe" }), (Loc.N("Made with"), new[] { "Unity", "Netcode for GameObjects", "Steamworks.NET" }), (Loc.N("Mission control"), new[] { "G.R.A.S.S.A." }), }; enum Phase { None, Call, Climb, Space, Results, Earth, Credits, End } enum Shot { None, Path, Rise, Orbit, Earth } Phase _phase; Shot _shot; Coroutine _run; float _near = 0.05f, _far = 14000f; // the orbit: round the ball's centre about an axis, the ball easing off to one side of the frame Vector3 _orbitFrom, _orbitAxis; float _orbitAngle, _orbitSpeed, _orbitDist, _shift, _shiftTo; // what the watcher saw last bool _seeded, _due; float _seedAt = -1f; double _mown; VisualElement _layer, _black, _top, _bottom, _titleBox, _stats, _creditsBox, _flash; // the punch on top of every shot: the lens's own field of view (eased), a kick that springs back, a shake, a bank into // turns, a lens bend and colour fringes, and blur from the lens's own motion float _fovShot = 70f, _fov = 70f, _fovShown = 70f, _fovKick, _fovKickV, _shake, _roll, _distort, _fringe; float _fovHold = -1f; Vector3 _lastEye; Volume _fx; MotionBlur _blur; LensDistortion _lens; ChromaticAberration _ca; float _shadow0 = -1f; static readonly int FarOnlyId = Shader.PropertyToID("_GcFarOnly"); // Earth, and the lens round it: how far round from the sun (degrees) and how far out EndingEarth _earth; float _eTheta, _eDist, _eDistTo, _warp; Label _ring, _title, _sub, _line, _skip, _theEnd, _unless; VisualElement _cardLayer; /// /// "-ending" on the command line (without a test bot): straight into a test world of its own, every sector mown, and /// the ending as a player gets it. Saves and awards go to the dev folders, never the player's. /// public static bool Preview => CommandLine.Has("-ending") && !CommandLine.Has("-autodemo"); void Awake() => I = this; void Start() { if (Preview) StartCoroutine(MowForPreview()); } IEnumerator MowForPreview() { // from the menu, as the test bots start: a fresh test world of its own (never the player's slots) yield return new WaitForSeconds(2f); TeamState.DeleteSave(); NetSession.Instance.HostLocal(); while (!TeamState.Instance || !TeamState.Instance.IsSpawned || !PlayerAgent.Local || !PlayerAgent.Local.IsSpawned) yield return null; yield return new WaitForSeconds(4f); var ts = TeamState.Instance; if (!ts.IsServer) yield break; // the milestones on the way would ring first and keep the ending waiting DirectorCall.Quiet = true; ts.ServerDeposit(48000f, CargoKind.Grass, PlayerAgent.Local.transform.position); for (int id = 0; id < HexGrid.Cells; id++) { MowMap.Close(id); if (id % 4000 == 0) yield return null; } } /// The dev bot's Space: straight to THE END and the card. public static void SkipNow() { if (I && Running && I._phase != Phase.End) I.SkipToEnd(); } static readonly int BaldId = Shader.PropertyToID("_GcBald"); float _bald = -1f; void Update() { Watch(); // the far meadow turns to stubble once the planet is mown, and in the film whatever the planet says var tsb = TeamState.Instance; float bald = Running || (tsb && tsb.IsSpawned && tsb.Mown01 >= Done) ? 1f : 0f; if (bald != _bald) { _bald = bald; Shader.SetGlobalFloat(BaldId, bald); } // calls still waiting (a lesser milestone passed on the way) would be stale after it: they go if (_due) DirectorCall.Drop(); if (_due && !Running && Ready()) { _due = false; _run = StartCoroutine(Run()); } if (!Running) return; var k = Keyboard.current; bool skip = k != null && (k.spaceKey.wasPressedThisFrame || k.enterKey.wasPressedThisFrame || k.escapeKey.wasPressedThisFrame); if (skip && _phase != Phase.End) SkipToEnd(); // the card is shut (its button, or Esc through the modal stack): back to the game if (_phase == Phase.End && _cardLayer != null && _cardLayer.pickingMode == PickingMode.Ignore) Finish(); } /// The planet going past the line while you are in the world; a save that loads already mown doesn't count. void Watch() { var ts = TeamState.Instance; var me = PlayerAgent.Local; if (!ts || !ts.IsSpawned || !me || !me.IsSpawned) { _seeded = false; _seedAt = -1f; _due = false; if (Running) Finish(); return; } if (Force) { Force = false; _due = true; } if (Demo.On) return; if (_seedAt < 0f) _seedAt = Time.time + 6f; double mown = ts.Mown01; if (!_seeded) { if (Time.time < _seedAt) return; _seeded = true; _mown = mown; return; } if (_mown < Done && mown >= Done) _due = true; _mown = mown; } /// Not over the opening film, a call or a menu. static bool Ready() => !IntroCinematic.Running && !Ctl.Cinematic && !DirectorCall.Busy && !Ctl.UIOpen && Phone.I && UIRoot.I; // ───────── the film ───────── IEnumerator Run() { Running = true; _phase = Phase.Call; Ctl.Cinematic = true; UIRoot.I.HideHud(true); Build(); // 1. a breath: the last blade is down, eyes out to the horizon. Then the phone. var me0 = PlayerAgent.Local; if (me0) { var up0 = Planet.Up(me0.transform.position); var f0 = Vector3.ProjectOnPlane(me0.transform.forward, up0).normalized; if (f0.sqrMagnitude > 0.01f) me0.LookAt(Planet.Surface(me0.transform.position + f0 * 60f) + up0 * 1.5f); } Sfx.Play("milestone", 0.8f, 1f, 0f); yield return new WaitForSeconds(1.8f); _ring.style.display = DisplayStyle.Flex; UIK.PopIn(_ring, 0f, 0.3f); for (int i = 0; i < 2; i++) { Sfx.Play("phone_ring", 0.5f, 1f, 0f); UIK.Punch(_ring, 0.12f); yield return new WaitForSeconds(1.5f); } _ring.style.display = DisplayStyle.None; Phone.I?.Show(PhoneMode.Up); yield return new WaitForSeconds(0.7f); yield return DirectorCall.Speak("dir_m100", true); Phone.I?.Show(PhoneMode.Away); yield return new WaitForSeconds(0.5f); // 2. flights: skimming the stubble in to the base, round the base, past a machine at work, then one long rise // from the ground into space that turns into the slow orbit of the ball _phase = Phase.Climb; Sfx.Music("music_menu_loop", 3f); Bars(true); GrassField.FurReach = 3.5f; var home = Planet.OnSurface(Vector3.up); var up = Planet.Up(home); var cam = CameraFx.Cam; var look0 = cam ? Vector3.ProjectOnPlane(cam.transform.forward, up) : Vector3.forward; var d = ClearHeading(home, look0.sqrMagnitude > 0.01f ? look0.normalized : Vector3.ProjectOnPlane(Vector3.forward, up).normalized); var side = Vector3.Cross(up, d); // skim: a metre and a half over the stubble, fast, straight in at the base and up over its rail { float[] at = { 135f, 100f, 66f, 36f, 15f }; float[] h = { 1.5f, 1.3f, 1.5f, 3.2f, 8.5f }; var eyes = new Vector3[at.Length]; var looks = new Vector3[at.Length]; for (int i = 0; i < at.Length; i++) { eyes[i] = Ground(home + d * at[i] + side * (2f - i) * 1.2f, h[i]); looks[i] = i >= at.Length - 2 ? home + up * (i == at.Length - 1 ? 1f : 4f) : Ground(home + d * (at[i] - 45f), 1.6f); } Sfx.Play("cut_whoosh_1", 0.4f, 0.85f, 0f); _fovShot = _fov = _fovShown = 84f; Kick(10f, 0.2f, -0.25f, 0.6f); yield return Fly(eyes, looks, 5f); } // past a machine or a robot near the base, if the crew has one if (Worker(home, out var wPos, out var wFwd)) { var wUp = Planet.Up(wPos); var wSide = Vector3.Cross(wUp, wFwd); var eyes = new[] { Ground(wPos - wFwd * 14f + wSide * 7f, 2.2f), Ground(wPos - wFwd * 2f + wSide * 6f, 1.8f), Ground(wPos + wFwd * 11f + wSide * 5f, 2.4f) }; var looks = new[] { wPos + wUp * 1f, wPos + wUp * 1f, wPos + wUp * 1.2f }; Sfx.Play("cut_whoosh_2", 0.35f, 0.95f, 0f); _fovShot = _fov = _fovShown = 72f; Kick(-6f, 0f, 0.15f, 0.4f); yield return Fly(eyes, looks, 4.2f); } // round the base, close, over the roofs, half way round it Vector3 arcEnd; { var c = home + up * 2.5f; int n = 7; var eyes = new Vector3[n]; var looks = new Vector3[n]; for (int i = 0; i < n; i++) { var r = Quaternion.AngleAxis(-20f + i * 30f, up) * d; eyes[i] = Ground(home + r * (26f - i * 0.6f), 9.5f + i * 0.9f); looks[i] = c; } arcEnd = eyes[n - 1]; Sfx.Play("cut_whoosh_1", 0.35f, 1.1f, 0f); _fovShot = _fov = _fovShown = 64f; Kick(-6f, 0f, 0.15f, 0.4f); yield return Fly(eyes, looks, 6.5f); } // the rise: on from where the arc left off, straight up over the base, then out, without a cut, into the orbit _phase = Phase.Space; OrbitSetup(Planet.Up(arcEnd), side); Sfx.Play("space_rumble", 0.8f, 1f, 0f); Sfx.Play("cut_whoosh_2", 0.45f, 0.7f, 0f); _fovShot = 60f; Kick(-12f, 0.45f, 0.3f, 0.7f); yield return Rise(arcEnd, home + up * 2.5f, 12f); _shot = Shot.Orbit; yield return new WaitForSeconds(0.9f); _title.text = Loc.T("HERBARIA-7"); _sub.text = Loc.T("100% MOWN"); _sub.style.display = DisplayStyle.Flex; Show(_titleBox, 0.25f); Slam(_title); SlideIn(_sub, 0.35f); yield return new WaitForSeconds(4.6f); Hide(_titleBox, 1.2f); yield return new WaitForSeconds(1.4f); _line.text = Loc.T("Every blade. Cut, packed and shipped."); Show(_line, 0.6f); SlideIn(_line, 0f); yield return new WaitForSeconds(3.4f); Hide(_line, 0.9f); yield return new WaitForSeconds(1.1f); // 4. what the crew did, the ball easing off to the right _phase = Phase.Results; _shiftTo = 1f; Kick(-4f, 0.1f, 0f, 0.25f); Sfx.Play("paper_whoosh", 0.35f, 0.9f, 0f); yield return new WaitForSeconds(0.8f); FillStats(true); yield return new WaitForSeconds(9.5f); Hide(_stats, 1.2f); _shiftTo = 0f; yield return new WaitForSeconds(1.4f); // 5. a jump across space to where the grass went: Earth, scorched and dry _phase = Phase.Earth; yield return Warp(); yield return new WaitForSeconds(1.4f); _title.text = Loc.T("EARTH"); _sub.style.display = DisplayStyle.None; Show(_titleBox, 0.25f); Slam(_title); yield return new WaitForSeconds(3.6f); Hide(_titleBox, 1.2f); yield return new WaitForSeconds(1.0f); // 6. the rocket from Herbaria-7 past the lens and down onto it, and the green spreading from where it lands _earth.OnPass = () => Kick(10f, 0f, -0.2f, 0.6f); _earth.OnLand = () => { Kick(-8f, 0f, 0.25f, 0.9f); Sfx.Play("bomb_boom", 0.45f, 0.7f, 0f); }; yield return _earth.Rocket(EarthPose, LandingPlace, 7f); float greenT = 0f; bool said = false; while (!_earth.Healed && greenT < 25f) { greenT += Time.deltaTime; if (!said && greenT > 9f) { said = true; _line.text = Loc.T("Earth has grass again."); Show(_line, 0.6f); SlideIn(_line, 0f); } yield return null; } yield return new WaitForSeconds(2.5f); if (said) Hide(_line, 0.9f); yield return new WaitForSeconds(1.2f); // 7. the credits roll up past it, the ball easing off to the right _phase = Phase.Credits; _shiftTo = 1f; Kick(-3f, 0.08f, 0f, 0.2f); yield return new WaitForSeconds(0.8f); yield return RollCredits(32f); // 8. THE END… and the card yield return End(); } /// /// A jump: the lens falls away from the ball and stretches wide, bent and fringed, the screen goes white; it comes back /// wide on Earth and settles. /// IEnumerator Warp() { Sfx.Play("meteor_whoosh", 0.8f, 0.7f, 0f); Sfx.Play("cut_whoosh_2", 0.6f, 0.6f, 0f); _flash.style.display = DisplayStyle.Flex; float fov0 = _fov; float t = 0f; while (t < 0.9f) { t += Time.deltaTime; float k = Mathf.Clamp01(t / 0.9f); _warp = k * k; _fovHold = Mathf.Lerp(fov0, 125f, k * k * k); _distort = Mathf.Lerp(0f, -0.65f, k * k); _fringe = k; _shake = Mathf.Max(_shake, k * 0.5f); _flash.style.opacity = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.55f, 1f, k)); yield return null; } _flash.style.opacity = 1f; EarthSetup(); _warp = 0f; _fovHold = -1f; _fov = _fovShown = 118f; _distort = -0.5f; yield return null; Sfx.Play("space_rumble", 0.7f, 0.8f, 0f); Sfx.Play("popk_boom_2", 0.5f, 0.55f, 0f); t = 0f; while (t < 1.0f) { t += Time.deltaTime; _flash.style.opacity = 1f - Mathf.SmoothStep(0f, 1f, t / 1.0f); yield return null; } _flash.style.display = DisplayStyle.None; } /// A title lands: big, then down to size with a bounce, the lens jolted with it. void Slam(VisualElement e) { e.style.scale = new Scale(new Vector2(1.8f, 1.8f)); Tween.Run(e, 0.55f, k => { float sc = Mathf.LerpUnclamped(1.8f, 1f, k); e.style.scale = new Scale(new Vector2(sc, sc)); }, Ease.OutBack); Kick(-7f, 0.35f, 0.25f, 0.6f); Sfx.Play("popk_boom_2", 0.55f, 0.6f, 0f); } /// Words come up into place from a little below. static void SlideIn(VisualElement e, float delay) { e.style.translate = new Translate(0f, 40f); Tween.Run(e, 0.6f, k => e.style.translate = new Translate(0f, Mathf.Lerp(40f, 0f, k)), Ease.OutCubic, delay); } /// A hit on the lens: field of view (degrees, springs back), shake, lens bend, colour fringes. void Kick(float fov, float shake, float distort, float fringe) { _fovKick += fov; _shake = Mathf.Max(_shake, shake); _distort += distort; _fringe = Mathf.Max(_fringe, fringe); } /// Earth made (once) and the lens out in front of it, stars round the new spot. void EarthSetup() { if (_earth == null) { var sun = Sun.Dir.sqrMagnitude > 0.01f ? Sun.Dir.normalized : Vector3.up; _earth = new EndingEarth(Planet.Center, sun); _eTheta = 58f; _eDist = EndingEarth.R * 3.0f; _eDistTo = EndingEarth.R * 2.3f; // America under the rocket when it comes down (about 15 s on) _earth.Face(LandingPlace, EarthLanding(), 15f); } _shift = _shiftTo = 0f; _shot = Shot.Earth; _fovShot = 64f; _near = 1f; _far = 60000f; SpaceSky.Set(false, Vector3.zero); SpaceSky.Set(true, EarthEye()); } // the middle of the United States (Kansas): green fields all round once it takes static readonly Vector3 LandingPlace = EndingEarth.Geo(39f, -98f); Vector3 EarthView() { float th = _eTheta * Mathf.Deg2Rad; return (_earth.Sun * Mathf.Cos(th) + _earth.Side * Mathf.Sin(th)).normalized; } Vector3 EarthEye() => _earth.Center + EarthView() * EarthDist(); // further out while the ball sits off to one side, so it stays round at the edge of the frame float EarthDist() => _eDist + EndingEarth.R * 0.9f * _shift; /// Where the lens is round Earth this frame, and which way it looks. Pose EarthPose() { var v = EarthView(); var e = _earth.Center + v * EarthDist(); var right = Vector3.Cross(_earth.Up, -v).normalized; var look = _earth.Center - right * EndingEarth.R * 1.15f * _shift; return new Pose(e, Quaternion.LookRotation(look - e, _earth.Up)); } /// Where the rocket comes down: on the face we see, up a little and towards the sun. Vector3 EarthLanding() => (EarthView() * 0.9f + _earth.Up * 0.32f + _earth.Sun * 0.22f).normalized; /// A point this high over the ground under p. static Vector3 Ground(Vector3 p, float h) { var g = Planet.Surface(p); return g + Planet.Up(g) * h; } /// The way out from the base with a clear run along the ground, starting from the one given. static Vector3 ClearHeading(Vector3 home, Vector3 prefer) { var up = Planet.Up(home); for (int k = 0; k < 8; k++) { var d = Quaternion.AngleAxis(k * 45f, up) * prefer; if (!Physics.Linecast(Ground(home + d * 180f, 1.5f), Ground(home + d * 60f, 2.5f)) && !Physics.Linecast(Ground(home + d * 60f, 4.5f), home + up * 6f)) return d; } return prefer; } /// The crew's machine or robot nearest the base (within reach of a flight), and which way it faces. static bool Worker(Vector3 home, out Vector3 pos, out Vector3 fwd) { pos = fwd = Vector3.zero; float best = 600f * 600f; Transform pick = null; foreach (var v in Vehicle.All) if (v && (v.transform.position - home).sqrMagnitude < best) { best = (v.transform.position - home).sqrMagnitude; pick = v.transform; } if (!pick) foreach (var m in Mowbot.All) if (m && (m.transform.position - home).sqrMagnitude < best) { best = (m.transform.position - home).sqrMagnitude; pick = m.transform; } if (!pick) return false; pos = pick.position; var up = Planet.Up(pos); fwd = Vector3.ProjectOnPlane(pick.forward, up).normalized; if (fwd.sqrMagnitude < 0.01f) fwd = Vector3.ProjectOnPlane(Vector3.forward, up).normalized; return true; } // a flight along a smooth curve through the eyes, looking along a smooth curve through the looks Vector3[] _pathEyes, _pathLooks; float[] _pathLen; /// Where along the curve (in points) the lens is when it has gone this share of the way by length. float PathAt(float share) { var L = _pathLen; if (L == null || L.Length < 2) return share * (_pathEyes.Length - 1); float want = share * L[L.Length - 1]; int lo = 0, hi = L.Length - 1; while (hi - lo > 1) { int mid = (lo + hi) / 2; if (L[mid] < want) lo = mid; else hi = mid; } float f = L[hi] > L[lo] ? (want - L[lo]) / (L[hi] - L[lo]) : 0f; return (lo + f) / (L.Length - 1) * (_pathEyes.Length - 1); } float _pathT, _pathFor; // the rise: from an eye over the ground out to the orbit's first spot Vector3 _riseFrom, _riseLook, _riseTop; float _riseAlt0; IEnumerator Fly(Vector3[] eyes, Vector3[] looks, float seconds) { _pathEyes = eyes; _pathLooks = looks; // the curve's length table: the lens runs along it at an even speed, like a dolly on its track const int Steps = 240; _pathLen = new float[Steps + 1]; var prev = Spline(eyes, 0f); for (int i = 1; i <= Steps; i++) { var e = Spline(eyes, i / (float)Steps * (eyes.Length - 1)); _pathLen[i] = _pathLen[i - 1] + Vector3.Distance(prev, e); prev = e; } _pathT = 0f; _pathFor = seconds; _shot = Shot.Path; _near = 0.05f; _far = 14000f; while (_pathT < _pathFor) yield return null; } IEnumerator Rise(Vector3 from, Vector3 look, float seconds) { _riseFrom = from; _riseLook = look; // the top of the frame while the lens looks down: the way from the start to the base, fixed in the world, so it // never flips when the eye passes over the base _riseTop = Vector3.ProjectOnPlane(look - from, Planet.Up(from)).normalized; _riseAlt0 = Mathf.Max(1f, Planet.Altitude(from)); _pathT = 0f; _pathFor = seconds; _shot = Shot.Rise; while (_pathT < _pathFor) yield return null; } static Vector3 Spline(Vector3[] p, float u) { int n = p.Length; if (n == 1) return p[0]; u = Mathf.Clamp(u, 0f, n - 1.0001f); int i = (int)u; float t = u - i; var p0 = p[Mathf.Max(0, i - 1)]; var p1 = p[i]; var p2 = p[Mathf.Min(n - 1, i + 1)]; var p3 = p[Mathf.Min(n - 1, i + 2)]; return 0.5f * (2f * p1 + (p2 - p0) * t + (2f * p0 - 5f * p1 + 4f * p2 - p3) * t * t + (3f * p1 - p0 - 3f * p2 + p3) * t * t * t); } IEnumerator RollCredits(float seconds) { FillCredits(); _creditsBox.style.opacity = 1f; _creditsBox.style.display = DisplayStyle.Flex; // one frame for it to lay out, then it climbs from under the screen to over the top _creditsBox.style.translate = new Translate(0f, 4000f); yield return null; yield return null; float screen = _layer.resolvedStyle.height > 0f ? _layer.resolvedStyle.height : 1080f; float tall = Mathf.Max(400f, _creditsBox.resolvedStyle.height); float t = 0f; while (t < seconds) { t += Time.deltaTime; float y = Mathf.Lerp(screen, -tall, t / seconds); _creditsBox.style.translate = new Translate(0f, y); yield return null; } _creditsBox.style.display = DisplayStyle.None; } IEnumerator End() { _phase = Phase.End; PlayerPrefs.SetInt(SeenKey, 1); PlayerPrefs.Save(); _shiftTo = 0f; _theEnd.style.display = DisplayStyle.Flex; _theEnd.style.opacity = 0f; Show(_theEnd, 1.6f); yield return new WaitForSeconds(2.6f); _unless.style.display = DisplayStyle.Flex; _unless.style.opacity = 0f; Show(_unless, 0.8f); yield return new WaitForSeconds(2.2f); Hide(_theEnd, 0.8f); Hide(_unless, 0.8f); Bars(false); _skip.style.display = DisplayStyle.None; yield return new WaitForSeconds(0.6f); OpenCard(); _run = null; } /// Space / Enter / Esc: whatever is left, straight to THE END and the card. void SkipToEnd() { if (_run != null) StopCoroutine(_run); if (_phase == Phase.Call) DirectorCall.Abort(); Sfx.Play("cut_return", 0.5f, 1f, 0f); if (Phone.I && Phone.I.Mode != PhoneMode.Away) Phone.I.Show(PhoneMode.Away); _ring.style.display = DisplayStyle.None; foreach (var e in new VisualElement[] { _titleBox, _line, _stats, _creditsBox, _flash }) { Tween.Kill(e); e.style.display = DisplayStyle.None; } Sfx.Music("music_menu_loop", 1.5f); Bars(true); GrassField.FurReach = 3.5f; // the last picture is Earth, green all over _warp = 0f; _fovHold = -1f; EarthSetup(); _earth.HealNow(); _run = StartCoroutine(End()); } void Finish() { if (_run != null) StopCoroutine(_run); _run = null; if (_phase == Phase.Call) DirectorCall.Abort(); Running = false; _phase = Phase.None; _shot = Shot.None; _shift = _shiftTo = 0f; _warp = 0f; _fovHold = -1f; _fovKick = _fovKickV = _shake = _roll = _distort = _fringe = 0f; if (_fx) _fx.enabled = false; Shader.SetGlobalFloat(FarOnlyId, 0f); GrassCutter.Ground.FarSkin = false; if (_shadow0 >= 0f && RenderSettings.sun) RenderSettings.sun.shadowStrength = _shadow0; _shadow0 = -1f; _earth?.Destroy(); _earth = null; if (_flash != null) _flash.style.display = DisplayStyle.None; SpaceSky.Set(false, Vector3.zero); GrassField.FurReach = 1f; var cam = CameraFx.Cam; if (cam) { cam.nearClipPlane = 0.05f; cam.farClipPlane = 14000f; cam.fieldOfView = CameraFx.BaseFov; } if (cam && cam.transform.parent) cam.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); Ctl.Cinematic = false; if (UIRoot.I) UIRoot.I.HideHud(false); Sfx.Duck(1f); if (_cardLayer != null && _cardLayer.pickingMode != PickingMode.Ignore) UIRoot.I?.CloseModal(_cardLayer); _cardLayer = null; if (_layer != null) _layer.style.display = DisplayStyle.None; if (Phone.I && Phone.I.Mode != PhoneMode.Away) Phone.I.Show(PhoneMode.Away); } // ───────── the card at the end ───────── void OpenCard() { _cardLayer = UIRoot.I.OpenModal(layer => { var card = UIK.El("card", layer); card.pickingMode = PickingMode.Position; card.style.width = 760; card.style.alignItems = Align.Stretch; UIK.Text(Loc.T("HERBARIA-7 IS MOWN"), "t-h1 t-dark t-center", card); var body = UIK.Text(Loc.T("Earth has grass again. Thank you for mowing with us."), "t-body t-dark t-center", card, false); body.style.whiteSpace = WhiteSpace.Normal; body.style.marginBottom = 10; var note = UIK.Text(Loc.T("The world is still yours: every machine, every belt, every robot."), "t-small t-muted t-center", card, false); note.style.whiteSpace = WhiteSpace.Normal; note.style.marginBottom = 16; UIK.Btn(Loc.T("KEEP MOWING"), () => UIRoot.I.CloseModal(layer), "btn btn-green", card); UIK.Btn(Loc.T("LEAVE A REVIEW"), () => SteamManager.OpenWeb(ReviewUrl), "btn btn-blue", card); UIK.Btn(Loc.T("LEAVE TO MENU"), () => { UIRoot.I.CloseModal(layer); Finish(); NetSession.Instance.Leave(); }, "btn btn-red", card); return card; }); } // ───────── the screen ───────── void Build() { if (_layer == null || _layer.panel == null) { var root = UIRoot.I.Cinema; _layer = UIK.El("layer", root); _layer.pickingMode = PickingMode.Ignore; _flash = new VisualElement { pickingMode = PickingMode.Ignore }; _flash.style.position = Position.Absolute; _flash.style.left = _flash.style.right = _flash.style.top = _flash.style.bottom = 0; _flash.style.backgroundColor = new Color(1f, 0.99f, 0.95f); _flash.style.display = DisplayStyle.None; _layer.Add(_flash); _top = Bar(_layer, true); _bottom = Bar(_layer, false); _ring = UIK.Text("", "director-ring t-outline", _layer); _titleBox = UIK.El("ending-titlebox", _layer); _title = UIK.Text("", "ending-title t-outline", _titleBox); _sub = UIK.Text("", "ending-sub t-outline", _titleBox); _line = UIK.Text("", "ending-line t-outline", _layer, false); _stats = UIK.El("ending-stats", _layer); _creditsBox = UIK.El("ending-credits", _layer); _theEnd = UIK.Text("", "ending-theend t-outline", _layer); _unless = UIK.Text("", "ending-unless t-outline", _layer, false); _skip = UIK.Text("", "cinema-skip t-outline", _layer, false); } _layer.style.display = DisplayStyle.Flex; MakeFx(); _fx.enabled = true; if (RenderSettings.sun && _shadow0 < 0f) _shadow0 = RenderSettings.sun.shadowStrength; var cam0 = CameraFx.Cam; _fov = _fovShot = _fovShown = cam0 ? cam0.fieldOfView : CameraFx.BaseFov; _fovKick = _fovKickV = _shake = _roll = _distort = _fringe = 0f; _ring.text = Loc.T("G.R.A.S.S.A. IS CALLING"); _theEnd.text = Loc.T("THE END"); _unless.text = Loc.T("…unless?"); _skip.text = Loc.T("SPACE skip"); foreach (var e in new VisualElement[] { _ring, _titleBox, _line, _stats, _creditsBox, _theEnd, _unless }) { Tween.Kill(e); e.style.display = DisplayStyle.None; } _skip.style.display = DisplayStyle.Flex; Bars(false); } void FillStats(bool animate) { var ts = TeamState.Instance; _stats.Clear(); if (!ts) return; UIK.Text(Loc.T("WHAT YOUR CREW DID"), "ending-stats-head t-outline", _stats); var rows = new List<(string label, double value, System.Func show)> { (Loc.T("Grass shipped to Earth"), ts.Shipped.Value, v => GameDefs.Kilos(v)), (Loc.T("Planet mown"), System.Math.Min(100d, ts.Mown01 * 100d), v => Loc.F("{0}%", Loc.Num(v, "0.##"))), (Loc.T("Sectors mown clean"), ts.Closed.Value, v => Loc.Num(v, "N0")), (Loc.T("Money earned"), ts.Earned.Value, v => UIK.Money(v)), (Loc.T("Days on Herbaria-7"), Mathf.Max(1, ts.Days), v => Loc.Num(v, "N0")), (Loc.T("Machines"), Vehicle.All.Count(v => v), v => Loc.Num(v, "N0")), (Loc.T("Robots at work"), Mowbot.All.Count, v => Loc.Num(v, "N0")), (Loc.T("Stations found"), ts.Opened.Count, v => Loc.F("{0} / {1}", Loc.Num(v, "N0"), Loc.Num(Stations.Count - 1))), (Loc.T("Survey stakes sorted out"), ts.FoundCount(false), v => Loc.F("{0} / {1}", Loc.Num(v, "N0"), Loc.Num(Landmarks.Stakes))), }; int i = 0; foreach (var (label, value, show) in rows) { var row = UIK.El("ending-row", _stats); UIK.Text(label, "ending-row-label t-outline", row, false); var val = UIK.Text(show(animate ? 0d : value), "ending-row-value t-outline", row); if (animate) { row.style.opacity = 0f; float delay = 0.25f + i * 0.35f; Tween.Run(row, 0.4f, k => row.style.opacity = k, Ease.OutQuad, delay); Tween.Run(val, 1.3f, k => val.text = show(value * k), Ease.OutQuad, delay); } i++; } var crew = PlayerAgent.All.Where(p => p).Select(p => p.DisplayName).ToList(); if (crew.Count > 0) { var c = UIK.Text(Loc.F("The crew: {0}", string.Join(", ", crew)), "ending-crew t-outline", _stats, false); if (animate) { c.style.opacity = 0f; Tween.Run(c, 0.6f, k => c.style.opacity = k, Ease.OutQuad, 0.4f + rows.Count * 0.35f); } } _stats.style.opacity = 1f; _stats.style.display = DisplayStyle.Flex; } void FillCredits() { _creditsBox.Clear(); UIK.Text("GRASS CUTTERS TOGETHER", "ending-credits-title t-outline", _creditsBox); foreach (var (role, names) in Credits) { UIK.Text(Loc.T(role), "ending-credits-role t-outline", _creditsBox, false); foreach (var n in names) UIK.Text(n, "ending-credits-name t-outline", _creditsBox); } UIK.Text(Loc.T("And you"), "ending-credits-role t-outline", _creditsBox, false); UIK.Text(Loc.T("for every blade."), "ending-credits-name t-outline", _creditsBox); var crew = PlayerAgent.All.Where(p => p).Select(p => p.DisplayName).ToList(); foreach (var n in crew) UIK.Text(n, "ending-credits-name t-outline", _creditsBox); UIK.Text(Loc.T("We take grass very seriously."), "ending-credits-motto t-outline", _creditsBox, false); } /// The film's own lens effects, over the game's look: motion blur, a lens bend and colour fringes. void MakeFx() { if (_fx) return; var go = new GameObject("Ending lens"); go.transform.SetParent(transform, false); var p = ScriptableObject.CreateInstance(); _blur = p.Add(true); _blur.mode.Override(MotionBlurMode.CameraOnly); _blur.quality.Override(MotionBlurQuality.Medium); _blur.intensity.Override(0.5f); _blur.clamp.Override(0.06f); _lens = p.Add(true); _lens.intensity.Override(0f); _lens.scale.Override(1f); _ca = p.Add(true); _ca.intensity.Override(0.05f); _fx = go.AddComponent(); _fx.isGlobal = true; _fx.priority = 40f; _fx.sharedProfile = p; _fx.enabled = false; } static VisualElement Bar(VisualElement root, bool top) { var b = new VisualElement { pickingMode = PickingMode.Ignore }; b.AddToClassList("cinema-bars"); if (top) b.style.top = 0; else b.style.bottom = 0; b.style.display = DisplayStyle.None; root.Add(b); return b; } void Bars(bool on) { if (_top == null) return; _top.style.display = _bottom.style.display = on ? DisplayStyle.Flex : DisplayStyle.None; } static void Show(VisualElement e, float seconds) { e.style.display = DisplayStyle.Flex; Tween.Kill(e); e.style.opacity = 0f; Tween.Run(e, seconds, k => e.style.opacity = k, Ease.InOutQuad); } static void Hide(VisualElement e, float seconds) { float from = e.resolvedStyle.opacity; Tween.Kill(e); Tween.Run(e, seconds, k => e.style.opacity = Mathf.Lerp(from, 0f, k), Ease.InOutQuad, 0f, () => e.style.display = DisplayStyle.None); } // ───────── the camera ───────── void Orbit(Vector3 from, Vector3 axisHint) { OrbitSetup(from, axisHint); _shot = Shot.Orbit; SpaceSky.Set(true, Planet.Center + _orbitFrom * _orbitDist); } void OrbitSetup(Vector3 from, Vector3 axisHint) { // round the sun's own axis, two thirds of the way to the sunny side of where the cuts ended: the light on the ball // stays the same however far it turns, the day side with the terminator along one edge var sun = Sun.Dir.normalized; var across = Vector3.ProjectOnPlane(from, sun); if (across.sqrMagnitude < 0.01f) across = Vector3.ProjectOnPlane(axisHint, sun); across.Normalize(); _orbitFrom = (sun * 0.62f + across * 0.78f + Vector3.Cross(sun, across) * 0.1f).normalized; _orbitAxis = sun; _orbitAngle = 0f; _orbitSpeed = 2.2f; _orbitDist = Planet.Radius * 2.6f; _near = 4f; _far = 60000f; } /// The orbit's eye and up at an angle round it. void OrbitPose(float angle, out Vector3 eye, out Vector3 up) { var dir = Quaternion.AngleAxis(angle, _orbitAxis) * _orbitFrom; eye = Planet.Center + dir * _orbitDist; up = Vector3.ProjectOnPlane(Vector3.Cross(_orbitAxis, dir), dir).normalized; if (up.sqrMagnitude < 0.01f) up = Vector3.ProjectOnPlane(Vector3.up, dir).normalized; } float _rollTo; void LateUpdate() { var cam = CameraFx.Cam; if (!cam || !Running || _shot == Shot.None) return; _rollTo = 0f; if (_shot == Shot.Path) { _pathT += Time.deltaTime; float k = Mathf.Clamp01(_pathT / _pathFor); // a dolly: eases off and in at the ends, an even glide between k = Mathf.Lerp(k, k * k * (3f - 2f * k), 0.5f); float u = PathAt(k); var e = Spline(_pathEyes, u); // never under the ground between the points float alt = Planet.Altitude(e); if (alt < 0.9f) e += Planet.Up(e) * (0.9f - alt); var l = Spline(_pathLooks, u); cam.transform.SetPositionAndRotation(e, Quaternion.LookRotation(l - e, Planet.Up(e))); } else if (_shot == Shot.Rise) { _pathT += Time.deltaTime; float k = Mathf.Clamp01(_pathT / _pathFor); OrbitPose(0f, out var oEye, out var oUp); // the height grows by the same factor every second: the ground falls away the same at 10 m as at 10 km float altTo = _orbitDist - Planet.Radius; float alt = Mathf.Exp(Mathf.Lerp(Mathf.Log(_riseAlt0), Mathf.Log(altTo), Mathf.Pow(k, 1.2f))); // straight up over the base first, then across to where the orbit begins float across = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.4f, 1f, k)); var dir = Vector3.Slerp(Planet.Up(_riseFrom), (oEye - Planet.Center).normalized, across); var e = Planet.Center + dir * (Planet.Radius + alt); float lookK = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.45f, 0.95f, k)); var l = Vector3.Lerp(_riseLook, Planet.Center, lookK); var upE = Planet.Up(e); var top = Vector3.ProjectOnPlane(_riseTop, upE); // the head tips down over the base as it climbs: the top of the frame leans from the sky to the way ahead var upv = top.sqrMagnitude > 1e-4f ? Vector3.Slerp(upE, top.normalized, Mathf.InverseLerp(15f, 300f, alt) * 0.95f) : upE; upv = Vector3.Slerp(upv, oUp, Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.6f, 1f, k))); var fwd = l - e; if (Vector3.Cross(fwd.normalized, upv).sqrMagnitude < 1e-4f) upv = top.sqrMagnitude > 1e-4f ? top.normalized : oUp; cam.transform.SetPositionAndRotation(e, Quaternion.LookRotation(fwd, upv)); _near = Mathf.Clamp(alt * 0.004f, 0.05f, 4f); _far = alt > 500f ? 60000f : 14000f; // the sky goes black while the lens still looks down at the ground, before the edge of the ball is in view if (alt > Planet.Radius * 0.15f && !SpaceSky.On) SpaceSky.Set(true, e); } else if (_shot == Shot.Earth) { if (_earth == null) return; float dt = Time.deltaTime; _earth.Tick(dt); // slowly round towards the sun and in a little: more of the ball lit as it turns green _eTheta = Mathf.MoveTowards(_eTheta, 22f, dt * 0.6f); _eDist = Mathf.Lerp(_eDist, _eDistTo, 1f - Mathf.Exp(-dt * 0.12f)); _shift = Mathf.Lerp(_shift, _shiftTo, 1f - Mathf.Exp(-dt * 0.9f)); var pose = EarthPose(); cam.transform.SetPositionAndRotation(pose.position, pose.rotation); } else { _orbitAngle += _orbitSpeed * Time.deltaTime; _shift = Mathf.Lerp(_shift, _shiftTo, 1f - Mathf.Exp(-Time.deltaTime * 0.9f)); _fovShot = 72f; OrbitPose(_orbitAngle, out var e, out var up0); var dir = (e - Planet.Center).normalized; if (_warp > 0f) e += dir * _orbitDist * 2.5f * _warp; var right = Vector3.Cross(up0, -dir).normalized; // the ball slides to the right of the frame while the words are on the left var look = Planet.Center - right * Planet.Radius * 1.25f * _shift; cam.transform.SetPositionAndRotation(e, Quaternion.LookRotation(look - e, up0)); } cam.nearClipPlane = _near; cam.farClipPlane = _far; Punch(cam); } /// /// Over whatever the shot set: the field of view (the shot's, eased, plus a push that eases back off: a zoom, never a /// jolt), the lens effects, and the planet's near detail going as the lens leaves the ground. No shake, no hand-held /// drift: a film camera on rails. /// void Punch(Camera cam) { float dt = Time.deltaTime; // a push in or out that eases back without overshoot _fovKick = Mathf.Lerp(_fovKick, 0f, 1f - Mathf.Exp(-dt * 1.4f)); _fov = Mathf.Lerp(_fov, _fovShot, 1f - Mathf.Exp(-dt * 1.6f)); _fovShown = Mathf.Lerp(_fovShown, Mathf.Clamp((_fovHold > 0f ? _fovHold : _fov) + _fovKick, 25f, 140f), 1f - Mathf.Exp(-dt * (_fovHold > 0f ? 30f : 5f))); cam.fieldOfView = _fovShown; _distort = Mathf.Lerp(_distort, 0f, 1f - Mathf.Exp(-dt * 2.6f)); _fringe = Mathf.Lerp(_fringe, 0f, 1f - Mathf.Exp(-dt * 2.2f)); var eye = cam.transform.position; if (_fx) { _lens.intensity.value = Mathf.Clamp(_distort, -0.75f, 0.75f); _ca.intensity.value = Mathf.Clamp01(0.05f + _fringe * 0.8f); // a cut is a jump of the lens: no streak across it float allow = (40f + Mathf.Max(0f, Planet.Altitude(eye)) * 0.6f) * Mathf.Max(dt, 0.016f) * 4f; bool cut = (eye - _lastEye).sqrMagnitude > allow * allow; _blur.intensity.value = cut ? 0f : 0.5f; } _lastEye = eye; // off the ground the near detail (the cut floor, the pile, the sector lines, the shadows' reach) gives way // evenly to the far planet, so no ring of it is left round the base float alt = _shot == Shot.Earth ? 1e6f : Planet.Altitude(eye); // (the detail goes from 5 m up, under the skim's end; the shadows, which hold the base down, only from 30 m) float far = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(5f, 10f, alt)); Shader.SetGlobalFloat(FarOnlyId, far); // high up: the even skin fixed to the ball, so the hills stay put as the lens moves round GrassCutter.Ground.FarSkin = alt > 250f; float shade = Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(30f, 160f, alt)); if (_shadow0 >= 0f && RenderSettings.sun) RenderSettings.sun.shadowStrength = _shadow0 * (1f - shade); } } }