Grass Cutters Together: the project as of moon-sweepers f3666f0
A clean start for the shared repository: the Unity project (Assets, Packages, ProjectSettings), ArtSource, Docs and Tools as they stood at f3666f0 in the old local repository, with its generated prefabs and scene brought up to date. Images, audio, models and binaries go through Git LFS (.gitattributes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
8
Assets/Scripts/Core.meta
Normal file
8
Assets/Scripts/Core.meta
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4d43a0706ad99634a800123035eb44f6
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
118
Assets/Scripts/Core/Achievements.cs
Normal file
118
Assets/Scripts/Core/Achievements.cs
Normal file
@ -0,0 +1,118 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Steamworks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public class Award
|
||||
{
|
||||
/// <summary>English patterns; <c>{0}</c> in them is <see cref="value"/> (as money when <see cref="money"/>).</summary>
|
||||
public string id, nameEn, descEn;
|
||||
public double value;
|
||||
public bool money;
|
||||
public Func<TeamState, PlayerAgent, bool> done;
|
||||
object Arg => money ? UIK.Money(value) : (object)value;
|
||||
public string name => Loc.F(nameEn, Arg);
|
||||
public string desc => Loc.F(descEn, Arg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The 33 awards: grass shipped, money, sectors, the planet, what was found and what was built. Each player earns them on
|
||||
/// their own computer, and on Steam as well once the game has an AppID of its own: on the test AppID the calls go nowhere.
|
||||
/// </summary>
|
||||
public static class Achievements
|
||||
{
|
||||
const float Every = 2f;
|
||||
|
||||
public static readonly List<Award> All = new List<Award>();
|
||||
|
||||
static readonly HashSet<string> s_got = new HashSet<string>();
|
||||
static float s_next;
|
||||
static bool s_read;
|
||||
|
||||
static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo");
|
||||
static string Key => Dev ? "gc_awards_dev" : "gc_awards";
|
||||
|
||||
static Achievements()
|
||||
{
|
||||
foreach (double kg in new[] { 1d, 100d, 1000d, 10000d, 100000d })
|
||||
Add($"SHIP_{kg:0}", kg < 2d ? Loc.N("First Delivery") : Loc.N("{0:N0} kg for Earth"), Loc.N("Ship {0:N0} kg of grass"), (t, p) => t.Shipped.Value >= kg, kg);
|
||||
foreach (double cash in new[] { 1000d, 10000d, 100000d, 1000000d })
|
||||
Add($"CASH_{cash:0}", Loc.N("{0} in the Bank"), Loc.N("Have {0} in the crew wallet"), (t, p) => t.Money.Value >= cash, cash, true);
|
||||
foreach (int n in new[] { 1, 10, 100, 1000, 10000 })
|
||||
Add($"SECTOR_{n}", n == 1 ? Loc.N("Clean Sweep") : Loc.N("{0:N0} Sectors"), Loc.N("Mow {0:N0} sectors clean"), (t, p) => t.Closed.Value >= n, n);
|
||||
foreach (double pc in new[] { 0.01d, 0.1d, 1d, 10d, 50d, 100d })
|
||||
Add($"PLANET_{pc * 100d:0}", pc >= 100d ? Loc.N("Herbaria Mown") : Loc.N("{0:0.##}% of Herbaria-7"), Loc.N("Mow {0:0.##}% of the planet"), (t, p) => t.Mown01 * 100d >= pc, pc);
|
||||
Add("STAKE_1", Loc.N("Untangled"), Loc.N("Sort out a survey stake"), (t, p) => t.FoundCount(false) >= 1);
|
||||
Add("STAKE_50", Loc.N("Fifty Stakes"), Loc.N("Sort out 50 survey stakes"), (t, p) => t.FoundCount(false) >= 50);
|
||||
Add("STAKE_ALL", Loc.N("Every Last Stake"), Loc.N("Sort out all {0} survey stakes"), (t, p) => t.FoundCount(false) >= Landmarks.Stakes, Landmarks.Stakes);
|
||||
Add("POINT_1", Loc.N("Surveyor"), Loc.N("Read a survey point"), (t, p) => t.FoundCount(true) >= 1);
|
||||
Add("POINT_ALL", Loc.N("The Whole Map"), Loc.N("Read all {0} survey points"), (t, p) => t.FoundCount(true) >= Landmarks.Points, Landmarks.Points);
|
||||
Add("STATION_1", Loc.N("Not Alone Out Here"), Loc.N("Find a far station"), (t, p) => t.Opened.Count >= 1);
|
||||
Add("STATION_5", Loc.N("Well Travelled"), Loc.N("Find 5 far stations"), (t, p) => t.Opened.Count >= 5);
|
||||
Add("STATION_ALL", Loc.N("All Twelve"), Loc.N("Find every station"), (t, p) => t.Opened.Count >= Stations.Count - 1);
|
||||
Add("TOOL_SCYTHE", Loc.N("A Proper Scythe"), Loc.N("Own the Scythe"), (t, p) => p.Owns(ToolId.Scythe));
|
||||
Add("TOOL_ALL", Loc.N("Full Tool Belt"), Loc.N("Own every blade on the wall"), (t, p) => p.Owns(ToolId.WideScythe) && p.Owns(ToolId.LongScythe) && p.Owns(ToolId.Scythe));
|
||||
Add("ROBOT_1", Loc.N("Let the Robot Do It"), Loc.N("Build a robot dock"), (t, p) => Mowbot.All.Count >= 1);
|
||||
Add("ROBOT_10", Loc.N("Robot Crew"), Loc.N("Have 10 robots at work"), (t, p) => Mowbot.All.Count >= 10);
|
||||
Add("REAPER", Loc.N("Fear the Reaper"), Loc.N("Set a Reaper loose"), (t, p) => Mowbot.All.Exists(m => m is Reaper));
|
||||
}
|
||||
|
||||
static void Add(string id, string name, string desc, Func<TeamState, PlayerAgent, bool> done, double value = 0d, bool money = false) => All.Add(new Award { id = id, nameEn = name, descEn = desc, done = done, value = value, money = money });
|
||||
|
||||
static void Read()
|
||||
{
|
||||
if (s_read) return;
|
||||
s_read = true;
|
||||
foreach (var id in PlayerPrefs.GetString(Key, "").Split(',')) if (id.Length > 0) s_got.Add(id);
|
||||
}
|
||||
|
||||
public static bool Has(Award a)
|
||||
{
|
||||
Read();
|
||||
return s_got.Contains(a.id);
|
||||
}
|
||||
|
||||
public static int Earned
|
||||
{
|
||||
get
|
||||
{
|
||||
Read();
|
||||
return s_got.Count;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The demo starts with a clean slate.</summary>
|
||||
public static void Forget()
|
||||
{
|
||||
s_got.Clear();
|
||||
s_read = true;
|
||||
PlayerPrefs.DeleteKey(Key);
|
||||
}
|
||||
|
||||
public static void Tick()
|
||||
{
|
||||
if (Time.time < s_next) return;
|
||||
s_next = Time.time + Every;
|
||||
var ts = TeamState.Instance;
|
||||
var me = PlayerAgent.Local;
|
||||
if (!ts || !me) return;
|
||||
Read();
|
||||
foreach (var a in All)
|
||||
{
|
||||
if (s_got.Contains(a.id) || !a.done(ts, me)) continue;
|
||||
s_got.Add(a.id);
|
||||
PlayerPrefs.SetString(Key, string.Join(",", s_got));
|
||||
PlayerPrefs.Save();
|
||||
Hud.Toast(Loc.F("Achievement: {0}", a.name), Hud.ToastKind.Info);
|
||||
Sfx.Play("milestone", 0.7f);
|
||||
if (SteamManager.Initialized)
|
||||
{
|
||||
SteamUserStats.SetAchievement(a.id);
|
||||
SteamUserStats.StoreStats();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Achievements.cs.meta
Normal file
2
Assets/Scripts/Core/Achievements.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7a7158c422d408343b2ff932295495d5
|
||||
72
Assets/Scripts/Core/AssetBank.cs
Normal file
72
Assets/Scripts/Core/AssetBank.cs
Normal file
@ -0,0 +1,72 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Name-indexed references to clips, textures, fonts, meshes and materials (filled by the editor builder).</summary>
|
||||
[CreateAssetMenu(menuName = "GrassCutter/AssetBank")]
|
||||
public class AssetBank : ScriptableObject
|
||||
{
|
||||
public List<AudioClip> clips = new List<AudioClip>();
|
||||
public List<Texture2D> textures = new List<Texture2D>();
|
||||
public List<Font> fonts = new List<Font>();
|
||||
public List<Mesh> meshes = new List<Mesh>();
|
||||
public List<Material> materials = new List<Material>();
|
||||
public List<GameObject> models = new List<GameObject>();
|
||||
|
||||
static AssetBank _inst;
|
||||
Dictionary<string, AudioClip> _clips;
|
||||
Dictionary<string, Texture2D> _tex;
|
||||
Dictionary<string, Mesh> _meshes;
|
||||
Dictionary<string, Material> _mats;
|
||||
Dictionary<string, GameObject> _models;
|
||||
|
||||
public static AssetBank I
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_inst == null)
|
||||
{
|
||||
_inst = Resources.Load<AssetBank>("AssetBank");
|
||||
if (_inst == null) _inst = CreateInstance<AssetBank>();
|
||||
_inst.Index();
|
||||
}
|
||||
return _inst;
|
||||
}
|
||||
}
|
||||
|
||||
void Index()
|
||||
{
|
||||
_clips = new Dictionary<string, AudioClip>();
|
||||
foreach (var c in clips) if (c) _clips[c.name] = c;
|
||||
_tex = new Dictionary<string, Texture2D>();
|
||||
foreach (var t in textures) if (t) _tex[t.name] = t;
|
||||
_meshes = new Dictionary<string, Mesh>();
|
||||
foreach (var m in meshes) if (m) _meshes[m.name.EndsWith("_baked") ? m.name.Substring(0, m.name.Length - 6) : m.name] = m;
|
||||
_mats = new Dictionary<string, Material>();
|
||||
foreach (var m in materials) if (m) _mats[m.name] = m;
|
||||
_models = new Dictionary<string, GameObject>();
|
||||
foreach (var m in models) if (m) _models[m.name] = m;
|
||||
}
|
||||
|
||||
public AudioClip Clip(string name) => name != null && _clips.TryGetValue(name, out var c) ? c : null;
|
||||
public Texture2D Tex(string name) => name != null && _tex.TryGetValue(name, out var t) ? t : null;
|
||||
public Mesh Mesh(string name) => name != null && _meshes.TryGetValue(name, out var m) ? m : null;
|
||||
public Material Mat(string name) => name != null && _mats.TryGetValue(name, out var m) ? m : null;
|
||||
public GameObject Model(string name) => name != null && _models.TryGetValue(name, out var m) ? m : null;
|
||||
|
||||
public Font Font(string contains)
|
||||
{
|
||||
foreach (var f in fonts) if (f && f.name.Contains(contains)) return f;
|
||||
return fonts.Count > 0 ? fonts[0] : null;
|
||||
}
|
||||
|
||||
/// <summary>All clips whose name starts with prefix (e.g. "pop_0" → pop_01..pop_09).</summary>
|
||||
public List<AudioClip> ClipsWithPrefix(string prefix)
|
||||
{
|
||||
var l = new List<AudioClip>();
|
||||
foreach (var c in clips) if (c && c.name.StartsWith(prefix)) l.Add(c);
|
||||
return l;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/AssetBank.cs.meta
Normal file
2
Assets/Scripts/Core/AssetBank.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3e79d5023278f164ca6a97d020d5610e
|
||||
19
Assets/Scripts/Core/AutoScreenshot.cs
Normal file
19
Assets/Scripts/Core/AutoScreenshot.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Dev helper: `-screenshot out.png [-shotdelay 6] [-autohost]` captures a frame and quits (used for automated checks).</summary>
|
||||
public class AutoScreenshot : MonoBehaviour
|
||||
{
|
||||
public string path;
|
||||
System.Collections.IEnumerator Start()
|
||||
{
|
||||
float delay = float.TryParse(CommandLine.Get("-shotdelay", "6"), out var d) ? d : 6f;
|
||||
if (CommandLine.Has("-autohost")) { yield return new WaitForSeconds(1.5f); NetSession.Instance.HostLocal(); }
|
||||
yield return new WaitForSeconds(delay);
|
||||
yield return BotCapture.Shot(path);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
Application.Quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/AutoScreenshot.cs.meta
Normal file
2
Assets/Scripts/Core/AutoScreenshot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4cc239fcb8181ca42bd0037544a695ba
|
||||
41
Assets/Scripts/Core/BaseRot.cs
Normal file
41
Assets/Scripts/Core/BaseRot.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Remembers the imported local rotation of model parts (Blender FBX nodes carry a 90° X rotation) so procedural
|
||||
/// animation can rotate *on top of* it instead of overwriting it.
|
||||
/// </summary>
|
||||
public static class BaseRot
|
||||
{
|
||||
static readonly Dictionary<Transform, Quaternion> _base = new Dictionary<Transform, Quaternion>();
|
||||
|
||||
public static Quaternion Of(Transform t)
|
||||
{
|
||||
if (!t) return Quaternion.identity;
|
||||
if (!_base.TryGetValue(t, out var q))
|
||||
{
|
||||
q = t.localRotation;
|
||||
_base[t] = q;
|
||||
if (_base.Count > 4096) Prune();
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
/// <summary>Which local axis (0=x,1=y,2=z) of t points along the given world direction.</summary>
|
||||
public static int LocalAxisFor(Transform t, Vector3 worldDir)
|
||||
{
|
||||
var l = t.InverseTransformDirection(worldDir);
|
||||
l = new Vector3(Mathf.Abs(l.x), Mathf.Abs(l.y), Mathf.Abs(l.z));
|
||||
return l.x >= l.y && l.x >= l.z ? 0 : (l.y >= l.z ? 1 : 2);
|
||||
}
|
||||
|
||||
static void Prune()
|
||||
{
|
||||
var dead = new List<Transform>();
|
||||
foreach (var k in _base.Keys) if (!k) dead.Add(k);
|
||||
foreach (var d in dead) _base.Remove(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/BaseRot.cs.meta
Normal file
2
Assets/Scripts/Core/BaseRot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a385cad938b13114f8937c9f759660fb
|
||||
118
Assets/Scripts/Core/BotCapture.cs
Normal file
118
Assets/Scripts/Core/BotCapture.cs
Normal file
@ -0,0 +1,118 @@
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Off-screen screenshots for the dev bots. The main camera and the UI panel render into textures that we
|
||||
/// composite and save, so the game can run with -batchmode (no window, no focus or mouse stealing).
|
||||
/// </summary>
|
||||
public static class BotCapture
|
||||
{
|
||||
static RenderTexture _scene, _ui;
|
||||
static Camera _cam;
|
||||
static Texture2D _read;
|
||||
public static bool Enabled => _scene != null;
|
||||
/// <summary>The next shots look from here instead of through the player's eyes.</summary>
|
||||
public static (Vector3 at, Vector3 target)? From;
|
||||
|
||||
public static void Setup(int w, int h)
|
||||
{
|
||||
if (_scene) return;
|
||||
_scene = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotScene", antiAliasing = 1 };
|
||||
_ui = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotUI" };
|
||||
_scene.Create(); _ui.Create();
|
||||
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
|
||||
if (cam) cam.targetTexture = _scene;
|
||||
_cam = cam;
|
||||
var doc = Object.FindAnyObjectByType<UIDocument>();
|
||||
if (doc && doc.panelSettings)
|
||||
{
|
||||
doc.panelSettings.targetTexture = _ui;
|
||||
doc.panelSettings.clearColor = true;
|
||||
doc.panelSettings.colorClearValue = new Color(0, 0, 0, 0);
|
||||
}
|
||||
Application.targetFrameRate = 60;
|
||||
Debug.Log($"[BotCapture] off-screen capture {w}x{h} (batchmode={Application.isBatchMode})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What a frame really costs: render by hand and wait for the GPU to finish it (a -batchmode player draws nothing
|
||||
/// on its own, so frames per second there say nothing). Hands back the mean milliseconds.
|
||||
/// </summary>
|
||||
public static IEnumerator FrameCost(int frames, System.Action<float> done)
|
||||
{
|
||||
if (!Enabled || !_cam) { done(0f); yield break; }
|
||||
var one = new Texture2D(1, 1, TextureFormat.RGBA32, false, false);
|
||||
var clock = new System.Diagnostics.Stopwatch();
|
||||
for (int i = 0; i < frames; i++)
|
||||
{
|
||||
yield return new WaitForEndOfFrame();
|
||||
clock.Start();
|
||||
_cam.targetTexture = _scene;
|
||||
_cam.Render();
|
||||
var prev = RenderTexture.active;
|
||||
RenderTexture.active = _scene;
|
||||
one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false);
|
||||
RenderTexture.active = prev;
|
||||
clock.Stop();
|
||||
}
|
||||
Object.Destroy(one);
|
||||
done((float)clock.Elapsed.TotalMilliseconds / frames);
|
||||
}
|
||||
|
||||
/// <summary>Saves the current frame (scene + UI) as PNG. Falls back to a normal screenshot if not set up.</summary>
|
||||
public static IEnumerator Shot(string path)
|
||||
{
|
||||
yield return new WaitForEndOfFrame();
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path));
|
||||
if (!Enabled) { ScreenCapture.CaptureScreenshot(path); yield break; }
|
||||
// a -batchmode player never renders cameras on its own (UI Toolkit panels still update), so render by hand
|
||||
if (Application.isBatchMode && _cam)
|
||||
{
|
||||
Vector3 eye = _cam.transform.position;
|
||||
Quaternion turn = _cam.transform.rotation;
|
||||
if (From is (Vector3, Vector3) f) _cam.transform.SetPositionAndRotation(f.at, Quaternion.LookRotation(f.target - f.at, Planet.Up(f.at)));
|
||||
_cam.targetTexture = _scene;
|
||||
_cam.Render();
|
||||
_cam.transform.SetPositionAndRotation(eye, turn);
|
||||
}
|
||||
int w = _scene.width, h = _scene.height;
|
||||
if (!_read) _read = new Texture2D(w, h, TextureFormat.RGBA32, false, false);
|
||||
var scene = Read(_scene, w, h);
|
||||
// `-clean`: the world alone as well, for the store page
|
||||
if (CommandLine.Has("-clean")) Save(Path.ChangeExtension(path, null) + "_clean.png", scene);
|
||||
var ui = Read(_ui, w, h);
|
||||
// UI is rendered over transparent black, i.e. premultiplied: out = ui + scene * (1 - ui.a)
|
||||
for (int i = 0; i < scene.Length; i++)
|
||||
{
|
||||
var u = ui[i];
|
||||
if (u.a == 0) continue;
|
||||
var s = scene[i];
|
||||
float k = 1f - u.a / 255f;
|
||||
scene[i] = new Color32((byte)Mathf.Min(255, u.r + s.r * k), (byte)Mathf.Min(255, u.g + s.g * k), (byte)Mathf.Min(255, u.b + s.b * k), 255);
|
||||
}
|
||||
Save(path, scene);
|
||||
Debug.Log("[BotCapture] " + path);
|
||||
}
|
||||
|
||||
static void Save(string path, Color32[] pixels)
|
||||
{
|
||||
_read.SetPixels32(pixels);
|
||||
_read.Apply();
|
||||
File.WriteAllBytes(path, _read.EncodeToPNG());
|
||||
}
|
||||
|
||||
static Color32[] Read(RenderTexture rt, int w, int h)
|
||||
{
|
||||
var prev = RenderTexture.active;
|
||||
RenderTexture.active = rt;
|
||||
_read.ReadPixels(new Rect(0, 0, w, h), 0, 0, false);
|
||||
_read.Apply();
|
||||
RenderTexture.active = prev;
|
||||
return _read.GetPixels32();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/BotCapture.cs.meta
Normal file
2
Assets/Scripts/Core/BotCapture.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7fbf0605a4228cd46adb6c6553baf8b1
|
||||
255
Assets/Scripts/Core/Cheats.cs
Normal file
255
Assets/Scripts/Core/Cheats.cs
Normal file
@ -0,0 +1,255 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Commands behind the cheat console (~ / F1). Anything that touches the shared game runs on the host only;
|
||||
/// "help", "clear" and friends work for everyone.
|
||||
/// </summary>
|
||||
public static class Cheats
|
||||
{
|
||||
public class Command
|
||||
{
|
||||
public string name, args, desc;
|
||||
public bool hostOnly = true;
|
||||
public Func<string[], string> run;
|
||||
/// <summary>Tab completion for the first argument.</summary>
|
||||
public Func<IEnumerable<string>> complete;
|
||||
}
|
||||
|
||||
public static readonly List<Command> All = new List<Command>();
|
||||
static readonly Dictionary<string, Command> s_byName = new Dictionary<string, Command>();
|
||||
|
||||
static readonly string[] Spawnables = { "bundle", "hay", "brick" };
|
||||
|
||||
static Cheats()
|
||||
{
|
||||
Add("help", "[command]", "List commands, or explain one.", Help, hostOnly: false, complete: () => All.Select(c => c.name));
|
||||
Add("money", "<amount> | set <amount>", "Add cash (10k, 2.5m, 1b work), or set the wallet.", Money);
|
||||
Add("perk", "<name|all> [level]", "Give a perk (max level by default). 'perk all' buys the whole web.", Perk, complete: () => PerkNames().Prepend("all"));
|
||||
Add("resetperks", "", "Take every perk back.", _ => { foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, 0); Ts.Save(); return "All perks reset."; });
|
||||
Add("tool", "<name|all>", "Hand yourself a tool: " + string.Join(", ", ToolNames()) + ".", Tool, complete: () => ToolNames().Prepend("all"));
|
||||
Add("time", "<hour 0-24>", "Set the clock at the base: 12 is noon, 0 is midnight.", args => { Ts.ServerSetPhase(float.Parse(args[0]) / 24f - 0.5f + 1f); return $"It's {args[0]}:00 at the base."; });
|
||||
Add("tank", "", "Fill the tool in your hands.", _ => { Me.Tools.CheatFill(); return "Container full."; }, hostOnly: false);
|
||||
Add("ship", "<kilos>", "Add shipped kilos (pays nothing).", Ship);
|
||||
Add("freebuild", "", "Build on standing grass, on or off.", _ => { BuildRules.AnyGround = !BuildRules.AnyGround; return BuildRules.AnyGround ? "Building on standing grass." : "Cut ground only."; });
|
||||
Add("mow", "", "Cut the whole sector you stand in.", _ => $"Cut {MowMap.CutSector(HexGrid.SectorAt(Planet.LocalUp)):0} m² here.");
|
||||
Add("tp", "<base|far|equator|stake|point|lat lon|x y z>", "Teleport to the base, across the planet, the nearest stake or survey point, or a spot.", Tp, complete: () => new[] { "base", "far", "equator", "stake", "point" });
|
||||
Add("spawn", "<thing> [count]", "Spawn cargo where you look: " + string.Join(", ", Spawnables) + ".", Spawn, complete: () => Spawnables);
|
||||
Add("fly", "", "Toggle flying / noclip. Space up, Ctrl down, Shift faster.", _ => { var p = Me; p.SetFlying(!p.Flying); return p.Flying ? "Flying ON" : "Flying OFF"; }, hostOnly: false);
|
||||
Add("speed", "<multiplier>", "Walk / fly speed multiplier (1 = normal).", Speed, hostOnly: false);
|
||||
Add("timescale", "<x>", "Game speed (0.1 – 5).", TimeScale);
|
||||
Add("weather", "<clear|clouds|rain|acidrain|wind|storm|meteors> [minutes]", "Change the weather now.", Weather, complete: () => WeatherNames());
|
||||
Add("twister", "", "Start a twister 25 m ahead of you.", _ => { Ts.ServerTwister(Me.transform.position + Me.transform.forward * 25f); return "Twister!"; });
|
||||
Add("beer", "", "Drink a Grass Beer, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Beer); return "Cheers."; });
|
||||
Add("cigar", "", "Light a Herb Cigar, no machine and no grass needed.", _ => { TreatHand.I?.Play(TreatId.Cigar); return "Puff."; });
|
||||
Add("ufo", "", "Bring a saucer down 30 m ahead of you.", _ => { Ts.ServerUfo(Me.transform.position + Me.transform.forward * 30f); return "They're coming."; });
|
||||
Add("save", "", "Save the game now.", _ => { Ts.Save(); return "Saved."; });
|
||||
Add("clear", "", "Clear the console.", _ => null, hostOnly: false);
|
||||
}
|
||||
|
||||
static void Add(string name, string args, string desc, Func<string[], string> run, bool hostOnly = true, Func<IEnumerable<string>> complete = null)
|
||||
{
|
||||
var c = new Command { name = name, args = args, desc = desc, run = run, hostOnly = hostOnly, complete = complete };
|
||||
All.Add(c);
|
||||
s_byName[name] = c;
|
||||
}
|
||||
|
||||
static IEnumerable<string> WeatherNames()
|
||||
{
|
||||
for (int i = 0; i < (int)WeatherKind.Count; i++) yield return ((WeatherKind)i).ToString().ToLowerInvariant();
|
||||
}
|
||||
|
||||
static string Weather(string[] args)
|
||||
{
|
||||
for (int i = 0; i < (int)WeatherKind.Count; i++)
|
||||
if (string.Equals(((WeatherKind)i).ToString(), args[0], StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
float minutes = args.Length > 1 ? float.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture) : 5f;
|
||||
Ts.ServerSetWeather((WeatherKind)i, minutes * 60f);
|
||||
return $"Weather: {(WeatherKind)i} for {minutes:0.#} min.";
|
||||
}
|
||||
return "Weather is one of: " + string.Join(", ", WeatherNames()) + ".";
|
||||
}
|
||||
|
||||
static TeamState Ts => TeamState.Instance;
|
||||
static PlayerAgent Me => PlayerAgent.Local;
|
||||
static bool IsHost => NetworkManager.Singleton && NetworkManager.Singleton.IsServer;
|
||||
|
||||
/// <summary>Runs one line. Returns the text to print (null = nothing; "clear" is handled by the console).</summary>
|
||||
public static string Run(string line)
|
||||
{
|
||||
var parts = (line ?? "").Trim().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length == 0) return null;
|
||||
string name = parts[0].ToLowerInvariant();
|
||||
if (!s_byName.TryGetValue(name, out var cmd)) return $"<color=#FF8A7A>Unknown command '{name}'.</color> Type <b>help</b>.";
|
||||
if (cmd.hostOnly && !IsHost) return "<color=#FF8A7A>Only the host can use cheats.</color>";
|
||||
if (cmd.hostOnly && (!Ts || !Me)) return "<color=#FF8A7A>Start or join a game first.</color>";
|
||||
try { return cmd.run(parts.Skip(1).ToArray()); }
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogWarning("[Cheats] " + e);
|
||||
return $"<color=#FF8A7A>Usage: {cmd.name} {cmd.args}</color>";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tab completion: the input with its current word completed (or unchanged), plus the candidates.</summary>
|
||||
public static string Complete(string line, out List<string> options)
|
||||
{
|
||||
options = new List<string>();
|
||||
var parts = (line ?? "").TrimStart().Split(' ');
|
||||
IEnumerable<string> pool;
|
||||
if (parts.Length <= 1) pool = All.Select(c => c.name);
|
||||
else if (parts.Length == 2 && s_byName.TryGetValue(parts[0].ToLowerInvariant(), out var cmd) && cmd.complete != null) pool = cmd.complete();
|
||||
else return line;
|
||||
string word = parts[parts.Length - 1].ToLowerInvariant();
|
||||
options = pool.Where(o => o.StartsWith(word, StringComparison.OrdinalIgnoreCase)).Distinct().ToList();
|
||||
if (options.Count == 0) return line;
|
||||
// longest common prefix of the matches
|
||||
string common = options[0];
|
||||
foreach (var o in options)
|
||||
{
|
||||
int n = 0;
|
||||
while (n < common.Length && n < o.Length && char.ToLowerInvariant(common[n]) == char.ToLowerInvariant(o[n])) n++;
|
||||
common = common.Substring(0, n);
|
||||
}
|
||||
parts[parts.Length - 1] = options.Count == 1 ? options[0] + " " : common;
|
||||
return string.Join(" ", parts);
|
||||
}
|
||||
|
||||
// ───────────────────────── commands ─────────────────────────
|
||||
|
||||
static string Help(string[] a)
|
||||
{
|
||||
if (a.Length > 0 && s_byName.TryGetValue(a[0].ToLowerInvariant(), out var c))
|
||||
return $"<b>{c.name}</b> {c.args}\n {c.desc}{(c.hostOnly ? " <color=#9AA3C7>(host)</color>" : "")}";
|
||||
return "Commands (Tab completes, ↑↓ history):\n" + string.Join("\n", All.Select(x => $" <b>{x.name}</b> <color=#9AA3C7>{x.args}</color> — {x.desc}"));
|
||||
}
|
||||
|
||||
/// <summary>"5000", "10k", "2.5m", "1b" → a number.</summary>
|
||||
public static long ParseAmount(string s)
|
||||
{
|
||||
s = s.Trim().ToLowerInvariant().Replace("$", "").Replace("_", "").Replace(",", ".");
|
||||
double mul = 1;
|
||||
if (s.EndsWith("k")) mul = 1e3;
|
||||
else if (s.EndsWith("m")) mul = 1e6;
|
||||
else if (s.EndsWith("b")) mul = 1e9;
|
||||
if (mul > 1) s = s.Substring(0, s.Length - 1);
|
||||
return (long)Math.Round(double.Parse(s, CultureInfo.InvariantCulture) * mul);
|
||||
}
|
||||
|
||||
static string Money(string[] a)
|
||||
{
|
||||
if (a[0].ToLowerInvariant() == "set") Ts.ServerSetMoney(ParseAmount(a[1]));
|
||||
else Ts.ServerSetMoney(Ts.Money.Value + ParseAmount(a[0]));
|
||||
return "Wallet: " + UIK.Money(Ts.Money.Value);
|
||||
}
|
||||
|
||||
static IEnumerable<string> PerkNames() => GameDefs.Perks.Select(p => p.id.ToString().ToLowerInvariant());
|
||||
|
||||
static string Perk(string[] a)
|
||||
{
|
||||
string what = a[0].ToLowerInvariant();
|
||||
int? level = a.Length > 1 ? int.Parse(a[1], CultureInfo.InvariantCulture) : (int?)null;
|
||||
if (what == "all")
|
||||
{
|
||||
foreach (var d in GameDefs.Perks) Ts.ServerSetPerk(d.id, level ?? d.maxLevel);
|
||||
Ts.Save();
|
||||
return level.HasValue ? $"Every perk set to level {level}." : "Every perk, every level. Enjoy.";
|
||||
}
|
||||
// match the id or the display name, ignoring spaces
|
||||
var def = GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant() == what || p.nameEn.Replace(" ", "").ToLowerInvariant() == what)
|
||||
?? GameDefs.Perks.FirstOrDefault(p => p.id.ToString().ToLowerInvariant().StartsWith(what));
|
||||
if (def == null) return $"<color=#FF8A7A>No perk '{what}'.</color> Tab shows the list.";
|
||||
Ts.ServerSetPerk(def.id, level ?? def.maxLevel);
|
||||
Ts.Save();
|
||||
return $"{def.name}: level {Ts.Level(def.id)}/{def.maxLevel}";
|
||||
}
|
||||
|
||||
static IEnumerable<string> ToolNames() => Enum.GetNames(typeof(ToolId)).Where(n => n != "None").Select(n => n.ToLowerInvariant());
|
||||
|
||||
static string Tool(string[] a)
|
||||
{
|
||||
string what = a[0].ToLowerInvariant();
|
||||
foreach (ToolId t in Enum.GetValues(typeof(ToolId)))
|
||||
{
|
||||
if (t == ToolId.None || (what != "all" && t.ToString().ToLowerInvariant() != what)) continue;
|
||||
Ts.ServerGiveTool(Me, t);
|
||||
if (what != "all") return GameDefs.Tool(t).name + " is yours.";
|
||||
}
|
||||
return what == "all" ? "Every tool is yours." : $"<color=#FF8A7A>No tool '{what}'.</color>";
|
||||
}
|
||||
|
||||
static string Ship(string[] a)
|
||||
{
|
||||
Ts.Shipped.Value += ParseAmount(a[0]);
|
||||
return $"Shipped {GameDefs.Kilos(Ts.Shipped.Value)}";
|
||||
}
|
||||
|
||||
static string Tp(string[] a)
|
||||
{
|
||||
Vector3 to;
|
||||
string where = a.Length > 0 ? a[0].ToLowerInvariant() : "base";
|
||||
if (a.Length >= 3)
|
||||
to = new Vector3(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture), float.Parse(a[2], CultureInfo.InvariantCulture));
|
||||
else if (a.Length == 2)
|
||||
to = Planet.OnSurface(Planet.FromLatLon(float.Parse(a[0], CultureInfo.InvariantCulture), float.Parse(a[1], CultureInfo.InvariantCulture)));
|
||||
else if (where == "far") to = Planet.OnSurface(Planet.FromLatLon(-89f, 0f));
|
||||
else if (where == "equator") to = Planet.OnSurface(Planet.FromLatLon(0f, 90f));
|
||||
else if (where == "stake" || where == "point")
|
||||
{
|
||||
int id = Landmarks.Instance.Nearest(Me.transform.position, where == "point");
|
||||
if (id < 0) return "None left.";
|
||||
to = Landmarks.Spot(id) + Me.transform.right * 2f;
|
||||
}
|
||||
else to = new Vector3(0f, 0.3f, -2f);
|
||||
if (a.Length != 3 && where != "base") to += Planet.Up(to) * 0.2f;
|
||||
Me.Teleport(to);
|
||||
return "Teleported to " + to.ToString("F1");
|
||||
}
|
||||
|
||||
/// <summary>A spot a couple of metres ahead of the camera, in front of any wall.</summary>
|
||||
static Vector3 AimSpot(float ahead = 2.5f)
|
||||
{
|
||||
var cam = CameraFx.Cam ? CameraFx.Cam.transform : Me.head;
|
||||
var dir = cam.forward;
|
||||
float d = ahead;
|
||||
if (Physics.Raycast(cam.position, dir, out var hit, ahead + 0.5f, (1 << Layers.Default) | (1 << Layers.Build) | (1 << Layers.Prop), QueryTriggerInteraction.Ignore))
|
||||
d = Mathf.Max(0.6f, hit.distance - 0.6f);
|
||||
var p = cam.position + dir * d;
|
||||
float above = Vector3.Dot(p - Me.transform.position, Me.transform.up);
|
||||
return above < 0.6f ? p + Me.transform.up * (0.6f - above) : p;
|
||||
}
|
||||
|
||||
static string Spawn(string[] a)
|
||||
{
|
||||
string what = a[0].ToLowerInvariant();
|
||||
int n = a.Length > 1 ? Mathf.Clamp(int.Parse(a[1], CultureInfo.InvariantCulture), 1, 50) : 1;
|
||||
int k = Array.IndexOf(Spawnables, what);
|
||||
if (k < 0) return $"<color=#FF8A7A>Can't spawn '{what}'.</color> Try: {string.Join(", ", Spawnables)}";
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var at = AimSpot() + new Vector3((i % 4 - 1.5f) * 0.8f, (i / 4) * 0.9f, 0f);
|
||||
Spawner.Instance.SpawnCargo((CargoKind)k, at, Quaternion.Euler(0f, UnityEngine.Random.Range(0f, 360f), 0f), Vector3.zero);
|
||||
}
|
||||
return $"Spawned {n} x {what}.";
|
||||
}
|
||||
|
||||
static string Speed(string[] a)
|
||||
{
|
||||
Me.CheatSpeed = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 10f);
|
||||
return $"Speed x{Me.CheatSpeed:0.##}";
|
||||
}
|
||||
|
||||
static string TimeScale(string[] a)
|
||||
{
|
||||
Time.timeScale = Mathf.Clamp(float.Parse(a[0], CultureInfo.InvariantCulture), 0.1f, 5f);
|
||||
return $"Time scale {Time.timeScale:0.##}";
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Cheats.cs.meta
Normal file
2
Assets/Scripts/Core/Cheats.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 040c37eaadae0a54da068b8698ed3d13
|
||||
170
Assets/Scripts/Core/DemoBot.Lang.cs
Normal file
170
Assets/Scripts/Core/DemoBot.Lang.cs
Normal file
@ -0,0 +1,170 @@
|
||||
using System.Collections;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public partial class DemoBot
|
||||
{
|
||||
/// <summary>
|
||||
/// `-demolang all` (or `-demolang de,ru,ja`): every screen in every interface language, to check the translations
|
||||
/// fit. Shots go to <folder>/<code>/NN_screen.png; the menu ones first, then one game in which the
|
||||
/// language is switched the way a player does it, from the settings.
|
||||
/// </summary>
|
||||
IEnumerator Languages(string which)
|
||||
{
|
||||
var langs = which == "all" ? Loc.All.ToList() : which.Split(',').Select(Loc.Find).Where(l => l != null).ToList();
|
||||
Log($"languages: {string.Join(", ", langs.Select(l => l.code))}");
|
||||
Achievements.Forget();
|
||||
TeamState.DeleteSave();
|
||||
yield return new WaitForSeconds(3f);
|
||||
var root = folder;
|
||||
|
||||
// the menu and what opens from it, before any game
|
||||
foreach (var l in langs)
|
||||
{
|
||||
Loc.Set(l.code, false);
|
||||
folder = Path.Combine(root, l.code);
|
||||
yield return new WaitForSeconds(1.2f);
|
||||
yield return Shot("00_menu");
|
||||
UIRoot.I.OpenSlots();
|
||||
yield return Settle("01_slots");
|
||||
UIRoot.I.OpenBrowser();
|
||||
yield return Settle("02_find_games");
|
||||
UIRoot.I.OpenCharacter();
|
||||
yield return Settle("03_character");
|
||||
UIRoot.I.OpenSettings();
|
||||
yield return Settle("04_settings", close: false);
|
||||
// every tab, and the bottom of the long keys list
|
||||
for (int t = 1; t < 6; t++)
|
||||
{
|
||||
UIRoot.I.SettingsTab(t);
|
||||
yield return Settle("04" + (char)('a' + t) + "_settings", close: false);
|
||||
}
|
||||
UIRoot.I.SettingsScrollEnd();
|
||||
yield return Settle("04g_settings_keys_end", close: false);
|
||||
UIRoot.I.SettingsTab(0);
|
||||
UIRoot.I.OpenLanguages();
|
||||
yield return Settle("05_languages");
|
||||
UIRoot.I.CloseTopModal();
|
||||
UIRoot.I.Confirm(Loc.T("Reset progress?"), Loc.T("Your base, cash, tools and upgrades will be wiped."), () => { });
|
||||
yield return Settle("06_confirm");
|
||||
UIRoot.I.OpenDifficulty(_ => { });
|
||||
yield return Settle("07_difficulty");
|
||||
}
|
||||
|
||||
folder = root;
|
||||
Loc.Set(langs[0].code, false);
|
||||
NetSession.Instance.HostLocal();
|
||||
while (!Me || !Ts) yield return null;
|
||||
yield return new WaitForSeconds(4f);
|
||||
Log("in game");
|
||||
|
||||
// a garage, a belt and a robot dock to open, money to spend
|
||||
var gAt = Soil17(26f, -30f);
|
||||
var garage = Spawner.Instance.SpawnPiece(PieceId.Garage, gAt, Quaternion.identity, gAt, true);
|
||||
var b0 = Soil17(20f, -42f) + Vector3.up * GameDefs.BeltLowest;
|
||||
var belt = Spawner.Instance.SpawnPiece(PieceId.Belt, b0, Quaternion.LookRotation(Vector3.right), b0 + Vector3.right * 6f, true);
|
||||
Ts.ServerSetMoney(1234567.5d);
|
||||
yield return new WaitForSeconds(2f);
|
||||
|
||||
foreach (var l in langs)
|
||||
{
|
||||
folder = Path.Combine(root, l.code);
|
||||
// the way a player does it: settings, then the language list
|
||||
UIRoot.I.OpenSettings();
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
Loc.Set(l.code, false);
|
||||
yield return new WaitForSeconds(1f);
|
||||
yield return Shot("10_settings_ingame");
|
||||
while (UIRoot.I.AnyModal) { UIRoot.I.CloseTopModal(); yield return null; }
|
||||
yield return new WaitForSeconds(0.4f);
|
||||
|
||||
// by the supply wall (empty hands and their hint in the first language only)
|
||||
Me.Teleport(new Vector3(-6.4f, 0.1f, -1.5f));
|
||||
Me.LookAt(new Vector3(-8.5f, 1.2f, -1.5f));
|
||||
UIRoot.I.Hud.Banner(Loc.T("WELCOME TO HERBARIA-7"), Loc.T("Earth has run out of grass. Cut it, bundle it, ship it home."), 3.2f);
|
||||
yield return new WaitForSeconds(1.2f);
|
||||
yield return Shot("11_hud_wall");
|
||||
UIRoot.I.OpenSupply();
|
||||
yield return Settle("12_supply");
|
||||
UIRoot.I.OpenShop();
|
||||
yield return Settle("13_upgrades");
|
||||
if (garage)
|
||||
{
|
||||
UIRoot.I.OpenGarage(garage.GetComponent<Garage>());
|
||||
yield return Settle("14_garage");
|
||||
UIRoot.I.OpenPiece(garage);
|
||||
yield return Settle("15_piece_garage");
|
||||
}
|
||||
if (belt)
|
||||
{
|
||||
UIRoot.I.OpenPiece(belt);
|
||||
yield return Settle("16_piece_belt");
|
||||
}
|
||||
UIRoot.I.OpenMap();
|
||||
yield return Settle("17_map");
|
||||
UIRoot.I.OpenNotebook();
|
||||
yield return Settle("18_notebook");
|
||||
UIRoot.I.OpenStations();
|
||||
yield return Settle("19_stations");
|
||||
UIRoot.I.OpenAwards();
|
||||
yield return Settle("20_achievements");
|
||||
UIRoot.I.OpenPause();
|
||||
yield return Settle("21_pause");
|
||||
|
||||
// tools in hand, the tab list, toasts
|
||||
Cheats.Run("tool all");
|
||||
yield return new WaitForSeconds(0.3f);
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
Me.Teleport(new Vector3(13f, Soil + 0.1f, -2f));
|
||||
Me.LookAt(new Vector3(15f, Soil, -2f));
|
||||
Hud.Toast(Loc.F("Sector {0:N0} mown clean! +{1}", 12345, UIK.Money(170d)), Hud.ToastKind.Money);
|
||||
Ts.AnnounceRpc(Loc.Pack("A new {0} is waiting at the garage!", Loc.Key(GameDefs.Vehicle(VehicleKind.Combine).nameEn)));
|
||||
Ctl.BotTabHeld = true;
|
||||
yield return new WaitForSeconds(1f);
|
||||
yield return Shot("22_tab_and_toasts");
|
||||
Ctl.BotTabHeld = false;
|
||||
|
||||
// the hammer's palette
|
||||
Me.Tools.Equip(ToolId.Hammer);
|
||||
yield return new WaitForSeconds(0.4f);
|
||||
var pb = PlayerBuild.Local;
|
||||
if (pb) pb.Select(PieceId.Garage);
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
yield return Shot("23_build");
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
|
||||
// looking at a built piece, and a call with its captions
|
||||
Me.Teleport(gAt + new Vector3(-6f, 0.4f, -9f));
|
||||
Me.LookAt(gAt + Vector3.up * 1.2f);
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
yield return Shot("24_aim_piece");
|
||||
DirectorCall.Call("dir_m1");
|
||||
float t0 = Time.time;
|
||||
while (Time.time - t0 < 9f) yield return null;
|
||||
yield return Shot("25_call");
|
||||
while (DirectorCall.Busy && Time.time - t0 < 40f) yield return null;
|
||||
yield return new WaitForSeconds(1f);
|
||||
Assistant.Say("asst_storm");
|
||||
yield return new WaitForSeconds(2.2f);
|
||||
yield return Shot("26_assistant");
|
||||
while (Assistant.Busy) yield return null;
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
Log($"{l.code} done");
|
||||
}
|
||||
folder = root;
|
||||
Log("languages done");
|
||||
Application.Quit();
|
||||
}
|
||||
|
||||
/// <summary>A screen just opened: let it pop in, take it, close it.</summary>
|
||||
IEnumerator Settle(string shot, bool close = true)
|
||||
{
|
||||
yield return new WaitForSeconds(0.9f);
|
||||
yield return Shot(shot);
|
||||
if (close) { UIRoot.I.CloseTopModal(); yield return new WaitForSeconds(0.3f); }
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/DemoBot.Lang.cs.meta
Normal file
2
Assets/Scripts/Core/DemoBot.Lang.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: aef158488b386584b9681bec62bd6ee5
|
||||
3365
Assets/Scripts/Core/DemoBot.cs
Normal file
3365
Assets/Scripts/Core/DemoBot.cs
Normal file
File diff suppressed because it is too large
Load Diff
2
Assets/Scripts/Core/DemoBot.cs.meta
Normal file
2
Assets/Scripts/Core/DemoBot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f3a2a8602043ca6439b8bfbc928c5179
|
||||
493
Assets/Scripts/Core/Fx.cs
Normal file
493
Assets/Scripts/Core/Fx.cs
Normal file
@ -0,0 +1,493 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>All particle juice in one place. Systems are built in code and emitted manually.</summary>
|
||||
public class Fx : MonoBehaviour
|
||||
{
|
||||
static Fx _i;
|
||||
internal static Fx I
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_i == null)
|
||||
{
|
||||
var go = new GameObject("[Fx]");
|
||||
DontDestroyOnLoad(go);
|
||||
_i = go.AddComponent<Fx>();
|
||||
_i.Build();
|
||||
}
|
||||
return _i;
|
||||
}
|
||||
}
|
||||
|
||||
ParticleSystem _drops, _spray, _foam, _puff, _steam, _frost, _sparkle, _confetti, _dust, _ring, _smoke, _wake, _motes;
|
||||
ParticleSystem _bubbles, _smokeRing, _breath;
|
||||
int _frame, _burstsThisFrame;
|
||||
float _moteDue;
|
||||
Material _flameMat, _softMat;
|
||||
|
||||
static readonly Color[] ConfettiColors =
|
||||
{
|
||||
new Color(0.69f, 0.25f, 0.17f), new Color(0.3f, 0.6f, 0.2f), new Color(0.94f, 0.89f, 0.76f),
|
||||
new Color(0.9f, 0.72f, 0.24f), new Color(0.55f, 0.78f, 0.25f), new Color(0.55f, 0.37f, 0.2f),
|
||||
};
|
||||
|
||||
static readonly Color[] ClipColors =
|
||||
{
|
||||
new Color(0.36f, 0.62f, 0.16f), new Color(0.5f, 0.74f, 0.22f), new Color(0.27f, 0.5f, 0.12f),
|
||||
new Color(0.66f, 0.78f, 0.3f), new Color(0.42f, 0.56f, 0.18f), new Color(0.3f, 0.58f, 0.2f),
|
||||
};
|
||||
/// <summary>A random grass-clipping green.</summary>
|
||||
public static Color Clip() => ClipColors[Random.Range(0, ClipColors.Length)];
|
||||
static readonly Color FoamTint = new Color(0.72f, 0.66f, 0.48f, 0.45f);
|
||||
static readonly Color Haze = new Color(0.78f, 0.82f, 0.6f, 0.3f);
|
||||
|
||||
void Build()
|
||||
{
|
||||
var bank = AssetBank.I;
|
||||
var soft = bank.Mat("FX_Soft");
|
||||
_softMat = soft;
|
||||
var drop = bank.Mat("FX_Drop") ?? bank.Mat("FX_Shard") ?? soft;
|
||||
var spark = bank.Mat("FX_Sparkle") ?? soft;
|
||||
_flameMat = bank.Mat("FX_Flame") ?? spark;
|
||||
|
||||
// grass clippings: flat fluttering leaf shards
|
||||
var leaf = bank.Mat("FX_Leaf") ?? drop;
|
||||
_drops = Make("drops", leaf, 1.1f, 0.05f, 6.5f, true);
|
||||
SetSizeCurve(_drops, 1f, 0.75f);
|
||||
var dlim = _drops.limitVelocityOverLifetime;
|
||||
dlim.enabled = true; dlim.limit = 16f; dlim.dampen = 0.05f;
|
||||
var drot = _drops.rotationOverLifetime;
|
||||
drot.z = new ParticleSystem.MinMaxCurve(-9f, 9f);
|
||||
_spray = Make("spray", soft, 0.8f, 0.3f, 2.5f, true);
|
||||
SetSizeCurve(_spray, 0.5f, 1.7f);
|
||||
SetFade(_spray, 0.75f);
|
||||
_foam = Make("foam", bank.Mat("FX_Foam") ?? soft, 2.2f, 0.6f, 0f, true);
|
||||
_foam.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
|
||||
SetSizeCurve(_foam, 0.6f, 1.6f);
|
||||
SetFade(_foam, 0.8f);
|
||||
_puff = Make("puff", soft, 0.25f, 0.06f, 0f, false);
|
||||
SetSizeCurve(_puff, 0.3f, 1.4f);
|
||||
SetFade(_puff, 0.5f);
|
||||
_ring = Make("ring", bank.Mat("FX_Ring") ?? soft, 0.6f, 0.5f, 0f, false);
|
||||
_ring.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
|
||||
SetSizeCurve(_ring, 0.15f, 1.6f);
|
||||
SetFade(_ring, 0.85f);
|
||||
_steam = Make("steam", soft, 2.6f, 0.8f, -0.25f, true);
|
||||
SetSizeCurve(_steam, 0.4f, 2.6f);
|
||||
SetFade(_steam, 0.55f);
|
||||
var sn = _steam.noise; sn.enabled = true; sn.strength = 0.6f; sn.frequency = 0.35f;
|
||||
_frost = Make("frost", spark, 1.4f, 0.06f, -0.15f, true);
|
||||
SetSizeCurve(_frost, 1f, 0f);
|
||||
var fn = _frost.noise; fn.enabled = true; fn.strength = 0.5f; fn.frequency = 0.8f;
|
||||
_sparkle = Make("sparkle", spark, 0.7f, 0.05f, -0.3f, false);
|
||||
SetSizeCurve(_sparkle, 1f, 0f);
|
||||
_dust = Make("dust", soft, 0.6f, 0.25f, -0.05f, false);
|
||||
SetSizeCurve(_dust, 0.4f, 1.6f);
|
||||
SetFade(_dust, 0.35f);
|
||||
_smoke = Make("smoke", soft, 4.5f, 2f, -0.1f, true);
|
||||
SetSizeCurve(_smoke, 0.5f, 3.2f);
|
||||
SetFade(_smoke, 0.7f);
|
||||
var smn = _smoke.noise; smn.enabled = true; smn.strength = 1.2f; smn.frequency = 0.2f;
|
||||
_wake = Make("wake", bank.Mat("FX_Foam") ?? soft, 3f, 0.9f, 0f, true);
|
||||
_wake.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.HorizontalBillboard;
|
||||
SetSizeCurve(_wake, 0.6f, 2.4f);
|
||||
SetFade(_wake, 0.7f);
|
||||
|
||||
// treats: beer bubbles that wobble up, smoke breath that hangs and curls, and rings blown off a cigar
|
||||
_bubbles = Make("bubbles", bank.Mat("FX_Ring") ?? spark, 1.6f, 0.05f, -0.6f, false);
|
||||
SetSizeCurve(_bubbles, 0.6f, 1.2f);
|
||||
SetFade(_bubbles, 0.9f);
|
||||
var bn = _bubbles.noise; bn.enabled = true; bn.strength = 0.4f; bn.frequency = 1.4f;
|
||||
_breath = Make("breath", soft, 3.2f, 0.4f, -0.08f, true);
|
||||
SetSizeCurve(_breath, 0.35f, 2.8f);
|
||||
SetFade(_breath, 0.55f);
|
||||
var brn = _breath.noise; brn.enabled = true; brn.strength = 0.35f; brn.frequency = 0.5f;
|
||||
var brl = _breath.limitVelocityOverLifetime; brl.enabled = true; brl.limit = 0.4f; brl.dampen = 0.08f;
|
||||
_smokeRing = Make("smokering", bank.Mat("FX_Ring") ?? soft, 2.4f, 0.2f, -0.05f, false);
|
||||
_smokeRing.GetComponent<ParticleSystemRenderer>().renderMode = ParticleSystemRenderMode.Billboard;
|
||||
SetSizeCurve(_smokeRing, 0.5f, 2.2f);
|
||||
SetFade(_smokeRing, 0.7f);
|
||||
var srl = _smokeRing.limitVelocityOverLifetime; srl.enabled = true; srl.limit = 0.3f; srl.dampen = 0.05f;
|
||||
|
||||
_confetti = Make("confetti", bank.Mat("FX_Confetti") ?? soft, 3.5f, 0.06f, 1.4f, true);
|
||||
_motes = Make("motes", soft, 5f, 0.05f, 0f, false);
|
||||
var wander = _motes.noise;
|
||||
wander.enabled = true; wander.strength = 0.35f; wander.frequency = 0.25f; wander.scrollSpeed = 0.2f;
|
||||
var glow = _motes.colorOverLifetime;
|
||||
glow.enabled = true;
|
||||
var fade = new Gradient();
|
||||
fade.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
|
||||
new[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(1f, 0.2f), new GradientAlphaKey(1f, 0.7f), new GradientAlphaKey(0f, 1f) });
|
||||
glow.color = fade;
|
||||
var noise = _confetti.noise;
|
||||
noise.enabled = true; noise.strength = 1.2f; noise.frequency = 0.6f;
|
||||
var vel = _confetti.limitVelocityOverLifetime;
|
||||
vel.enabled = true; vel.limit = 6f; vel.dampen = 0.08f;
|
||||
}
|
||||
|
||||
/// <summary>Keeps the air around a spot alive: pollen on the breeze by day, fireflies low over the grass after dark.</summary>
|
||||
public static void Motes(Vector3 eye, float dark)
|
||||
{
|
||||
var i = I;
|
||||
i._moteDue += Time.deltaTime * Mathf.Lerp(16f, 5f, dark);
|
||||
for (; i._moteDue >= 1f; i._moteDue -= 1f)
|
||||
{
|
||||
var at = Planet.Surface(eye + Random.insideUnitSphere * 16f);
|
||||
var up = Planet.Up(at);
|
||||
bool fly = dark > 0.5f;
|
||||
at += up * (fly ? Random.Range(0.5f, 1.5f) : Random.Range(0.3f, 4f));
|
||||
var drift = Vector3.ProjectOnPlane(new Vector3(0.87f, 0.11f, 0.48f), up) * (fly ? 0.1f : 0.45f) + Random.insideUnitSphere * 0.2f;
|
||||
Emit(i._motes, at, drift, fly ? Random.Range(0.1f, 0.16f) : Random.Range(0.03f, 0.06f), fly ? new Color(1.6f, 2.2f, 0.5f, 1f) : new Color(1f, 0.97f, 0.76f, 0.55f), Random.Range(4f, 7f));
|
||||
}
|
||||
}
|
||||
|
||||
internal ParticleSystem Make(string n, Material mat, float life, float size, float gravity, bool rotate)
|
||||
{
|
||||
var go = new GameObject(n);
|
||||
go.transform.SetParent(transform, false);
|
||||
var ps = go.AddComponent<ParticleSystem>();
|
||||
ps.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
|
||||
var main = ps.main;
|
||||
main.playOnAwake = false;
|
||||
main.loop = false;
|
||||
main.startLifetime = life;
|
||||
main.startSize = size;
|
||||
main.startSpeed = 0f;
|
||||
main.gravityModifier = gravity / 9.81f;
|
||||
main.simulationSpace = ParticleSystemSimulationSpace.World;
|
||||
main.maxParticles = 5000;
|
||||
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
|
||||
if (rotate)
|
||||
{
|
||||
main.startRotation3D = false;
|
||||
main.startRotation = new ParticleSystem.MinMaxCurve(0f, Mathf.PI * 2f);
|
||||
var rol = ps.rotationOverLifetime;
|
||||
rol.enabled = true;
|
||||
rol.z = new ParticleSystem.MinMaxCurve(-1.5f, 1.5f);
|
||||
}
|
||||
var em = ps.emission; em.enabled = false;
|
||||
var sh = ps.shape; sh.enabled = false;
|
||||
var r = go.GetComponent<ParticleSystemRenderer>();
|
||||
r.sharedMaterial = mat;
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
r.receiveShadows = false;
|
||||
ps.Play();
|
||||
return ps;
|
||||
}
|
||||
|
||||
internal static void SetSizeCurve(ParticleSystem ps, float a, float b)
|
||||
{
|
||||
var s = ps.sizeOverLifetime;
|
||||
s.enabled = true;
|
||||
s.size = new ParticleSystem.MinMaxCurve(1f, AnimationCurve.EaseInOut(0f, a, 1f, b));
|
||||
}
|
||||
|
||||
internal static void SetFade(ParticleSystem ps, float startAlpha)
|
||||
{
|
||||
var c = ps.colorOverLifetime;
|
||||
c.enabled = true;
|
||||
var g = new Gradient();
|
||||
g.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) },
|
||||
new[] { new GradientAlphaKey(startAlpha, 0f), new GradientAlphaKey(startAlpha, 0.25f), new GradientAlphaKey(0f, 1f) });
|
||||
c.color = g;
|
||||
}
|
||||
|
||||
internal static void Emit(ParticleSystem ps, Vector3 pos, Vector3 vel, float size, Color color, float life = -1f)
|
||||
{
|
||||
var ep = new ParticleSystem.EmitParams
|
||||
{
|
||||
position = pos,
|
||||
velocity = vel,
|
||||
startSize = size,
|
||||
startColor = color,
|
||||
applyShapeToPosition = false,
|
||||
};
|
||||
if (life > 0f) ep.startLifetime = life;
|
||||
ps.Emit(ep, 1);
|
||||
}
|
||||
|
||||
static Vector3 Hemi(Vector3 n, float spread)
|
||||
{
|
||||
var r = Random.onUnitSphere;
|
||||
if (Vector3.Dot(r, n) < 0f) r = -r;
|
||||
return Vector3.Slerp(n, r, spread).normalized;
|
||||
}
|
||||
|
||||
bool Budget(int cost)
|
||||
{
|
||||
if (_frame != Time.frameCount) { _frame = Time.frameCount; _burstsThisFrame = 0; }
|
||||
_burstsThisFrame += cost;
|
||||
return _burstsThisFrame <= 80;
|
||||
}
|
||||
|
||||
// ───────────────────────── grass ─────────────────────────
|
||||
|
||||
/// <summary>Something thumps into the meadow: a burst of clippings, a dust puff, a flattened ring.</summary>
|
||||
public static void Splash(Vector3 pos, float power)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(2)) return;
|
||||
power = Mathf.Max(0.1f, power);
|
||||
int n = Mathf.RoundToInt(10 + 30 * Mathf.Min(power, 2.5f));
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var d = Random.insideUnitCircle.normalized;
|
||||
var v = Planet.Frame * new Vector3(d.x * Random.Range(0.6f, 2.2f), Random.Range(2.5f, 6.5f), d.y * Random.Range(0.6f, 2.2f)) * Mathf.Sqrt(power);
|
||||
Emit(i._drops, pos + Planet.Frame * new Vector3(d.x, 0f, d.y) * 0.25f * power, v * 0.8f, Random.Range(0.05f, 0.11f) * (0.7f + power * 0.3f), Clip());
|
||||
}
|
||||
for (int k = 0; k < 3 + power * 4; k++)
|
||||
Emit(i._spray, pos + Random.insideUnitSphere * 0.3f * power, Planet.LocalUp * Random.Range(0.8f, 2.4f) * power + Random.insideUnitSphere * 0.6f,
|
||||
Random.Range(0.4f, 0.9f) * power, Haze);
|
||||
Emit(i._ring, pos + Planet.LocalUp * 0.04f, Vector3.zero, 1.6f * power + 0.4f, FoamTint, 0.9f);
|
||||
Emit(i._foam, pos + Planet.LocalUp * 0.05f, Vector3.zero, 1.2f * power + 0.3f, FoamTint);
|
||||
}
|
||||
|
||||
/// <summary>A few clippings flung in a direction (mower chutes, jetpack, full bags).</summary>
|
||||
public static void Droplets(Vector3 pos, Vector3 dir, int count)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
for (int k = 0; k < count; k++)
|
||||
Emit(i._drops, pos + Random.insideUnitSphere * 0.15f, (dir.normalized + Random.insideUnitSphere * 0.6f) * Random.Range(1.5f, 3.5f),
|
||||
Random.Range(0.045f, 0.09f), Clip(), 0.9f);
|
||||
}
|
||||
|
||||
/// <summary>A stream of clippings ripped out of the meadow toward a nozzle (mowing tools, drones, edge mowers).</summary>
|
||||
public static void Stream(Vector3 from, Vector3 to, float power)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
var d = to - from;
|
||||
float len = d.magnitude;
|
||||
if (len < 0.05f) return;
|
||||
var dir = d / len;
|
||||
int n = Mathf.Clamp(Mathf.RoundToInt(3 + power * 6), 2, 14);
|
||||
float speed = Mathf.Max(6f, len * 3.2f);
|
||||
float life = len / speed;
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var side = Vector3.Cross(dir, Random.onUnitSphere).normalized * Random.Range(0f, 0.35f) * (0.5f + power);
|
||||
var p = from + side;
|
||||
Emit(i._drops, p, (to - p).normalized * speed + Random.insideUnitSphere * 0.6f, Random.Range(0.05f, 0.1f) * (0.7f + power * 0.4f), Clip(), life);
|
||||
}
|
||||
if (Random.value < 0.6f)
|
||||
Emit(i._spray, from + Planet.LocalUp * 0.1f, dir * speed * 0.6f + Random.insideUnitSphere * 0.5f, Random.Range(0.2f, 0.45f) * (0.6f + power), Haze, life * 1.4f);
|
||||
if (Random.value < 0.25f)
|
||||
Emit(i._foam, from + Planet.LocalUp * 0.04f + Random.insideUnitSphere.Flat() * 0.6f, Vector3.zero, Random.Range(0.4f, 0.9f) * (0.6f + power), FoamTint, 1.2f);
|
||||
}
|
||||
|
||||
/// <summary>A spray of mulch out of a nozzle (dumping, mulch blast).</summary>
|
||||
public static void Jet(Vector3 nozzle, Vector3 dir, float power)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
for (int k = 0; k < 4; k++)
|
||||
{
|
||||
var d = Vector3.Slerp(dir, Random.onUnitSphere, 0.06f).normalized;
|
||||
Emit(i._drops, nozzle + d * 0.05f, d * Random.Range(9f, 14f) * power, Random.Range(0.05f, 0.1f), Clip(), 0.9f);
|
||||
}
|
||||
if (Random.value < 0.5f) Emit(i._spray, nozzle, dir * 6f * power, Random.Range(0.12f, 0.25f), Haze, 0.4f);
|
||||
}
|
||||
|
||||
/// <summary>Vehicle trail: a dust wake + clippings thrown out of the sides.</summary>
|
||||
public static void Wake(Vector3 pos, Vector3 back, float speed01)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1) || speed01 < 0.05f) return;
|
||||
Emit(i._wake, pos + Random.insideUnitSphere.Flat() * 0.3f, back * 0.5f, Random.Range(0.8f, 1.4f) * (0.6f + speed01), new Color(FoamTint.r, FoamTint.g, FoamTint.b, 0.3f + speed01 * 0.3f));
|
||||
var side = Vector3.Cross(Planet.LocalUp, back).normalized;
|
||||
if (Random.value < speed01)
|
||||
for (int s = -1; s <= 1; s += 2)
|
||||
Emit(i._drops, pos + side * s * 0.5f, (side * s * 1.8f + Planet.LocalUp * 2.4f) * (0.6f + speed01), Random.Range(0.05f, 0.09f), Clip(), 0.8f);
|
||||
}
|
||||
|
||||
/// <summary>Vaporizer / hot vent: big soft white billows.</summary>
|
||||
public static void Steam(Vector3 pos, float amount)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
int n = Mathf.Clamp(Mathf.RoundToInt(2 + amount * 6), 1, 24);
|
||||
for (int k = 0; k < n; k++)
|
||||
Emit(i._steam, pos + Random.insideUnitSphere * 0.25f * amount, Planet.LocalUp * Random.Range(1.2f, 2.6f) + Random.insideUnitSphere * 0.5f,
|
||||
Random.Range(0.5f, 1f) * (0.6f + amount * 0.4f), new Color(1f, 1f, 1f, 0.6f));
|
||||
}
|
||||
|
||||
/// <summary>Cryo Press: icy glitter and cold mist.</summary>
|
||||
public static void Frost(Vector3 pos, float amount)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
int n = Mathf.Clamp(Mathf.RoundToInt(6 + amount * 24), 2, 40);
|
||||
for (int k = 0; k < n; k++)
|
||||
Emit(i._frost, pos + Random.insideUnitSphere * 0.5f, Random.insideUnitSphere * 1.4f + Planet.LocalUp * 0.3f, Random.Range(0.04f, 0.1f),
|
||||
Color.Lerp(new Color(0.55f, 0.78f, 0.25f), new Color(0.9f, 0.82f, 0.45f), Random.value));
|
||||
for (int k = 0; k < 2 + amount * 4; k++)
|
||||
Emit(i._steam, pos + Random.insideUnitSphere * 0.4f, -Planet.LocalUp * 0.4f + Random.insideUnitSphere * 0.5f, Random.Range(0.6f, 1.2f), new Color(0.85f, 0.95f, 1f, 0.45f), 1.8f);
|
||||
}
|
||||
|
||||
/// <summary>Rocket lift-off: shock ring, steam blast hugging the deck, debris of spray.</summary>
|
||||
public static void LaunchBlast(Vector3 pos)
|
||||
{
|
||||
var i = I;
|
||||
Emit(i._ring, pos + Planet.LocalUp * 0.05f, Vector3.zero, 14f, new Color(1f, 0.9f, 0.7f, 0.9f), 0.7f);
|
||||
Emit(i._ring, pos + Planet.LocalUp * 0.08f, Vector3.zero, 8f, new Color(1f, 0.7f, 0.35f, 0.9f), 0.45f);
|
||||
for (int k = 0; k < 40; k++)
|
||||
{
|
||||
var d = Random.insideUnitCircle.normalized;
|
||||
Emit(i._smoke, pos + Planet.Frame * new Vector3(d.x, 0.2f, d.y) * 1.5f, Planet.Frame * new Vector3(d.x, 0.08f, d.y) * Random.Range(6f, 14f), Random.Range(1.5f, 3f), new Color(1f, 0.98f, 0.95f, 0.85f));
|
||||
}
|
||||
for (int k = 0; k < 60; k++)
|
||||
Emit(i._drops, pos + Random.insideUnitSphere, Hemi(Planet.LocalUp, 0.9f) * Random.Range(4f, 12f), Random.Range(0.05f, 0.1f), Clip());
|
||||
for (int k = 0; k < 24; k++)
|
||||
Emit(i._sparkle, pos + Planet.LocalUp * 0.5f, Random.onUnitSphere * Random.Range(3f, 8f), Random.Range(0.08f, 0.16f), new Color(1f, 0.75f, 0.35f));
|
||||
}
|
||||
|
||||
/// <summary>A puff of grey diesel smoke out of a stack; power over 1 is a black cough.</summary>
|
||||
public static void Exhaust(Vector3 pos, Vector3 up, float power)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
int n = power > 1f ? 5 : 1;
|
||||
float dark = power > 1f ? 0.18f : 0.42f;
|
||||
for (int k = 0; k < n; k++)
|
||||
Emit(i._smoke, pos + Random.insideUnitSphere * 0.05f, up * Random.Range(1.2f, 2.2f) * Mathf.Min(power, 1.5f) + Random.insideUnitSphere * 0.25f,
|
||||
Random.Range(0.18f, 0.32f) * (0.7f + power * 0.4f), new Color(dark, dark, dark * 1.05f, power > 1f ? 0.55f : 0.32f), Random.Range(1.1f, 1.8f));
|
||||
}
|
||||
|
||||
/// <summary>Dust and a few clippings thrown up behind a wheel.</summary>
|
||||
public static void Kick(Vector3 ground, Vector3 back, float speed01)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
var up = Planet.Up(ground);
|
||||
Emit(i._dust, ground + up * 0.1f + Random.insideUnitSphere * 0.15f, (back * 1.2f + up * 0.8f) * (0.5f + speed01) + Random.insideUnitSphere * 0.3f,
|
||||
Random.Range(0.35f, 0.7f) * (0.6f + speed01), new Color(0.76f, 0.68f, 0.5f, 0.28f + speed01 * 0.22f), Random.Range(0.6f, 1.1f));
|
||||
if (Random.value < 0.5f + speed01 * 0.5f)
|
||||
Emit(i._drops, ground + up * 0.1f, (back * 1.5f + up * 2.2f) * (0.5f + speed01) + Random.insideUnitSphere * 0.6f, Random.Range(0.04f, 0.08f), Clip(), 0.8f);
|
||||
}
|
||||
|
||||
public static void Smoke(Vector3 pos, float size)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
Emit(i._smoke, pos + Random.insideUnitSphere * 0.3f, Random.insideUnitSphere * 1.2f + -Planet.LocalUp * 1.5f, size * Random.Range(0.8f, 1.3f), new Color(1f, 0.97f, 0.93f, 0.7f));
|
||||
}
|
||||
|
||||
// ───────────────────────── treats ─────────────────────────
|
||||
|
||||
/// <summary>A breath of cigar smoke: a soft cloud that drifts out the way you face, slows, and curls up.</summary>
|
||||
public static void Exhale(Vector3 mouth, Vector3 dir, float amount)
|
||||
{
|
||||
var i = I;
|
||||
int n = Mathf.Clamp(Mathf.RoundToInt(4 + amount * 14), 2, 24);
|
||||
for (int k = 0; k < n; k++)
|
||||
Emit(i._breath, mouth + Random.insideUnitSphere * 0.05f, (dir * Random.Range(0.6f, 1.6f) + Random.insideUnitSphere * 0.25f) * (0.5f + amount * 0.6f),
|
||||
Random.Range(0.12f, 0.3f) * (0.6f + amount * 0.5f), new Color(0.93f, 0.92f, 0.88f, Random.Range(0.35f, 0.6f)), Random.Range(2.2f, 3.4f));
|
||||
}
|
||||
|
||||
/// <summary>A smoke ring, blown off the lips and drifting away as it opens.</summary>
|
||||
public static void SmokeRing(Vector3 mouth, Vector3 dir)
|
||||
{
|
||||
Emit(I._smokeRing, mouth, dir * Random.Range(0.9f, 1.3f), Random.Range(0.12f, 0.18f), new Color(0.95f, 0.94f, 0.9f, 0.75f));
|
||||
}
|
||||
|
||||
/// <summary>Beer bubbles wobbling up and popping.</summary>
|
||||
public static void Bubbles(Vector3 pos, int count)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < count; k++)
|
||||
Emit(i._bubbles, pos + Random.insideUnitSphere * 0.15f, Planet.LocalUp * Random.Range(0.3f, 0.9f) + Random.insideUnitSphere * 0.2f,
|
||||
Random.Range(0.025f, 0.06f), new Color(1f, 0.9f, 0.55f, 0.9f), Random.Range(0.8f, 1.6f));
|
||||
}
|
||||
|
||||
/// <summary>A can cracked open: a fizz of foam and spray up out of the top.</summary>
|
||||
public static void Fizz(Vector3 pos, Vector3 up)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < 14; k++)
|
||||
Emit(i._puff, pos, (up * Random.Range(0.6f, 1.4f) + Random.insideUnitSphere * 0.5f), Random.Range(0.02f, 0.05f), new Color(1f, 0.97f, 0.88f, 0.8f), 0.35f);
|
||||
Bubbles(pos, 8);
|
||||
}
|
||||
|
||||
/// <summary>The ember catches: a few orange sparks.</summary>
|
||||
public static void Embers(Vector3 pos, int count)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < count; k++)
|
||||
Emit(i._sparkle, pos + Random.insideUnitSphere * 0.01f, Random.onUnitSphere * Random.Range(0.3f, 1.2f) + Planet.LocalUp * 0.4f, Random.Range(0.012f, 0.03f),
|
||||
Color.Lerp(new Color(1f, 0.45f, 0.1f), new Color(1f, 0.85f, 0.4f), Random.value), Random.Range(0.3f, 0.7f));
|
||||
}
|
||||
|
||||
// ───────────────────────── generic ─────────────────────────
|
||||
|
||||
public static void Confetti(Vector3 pos, int amount = 120, float power = 6f)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < amount; k++)
|
||||
Emit(i._confetti, pos + Random.insideUnitSphere * 0.3f, Hemi(Planet.LocalUp, 0.55f) * Random.Range(power * 0.5f, power),
|
||||
Random.Range(0.05f, 0.09f), ConfettiColors[Random.Range(0, ConfettiColors.Length)]);
|
||||
}
|
||||
|
||||
public static void Slam(Vector3 pos, Vector3 normal, float radius)
|
||||
{
|
||||
var i = I;
|
||||
Emit(i._ring, pos + normal * 0.01f, Vector3.zero, radius * 2.4f, new Color(1f, 1f, 1f, 0.8f), 0.35f);
|
||||
for (int k = 0; k < 8; k++)
|
||||
Emit(i._dust, pos + Random.insideUnitSphere * radius * 0.5f, (Random.insideUnitSphere + normal) * 0.7f, Random.Range(0.15f, 0.3f),
|
||||
new Color(1f, 1f, 1f, 0.5f));
|
||||
}
|
||||
|
||||
public static void Dust(Vector3 pos, float size = 0.3f, int count = 6)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
var d = Random.insideUnitCircle.normalized;
|
||||
Emit(i._dust, pos + Planet.Frame * new Vector3(d.x, 0.05f, d.y) * 0.2f, Planet.Frame * new Vector3(d.x, 0.15f, d.y) * Random.Range(0.6f, 1.3f), size * Random.Range(0.7f, 1.3f),
|
||||
new Color(0.82f, 0.74f, 0.58f, 0.5f));
|
||||
}
|
||||
}
|
||||
|
||||
public static void Sparkles(Vector3 pos, int count, Color c)
|
||||
{
|
||||
var i = I;
|
||||
for (int k = 0; k < count; k++)
|
||||
Emit(i._sparkle, pos + Random.insideUnitSphere * 0.2f, Random.onUnitSphere * Random.Range(0.5f, 2f) + Planet.LocalUp, Random.Range(0.04f, 0.09f), c);
|
||||
}
|
||||
|
||||
/// <summary>Suction nozzle intake: spray specks spiralling into the nozzle.</summary>
|
||||
public static void Suck(Vector3 nozzle, Vector3 dir)
|
||||
{
|
||||
var i = I;
|
||||
if (!i.Budget(1)) return;
|
||||
for (int k = 0; k < 2; k++)
|
||||
{
|
||||
var from = nozzle + Vector3.Slerp(dir, Random.onUnitSphere, 0.35f).normalized * Random.Range(0.6f, 1.4f);
|
||||
Emit(i._puff, from, (nozzle - from) * 4f, Random.Range(0.04f, 0.09f), new Color(0.85f, 0.95f, 1f, 0.45f), 0.25f);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Build(Vector3 pos, Vector2 size)
|
||||
{
|
||||
var i = I;
|
||||
int n = Mathf.RoundToInt(8 + size.x * size.y * 4);
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var p = pos + new Vector3(Random.Range(-0.5f, 0.5f) * size.x, 0.05f, Random.Range(-0.5f, 0.5f) * size.y);
|
||||
Emit(i._dust, p, new Vector3(Random.Range(-0.6f, 0.6f), 0.4f, Random.Range(-0.6f, 0.6f)), Random.Range(0.2f, 0.4f), new Color(1f, 1f, 1f, 0.6f));
|
||||
}
|
||||
for (int k = 0; k < 8; k++)
|
||||
Emit(i._sparkle, pos + Planet.LocalUp * 0.5f + Random.insideUnitSphere * 0.4f, Random.onUnitSphere * 1.5f + Planet.LocalUp, Random.Range(0.04f, 0.08f), new Color(1f, 0.75f, 0.35f));
|
||||
}
|
||||
|
||||
/// <summary>Make sure the singleton (and its systems) exist before gameplay starts emitting.</summary>
|
||||
public static void Warmup() { _ = I; }
|
||||
}
|
||||
|
||||
static class VecExt
|
||||
{
|
||||
public static Vector3 Flat(this Vector3 v) => Vector3.ProjectOnPlane(v, Planet.LocalUp);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Fx.cs.meta
Normal file
2
Assets/Scripts/Core/Fx.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5901c7ca94c078544bb25a49060bf946
|
||||
28
Assets/Scripts/Core/GameBoot.cs
Normal file
28
Assets/Scripts/Core/GameBoot.cs
Normal file
@ -0,0 +1,28 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Scene entry point: warms up singletons and configures physics layers.</summary>
|
||||
public class GameBoot : MonoBehaviour
|
||||
{
|
||||
void Awake()
|
||||
{
|
||||
Application.targetFrameRate = -1;
|
||||
Layers.SetupCollisions();
|
||||
Fx.Warmup();
|
||||
_ = Sfx.I;
|
||||
GameSettings.Apply();
|
||||
if (CommandLine.Has("-resetsave")) { TeamState.DeleteSave(); Debug.Log("[Boot] save reset"); }
|
||||
foreach (var d in UnityEngine.InputSystem.InputSystem.devices) Debug.Log($"[Input] device: {d.name} ({d.layout}) {d.description.product}");
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
// dev bots render off-screen so they can run with -batchmode without touching the user's desktop
|
||||
if (CommandLine.Has("-screenshot") || CommandLine.Has("-autodemo"))
|
||||
BotCapture.Setup(int.TryParse(CommandLine.Get("-shotw", "1600"), out var w) ? w : 1600, int.TryParse(CommandLine.Get("-shoth", "900"), out var h) ? h : 900);
|
||||
if (CommandLine.Get("-screenshot") is string path) gameObject.AddComponent<AutoScreenshot>().path = path;
|
||||
if (CommandLine.Get("-autodemo") is string demo) gameObject.AddComponent<DemoBot>().folder = demo;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/GameBoot.cs.meta
Normal file
2
Assets/Scripts/Core/GameBoot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 096b7cba51af85342a8c2a594e49af61
|
||||
257
Assets/Scripts/Core/GameSettings.cs
Normal file
257
Assets/Scripts/Core/GameSettings.cs
Normal file
@ -0,0 +1,257 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public static class GameSettings
|
||||
{
|
||||
// ───────────────────────── sound ─────────────────────────
|
||||
public static float Master { get => PlayerPrefs.GetFloat("s_master", 0.9f); set { PlayerPrefs.SetFloat("s_master", value); Apply(); } }
|
||||
public static float Music { get => PlayerPrefs.GetFloat("s_music", 0.55f); set { PlayerPrefs.SetFloat("s_music", value); Apply(); } }
|
||||
public static float Effects { get => PlayerPrefs.GetFloat("s_sfx", 1f); set { PlayerPrefs.SetFloat("s_sfx", value); Apply(); } }
|
||||
public static float Voices { get => PlayerPrefs.GetFloat("s_voice", 1f); set { PlayerPrefs.SetFloat("s_voice", value); Apply(); } }
|
||||
public static float PhoneVolume { get => PlayerPrefs.GetFloat("s_phone", 0.7f); set => PlayerPrefs.SetFloat("s_phone", value); }
|
||||
/// <summary>Keep playing sound while the game is in the background.</summary>
|
||||
public static bool BackgroundSound { get => PlayerPrefs.GetInt("s_bgsound", 1) == 1; set { PlayerPrefs.SetInt("s_bgsound", value ? 1 : 0); ApplyFocus(Application.isFocused); } }
|
||||
|
||||
/// <summary>Who you go as. Until you choose, someone at random, so a new crew doesn't arrive as eight Hanks.</summary>
|
||||
public static int Character
|
||||
{
|
||||
get
|
||||
{
|
||||
int i = PlayerPrefs.GetInt("s_crew", -1);
|
||||
if (i >= 0 && i < Roster.All.Length) return i;
|
||||
i = Random.Range(0, Roster.All.Length);
|
||||
PlayerPrefs.SetInt("s_crew", i);
|
||||
return i;
|
||||
}
|
||||
set => PlayerPrefs.SetInt("s_crew", value);
|
||||
}
|
||||
|
||||
// ───────────────────────── game ─────────────────────────
|
||||
/// <summary>Interface language code ("en", "ru", "zh-Hans"…), kept as "s_lang". Until chosen: Steam's language, else the system's.</summary>
|
||||
public static string Language { get => Loc.Code; set => Loc.Set(value); }
|
||||
public static float Shake { get => PlayerPrefs.GetFloat("s_shake", 1f); set { PlayerPrefs.SetFloat("s_shake", value); Apply(); } }
|
||||
/// <summary>The assistant chips in with tips.</summary>
|
||||
public static bool Tips { get => PlayerPrefs.GetInt("s_tips", 1) == 1; set => PlayerPrefs.SetInt("s_tips", value ? 1 : 0); }
|
||||
/// <summary>The key caps down the right of the screen.</summary>
|
||||
public static bool KeyHints { get => PlayerPrefs.GetInt("s_hints", 1) == 1; set => PlayerPrefs.SetInt("s_hints", value ? 1 : 0); }
|
||||
|
||||
// ───────────────────────── controls ─────────────────────────
|
||||
public static float Sensitivity { get => PlayerPrefs.GetFloat("s_sens", 1f); set { PlayerPrefs.SetFloat("s_sens", value); Apply(); } }
|
||||
public static float PadSensitivity { get => PlayerPrefs.GetFloat("s_padsens", 1f); set { PlayerPrefs.SetFloat("s_padsens", value); Apply(); } }
|
||||
public static bool InvertY { get => PlayerPrefs.GetInt("s_invy", 0) == 1; set { PlayerPrefs.SetInt("s_invy", value ? 1 : 0); Apply(); } }
|
||||
public static bool SprintToggle { get => PlayerPrefs.GetInt("s_sprinttog", 0) == 1; set { PlayerPrefs.SetInt("s_sprinttog", value ? 1 : 0); Apply(); } }
|
||||
|
||||
// ───────────────────────── display ─────────────────────────
|
||||
/// <summary>0 fullscreen, 1 borderless window, 2 window. Before there was a choice it was a fullscreen yes/no ("s_fs").</summary>
|
||||
public static int DisplayMode
|
||||
{
|
||||
get => PlayerPrefs.GetInt("s_dmode", PlayerPrefs.GetInt("s_fs", 1) == 1 ? 1 : 2);
|
||||
set { PlayerPrefs.SetInt("s_dmode", value); ApplyScreen(); }
|
||||
}
|
||||
/// <summary>Width × height for fullscreen and the window; 0 × 0 is the desktop's own.</summary>
|
||||
public static Vector2Int Resolution
|
||||
{
|
||||
get => new Vector2Int(PlayerPrefs.GetInt("s_resw", 0), PlayerPrefs.GetInt("s_resh", 0));
|
||||
set { PlayerPrefs.SetInt("s_resw", value.x); PlayerPrefs.SetInt("s_resh", value.y); ApplyScreen(); }
|
||||
}
|
||||
public static bool VSync { get => PlayerPrefs.GetInt("s_vsync", 1) == 1; set { PlayerPrefs.SetInt("s_vsync", value ? 1 : 0); ApplyFrames(); } }
|
||||
public static readonly int[] FpsCaps = { 30, 60, 90, 120, 144, 165, 240, 0 };
|
||||
/// <summary>Frames a second without v-sync, an index into <see cref="FpsCaps"/> (0 there is no limit).</summary>
|
||||
public static int FpsCap { get => Mathf.Clamp(PlayerPrefs.GetInt("s_fpscap", 6), 0, FpsCaps.Length - 1); set { PlayerPrefs.SetInt("s_fpscap", value); ApplyFrames(); } }
|
||||
public static float Fov { get => PlayerPrefs.GetFloat("s_fov", 80f); set { PlayerPrefs.SetFloat("s_fov", value); Apply(); } }
|
||||
/// <summary>Exposure on top of the day's, in stops (-1..1).</summary>
|
||||
public static float Brightness { get => PlayerPrefs.GetFloat("s_bright", 0f); set => PlayerPrefs.SetFloat("s_bright", value); }
|
||||
|
||||
// ───────────────────────── graphics ─────────────────────────
|
||||
/// <summary>0 low, 1 medium, 2 high, 3 ultra, 4 own mix (what the rows below say).</summary>
|
||||
public static int Quality { get => Mathf.Clamp(PlayerPrefs.GetInt("s_quality", 2), 0, 4); set { if (value < Custom) { Preset(value); PlayerPrefs.SetInt("s_quality", value); } else Freeze(); ApplyGraphics(); } }
|
||||
public const int Custom = 4;
|
||||
// a row nobody has set follows the preset (an own mix that lacks one follows high)
|
||||
// low medium high ultra
|
||||
static readonly float[] PScale = { 0.75f, 0.9f, 1f, 1f };
|
||||
static readonly int[] PShadows = { 1, 2, 3, 4 };
|
||||
static readonly int[] PMsaa = { 0, 1, 2, 3 };
|
||||
static readonly int[] PGrass = { 0, 1, 2, 2 };
|
||||
static readonly int[] PBloom = { 0, 1, 1, 1 };
|
||||
static int P => Quality == Custom ? 2 : Quality;
|
||||
static readonly string[] GraphicsKeys = { "s_rscale", "s_shadows", "s_msaa", "s_grass", "s_bloom" };
|
||||
|
||||
public static float RenderScale { get => PlayerPrefs.GetFloat("s_rscale", PScale[P]); set => SetOwn("s_rscale", value); }
|
||||
/// <summary>0 off, 1 low, 2 medium, 3 high, 4 ultra.</summary>
|
||||
public static int Shadows { get => PlayerPrefs.GetInt("s_shadows", PShadows[P]); set => SetOwn("s_shadows", value); }
|
||||
/// <summary>MSAA: 0 off, 1 2×, 2 4×, 3 8×.</summary>
|
||||
public static int Antialias { get => PlayerPrefs.GetInt("s_msaa", PMsaa[P]); set => SetOwn("s_msaa", value); }
|
||||
/// <summary>Blades of grass drawn: 0 fewer, 1 more, 2 all.</summary>
|
||||
public static int GrassDetail { get => PlayerPrefs.GetInt("s_grass", PGrass[P]); set => SetOwn("s_grass", value); }
|
||||
public static bool Bloom { get => PlayerPrefs.GetInt("s_bloom", PBloom[P]) == 1; set => SetOwn("s_bloom", value ? 1 : 0); }
|
||||
|
||||
/// <summary>A single row changed: the others keep what they show, and the preset becomes the player's own mix.</summary>
|
||||
static void SetOwn(string key, float v)
|
||||
{
|
||||
Freeze();
|
||||
PlayerPrefs.SetFloat(key, v);
|
||||
ApplyGraphics();
|
||||
}
|
||||
static void SetOwn(string key, int v)
|
||||
{
|
||||
Freeze();
|
||||
PlayerPrefs.SetInt(key, v);
|
||||
ApplyGraphics();
|
||||
}
|
||||
static void Freeze()
|
||||
{
|
||||
if (Quality == Custom) return;
|
||||
float scale = RenderScale;
|
||||
int shadows = Shadows, msaa = Antialias, grass = GrassDetail;
|
||||
bool bloom = Bloom;
|
||||
PlayerPrefs.SetFloat("s_rscale", scale);
|
||||
PlayerPrefs.SetInt("s_shadows", shadows);
|
||||
PlayerPrefs.SetInt("s_msaa", msaa);
|
||||
PlayerPrefs.SetInt("s_grass", grass);
|
||||
PlayerPrefs.SetInt("s_bloom", bloom ? 1 : 0);
|
||||
PlayerPrefs.SetInt("s_quality", Custom);
|
||||
}
|
||||
|
||||
/// <summary>A preset: the rows go back to following it.</summary>
|
||||
static void Preset(int q)
|
||||
{
|
||||
foreach (var k in GraphicsKeys) PlayerPrefs.DeleteKey(k);
|
||||
}
|
||||
|
||||
/// <summary>A tab's settings as they come out of the box.</summary>
|
||||
public static void Defaults(int tab)
|
||||
{
|
||||
string[][] keys =
|
||||
{
|
||||
new[] { "s_shake", "s_tips", "s_hints" },
|
||||
new[] { "s_dmode", "s_fs", "s_resw", "s_resh", "s_vsync", "s_fpscap", "s_fov", "s_bright" },
|
||||
new[] { "s_quality", "s_rscale", "s_shadows", "s_msaa", "s_grass", "s_bloom" },
|
||||
new[] { "s_master", "s_music", "s_sfx", "s_voice", "s_phone", "s_bgsound" },
|
||||
new[] { "s_sens", "s_padsens", "s_invy", "s_sprinttog" },
|
||||
};
|
||||
if (tab == 5) { Binds.ResetAll(); return; }
|
||||
if (tab < 0 || tab >= keys.Length) return;
|
||||
foreach (var k in keys[tab]) PlayerPrefs.DeleteKey(k);
|
||||
Apply();
|
||||
ApplyDisplay();
|
||||
}
|
||||
|
||||
// ───────────────────────── applying ─────────────────────────
|
||||
|
||||
public static void Apply()
|
||||
{
|
||||
Sfx.MasterVolume = Master;
|
||||
Sfx.MusicVolume = Music;
|
||||
Sfx.SfxVolume = Effects;
|
||||
Sfx.VoiceVolume = Voices;
|
||||
Sfx.ApplyVolumes();
|
||||
Sfx.RefreshMusicVolume();
|
||||
Ctl.Sensitivity = Sensitivity;
|
||||
Ctl.PadSensitivity = PadSensitivity;
|
||||
Ctl.InvertY = InvertY;
|
||||
Ctl.SprintToggle = SprintToggle;
|
||||
CameraFx.BaseFov = Fov;
|
||||
CameraFx.ShakeScale = Shake;
|
||||
}
|
||||
|
||||
static bool s_hooked;
|
||||
|
||||
public static void ApplyDisplay()
|
||||
{
|
||||
if (!s_hooked)
|
||||
{
|
||||
s_hooked = true;
|
||||
Application.focusChanged += ApplyFocus;
|
||||
}
|
||||
ApplyFrames();
|
||||
ApplyGraphics();
|
||||
ApplyScreen();
|
||||
}
|
||||
|
||||
static void ApplyFocus(bool focused) => AudioListener.pause = !focused && !BackgroundSound;
|
||||
|
||||
static void ApplyFrames()
|
||||
{
|
||||
QualitySettings.vSyncCount = VSync ? 1 : 0;
|
||||
int cap = FpsCaps[FpsCap];
|
||||
Application.targetFrameRate = VSync ? -1 : cap > 0 ? cap : -1;
|
||||
}
|
||||
|
||||
static bool Bot => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo") || CommandLine.Has("-screenshot");
|
||||
|
||||
/// <summary>Fullscreen, borderless or a window, at the chosen size. Scripted runs keep the size from the command line.</summary>
|
||||
static void ApplyScreen()
|
||||
{
|
||||
if (Application.isEditor || Bot) return;
|
||||
var mode = DisplayMode switch { 0 => FullScreenMode.ExclusiveFullScreen, 1 => FullScreenMode.FullScreenWindow, _ => FullScreenMode.Windowed };
|
||||
var r = Resolution;
|
||||
int w = r.x, h = r.y;
|
||||
if (mode == FullScreenMode.FullScreenWindow || w <= 0 || h <= 0) { w = Display.main.systemWidth; h = Display.main.systemHeight; }
|
||||
if (mode == FullScreenMode.Windowed && (r.x <= 0 || r.y <= 0)) { w = Mathf.Min(1600, w); h = Mathf.Min(900, h); }
|
||||
if (Screen.fullScreenMode != mode || Screen.width != w || Screen.height != h) Screen.SetResolution(w, h, mode);
|
||||
}
|
||||
|
||||
/// <summary>The sizes this screen offers, biggest first, one per width × height.</summary>
|
||||
public static List<Vector2Int> Resolutions()
|
||||
{
|
||||
var list = new List<Vector2Int>();
|
||||
foreach (var r in Screen.resolutions)
|
||||
{
|
||||
var v = new Vector2Int(r.width, r.height);
|
||||
if (v.x >= 1024 && !list.Contains(v)) list.Add(v);
|
||||
}
|
||||
var now = new Vector2Int(Screen.width, Screen.height);
|
||||
if (!list.Contains(now)) list.Add(now);
|
||||
list.Sort((a, b) => b.x != a.x ? b.x.CompareTo(a.x) : b.y.CompareTo(a.y));
|
||||
return list;
|
||||
}
|
||||
|
||||
static UniversalRenderPipelineAsset s_rp;
|
||||
|
||||
/// <summary>
|
||||
/// The top quality level always, tuned from the rows: render scale, shadows, MSAA, grass and bloom. Its pipeline
|
||||
/// asset is copied once and the copy is what changes, so the project's asset is never touched.
|
||||
/// </summary>
|
||||
public static void ApplyGraphics()
|
||||
{
|
||||
int top = QualitySettings.names.Length - 1;
|
||||
if (s_rp == null)
|
||||
{
|
||||
if (top >= 0 && QualitySettings.GetQualityLevel() != top) QualitySettings.SetQualityLevel(top, true);
|
||||
var src = (QualitySettings.renderPipeline ?? GraphicsSettings.defaultRenderPipeline) as UniversalRenderPipelineAsset;
|
||||
if (src)
|
||||
{
|
||||
s_rp = Object.Instantiate(src);
|
||||
s_rp.name = src.name + " (settings)";
|
||||
QualitySettings.renderPipeline = s_rp;
|
||||
}
|
||||
}
|
||||
int q = Quality;
|
||||
QualitySettings.lodBias = q == 0 ? 1f : q == 1 ? 1.5f : 2f;
|
||||
if (s_rp)
|
||||
{
|
||||
s_rp.renderScale = Mathf.Clamp(RenderScale, 0.5f, 1f);
|
||||
s_rp.upscalingFilter = UpscalingFilterSelection.Auto;
|
||||
int sh = Mathf.Clamp(Shadows, 0, 4);
|
||||
s_rp.shadowDistance = new[] { 0f, 40f, 70f, 90f, 150f }[sh];
|
||||
s_rp.shadowCascadeCount = new[] { 1, 1, 2, 4, 4 }[sh];
|
||||
s_rp.mainLightShadowmapResolution = new[] { 1024, 1024, 2048, 2048, 4096 }[sh];
|
||||
s_rp.msaaSampleCount = new[] { 1, 2, 4, 8 }[Mathf.Clamp(Antialias, 0, 3)];
|
||||
}
|
||||
GrassField.Detail = new[] { 0.5f, 0.75f, 1f }[Mathf.Clamp(GrassDetail, 0, 2)];
|
||||
ApplyBloom();
|
||||
}
|
||||
|
||||
/// <summary>Bloom on every post volume in the scene (their own copies of the profile, not the project's).</summary>
|
||||
public static void ApplyBloom()
|
||||
{
|
||||
bool on = Bloom;
|
||||
foreach (var v in Object.FindObjectsByType<Volume>(FindObjectsSortMode.None))
|
||||
if (v && v.profile && v.profile.TryGet(out UnityEngine.Rendering.Universal.Bloom b)) b.active = on;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/GameSettings.cs.meta
Normal file
2
Assets/Scripts/Core/GameSettings.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ac4d4f6da0989d1449b583565eac5c06
|
||||
262
Assets/Scripts/Core/Loc.cs
Normal file
262
Assets/Scripts/Core/Loc.cs
Normal file
@ -0,0 +1,262 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface languages. Every player-facing string is written in English in the code and looked up here by that
|
||||
/// English text: <c>Loc.T("PLAY")</c>, or <c>Loc.F("{0} sectors clean", n)</c> for text with values in it. A missing
|
||||
/// translation shows the English. Tables are <c>Resources/Loc/<code>.txt</c>, one "english TAB translation" per line
|
||||
/// (Tools/loc/extract.py lists every key the code uses). Text kept in data tables (tool names, perk descriptions…)
|
||||
/// is marked <c>Loc.N("…")</c> where it is written and translated with <c>Loc.T</c> where it is shown.
|
||||
/// </summary>
|
||||
public static class Loc
|
||||
{
|
||||
public class Lang
|
||||
{
|
||||
public string code, steam, native;
|
||||
/// <summary>Numbers are written the way this culture writes them.</summary>
|
||||
public string culture;
|
||||
/// <summary>Chinese, Japanese, Korean: drawn with the Noto CJK cut, not LilitaOne/Nunito.</summary>
|
||||
public string cjkFont;
|
||||
/// <summary>LilitaOne has no Cyrillic, nor Polish or Turkish letters: these draw headings in Nunito Black.</summary>
|
||||
public bool latinDisplayOnly;
|
||||
}
|
||||
|
||||
/// <summary>The twelve ticked as "Interface" on the Steam page, English first. <c>steam</c> is what Steam's
|
||||
/// GetCurrentGameLanguage() answers.</summary>
|
||||
public static readonly Lang[] All =
|
||||
{
|
||||
new Lang { code = "en", steam = "english", native = "English", culture = "en-US" },
|
||||
new Lang { code = "fr", steam = "french", native = "Français", culture = "fr-FR" },
|
||||
new Lang { code = "it", steam = "italian", native = "Italiano", culture = "it-IT" },
|
||||
new Lang { code = "de", steam = "german", native = "Deutsch", culture = "de-DE" },
|
||||
new Lang { code = "es", steam = "spanish", native = "Español", culture = "es-ES" },
|
||||
new Lang { code = "pt-BR", steam = "brazilian", native = "Português (Brasil)", culture = "pt-BR" },
|
||||
new Lang { code = "pl", steam = "polish", native = "Polski", culture = "pl-PL", latinDisplayOnly = true },
|
||||
new Lang { code = "tr", steam = "turkish", native = "Türkçe", culture = "tr-TR", latinDisplayOnly = true },
|
||||
new Lang { code = "ru", steam = "russian", native = "Русский", culture = "ru-RU", latinDisplayOnly = true },
|
||||
new Lang { code = "zh-Hans", steam = "schinese", native = "简体中文", culture = "zh-CN", cjkFont = "GcCjkSC" },
|
||||
new Lang { code = "ja", steam = "japanese", native = "日本語", culture = "ja-JP", cjkFont = "GcCjkJP" },
|
||||
new Lang { code = "ko", steam = "koreana", native = "한국어", culture = "ko-KR", cjkFont = "GcCjkKR" },
|
||||
};
|
||||
|
||||
public static Lang Current { get; private set; } = All[0];
|
||||
public static string Code => Current.code;
|
||||
public static bool IsEnglish => Current == All[0];
|
||||
/// <summary>For numbers on screen (thousands, decimals). Never for saves or the network: those stay invariant.</summary>
|
||||
public static CultureInfo Culture { get; private set; } = CultureInfo.GetCultureInfo("en-US");
|
||||
/// <summary>After the language changes: screens rebuild themselves.</summary>
|
||||
public static event Action Changed;
|
||||
|
||||
static Dictionary<string, string> _table;
|
||||
static bool _ready;
|
||||
|
||||
/// <summary>The English text in the current language, or the English if it has no translation.</summary>
|
||||
public static string T(string en)
|
||||
{
|
||||
if (!_ready) Init();
|
||||
if (string.IsNullOrEmpty(en) || _table == null) return en;
|
||||
return _table.TryGetValue(en, out var s) && !string.IsNullOrEmpty(s) ? s : en;
|
||||
}
|
||||
|
||||
/// <summary>T, then string.Format with this language's culture: "{0:N0} sectors" etc.</summary>
|
||||
public static string F(string en, params object[] args)
|
||||
{
|
||||
var fmt = T(en);
|
||||
try { return string.Format(Culture, fmt, args); }
|
||||
catch (FormatException)
|
||||
{
|
||||
// a broken translation must never take the UI down: fall back to the English pattern
|
||||
try { return string.Format(Culture, en, args); } catch (FormatException) { return en; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks English kept in a data table for the extractor; the table hands it to T where it is shown.</summary>
|
||||
public static string N(string en) => en;
|
||||
|
||||
/// <summary>A number the way the language writes it ("1,234.5", "1 234,5", "1.234,5").</summary>
|
||||
public static string Num(double v, string format = "N0") => v.ToString(format, Culture);
|
||||
public static string Num(float v, string format) => v.ToString(format, Culture);
|
||||
|
||||
// ───────────────────────── text sent over the network ─────────────────────────
|
||||
|
||||
const char PackMark = '\u0001', ArgMark = '\u0002', KeyMark = '\u0003';
|
||||
|
||||
/// <summary>Server text (announcements) goes out as the English pattern and its values, and every client reads it
|
||||
/// in its own language. Arguments that are themselves English keys go through <see cref="Key"/>.</summary>
|
||||
public static string Pack(string en, params string[] args)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(PackMark).Append(en);
|
||||
foreach (var a in args) sb.Append(ArgMark).Append(a ?? "");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>An argument of <see cref="Pack"/> that the reader translates too (a tool or machine name).</summary>
|
||||
public static string Key(string en) => KeyMark + en;
|
||||
|
||||
/// <summary>The reader's side of <see cref="Pack"/>; plain text goes through T.</summary>
|
||||
public static string Unpack(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return text;
|
||||
if (text[0] != PackMark) return text[0] == KeyMark ? Arg(text) : T(text);
|
||||
var parts = text.Substring(1).Split(ArgMark);
|
||||
var args = new object[parts.Length - 1];
|
||||
for (int i = 1; i < parts.Length; i++) args[i - 1] = Arg(parts[i]);
|
||||
return F(parts[0], args);
|
||||
}
|
||||
|
||||
/// <summary>A translated name with something after it, like "Sickle" + " III".</summary>
|
||||
public static string Key(string en, string suffix) => KeyMark + en + SuffixMark + suffix;
|
||||
const char SuffixMark = '\u0004';
|
||||
|
||||
static string Arg(string a)
|
||||
{
|
||||
if (a.Length == 0 || a[0] != KeyMark) return a;
|
||||
a = a.Substring(1);
|
||||
int s = a.IndexOf(SuffixMark);
|
||||
return s < 0 ? T(a) : T(a.Substring(0, s)) + " " + a.Substring(s + 1);
|
||||
}
|
||||
|
||||
// ───────────────────────── choosing ─────────────────────────
|
||||
|
||||
const string Pref = "s_lang";
|
||||
|
||||
/// <summary>Saved choice, else Steam's language for this game, else the system's, else English.</summary>
|
||||
public static void Init()
|
||||
{
|
||||
if (_ready) return;
|
||||
_ready = true;
|
||||
string code = CommandLine.Get("-demolang") ?? CommandLine.Get("-lang");
|
||||
if (Find(code) == null) code = PlayerPrefs.GetString(Pref, "");
|
||||
if (Find(code) == null) code = FromSteam();
|
||||
if (Find(code) == null) code = FromSystem();
|
||||
Load(Find(code) ?? All[0]);
|
||||
}
|
||||
|
||||
public static Lang Find(string code)
|
||||
{
|
||||
if (string.IsNullOrEmpty(code)) return null;
|
||||
foreach (var l in All) if (string.Equals(l.code, code, StringComparison.OrdinalIgnoreCase) || l.steam == code) return l;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The settings screen's choice: remembered, and the screens rebuild. The language shots switch without remembering.</summary>
|
||||
public static void Set(string code, bool remember = true)
|
||||
{
|
||||
var l = Find(code) ?? All[0];
|
||||
if (remember)
|
||||
{
|
||||
PlayerPrefs.SetString(Pref, l.code);
|
||||
PlayerPrefs.Save();
|
||||
}
|
||||
_ready = true;
|
||||
if (l == Current && _table != null) return;
|
||||
Load(l);
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
static string FromSteam()
|
||||
{
|
||||
try { return SteamManager.Initialized ? Steamworks.SteamApps.GetCurrentGameLanguage() : null; }
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
static string FromSystem()
|
||||
{
|
||||
switch (Application.systemLanguage)
|
||||
{
|
||||
case SystemLanguage.French: return "fr";
|
||||
case SystemLanguage.Italian: return "it";
|
||||
case SystemLanguage.German: return "de";
|
||||
case SystemLanguage.Spanish: return "es";
|
||||
case SystemLanguage.Portuguese: return "pt-BR";
|
||||
case SystemLanguage.Polish: return "pl";
|
||||
case SystemLanguage.Turkish: return "tr";
|
||||
case SystemLanguage.Russian: case SystemLanguage.Ukrainian: case SystemLanguage.Belarusian: return "ru";
|
||||
case SystemLanguage.Chinese: case SystemLanguage.ChineseSimplified: return "zh-Hans";
|
||||
case SystemLanguage.Japanese: return "ja";
|
||||
case SystemLanguage.Korean: return "ko";
|
||||
default: return "en";
|
||||
}
|
||||
}
|
||||
|
||||
static void Load(Lang l)
|
||||
{
|
||||
Current = l;
|
||||
try { Culture = CultureInfo.GetCultureInfo(l.culture); }
|
||||
catch (CultureNotFoundException) { Culture = CultureInfo.InvariantCulture; }
|
||||
_table = null;
|
||||
if (l == All[0]) return;
|
||||
var asset = Resources.Load<TextAsset>("Loc/" + l.code);
|
||||
if (!asset) { Debug.LogWarning($"[Loc] no table for {l.code}"); return; }
|
||||
_table = Parse(asset.text);
|
||||
Resources.UnloadAsset(asset);
|
||||
Debug.Log($"[Loc] {l.code}: {_table.Count} strings");
|
||||
}
|
||||
|
||||
/// <summary>"english TAB translation" per line; # starts a comment; \n \t \\ are escapes on both sides.</summary>
|
||||
public static Dictionary<string, string> Parse(string text)
|
||||
{
|
||||
var d = new Dictionary<string, string>(4096);
|
||||
foreach (var raw in text.Split('\n'))
|
||||
{
|
||||
var line = raw.TrimEnd('\r');
|
||||
if (line.Length == 0 || line[0] == '#') continue;
|
||||
int tab = line.IndexOf('\t');
|
||||
if (tab <= 0) continue;
|
||||
var key = Unescape(line.Substring(0, tab));
|
||||
var val = Unescape(line.Substring(tab + 1));
|
||||
d[key] = val;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static string Unescape(string s)
|
||||
{
|
||||
if (s.IndexOf('\\') < 0) return s;
|
||||
var sb = new StringBuilder(s.Length);
|
||||
for (int i = 0; i < s.Length; i++)
|
||||
{
|
||||
char c = s[i];
|
||||
if (c == '\\' && i + 1 < s.Length)
|
||||
{
|
||||
char n = s[++i];
|
||||
sb.Append(n == 'n' ? '\n' : n == 't' ? '\t' : n);
|
||||
}
|
||||
else sb.Append(c);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
// ───────────────────────── fonts ─────────────────────────
|
||||
|
||||
/// <summary>The heading and body fonts for the current language.</summary>
|
||||
public static void Fonts(AssetBank bank, out Font display, out Font body)
|
||||
{
|
||||
var lilita = Named(bank, "LilitaOne");
|
||||
var nunito = Named(bank, "Nunito-Black") ?? Named(bank, "Nunito");
|
||||
display = lilita;
|
||||
body = nunito;
|
||||
if (Current.cjkFont != null)
|
||||
{
|
||||
var cjk = Named(bank, Current.cjkFont);
|
||||
if (cjk) { display = cjk; body = cjk; }
|
||||
else Debug.LogWarning($"[Loc] font {Current.cjkFont} missing: {Current.code} will show boxes");
|
||||
}
|
||||
else if (Current.latinDisplayOnly && nunito) display = nunito;
|
||||
if (!display) display = body;
|
||||
}
|
||||
|
||||
static Font Named(AssetBank bank, string name)
|
||||
{
|
||||
if (bank == null) return null;
|
||||
foreach (var f in bank.fonts) if (f && f.name.Contains(name)) return f;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Loc.cs.meta
Normal file
2
Assets/Scripts/Core/Loc.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a22fef65b38d3fc4380fe0f34abf1b40
|
||||
45
Assets/Scripts/Core/MenuCamera.cs
Normal file
45
Assets/Scripts/Core/MenuCamera.cs
Normal file
@ -0,0 +1,45 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Slow cinematic drift around the ocean rig while in the main menu. Gives the camera to the local player in game.</summary>
|
||||
public class MenuCamera : MonoBehaviour
|
||||
{
|
||||
static MenuCamera _i;
|
||||
public Transform cam;
|
||||
public Vector3 focus = new Vector3(0f, 2.5f, 0f);
|
||||
public float radius = 22f, height = 7f, speed = 0.02f;
|
||||
bool _active = true;
|
||||
float _t;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_i = this;
|
||||
if (!cam && Camera.main) cam = Camera.main.transform;
|
||||
}
|
||||
|
||||
public static void Release()
|
||||
{
|
||||
if (_i) _i._active = false;
|
||||
}
|
||||
|
||||
public static void Reclaim()
|
||||
{
|
||||
if (!_i || !_i.cam) return;
|
||||
_i._active = true;
|
||||
_i.cam.SetParent(_i.transform, false);
|
||||
CameraFx.FovTarget(0f);
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (!_active || !cam) return;
|
||||
_t += Time.unscaledDeltaTime * speed;
|
||||
float a = _t * Mathf.PI * 2f;
|
||||
var pos = focus + new Vector3(Mathf.Cos(a) * radius, height + Mathf.Sin(a * 2f) * 0.6f, Mathf.Sin(a) * radius * 0.75f);
|
||||
cam.position = pos;
|
||||
cam.rotation = Quaternion.LookRotation(focus + new Vector3(Mathf.Sin(a * 0.7f) * 1.5f, 0, 0) - pos, Vector3.up);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
2
Assets/Scripts/Core/MenuCamera.cs.meta
Normal file
2
Assets/Scripts/Core/MenuCamera.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2ddd44c2603794c4fb0709a53ac4b981
|
||||
41
Assets/Scripts/Core/MeshUtil.cs
Normal file
41
Assets/Scripts/Core/MeshUtil.cs
Normal file
@ -0,0 +1,41 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public static class MeshUtil
|
||||
{
|
||||
/// <summary>Axis-aligned box mesh with per-face UVs scaled in metres (so tiling textures stay square).</summary>
|
||||
public static Mesh Box(Vector3 size, Vector3 center)
|
||||
{
|
||||
var h = size * 0.5f;
|
||||
Vector3[] n = { Vector3.up, Vector3.down, Vector3.forward, Vector3.back, Vector3.right, Vector3.left };
|
||||
var verts = new Vector3[24];
|
||||
var norms = new Vector3[24];
|
||||
var uvs = new Vector2[24];
|
||||
var tris = new int[36];
|
||||
for (int f = 0; f < 6; f++)
|
||||
{
|
||||
Vector3 nz = n[f];
|
||||
Vector3 ax = Mathf.Abs(nz.y) > 0.5f ? Vector3.right : Vector3.Cross(Vector3.up, nz);
|
||||
Vector3 ay = Vector3.Cross(nz, ax);
|
||||
float ex = Vector3.Scale(ax, h).magnitude, ey = Vector3.Scale(ay, h).magnitude, ez = Vector3.Scale(nz, h).magnitude;
|
||||
for (int k = 0; k < 4; k++)
|
||||
{
|
||||
float sx = (k == 1 || k == 2) ? 1 : -1, sy = (k >= 2) ? 1 : -1;
|
||||
int vi = f * 4 + k;
|
||||
verts[vi] = center + nz * ez + ax * (sx * ex) + ay * (sy * ey);
|
||||
norms[vi] = nz;
|
||||
uvs[vi] = new Vector2((sx * 0.5f + 0.5f) * ex * 2f, (sy * 0.5f + 0.5f) * ey * 2f);
|
||||
}
|
||||
int t = f * 6, b = f * 4;
|
||||
tris[t] = b; tris[t + 1] = b + 1; tris[t + 2] = b + 2;
|
||||
tris[t + 3] = b; tris[t + 4] = b + 2; tris[t + 5] = b + 3;
|
||||
}
|
||||
var m = new Mesh { name = "Box" };
|
||||
m.vertices = verts; m.normals = norms; m.uv = uvs; m.triangles = tris;
|
||||
m.RecalculateBounds();
|
||||
m.RecalculateTangents();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/MeshUtil.cs.meta
Normal file
2
Assets/Scripts/Core/MeshUtil.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4b686c25fd73b5f43be160e72f3a9c57
|
||||
675
Assets/Scripts/Core/PhoneWeb.cs
Normal file
675
Assets/Scripts/Core/PhoneWeb.cs
Normal file
@ -0,0 +1,675 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Net.WebSockets;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The web behind the phone: the player's own Edge or Chrome, with no window and a profile of its own, driven over the
|
||||
/// DevTools protocol. It renders a real phone-sized page, we copy its screencast into a texture and send touches and
|
||||
/// text back, so feeds, logins and video behave as they do on a phone. It starts on the first page opened, is paused
|
||||
/// while the phone is put away, comes back if it dies, and goes when the match does.
|
||||
/// </summary>
|
||||
public class PhoneWeb
|
||||
{
|
||||
const int TallW = 390, WideH = 390, FrameTall = 540, FrameWide = 1120;
|
||||
const int Retries = 4;
|
||||
// our eyes in every document and frame: the game's volume, quiet when the phone goes away, and new windows in the one tab
|
||||
const string Keep =
|
||||
"(()=>{const s=window.__gc={vol:.6,hold:false};" +
|
||||
"setInterval(()=>{for(const v of document.querySelectorAll('video,audio')){if(v.volume!==s.vol)v.volume=s.vol;" +
|
||||
"if(s.hold){if(!v.paused){v.pause();v.__gcHeld=1}}else if(v.__gcHeld){v.__gcHeld=0;v.play().catch(()=>{})}}" +
|
||||
"for(let i=0;i<frames.length;i++)try{frames[i].postMessage({__gc:[s.vol,s.hold]},'*')}catch(e){}},300);" +
|
||||
"addEventListener('message',e=>{const m=e.data&&e.data.__gc;if(m){s.vol=m[0];s.hold=m[1]}});" +
|
||||
"window.open=u=>{if(u)location.href=u;return window};" +
|
||||
"addEventListener('click',e=>{const a=e.target.closest&&e.target.closest('a[target]');if(a)a.target='_self'},true)})()";
|
||||
|
||||
/// <summary>One running browser. A new one is made after a crash, so a late message from the old one can't touch it.</summary>
|
||||
sealed class Link
|
||||
{
|
||||
public Process Proc;
|
||||
public IntPtr Job;
|
||||
public ClientWebSocket Ws;
|
||||
public string Tab;
|
||||
public readonly CancellationTokenSource Stop = new CancellationTokenSource();
|
||||
public readonly BlockingCollection<string> Out = new BlockingCollection<string>();
|
||||
public volatile bool Ready;
|
||||
}
|
||||
|
||||
/// <summary>A frame on its way to the screen. Reused: at 30 a second, fresh arrays of half a megabyte would be a garbage collection a second.</summary>
|
||||
sealed class Shot
|
||||
{
|
||||
public byte[] Jpeg = new byte[1 << 18];
|
||||
public int Session;
|
||||
}
|
||||
|
||||
readonly Texture2D _decoded;
|
||||
readonly RenderTexture _rt;
|
||||
readonly string _profile;
|
||||
readonly bool _mute;
|
||||
readonly int _pageH, _fullW;
|
||||
readonly ConcurrentBag<Shot> _spare = new ConcurrentBag<Shot>();
|
||||
readonly ConcurrentDictionary<int, TaskCompletionSource<string>> _wait = new ConcurrentDictionary<int, TaskCompletionSource<string>>();
|
||||
|
||||
Link _link;
|
||||
Shot _shot;
|
||||
int _id, _frames, _decodes, _tries, _restarts;
|
||||
volatile int _navId;
|
||||
volatile bool _loading, _died, _failed;
|
||||
volatile string _url, _navError, _problem;
|
||||
string _pending, _wanted, _last;
|
||||
bool _shown, _wide, _page;
|
||||
float _retryAt, _nextState, _nextDecode, _nextFlick, _decodeMs;
|
||||
|
||||
/// <summary>The page, as a texture of its own. It is stretched to fit, so the page's shape doesn't matter here.</summary>
|
||||
public Texture Picture => _rt;
|
||||
public bool Fresh { get; private set; }
|
||||
public bool Ready => _link != null && _link.Ready;
|
||||
public bool Loading => _loading;
|
||||
public string Url => _url;
|
||||
public int CssW => _wide ? _fullW : TallW;
|
||||
public int CssH => _wide ? WideH : _pageH;
|
||||
/// <summary>What went wrong, once.</summary>
|
||||
public string TakeProblem() { var p = _problem; _problem = null; return p; }
|
||||
|
||||
public static bool Available => Engine() != null;
|
||||
|
||||
/// <param name="tall">The page's height over its width with the phone upright.</param>
|
||||
/// <param name="wide">Its width over its height with the phone on its side.</param>
|
||||
public PhoneWeb(float tall, float wide)
|
||||
{
|
||||
_pageH = Mathf.RoundToInt(TallW * tall);
|
||||
_fullW = Mathf.RoundToInt(WideH * wide);
|
||||
// a test run keeps away from the player's logins and out of their speakers
|
||||
_mute = CommandLine.Has("-autodemo");
|
||||
_profile = Path.Combine(_mute ? Application.temporaryCachePath : Application.persistentDataPath, "PhoneWeb");
|
||||
_decoded = new Texture2D(FrameTall, FrameTall, TextureFormat.RGB24, false);
|
||||
_rt = new RenderTexture(1024, 1024, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "PhoneWeb" };
|
||||
_rt.Create();
|
||||
}
|
||||
|
||||
// ───────────────────────── what the phone asks of it ─────────────────────────
|
||||
|
||||
public void Go(string url)
|
||||
{
|
||||
if (!Available) return;
|
||||
_page = true;
|
||||
_url = null;
|
||||
_navError = null;
|
||||
_wanted = null;
|
||||
_pending = url;
|
||||
_loading = true;
|
||||
_restarts = 0;
|
||||
Boot();
|
||||
}
|
||||
|
||||
/// <summary>The home screen is up: the page goes, and with it anything still playing.</summary>
|
||||
public void Leave()
|
||||
{
|
||||
_page = false;
|
||||
_pending = _wanted = _last = null;
|
||||
_loading = false;
|
||||
_url = null;
|
||||
if (Ready) Cmd("Page.navigate", "{\"url\":\"about:blank\"}");
|
||||
}
|
||||
|
||||
public void Back() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.back()\"}"); }
|
||||
public void Forward() { if (Ready) Cmd("Runtime.evaluate", "{\"expression\":\"void history.forward()\"}"); }
|
||||
public void Reload() { if (Ready) { _loading = true; Cmd("Page.reload"); } }
|
||||
|
||||
/// <summary>The phone came out or went away: frames only flow while someone can see them.</summary>
|
||||
public void Show(bool on)
|
||||
{
|
||||
if (_shown == on) return;
|
||||
_shown = on;
|
||||
_nextState = 0f;
|
||||
if (Ready) Screencast(on);
|
||||
}
|
||||
|
||||
public void Wide(bool on)
|
||||
{
|
||||
if (_wide == on) return;
|
||||
_wide = on;
|
||||
if (Ready) { Metrics(); if (_shown) { Cmd("Page.stopScreencast"); Screencast(true); } }
|
||||
}
|
||||
|
||||
void Screencast(bool on)
|
||||
{
|
||||
if (on) Cmd("Page.startScreencast", _wide
|
||||
? $"{{\"format\":\"jpeg\",\"quality\":62,\"maxWidth\":{FrameWide},\"maxHeight\":{FrameWide * WideH / _fullW},\"everyNthFrame\":1}}"
|
||||
: $"{{\"format\":\"jpeg\",\"quality\":58,\"maxWidth\":{FrameTall},\"maxHeight\":{FrameTall * _pageH / TallW},\"everyNthFrame\":1}}");
|
||||
else Cmd("Page.stopScreencast");
|
||||
}
|
||||
|
||||
void Metrics()
|
||||
{
|
||||
string turned = _wide ? ",\"screenOrientation\":{\"type\":\"landscapePrimary\",\"angle\":90}" : ",\"screenOrientation\":{\"type\":\"portraitPrimary\",\"angle\":0}";
|
||||
Cmd("Emulation.setDeviceMetricsOverride", $"{{\"width\":{CssW},\"height\":{CssH},\"deviceScaleFactor\":2,\"mobile\":true{turned}}}");
|
||||
}
|
||||
|
||||
// ───────────────────────── fingers ─────────────────────────
|
||||
|
||||
public void Touch(string type, float x, float y)
|
||||
{
|
||||
if (Ready) Cmd("Input.dispatchTouchEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"{0}\",\"touchPoints\":[{{\"x\":{1:0.#},\"y\":{2:0.#}}}]}}", type, x, y));
|
||||
}
|
||||
|
||||
public void TouchEnd() { if (Ready) Cmd("Input.dispatchTouchEvent", "{\"type\":\"touchEnd\",\"touchPoints\":[]}"); }
|
||||
|
||||
/// <summary>A quick swipe: the next video in a feed, or a screenful anywhere else.</summary>
|
||||
void Flick(int dir)
|
||||
{
|
||||
float x = CssW * 0.5f, y0 = dir > 0 ? CssH * 0.72f : CssH * 0.28f;
|
||||
float step = -dir * CssH * 0.05f;
|
||||
Task.Run(async () =>
|
||||
{
|
||||
Touch("touchStart", x, y0);
|
||||
for (int i = 1; i <= 9; i++)
|
||||
{
|
||||
Touch("touchMove", x, y0 + step * i);
|
||||
await Task.Delay(14);
|
||||
}
|
||||
TouchEnd();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>A feed moves one video at a time; anything else scrolls like a page.</summary>
|
||||
bool OnFeed
|
||||
{
|
||||
get
|
||||
{
|
||||
string u = _url ?? "";
|
||||
return u.Contains("tiktok.com") || u.Contains("instagram.com") || u.Contains("/shorts");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The mouse wheel, one notch at a time. Positive is on down the page.</summary>
|
||||
public void Wheel(int dir)
|
||||
{
|
||||
if (!Ready) return;
|
||||
if (OnFeed)
|
||||
{
|
||||
if (Time.unscaledTime < _nextFlick) return;
|
||||
_nextFlick = Time.unscaledTime + 0.35f;
|
||||
Flick(dir);
|
||||
return;
|
||||
}
|
||||
Cmd("Input.dispatchMouseEvent", string.Format(CultureInfo.InvariantCulture, "{{\"type\":\"mouseWheel\",\"x\":{0},\"y\":{1},\"deltaX\":0,\"deltaY\":{2}}}", CssW / 2, CssH / 2, dir * 260));
|
||||
}
|
||||
|
||||
public void Insert(string text) { if (Ready) Cmd("Input.insertText", "{\"text\":" + Str(text) + "}"); }
|
||||
|
||||
public void Key(string name, int code, string text)
|
||||
{
|
||||
if (!Ready) return;
|
||||
string common = $"\"key\":\"{name}\",\"code\":\"{name}\",\"windowsVirtualKeyCode\":{code}";
|
||||
Cmd("Input.dispatchKeyEvent", "{\"type\":\"" + (text != null ? "keyDown" : "rawKeyDown") + "\"," + common + (text != null ? ",\"text\":\"" + text + "\"" : "") + "}");
|
||||
Cmd("Input.dispatchKeyEvent", "{\"type\":\"keyUp\"," + common + "}");
|
||||
}
|
||||
|
||||
/// <summary>Is the page waiting for typing?</summary>
|
||||
public async Task<bool> FieldActive()
|
||||
{
|
||||
const string js = "(()=>{const e=document.activeElement;return String(!!e&&(e.isContentEditable||e.tagName==='TEXTAREA'||e.tagName==='IFRAME'||(e.tagName==='INPUT'&&!/^(checkbox|radio|button|submit|range|file)$/.test(e.type))))})()";
|
||||
return await Ask(js) == "true";
|
||||
}
|
||||
|
||||
/// <summary>A question for the page, answered as a string, or null if it never comes.</summary>
|
||||
public Task<string> Ask(string js)
|
||||
{
|
||||
int id = Interlocked.Increment(ref _id);
|
||||
var done = new TaskCompletionSource<string>();
|
||||
if (!Ready) { done.TrySetResult(null); return done.Task; }
|
||||
_wait[id] = done;
|
||||
Send(_link, "{\"id\":" + id + ",\"method\":\"Runtime.evaluate\",\"params\":{\"expression\":" + Str(js) + ",\"awaitPromise\":true}}");
|
||||
return done.Task;
|
||||
}
|
||||
|
||||
/// <summary>For the test bot: how the frames are doing.</summary>
|
||||
public string Stats => $"{_frames} frames in, {_decodes} shown, {_decodeMs * 1000f / Mathf.Max(_decodes, 1):0.0} ms each";
|
||||
/// <summary>For the test bot: the browser dies under the phone.</summary>
|
||||
public void Kill() { try { _link?.Proc?.Kill(); } catch (InvalidOperationException) { } }
|
||||
public bool Running { get { try { return _link?.Proc != null && !_link.Proc.HasExited; } catch (InvalidOperationException) { return false; } } }
|
||||
|
||||
// ───────────────────────── every frame ─────────────────────────
|
||||
|
||||
/// <summary>Runs whether the phone is out or not, or nothing could tell a page to stop.</summary>
|
||||
public void Tick(bool sharp)
|
||||
{
|
||||
Fresh = false;
|
||||
if (_failed)
|
||||
{
|
||||
_failed = false;
|
||||
_loading = false;
|
||||
_died = false;
|
||||
Drop(_link);
|
||||
_link = null;
|
||||
}
|
||||
if (_died) Revive();
|
||||
if (Ready)
|
||||
{
|
||||
if (_pending != null)
|
||||
{
|
||||
_wanted = _pending;
|
||||
_pending = null;
|
||||
_tries = 0;
|
||||
_retryAt = Time.unscaledTime + 5f;
|
||||
Navigate();
|
||||
}
|
||||
KeepNavigating();
|
||||
SendState();
|
||||
}
|
||||
float now = Time.unscaledTime;
|
||||
if (now >= _nextDecode)
|
||||
{
|
||||
var s = Interlocked.Exchange(ref _shot, null);
|
||||
if (s != null)
|
||||
{
|
||||
// the screen of a phone is no reason to spend a frame of the game on every frame of a video
|
||||
_nextDecode = now + (sharp ? 1f / 30f : 1f / 24f);
|
||||
if (_page)
|
||||
{
|
||||
float started = Time.realtimeSinceStartup;
|
||||
if (_decoded.LoadImage(s.Jpeg, false))
|
||||
{
|
||||
Graphics.Blit(_decoded, _rt);
|
||||
Fresh = true;
|
||||
}
|
||||
_decodeMs += Time.realtimeSinceStartup - started;
|
||||
_decodes++;
|
||||
}
|
||||
Ack(s);
|
||||
}
|
||||
}
|
||||
var at = _url;
|
||||
if (at != null && at != "about:blank") _last = at;
|
||||
}
|
||||
|
||||
void Navigate() => _navId = Cmd("Page.navigate", "{\"url\":" + Str(_wanted) + "}");
|
||||
|
||||
/// <summary>Until the page has actually arrived it can still get lost: a navigation is dropped while the tab is busy.</summary>
|
||||
void KeepNavigating()
|
||||
{
|
||||
if (_wanted == null) return;
|
||||
string at = _url, failed = _navError;
|
||||
if (at != null && at != "about:blank") { _wanted = null; return; }
|
||||
if (failed != null)
|
||||
{
|
||||
_navError = null;
|
||||
if (!failed.Contains("ABORTED")) { GiveUp(); return; }
|
||||
_retryAt = 0f;
|
||||
}
|
||||
if (Time.unscaledTime < _retryAt) return;
|
||||
if (_tries >= Retries) { GiveUp(); return; }
|
||||
_tries++;
|
||||
_retryAt = Time.unscaledTime + 5f * (_tries + 1);
|
||||
Navigate();
|
||||
}
|
||||
|
||||
void GiveUp()
|
||||
{
|
||||
_wanted = null;
|
||||
_loading = false;
|
||||
_problem = Loc.N("Can't reach that site.");
|
||||
}
|
||||
|
||||
/// <summary>Sent again and again: a new document starts with nothing, and the phone may have gone away before it arrived.</summary>
|
||||
void SendState()
|
||||
{
|
||||
if (Time.unscaledTime < _nextState) return;
|
||||
_nextState = Time.unscaledTime + 0.5f;
|
||||
string v = (GameSettings.Master * GameSettings.PhoneVolume).ToString("0.00", CultureInfo.InvariantCulture);
|
||||
Cmd("Runtime.evaluate", "{\"expression\":\"void(window.__gc&&(__gc.vol=" + v + ",__gc.hold=" + (_shown ? "false" : "true") + "))\"}");
|
||||
}
|
||||
|
||||
void Revive()
|
||||
{
|
||||
_died = false;
|
||||
Drop(_link);
|
||||
_link = null;
|
||||
if (!_page) return;
|
||||
string back = _wanted ?? _pending ?? _last;
|
||||
if (back != null && _restarts < 3)
|
||||
{
|
||||
_restarts++;
|
||||
_pending = back;
|
||||
_url = null;
|
||||
_loading = true;
|
||||
Boot();
|
||||
return;
|
||||
}
|
||||
_loading = false;
|
||||
_problem = Loc.N("The connection dropped.");
|
||||
}
|
||||
|
||||
// ───────────────────────── the engine ─────────────────────────
|
||||
|
||||
static string Engine()
|
||||
{
|
||||
string pf = Environment.GetEnvironmentVariable("ProgramFiles"), pf86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
|
||||
string local = Environment.GetEnvironmentVariable("LOCALAPPDATA");
|
||||
foreach (var root in new[] { pf86, pf, local })
|
||||
{
|
||||
if (string.IsNullOrEmpty(root)) continue;
|
||||
foreach (var exe in new[] { @"Microsoft\Edge\Application\msedge.exe", @"Google\Chrome\Application\chrome.exe" })
|
||||
{
|
||||
var path = Path.Combine(root, exe);
|
||||
if (File.Exists(path)) return path;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void Boot()
|
||||
{
|
||||
if (_link != null) return;
|
||||
var link = _link = new Link();
|
||||
string exe = Engine();
|
||||
Application.quitting -= Close;
|
||||
Application.quitting += Close;
|
||||
Task.Run(() => Connect(link, exe));
|
||||
}
|
||||
|
||||
async Task Connect(Link link, string exe)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_profile);
|
||||
string portFile = Path.Combine(_profile, "DevToolsActivePort");
|
||||
// the last browser may still be letting go of its profile
|
||||
for (int i = 0; i < 20 && File.Exists(portFile); i++)
|
||||
{
|
||||
try { File.Delete(portFile); }
|
||||
catch (IOException) { await Task.Delay(100); }
|
||||
catch (UnauthorizedAccessException) { await Task.Delay(100); }
|
||||
}
|
||||
string args = "--headless=new --remote-debugging-port=0 --user-data-dir=\"" + _profile + "\" --no-first-run --no-default-browser-check " +
|
||||
"--autoplay-policy=no-user-gesture-required --hide-crash-restore-bubble --disable-sync --disk-cache-size=157286400 --window-size=412,875 " + (_mute ? "--mute-audio " : "") + "about:blank";
|
||||
link.Proc = Process.Start(new ProcessStartInfo(exe, args) { UseShellExecute = false, CreateNoWindow = true });
|
||||
TieToGame(link);
|
||||
|
||||
string port = null;
|
||||
for (int i = 0; i < 150 && port == null; i++)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
try { port = File.ReadAllText(portFile).Split('\n')[0].Trim(); } catch (IOException) { }
|
||||
if (port == "") port = null;
|
||||
}
|
||||
if (port == null) throw new TimeoutException("The browser didn't start.");
|
||||
|
||||
string ws, ua;
|
||||
using (var http = new HttpClient(new HttpClientHandler { UseProxy = false }))
|
||||
{
|
||||
// the debug server hangs up after each answer, so no reusing the connection
|
||||
http.DefaultRequestHeaders.ConnectionClose = true;
|
||||
// a fresh tab of our own: what's already open can be a restored page, a start-up about:blank still on its
|
||||
// way, or Edge's hidden extension pages, which come first in its list and would swallow the page we ask for
|
||||
var open = await http.GetStringAsync($"http://127.0.0.1:{port}/json");
|
||||
var made = await http.SendAsync(new HttpRequestMessage(HttpMethod.Put, $"http://127.0.0.1:{port}/json/new?about:blank"));
|
||||
made.EnsureSuccessStatusCode();
|
||||
var tab = await made.Content.ReadAsStringAsync();
|
||||
ws = Regex.Match(tab, "\"webSocketDebuggerUrl\"\\s*:\\s*\"(ws://[^\"]+)\"").Groups[1].Value;
|
||||
link.Tab = Regex.Match(tab, "\"id\"\\s*:\\s*\"([^\"]+)\"").Groups[1].Value;
|
||||
foreach (Match old in Regex.Matches(open, "\"id\"\\s*:\\s*\"([^\"]+)\"[^{}]*?\"type\"\\s*:\\s*\"page\""))
|
||||
await http.GetAsync($"http://127.0.0.1:{port}/json/close/{old.Groups[1].Value}");
|
||||
var version = await http.GetStringAsync($"http://127.0.0.1:{port}/json/version");
|
||||
string chrome = Regex.Match(version, "\"Browser\"\\s*:\\s*\"[^/]+/(\\d+)").Groups[1].Value;
|
||||
ua = $"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{chrome}.0.0.0 Mobile Safari/537.36";
|
||||
}
|
||||
|
||||
link.Ws = new ClientWebSocket();
|
||||
link.Ws.Options.Proxy = null;
|
||||
await link.Ws.ConnectAsync(new Uri(ws), link.Stop.Token);
|
||||
_ = Task.Run(() => Sender(link));
|
||||
_ = Task.Run(() => Receiver(link));
|
||||
|
||||
Send(link, "Page.enable", "{}");
|
||||
Send(link, "Emulation.setUserAgentOverride", "{\"userAgent\":" + Str(ua) + ",\"platform\":\"Linux armv8l\"}");
|
||||
Send(link, "Emulation.setTouchEmulationEnabled", "{\"enabled\":true,\"maxTouchPoints\":5}");
|
||||
Send(link, "Browser.setDownloadBehavior", "{\"behavior\":\"deny\"}");
|
||||
Send(link, "Page.addScriptToEvaluateOnNewDocument", "{\"source\":" + Str(Keep) + "}");
|
||||
Metrics();
|
||||
if (_shown) Screencast(true);
|
||||
link.Ready = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (link.Stop.IsCancellationRequested) return;
|
||||
UnityEngine.Debug.LogWarning("[PhoneWeb] " + e.GetType().Name + ": " + (e.InnerException ?? e).Message);
|
||||
_problem = Loc.N("Something on this PC stopped the browser from starting.");
|
||||
_failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
int Cmd(string method, string args = "{}")
|
||||
{
|
||||
int id = Interlocked.Increment(ref _id);
|
||||
Send(_link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}");
|
||||
return id;
|
||||
}
|
||||
|
||||
void Send(Link link, string method, string args)
|
||||
{
|
||||
int id = Interlocked.Increment(ref _id);
|
||||
Send(link, "{\"id\":" + id + ",\"method\":\"" + method + "\",\"params\":" + args + "}");
|
||||
}
|
||||
|
||||
static void Send(Link link, string message)
|
||||
{
|
||||
if (link == null || link.Out.IsAddingCompleted) return;
|
||||
try { link.Out.Add(message); }
|
||||
catch (InvalidOperationException) { }
|
||||
}
|
||||
|
||||
void Ack(Shot s)
|
||||
{
|
||||
Cmd("Page.screencastFrameAck", "{\"sessionId\":" + s.Session + "}");
|
||||
_spare.Add(s);
|
||||
}
|
||||
|
||||
static string Str(string s)
|
||||
{
|
||||
var b = new StringBuilder("\"");
|
||||
foreach (char c in s)
|
||||
{
|
||||
if (c == '"' || c == '\\') b.Append('\\').Append(c);
|
||||
else if (c < 32) b.Append("\\u").Append(((int)c).ToString("x4"));
|
||||
else b.Append(c);
|
||||
}
|
||||
return b.Append('"').ToString();
|
||||
}
|
||||
|
||||
async Task Sender(Link link)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var m in link.Out.GetConsumingEnumerable(link.Stop.Token))
|
||||
await link.Ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(m)), WebSocketMessageType.Text, true, link.Stop.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (WebSocketException) { Lost(link); }
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
|
||||
[Serializable] class Msg { public int id; public string method; public Params @params; public Outer result; }
|
||||
[Serializable] class Params { public string url, frameId; public FrameInfo frame; }
|
||||
[Serializable] class FrameInfo { public string url; public string parentId; }
|
||||
[Serializable] class Outer { public Inner result; public string errorText; }
|
||||
[Serializable] class Inner { public string value; }
|
||||
|
||||
async Task Receiver(Link link)
|
||||
{
|
||||
var buffer = new byte[1 << 16];
|
||||
var message = new MemoryStream(1 << 20);
|
||||
try
|
||||
{
|
||||
while (!link.Stop.IsCancellationRequested)
|
||||
{
|
||||
var r = await link.Ws.ReceiveAsync(new ArraySegment<byte>(buffer), link.Stop.Token);
|
||||
if (r.MessageType == WebSocketMessageType.Close) { Lost(link); return; }
|
||||
message.Write(buffer, 0, r.Count);
|
||||
if (!r.EndOfMessage) continue;
|
||||
try { Handle(link, message.GetBuffer(), (int)message.Length); }
|
||||
catch (ArgumentException e) { UnityEngine.Debug.LogWarning("[PhoneWeb] bad message: " + e.Message); }
|
||||
message.SetLength(0);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (WebSocketException) { Lost(link); }
|
||||
catch (ObjectDisposedException) { }
|
||||
}
|
||||
|
||||
static readonly byte[] FrameMark = Encoding.ASCII.GetBytes("\"Page.screencastFrame\""), DataMark = Encoding.ASCII.GetBytes("\"data\":\""), SessionMark = Encoding.ASCII.GetBytes("\"sessionId\":");
|
||||
static readonly sbyte[] Sextet = MakeSextets();
|
||||
|
||||
static sbyte[] MakeSextets()
|
||||
{
|
||||
var t = new sbyte[256];
|
||||
for (int i = 0; i < 256; i++) t[i] = -1;
|
||||
const string abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
for (int i = 0; i < 64; i++) t[abc[i]] = (sbyte)i;
|
||||
return t;
|
||||
}
|
||||
|
||||
static int Find(byte[] b, int from, int to, byte[] what)
|
||||
{
|
||||
for (int i = from; i <= to - what.Length; i++)
|
||||
{
|
||||
int k = 0;
|
||||
while (k < what.Length && b[i + k] == what[k]) k++;
|
||||
if (k == what.Length) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void Handle(Link link, byte[] b, int n)
|
||||
{
|
||||
// video frames are nearly all of the traffic, and big: picked out of the bytes, with no strings made of them
|
||||
if (Find(b, 0, Math.Min(n, 64), FrameMark) >= 0)
|
||||
{
|
||||
TakeFrame(b, n);
|
||||
return;
|
||||
}
|
||||
var m = JsonUtility.FromJson<Msg>(Encoding.UTF8.GetString(b, 0, n));
|
||||
if (m.id != 0)
|
||||
{
|
||||
if (_wait.TryRemove(m.id, out var done)) done.TrySetResult(m.result?.result?.value);
|
||||
if (m.id == _navId && !string.IsNullOrEmpty(m.result?.errorText)) _navError = m.result.errorText;
|
||||
}
|
||||
else if (m.method == "Page.frameNavigated")
|
||||
{
|
||||
if (string.IsNullOrEmpty(m.@params?.frame?.parentId)) _url = m.@params?.frame?.url;
|
||||
}
|
||||
else if (m.method == "Page.navigatedWithinDocument") _url = m.@params?.url;
|
||||
else if (m.method == "Page.frameStartedLoading") { if (m.@params?.frameId == link.Tab) _loading = true; }
|
||||
else if (m.method == "Page.frameStoppedLoading") { if (m.@params?.frameId == link.Tab) _loading = false; }
|
||||
else if (m.method == "Page.javascriptDialogOpening") Cmd("Page.handleJavaScriptDialog", "{\"accept\":true}");
|
||||
}
|
||||
|
||||
void TakeFrame(byte[] b, int n)
|
||||
{
|
||||
int a = Find(b, 0, n, DataMark) + DataMark.Length;
|
||||
int e = a;
|
||||
while (e < n && b[e] != (byte)'"') e++;
|
||||
int s = -1;
|
||||
for (int i = n - SessionMark.Length; i > e && s < 0; i--) if (Find(b, i, i + SessionMark.Length, SessionMark) == i) s = i + SessionMark.Length;
|
||||
int session = 0;
|
||||
while (s > 0 && s < n && b[s] >= (byte)'0' && b[s] <= (byte)'9') session = session * 10 + b[s++] - '0';
|
||||
|
||||
if (!_spare.TryTake(out var shot)) shot = new Shot();
|
||||
int need = (e - a) / 4 * 3 + 3;
|
||||
if (shot.Jpeg.Length < need) shot.Jpeg = new byte[need * 5 / 4];
|
||||
var o = shot.Jpeg;
|
||||
int w = 0, bits = 0, count = 0;
|
||||
for (int i = a; i < e; i++)
|
||||
{
|
||||
int v = Sextet[b[i]];
|
||||
if (v < 0) continue;
|
||||
bits = (bits << 6) | v;
|
||||
if (++count == 4)
|
||||
{
|
||||
o[w++] = (byte)(bits >> 16); o[w++] = (byte)(bits >> 8); o[w++] = (byte)bits;
|
||||
bits = 0;
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
if (count == 3) { o[w++] = (byte)(bits >> 10); o[w++] = (byte)(bits >> 2); }
|
||||
else if (count == 2) o[w++] = (byte)(bits >> 4);
|
||||
// what's left of a bigger frame after the end of this one is past the JPEG's own end marker, where nothing reads it
|
||||
shot.Session = session;
|
||||
Interlocked.Increment(ref _frames);
|
||||
var old = Interlocked.Exchange(ref _shot, shot);
|
||||
if (old != null) Ack(old);
|
||||
}
|
||||
|
||||
void Lost(Link link)
|
||||
{
|
||||
if (link != _link || link.Stop.IsCancellationRequested) return;
|
||||
link.Ready = false;
|
||||
_died = true;
|
||||
}
|
||||
|
||||
/// <summary>Closed properly, so the logins from this session make it to disk.</summary>
|
||||
public void Close()
|
||||
{
|
||||
Application.quitting -= Close;
|
||||
var link = _link;
|
||||
_link = null;
|
||||
_page = false;
|
||||
_pending = _wanted = _last = null;
|
||||
_url = null;
|
||||
_loading = false;
|
||||
if (link == null) return;
|
||||
if (link.Ready)
|
||||
{
|
||||
link.Ready = false;
|
||||
Send(link, "Browser.close", "{}");
|
||||
try { link.Proc?.WaitForExit(1500); } catch (InvalidOperationException) { }
|
||||
}
|
||||
Drop(link);
|
||||
}
|
||||
|
||||
void Drop(Link link)
|
||||
{
|
||||
if (link == null) return;
|
||||
link.Ready = false;
|
||||
link.Stop.Cancel();
|
||||
link.Out.CompleteAdding();
|
||||
try { if (link.Proc != null && !link.Proc.HasExited) link.Proc.Kill(); } catch (InvalidOperationException) { } catch (System.ComponentModel.Win32Exception) { }
|
||||
if (link.Job != IntPtr.Zero) CloseHandle(link.Job);
|
||||
foreach (var w in _wait.Values) w.TrySetResult(null);
|
||||
_wait.Clear();
|
||||
}
|
||||
|
||||
// ───────────────────────── never outlive the game, even after a crash ─────────────────────────
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)] struct BasicLimits { public long a, b; public uint flags; public UIntPtr c, d; public uint e; public UIntPtr f; public uint g, h; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct IoCounters { public ulong a, b, c, d, e, f; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct ExtendedLimits { public BasicLimits basic; public IoCounters io; public UIntPtr a, b, c, d; }
|
||||
[DllImport("kernel32", SetLastError = true)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
|
||||
[DllImport("kernel32", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr job, int kind, ref ExtendedLimits info, int size);
|
||||
[DllImport("kernel32", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
||||
[DllImport("kernel32", SetLastError = true)] static extern bool CloseHandle(IntPtr handle);
|
||||
|
||||
static void TieToGame(Link link)
|
||||
{
|
||||
const int ExtendedLimitInformation = 9;
|
||||
const uint KillOnJobClose = 0x2000;
|
||||
link.Job = CreateJobObject(IntPtr.Zero, null);
|
||||
if (link.Job == IntPtr.Zero) return;
|
||||
var info = new ExtendedLimits { basic = new BasicLimits { flags = KillOnJobClose } };
|
||||
if (SetInformationJobObject(link.Job, ExtendedLimitInformation, ref info, Marshal.SizeOf<ExtendedLimits>()))
|
||||
AssignProcessToJobObject(link.Job, link.Proc.Handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/PhoneWeb.cs.meta
Normal file
2
Assets/Scripts/Core/PhoneWeb.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ad35fc6320c9df3408f645c35e06ec86
|
||||
224
Assets/Scripts/Core/SaveSlots.cs
Normal file
224
Assets/Scripts/Core/SaveSlots.cs
Normal file
@ -0,0 +1,224 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public struct SlotInfo
|
||||
{
|
||||
public bool used;
|
||||
public double money, shipped, mown;
|
||||
public DateTime when;
|
||||
public Difficulty level;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Five saves on disk, each in a folder of its own: the game, the mow map and up to five backups, the first a minute in and
|
||||
/// then one every half hour. A save that can't be read is put right from its newest good backup.
|
||||
/// Each Steam account has its own folder, <c>saves/<SteamID64></c>, which Steam Auto-Cloud syncs as
|
||||
/// <c>WinAppDataLocalLow / GreenHaul/Grass Cutters Together/saves/{64BitSteamID}</c>: two people on one PC never share saves.
|
||||
/// </summary>
|
||||
public static class SaveSlots
|
||||
{
|
||||
public const int Count = 5, Backups = 5;
|
||||
const string GameFile = "game.json", MapFile = "mow.bin", OldKey = "grasscutter_save_v2";
|
||||
|
||||
[Serializable] class Head { public double money, shipped, mown; public int level; public int[] tiles; }
|
||||
|
||||
public static int Current { get; set; }
|
||||
|
||||
/// <summary>The game used to be called Grass Cutter and so did its folder. The saves come over once, and the old ones stay where they were.</summary>
|
||||
static void TakeOldFolder()
|
||||
{
|
||||
var old = Path.Combine(Path.GetDirectoryName(Application.persistentDataPath), "Grass Cutter", "saves");
|
||||
if (Dev || Directory.Exists(Shared) || !Directory.Exists(old)) return;
|
||||
foreach (var file in Directory.GetFiles(old, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
var to = Shared + file.Substring(old.Length);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(to));
|
||||
File.Copy(file, to);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Slots from before saves were kept per Steam account sit straight in <c>saves</c>. The first account to start the game
|
||||
/// takes them into its own folder; anyone after starts with empty slots. Checked slot by slot, not by the folder: Steam
|
||||
/// makes the account folder itself (for <c>steam_autocloud.vdf</c>) before the game ever runs. A slot already played in
|
||||
/// the account folder stays, and the old one waits under the next free number, or where it is if none is free.
|
||||
/// </summary>
|
||||
static void TakeSharedSlots(string mine)
|
||||
{
|
||||
if (!Directory.Exists(Shared)) return;
|
||||
for (int i = 0; i < Count; i++)
|
||||
{
|
||||
var from = Path.Combine(Shared, "slot" + (i + 1));
|
||||
if (!Directory.Exists(from)) continue;
|
||||
int to = Directory.Exists(Path.Combine(mine, "slot" + (i + 1))) ? FreeSlot(mine) : i;
|
||||
if (to < 0) { Debug.LogWarning("[Save] no free slot for old slot " + (i + 1) + ", left in " + Shared); continue; }
|
||||
Directory.CreateDirectory(mine);
|
||||
Directory.Move(from, Path.Combine(mine, "slot" + (to + 1)));
|
||||
Debug.Log("[Save] old slot " + (i + 1) + " moved into " + mine + " as slot " + (to + 1));
|
||||
}
|
||||
}
|
||||
|
||||
static int FreeSlot(string root)
|
||||
{
|
||||
for (int i = 0; i < Count; i++) if (!Directory.Exists(Path.Combine(root, "slot" + (i + 1)))) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static bool Dev => CommandLine.Has("-autodemo") || CommandLine.Has("-mpdemo");
|
||||
/// <summary>Without Steam (and in test runs) the slots sit straight in here.</summary>
|
||||
static string Shared => Path.Combine(Application.persistentDataPath, Dev ? "saves_dev" : "saves");
|
||||
static string _ready;
|
||||
static string Root
|
||||
{
|
||||
get
|
||||
{
|
||||
var root = !Dev && SteamManager.Initialized ? Path.Combine(Shared, SteamManager.MySteamId.m_SteamID.ToString()) : Shared;
|
||||
if (_ready != root)
|
||||
{
|
||||
_ready = root;
|
||||
try
|
||||
{
|
||||
TakeOldFolder();
|
||||
if (root != Shared) TakeSharedSlots(root);
|
||||
}
|
||||
catch (IOException e) { Debug.LogWarning("[Save] couldn't bring old saves over: " + e.Message); }
|
||||
}
|
||||
return root;
|
||||
}
|
||||
}
|
||||
static string Folder(int slot) => Path.Combine(Root, "slot" + (slot + 1));
|
||||
static string Copy(int slot, int n) => Path.Combine(Folder(slot), "backup" + (n + 1));
|
||||
|
||||
public static string MapPath => Path.Combine(Folder(Current), MapFile);
|
||||
public static string GamePath => Path.Combine(Folder(Current), GameFile);
|
||||
|
||||
// ───────────────────────── writing ─────────────────────────
|
||||
|
||||
public static void Write(string json, byte[] map)
|
||||
{
|
||||
var dir = Folder(Current);
|
||||
Directory.CreateDirectory(dir);
|
||||
Put(Path.Combine(dir, GameFile), Encoding.UTF8.GetBytes(json));
|
||||
Put(Path.Combine(dir, MapFile), map);
|
||||
}
|
||||
|
||||
/// <summary>Written whole or not at all: a crash halfway leaves the last save as it was.</summary>
|
||||
static void Put(string path, byte[] data)
|
||||
{
|
||||
string tmp = path + ".tmp";
|
||||
File.WriteAllBytes(tmp, data);
|
||||
if (File.Exists(path)) File.Delete(path);
|
||||
File.Move(tmp, path);
|
||||
}
|
||||
|
||||
/// <summary>The current save goes over the oldest of its backups.</summary>
|
||||
public static void Backup()
|
||||
{
|
||||
var dir = Folder(Current);
|
||||
var game = Path.Combine(dir, GameFile);
|
||||
if (!File.Exists(game)) return;
|
||||
int pick = 0;
|
||||
var oldest = DateTime.MaxValue;
|
||||
for (int n = 0; n < Backups; n++)
|
||||
{
|
||||
var path = Path.Combine(Copy(Current, n), GameFile);
|
||||
var when = File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue;
|
||||
if (when < oldest) { oldest = when; pick = n; }
|
||||
}
|
||||
var to = Copy(Current, pick);
|
||||
Directory.CreateDirectory(to);
|
||||
File.Copy(game, Path.Combine(to, GameFile), true);
|
||||
File.SetLastWriteTimeUtc(Path.Combine(to, GameFile), DateTime.UtcNow);
|
||||
var map = Path.Combine(dir, MapFile);
|
||||
if (File.Exists(map)) File.Copy(map, Path.Combine(to, MapFile), true);
|
||||
}
|
||||
|
||||
// ───────────────────────── reading ─────────────────────────
|
||||
|
||||
static string Text(string path)
|
||||
{
|
||||
try { return File.Exists(path) ? File.ReadAllText(path) : null; }
|
||||
catch (IOException e) { Debug.LogWarning("[Save] can't read " + path + ": " + e.Message); return null; }
|
||||
}
|
||||
|
||||
static Head Parse(string json)
|
||||
{
|
||||
if (string.IsNullOrEmpty(json)) return null;
|
||||
try
|
||||
{
|
||||
var h = JsonUtility.FromJson<Head>(json);
|
||||
return h != null && h.tiles != null && h.tiles.Length > 0 ? h : null;
|
||||
}
|
||||
catch (ArgumentException) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Backups of a slot, the newest first.</summary>
|
||||
static List<string> Newest(int slot)
|
||||
{
|
||||
var list = new List<string>();
|
||||
for (int n = 0; n < Backups; n++)
|
||||
if (File.Exists(Path.Combine(Copy(slot, n), GameFile))) list.Add(Copy(slot, n));
|
||||
list.Sort((a, b) => File.GetLastWriteTimeUtc(Path.Combine(b, GameFile)).CompareTo(File.GetLastWriteTimeUtc(Path.Combine(a, GameFile))));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>The save to load, or null for a new game. A bad one is replaced from its backups first.</summary>
|
||||
public static string Read()
|
||||
{
|
||||
Migrate();
|
||||
var dir = Folder(Current);
|
||||
var json = Text(Path.Combine(dir, GameFile));
|
||||
if (Parse(json) != null) return json;
|
||||
foreach (var copy in Newest(Current))
|
||||
{
|
||||
var old = Text(Path.Combine(copy, GameFile));
|
||||
if (Parse(old) == null) continue;
|
||||
Debug.LogWarning("[Save] the save was damaged, restored from " + copy);
|
||||
File.Copy(Path.Combine(copy, GameFile), Path.Combine(dir, GameFile), true);
|
||||
if (File.Exists(Path.Combine(copy, MapFile))) File.Copy(Path.Combine(copy, MapFile), Path.Combine(dir, MapFile), true);
|
||||
return old;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Mow maps to fall back on when the slot's own won't load, the newest first.</summary>
|
||||
public static IEnumerable<string> OlderMaps()
|
||||
{
|
||||
foreach (var copy in Newest(Current)) yield return Path.Combine(copy, MapFile);
|
||||
}
|
||||
|
||||
public static SlotInfo Info(int slot)
|
||||
{
|
||||
var path = Path.Combine(Folder(slot), GameFile);
|
||||
var h = Parse(Text(path));
|
||||
if (h == null) return new SlotInfo { used = File.Exists(path) };
|
||||
return new SlotInfo { used = true, money = h.money, shipped = h.shipped, mown = h.mown, level = (Difficulty)h.level, when = File.GetLastWriteTime(path) };
|
||||
}
|
||||
|
||||
public static void Delete(int slot)
|
||||
{
|
||||
if (Directory.Exists(Folder(slot))) Directory.Delete(Folder(slot), true);
|
||||
}
|
||||
|
||||
/// <summary>Saves from before the slots lived in the registry: they become the first slot.</summary>
|
||||
static void Migrate()
|
||||
{
|
||||
if (Dev || !PlayerPrefs.HasKey(OldKey)) return;
|
||||
var dir = Folder(0);
|
||||
if (!File.Exists(Path.Combine(dir, GameFile)))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(Path.Combine(dir, GameFile), PlayerPrefs.GetString(OldKey));
|
||||
var map = Path.Combine(Application.persistentDataPath, MapFile);
|
||||
if (File.Exists(map)) File.Move(map, Path.Combine(dir, MapFile));
|
||||
}
|
||||
PlayerPrefs.DeleteKey(OldKey);
|
||||
PlayerPrefs.Save();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/SaveSlots.cs.meta
Normal file
2
Assets/Scripts/Core/SaveSlots.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1ca3fc6d67911294db4381271db54c78
|
||||
180
Assets/Scripts/Core/Sfx.cs
Normal file
180
Assets/Scripts/Core/Sfx.cs
Normal file
@ -0,0 +1,180 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Pooled 2D/3D sound effects, music crossfading.</summary>
|
||||
public class Sfx : MonoBehaviour
|
||||
{
|
||||
static Sfx _i;
|
||||
public static Sfx I
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_i == null)
|
||||
{
|
||||
var go = new GameObject("[Sfx]");
|
||||
DontDestroyOnLoad(go);
|
||||
_i = go.AddComponent<Sfx>();
|
||||
}
|
||||
return _i;
|
||||
}
|
||||
}
|
||||
|
||||
const int Voices = 40;
|
||||
readonly List<AudioSource> _pool = new List<AudioSource>();
|
||||
int _next;
|
||||
AudioSource _musicA, _musicB;
|
||||
bool _musicOnA = true;
|
||||
string _currentMusic;
|
||||
readonly Dictionary<string, float> _lastPlayed = new Dictionary<string, float>();
|
||||
|
||||
public static float MasterVolume = 1f, MusicVolume = 0.6f, SfxVolume = 1f;
|
||||
/// <summary>The people on the calls: the Director and his assistant. Their own slider, apart from the effects.</summary>
|
||||
public static float VoiceVolume = 1f;
|
||||
/// <summary>Music sinks under a voice: 1 is full, 0 silent.</summary>
|
||||
static float _duck = 1f;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
for (int i = 0; i < Voices; i++)
|
||||
{
|
||||
var go = new GameObject("voice" + i);
|
||||
go.transform.SetParent(transform);
|
||||
var s = go.AddComponent<AudioSource>();
|
||||
s.playOnAwake = false;
|
||||
s.rolloffMode = AudioRolloffMode.Linear;
|
||||
s.minDistance = 2f;
|
||||
s.maxDistance = 28f;
|
||||
s.dopplerLevel = 0f;
|
||||
_pool.Add(s);
|
||||
}
|
||||
_musicA = MakeMusic("musicA");
|
||||
_musicB = MakeMusic("musicB");
|
||||
ApplyVolumes();
|
||||
}
|
||||
|
||||
AudioSource MakeMusic(string n)
|
||||
{
|
||||
var go = new GameObject(n);
|
||||
go.transform.SetParent(transform);
|
||||
var s = go.AddComponent<AudioSource>();
|
||||
s.loop = true;
|
||||
s.spatialBlend = 0f;
|
||||
s.playOnAwake = false;
|
||||
s.volume = 0f;
|
||||
return s;
|
||||
}
|
||||
|
||||
public static void ApplyVolumes()
|
||||
{
|
||||
AudioListener.volume = MasterVolume;
|
||||
}
|
||||
|
||||
AudioSource NextVoice()
|
||||
{
|
||||
// prefer a free voice, otherwise steal round-robin
|
||||
for (int k = 0; k < _pool.Count; k++)
|
||||
{
|
||||
var s = _pool[(_next + k) % _pool.Count];
|
||||
if (!s.isPlaying) { _next = (_next + k + 1) % _pool.Count; return s; }
|
||||
}
|
||||
var v = _pool[_next];
|
||||
_next = (_next + 1) % _pool.Count;
|
||||
return v;
|
||||
}
|
||||
|
||||
/// <summary>Every sound asked for: name, volume, pitch, and where in the world (null: in the ears). The trailer logs them.</summary>
|
||||
public static System.Action<string, float, float, Vector3?> Heard;
|
||||
|
||||
public static AudioSource Play(string clip, float volume = 1f, float pitch = 1f, float pitchJitter = 0.05f, float minInterval = 0f)
|
||||
{
|
||||
Heard?.Invoke(clip, volume, pitch, null);
|
||||
return I.PlayAt(AssetBank.I.Clip(clip), null, volume, pitch, pitchJitter, minInterval, clip);
|
||||
}
|
||||
|
||||
public static AudioSource PlayAt(string clip, Vector3 pos, float volume = 1f, float pitch = 1f, float pitchJitter = 0.06f, float minInterval = 0f)
|
||||
{
|
||||
Heard?.Invoke(clip, volume, pitch, pos);
|
||||
return I.PlayAt(AssetBank.I.Clip(clip), pos, volume, pitch, pitchJitter, minInterval, clip);
|
||||
}
|
||||
|
||||
AudioSource PlayAt(AudioClip c, Vector3? pos, float volume, float pitch, float jitter, float minInterval, string key)
|
||||
{
|
||||
if (!c) return null;
|
||||
if (minInterval > 0f)
|
||||
{
|
||||
if (_lastPlayed.TryGetValue(key, out float t) && Time.unscaledTime - t < minInterval) return null;
|
||||
_lastPlayed[key] = Time.unscaledTime;
|
||||
}
|
||||
var s = NextVoice();
|
||||
s.clip = c;
|
||||
s.volume = volume * SfxVolume;
|
||||
s.pitch = pitch * (1f + Random.Range(-jitter, jitter));
|
||||
s.loop = false;
|
||||
if (pos.HasValue) { s.spatialBlend = 0.85f; s.transform.position = pos.Value; }
|
||||
else s.spatialBlend = 0f;
|
||||
s.Play();
|
||||
return s;
|
||||
}
|
||||
|
||||
public static void Music(string name, float fade = 1.5f)
|
||||
{
|
||||
var i = I;
|
||||
if (i._currentMusic == name) return;
|
||||
i._currentMusic = name;
|
||||
var clip = AssetBank.I.Clip(name);
|
||||
var from = i._musicOnA ? i._musicA : i._musicB;
|
||||
var to = i._musicOnA ? i._musicB : i._musicA;
|
||||
i._musicOnA = !i._musicOnA;
|
||||
Tween.Kill(i._musicA); Tween.Kill(i._musicB);
|
||||
float fromStart = from.volume;
|
||||
Tween.Run(from, fade, k => from.volume = Mathf.Lerp(fromStart, 0f, k), Ease.Linear, 0f, () => from.Stop());
|
||||
if (!clip) return;
|
||||
to.clip = clip;
|
||||
to.volume = 0f;
|
||||
to.Play();
|
||||
Tween.Run(to, fade, k => to.volume = k * MusicVolume * 0.55f * _duck, Ease.Linear);
|
||||
}
|
||||
|
||||
/// <summary>Lowers (or restores) the music under the director's voice.</summary>
|
||||
public static void Duck(float k)
|
||||
{
|
||||
k = Mathf.Clamp01(k);
|
||||
if (Mathf.Abs(k - _duck) < 0.001f) return;
|
||||
_duck = k;
|
||||
var i = I;
|
||||
if (!i) return;
|
||||
var active = i._musicOnA ? i._musicA : i._musicB;
|
||||
if (active.isPlaying && !Tween.Running(active)) active.volume = MusicVolume * 0.55f * _duck;
|
||||
}
|
||||
|
||||
public static void RefreshMusicVolume()
|
||||
{
|
||||
var i = I;
|
||||
// Music() flips _musicOnA after picking the target, so the active source is the one it now names.
|
||||
var active = i._musicOnA ? i._musicA : i._musicB;
|
||||
if (active.isPlaying) active.volume = MusicVolume * 0.55f * _duck;
|
||||
}
|
||||
|
||||
/// <summary>Starts a looping 3D sound and returns its source (caller stops it).</summary>
|
||||
public static AudioSource Loop(string clip, Transform follow, float volume)
|
||||
{
|
||||
var c = AssetBank.I.Clip(clip);
|
||||
if (!c || !follow) return null;
|
||||
var go = new GameObject("loop_" + clip);
|
||||
go.transform.SetParent(follow, false);
|
||||
var s = go.AddComponent<AudioSource>();
|
||||
s.clip = c;
|
||||
s.loop = true;
|
||||
s.spatialBlend = 0.9f;
|
||||
s.minDistance = 2f;
|
||||
s.maxDistance = 25f;
|
||||
s.rolloffMode = AudioRolloffMode.Linear;
|
||||
s.volume = volume * SfxVolume;
|
||||
s.dopplerLevel = 0f;
|
||||
s.Play();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Sfx.cs.meta
Normal file
2
Assets/Scripts/Core/Sfx.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 032407d0204ee1645a31139af59be395
|
||||
270
Assets/Scripts/Core/Trailer.Game.cs
Normal file
270
Assets/Scripts/Core/Trailer.Game.cs
Normal file
@ -0,0 +1,270 @@
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The gameplay takes, `g_`: through the player's own eyes, with the hands, the tool and the HUD, played by the script the
|
||||
/// way a player would. The HUD draws into a texture of its own and goes over each frame.
|
||||
/// </summary>
|
||||
public partial class Trailer
|
||||
{
|
||||
RenderTexture _ui;
|
||||
Texture2D _uiRead;
|
||||
|
||||
/// <summary>The camera back on the player's head with its own shake and field of view, the hands and the HUD on; or off again.</summary>
|
||||
void Eyes(bool on)
|
||||
{
|
||||
var fx = _cam.GetComponent<CameraFx>();
|
||||
var doc = FindAnyObjectByType<UIDocument>();
|
||||
if (on)
|
||||
{
|
||||
_cam.transform.SetParent(Me.head, false);
|
||||
_cam.transform.localPosition = Vector3.zero;
|
||||
_cam.transform.localRotation = Quaternion.identity;
|
||||
_cam.fieldOfView = CameraFx.BaseFov;
|
||||
if (fx) fx.enabled = true;
|
||||
ViewModel.Hidden = false;
|
||||
if (!_ui)
|
||||
{
|
||||
_ui = new RenderTexture(W, H, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "TrailerUI" };
|
||||
_ui.Create();
|
||||
_uiRead = new Texture2D(W, H, TextureFormat.RGBA32, false, false);
|
||||
}
|
||||
if (doc && doc.panelSettings)
|
||||
{
|
||||
doc.panelSettings.targetTexture = _ui;
|
||||
doc.panelSettings.clearColor = true;
|
||||
doc.panelSettings.colorClearValue = new Color(0f, 0f, 0f, 0f);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Ctl.BotUseHeld = false;
|
||||
Ctl.BotMove = Vector2.zero;
|
||||
_cam.transform.SetParent(null, true);
|
||||
if (fx) fx.enabled = false;
|
||||
ViewModel.Hidden = true;
|
||||
if (doc && doc.panelSettings) doc.panelSettings.targetTexture = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The HUD over the frame in _read. It comes premultiplied over clear black: out = ui + scene * (1 - ui.a).</summary>
|
||||
void Overlay()
|
||||
{
|
||||
var was = RenderTexture.active;
|
||||
RenderTexture.active = _ui;
|
||||
_uiRead.ReadPixels(new Rect(0, 0, W, H), 0, 0, false);
|
||||
RenderTexture.active = was;
|
||||
var u = _uiRead.GetRawTextureData<byte>();
|
||||
var s = _read.GetRawTextureData<byte>();
|
||||
for (int i = 0, j = 0; i < s.Length; i += 3, j += 4)
|
||||
{
|
||||
int a = u[j + 3];
|
||||
if (a == 0) continue;
|
||||
int k = 255 - a;
|
||||
s[i] = (byte)Mathf.Min(255, u[j] + s[i] * k / 255);
|
||||
s[i + 1] = (byte)Mathf.Min(255, u[j + 1] + s[i + 1] * k / 255);
|
||||
s[i + 2] = (byte)Mathf.Min(255, u[j + 2] + s[i + 2] * k / 255);
|
||||
}
|
||||
}
|
||||
|
||||
static Vector3 North(Vector3 at) => Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(at)).normalized;
|
||||
|
||||
/// <summary>The first spot from x, z eastward with nothing standing in the next 40 m north of it: no rock, tree or wreck.</summary>
|
||||
static Vector2 Open(float x, float z)
|
||||
{
|
||||
for (int i = 0; i < 40; i++, x += 9f)
|
||||
{
|
||||
var at = On(x, z);
|
||||
var up = Planet.Up(at);
|
||||
var hits = Physics.OverlapCapsule(at + up * 1.6f, at + North(at) * 40f + up * 2.4f, 3.2f, ~0, QueryTriggerInteraction.Ignore);
|
||||
if (hits.All(h => h.attachedRigidbody || h.GetComponentInParent<PlayerAgent>())) return new Vector2(x, z);
|
||||
}
|
||||
return new Vector2(x, z);
|
||||
}
|
||||
|
||||
/// <summary>Stands the player at x, z facing north, looking `ahead` metres on.</summary>
|
||||
IEnumerator Stand(float x, float z, float ahead = 5f)
|
||||
{
|
||||
var at = On(x, z);
|
||||
Me.Teleport(at + Planet.Up(at) * 0.2f);
|
||||
yield return null;
|
||||
Me.LookAt(Planet.Surface(at + North(at) * ahead));
|
||||
yield return new WaitForSeconds(0.3f);
|
||||
}
|
||||
|
||||
/// <summary>A strip mown on foot: a slow walk north, the aim swinging across the grass ahead the way a mouse does.</summary>
|
||||
IEnumerator Mow(string name, ToolId tool, float x, float z, float seconds, float swing, float pace = 0.45f, float ahead = 3.2f, double money = -1)
|
||||
{
|
||||
if (!Wanted(name)) yield break;
|
||||
if (money >= 0) Cheats.Run("money set " + money);
|
||||
Me.Tools.Equip(tool);
|
||||
yield return Stand(x, z, ahead);
|
||||
var way = North(Me.transform.position);
|
||||
var side = Vector3.Cross(Planet.Up(Me.transform.position), way);
|
||||
float t = 0f;
|
||||
Ctl.BotUseHeld = true;
|
||||
Ctl.BotMove = Vector2.up * pace;
|
||||
yield return Take(name, seconds, 60, null, 0.8f, k =>
|
||||
{
|
||||
t += Time.deltaTime;
|
||||
var p = Me.transform.position;
|
||||
Me.LookAt(Planet.Surface(p + way * ahead + side * Mathf.Sin(t * 2.1f) * swing));
|
||||
Me.Tools.CheatEmpty();
|
||||
}, true);
|
||||
Ctl.BotUseHeld = false;
|
||||
Ctl.BotMove = Vector2.zero;
|
||||
}
|
||||
|
||||
/// <summary>One of the game's own screens, open over the world.</summary>
|
||||
IEnumerator OnScreen(string name, float seconds, System.Action open, Vector3 lookAt)
|
||||
{
|
||||
if (!Wanted(name)) yield break;
|
||||
Me.Tools.Select(ToolId.None);
|
||||
Me.LookAt(lookAt);
|
||||
yield return null;
|
||||
open();
|
||||
yield return Take(name, seconds, 60, null, 0.6f, null, true);
|
||||
UIRoot.I?.CloseTopModal();
|
||||
yield return new WaitForSeconds(0.3f);
|
||||
}
|
||||
|
||||
IEnumerator Gameplay()
|
||||
{
|
||||
if (!Wanted("g_")) yield break;
|
||||
Sky(0.42f, false);
|
||||
Me.Character.Value = 0;
|
||||
// past the first deliveries, so the HUD has no beginner's hints over the picture
|
||||
Cheats.Run("ship 60");
|
||||
Eyes(true);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
|
||||
// from the nail scissors to the two-handed scythe, each a little further out from the base
|
||||
yield return Mow("g_scissors", ToolId.NailScissors, 28f, 8f, 4f, 0.35f, 0.25f, 1.8f, 3);
|
||||
yield return Mow("g_shears", ToolId.GardenShears, 31f, 8f, 3.5f, 0.45f, 0.3f, 2f, 18);
|
||||
yield return Mow("g_sickle", ToolId.Sickle, 34f, 8f, 3.5f, 0.6f, 0.35f, 2.4f, 41);
|
||||
yield return Mow("g_scythe", ToolId.Scythe, 38f, 8f, 5f, 1.1f, 0.45f, 3.2f, 127);
|
||||
yield return Mow("g_wide", ToolId.WideScythe, 44f, 8f, 5f, 1.5f, 0.5f, 2.8f, 486);
|
||||
|
||||
// the crew alongside, keeping pace on either side
|
||||
if (Wanted("g_coop"))
|
||||
{
|
||||
Cheats.Run("money set 2310");
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
// a step or two ahead on either side, so they are in the picture
|
||||
float off = (i < 2 ? -1 : 1) * (2.6f + (i % 2) * 2.6f), back = -(3f + (i % 2) * 2.5f);
|
||||
Actor(new[] { 4, 6, 2, 7 }[i], On(56f + off, 8f - back), Vector3.forward, i % 2 == 0 ? ToolId.WideScythe : ToolId.LongScythe, true,
|
||||
s => Me.transform.position + Vector3.Cross(Planet.Up(Me.transform.position), North(Me.transform.position)) * off - North(Me.transform.position) * back);
|
||||
}
|
||||
yield return Mow("g_coop", ToolId.WideScythe, 56f, 8f, 6f, 1.2f, 0.5f, 2.8f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
// a full basket handed in at the depot: the money comes up on the HUD
|
||||
var depot = Depot.All.FirstOrDefault();
|
||||
if (depot && Wanted("g_deposit"))
|
||||
{
|
||||
Cheats.Run("money set 127");
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
// the scythe has to be in the hands before the cheat can fill it
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
Cheats.Run("tank");
|
||||
var d = depot.transform.position;
|
||||
var from = d + new Vector3(0f, 0.2f, -6.5f);
|
||||
Me.Teleport(from);
|
||||
yield return null;
|
||||
Me.LookAt(d + Planet.Up(d) * 0.9f);
|
||||
bool paid = false;
|
||||
Ctl.BotMove = Vector2.up * 0.6f;
|
||||
yield return Take("g_deposit", 4f, 60, null, 0.4f, k =>
|
||||
{
|
||||
Me.LookAt(d + Planet.Up(d) * 0.9f);
|
||||
if ((Me.transform.position - d).magnitude < 3.2f) Ctl.BotMove = Vector2.zero;
|
||||
if (!paid && k > 0.5f) { paid = true; Me.Tools.Deposit(depot); }
|
||||
}, true);
|
||||
Ctl.BotMove = Vector2.zero;
|
||||
}
|
||||
|
||||
// the base's own screens
|
||||
var shop = FindAnyObjectByType<ShopTerminal>();
|
||||
var wall = FindAnyObjectByType<SupplyWall>();
|
||||
Cheats.Run("money set 1840");
|
||||
if (wall) yield return OnScreen("g_supply", 3f, () => UIRoot.I.OpenSupply(), wall.transform.position + Vector3.up * 1.4f);
|
||||
if (shop) yield return OnScreen("g_shop", 3.5f, () => UIRoot.I.OpenShop(), shop.transform.position + Vector3.up * 1.2f);
|
||||
yield return OnScreen("g_map", 3f, () => UIRoot.I.OpenMap(), Me.transform.position + North(Me.transform.position) * 10f);
|
||||
yield return OnScreen("g_character", 3f, () => UIRoot.I.OpenCharacter(), Me.transform.position + North(Me.transform.position) * 10f);
|
||||
|
||||
// the hammer: a press set down on mown ground, the ghost sweeping in before the click
|
||||
if (Wanted("g_build") && PlayerBuild.Local)
|
||||
{
|
||||
Cheats.Run("money set 4200");
|
||||
float x = 70f, z = 8f;
|
||||
for (float dz = -4f; dz <= 18f; dz += 2f) MowMap.Cut(On(x - 9f, z + dz), On(x + 9f, z + dz), 2.4f);
|
||||
Me.Tools.Equip(ToolId.Hammer);
|
||||
yield return Stand(x, z - 2f, 7f);
|
||||
var b = PlayerBuild.Local;
|
||||
b.Select(PieceId.Press);
|
||||
var way = North(Me.transform.position);
|
||||
var side = Vector3.Cross(Planet.Up(Me.transform.position), way);
|
||||
var p0 = Me.transform.position;
|
||||
bool built = false;
|
||||
yield return Take("g_build", 5f, 60, null, 0.5f, k =>
|
||||
{
|
||||
// in to the spot, the click, then on to the next free spot so the ghost doesn't sit red on the new press
|
||||
float s = k < 0.62f ? Mathf.Lerp(-3f, 0f, Ease(Mathf.Clamp01(k * 1.8f))) : Mathf.Lerp(0f, 5f, Ease(Mathf.Clamp01((k - 0.62f) * 6f)));
|
||||
Me.LookAt(Planet.Surface(p0 + way * 5.5f + side * s));
|
||||
Ctl.BotUsePressed = !built && k > 0.6f;
|
||||
if (Ctl.BotUsePressed) built = true;
|
||||
}, true);
|
||||
Ctl.BotUsePressed = false;
|
||||
}
|
||||
|
||||
// in the seat: the rider, then the combine, mowing on
|
||||
foreach (var (take, kind, x) in new[] { ("g_ride", VehicleKind.Rider, 90f), ("g_combine", VehicleKind.Combine, 120f) })
|
||||
{
|
||||
if (!Wanted(take)) continue;
|
||||
Cheats.Run("money set " + (kind == VehicleKind.Rider ? 12400 : 286000));
|
||||
var spot = Open(x, 0f);
|
||||
var at = On(spot.x, spot.y);
|
||||
var up = Planet.Up(at);
|
||||
var turn = Quaternion.LookRotation(North(at), up);
|
||||
Spawner.Instance.SpawnVehicle(kind, Me.SaveId, at + up * 1.2f, turn);
|
||||
yield return null;
|
||||
var v = Vehicle.All.Last(o => o.kind == kind);
|
||||
v.ServerPut(at + up * 1.2f, turn);
|
||||
yield return new WaitForSeconds(1f);
|
||||
Me.Teleport(v.transform.position + v.transform.right * 2.2f + up * 0.2f);
|
||||
yield return new WaitForSeconds(0.3f);
|
||||
v.Interact();
|
||||
float t0 = Time.time;
|
||||
while (!Me.Driving.Value && Time.time - t0 < 3f) yield return null;
|
||||
Hud.ClearToasts();
|
||||
Me.LookAt(v.transform.position + v.transform.forward * 25f);
|
||||
Ctl.BotMove = Vector2.up;
|
||||
yield return Take(take, 6f, 60, null, 2f, k => Me.LookAt(v.transform.position + v.transform.forward * 25f + Planet.Up(v.transform.position) * 0.8f), true);
|
||||
Log($"{take}: at {spot}, {v.Body.linearVelocity.magnitude:0.0} m/s at the end");
|
||||
Ctl.BotMove = Vector2.zero;
|
||||
v.RequestExit();
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
v.NetworkObject.Despawn(true);
|
||||
}
|
||||
|
||||
// the phone, out at the side while the grass waits
|
||||
if (Wanted("g_phone"))
|
||||
{
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
yield return Stand(28f, 30f, 6f);
|
||||
Phone.I.Show(PhoneMode.Side);
|
||||
yield return Take("g_phone", 3.5f, 60, null, 1.2f, null, true);
|
||||
Phone.I.Show(PhoneMode.Away);
|
||||
}
|
||||
|
||||
Eyes(false);
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.Game.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.Game.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f76ce5023f85cb447b398e88eb92f1c1
|
||||
143
Assets/Scripts/Core/Trailer.Polden.cs
Normal file
143
Assets/Scripts/Core/Trailer.Polden.cs
Normal file
@ -0,0 +1,143 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The takes the scripted trailer (Docs/TRAILER_SCRIPT.md) needs that the song trailer never shot: one pair of nail
|
||||
/// scissors against the whole planet, a bundle thrown in a friend's face, and a belt that "mostly works".
|
||||
/// </summary>
|
||||
public partial class Trailer
|
||||
{
|
||||
IEnumerator Polden()
|
||||
{
|
||||
if (!Wanted("z_")) yield break;
|
||||
Sky(0.42f, false);
|
||||
|
||||
// the hook: close on the scissors, then up and back until the crewman is a speck in a lawn without end
|
||||
float x = -150f, z = 380f;
|
||||
if (Wanted("z_blade"))
|
||||
{
|
||||
var e = Actor(1, On(x, z), Vector3.forward, ToolId.NailScissors, true, s => On(x, z + s * 0.25f));
|
||||
e.Width = 0.4f; e.Sweep = 0.12f;
|
||||
yield return Take("z_blade", 6f, 60, t =>
|
||||
{
|
||||
var near = Ride(e.transform, new Vector3(0.8f, 0.98f, 1.5f), new Vector3(0.1f, 0.74f, 0.25f), 36f);
|
||||
var b = e.transform.position;
|
||||
var up = Planet.Up(b);
|
||||
var far = new Lens(b + up * 30f - e.transform.forward * 26f, On(x, z + 30f), 66f);
|
||||
float u = Ease(Mathf.InverseLerp(0.28f, 1f, t));
|
||||
return new Lens(Vector3.Lerp(near.at, far.at, u * u), Vector3.Lerp(near.look, far.look, u), Mathf.Lerp(near.fov, far.fov, u));
|
||||
}, 0.4f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
// "Catch!": through the foreman's eyes, a bundle from the gremlin, full in the face
|
||||
x = -300f; z = 420f;
|
||||
if (Wanted("z_catch"))
|
||||
{
|
||||
Clear(x, z + 4f, 6f);
|
||||
var g = Actor(4, On(x + 0.5f, z + 4f), Vector3.back, ToolId.Scythe);
|
||||
g.Pitch = 4f;
|
||||
var m1 = Actor(1, On(x - 5f, z + 9f), Vector3.forward, ToolId.Scythe, true, s => On(x - 5f, z + 9f + s * 1.2f));
|
||||
var m2 = Actor(6, On(x + 5.5f, z + 10f), Vector3.forward, ToolId.WideScythe, true, s => On(x + 5.5f, z + 10f + s * 1.2f));
|
||||
var eye = On(x, z, 1.55f);
|
||||
var look = On(x + 0.4f, z + 4f, 1.2f);
|
||||
Cargo bundle = null;
|
||||
Rigidbody body = null;
|
||||
Vector3 from = Vector3.zero;
|
||||
const float Throw = 0.32f, Fly = 0.42f;
|
||||
float hitAt = -1f;
|
||||
yield return Take("z_catch", 3.2f, 60, t =>
|
||||
{
|
||||
var l = new Lens(eye, look, 50f);
|
||||
if (hitAt >= 0f && t >= hitAt)
|
||||
{
|
||||
float since = (t - hitAt) * 3.2f;
|
||||
float shake = Mathf.Exp(-since * 5f);
|
||||
var up = Planet.Up(eye);
|
||||
l.at += up * (-0.25f * shake) + Random.insideUnitSphere * 0.05f * shake;
|
||||
l.look += up * (-1.6f * shake);
|
||||
l.roll = 9f * shake * Mathf.Sin(since * 30f);
|
||||
}
|
||||
return l;
|
||||
}, 0.6f, k =>
|
||||
{
|
||||
if (bundle == null && k >= Throw)
|
||||
{
|
||||
from = g.transform.position + Planet.Up(g.transform.position) * 1.2f - g.transform.forward * -0.6f;
|
||||
bundle = Spawner.Instance.SpawnCargo(CargoKind.Grass, from, Quaternion.Euler(20f, 40f, 0f), Vector3.zero);
|
||||
body = bundle ? bundle.GetComponent<Rigidbody>() : null;
|
||||
if (body) body.isKinematic = true;
|
||||
}
|
||||
if (!bundle) return;
|
||||
float f = (k - Throw) * 3.2f / Fly;
|
||||
if (f <= 1f && body && body.isKinematic)
|
||||
{
|
||||
var to = eye + (look - eye).normalized * 0.25f;
|
||||
var p = Vector3.Lerp(from, to, f) + Planet.Up(eye) * (Mathf.Sin(f * Mathf.PI) * 0.7f);
|
||||
bundle.transform.SetPositionAndRotation(p, Quaternion.Euler(20f + f * 300f, 40f + f * 120f, f * 90f));
|
||||
}
|
||||
else if (body && body.isKinematic)
|
||||
{
|
||||
hitAt = k;
|
||||
body.isKinematic = false;
|
||||
body.linearVelocity = -Planet.Up(eye) * 2f + (look - eye).normalized * 1.5f;
|
||||
Fx.Dust(eye + (look - eye).normalized * 0.6f, 1.4f, 70);
|
||||
Fx.Dust(eye + (look - eye).normalized * 1.2f, 0.9f, 40);
|
||||
g.Laughing = true;
|
||||
}
|
||||
});
|
||||
foreach (var c in Cargo.All.ToList()) if (c && c.IsSpawned) c.NetworkObject.Despawn(true);
|
||||
Strike();
|
||||
}
|
||||
|
||||
// "It works. It actually works." ... the belt runs to nowhere and the bundles pour off the end
|
||||
x = -360f; z = -420f;
|
||||
if (Wanted("z_spill"))
|
||||
{
|
||||
BuildRules.AnyGround = true;
|
||||
for (int i = -12; i <= 12; i += 6) MowMap.Cut(On(x - 26f, z + i * 2f), On(x + 26f, z + i * 2f), 13f);
|
||||
var at = On(x, z);
|
||||
Ts.BuildRpc((byte)PieceId.Binder, at, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(at)), Planet.Up(at)), Vector3.zero);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
var binder = BuildPiece.All.Where(p => p.piece == PieceId.Binder).OrderBy(p => (p.transform.position - at).sqrMagnitude).FirstOrDefault();
|
||||
if (binder)
|
||||
{
|
||||
var ports = new List<Port>();
|
||||
binder.Ports(ports);
|
||||
var start = ports[0].at;
|
||||
var end = Planet.Surface(ports[0].at + ports[0].dir * 12f);
|
||||
end += Planet.Up(end);
|
||||
Ts.BuildRpc((byte)PieceId.Belt, start, BuildRules.RunRotation(start, end), end);
|
||||
yield return null;
|
||||
binder.GetComponent<Binder>().TakeRpc(60f);
|
||||
var w = (end - start).normalized;
|
||||
var u = Planet.Up(end);
|
||||
var side = Vector3.Cross(u, w);
|
||||
var eng = Actor(2, end + w * 2.2f + side * 2.4f, -side, ToolId.Hammer);
|
||||
eng.Pitch = 22f;
|
||||
int poured = 0;
|
||||
var rng = new System.Random(7);
|
||||
yield return Take("z_spill", 4.5f, 60, t =>
|
||||
new Lens(end + w * 5.5f - side * 3.2f + u * (1.3f - t * 0.2f), end + w * 1.2f + side * 0.4f + u * 0.2f, 50f - t * 6f), 6f, k =>
|
||||
{
|
||||
// the jam: more than the end can let go of
|
||||
int want = Mathf.FloorToInt(k * 26f);
|
||||
while (poured < want)
|
||||
{
|
||||
poured++;
|
||||
float s = (float)(rng.NextDouble() - 0.5) * 2f;
|
||||
var p = end + w * 0.4f + u * (0.6f + (float)rng.NextDouble() * 0.3f) + side * s * 0.3f;
|
||||
Spawner.Instance.SpawnCargo(CargoKind.Grass, p, Quaternion.Euler(rng.Next(360), rng.Next(360), 0f), w * (1.2f + (float)rng.NextDouble() * 1.0f) + u * 0.5f + side * s * 1.0f);
|
||||
}
|
||||
});
|
||||
}
|
||||
foreach (var c in Cargo.All.ToList()) if (c && c.IsSpawned) c.NetworkObject.Despawn(true);
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.Polden.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.Polden.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 14a1b6fc5b2b346429fc281f9054c9ab
|
||||
680
Assets/Scripts/Core/Trailer.Script.cs
Normal file
680
Assets/Scripts/Core/Trailer.Script.cs
Normal file
@ -0,0 +1,680 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The shooting script. The song's words are the shot list; every take is named for where it goes in the edit.</summary>
|
||||
public partial class Trailer
|
||||
{
|
||||
static float Ease(float t) => t * t * (3f - 2f * t);
|
||||
static Lens Ride(Transform v, Vector3 from, Vector3 to, float fov = 50f, float roll = 0f) => new Lens(v.TransformPoint(from), v.TransformPoint(to), fov, roll);
|
||||
|
||||
IEnumerator Script()
|
||||
{
|
||||
// first, while the world is new: the opening film and the story around it
|
||||
yield return Story();
|
||||
yield return Seats();
|
||||
yield return Opening();
|
||||
yield return Portraits();
|
||||
yield return Hooks();
|
||||
yield return Chorus();
|
||||
yield return VerseOne();
|
||||
yield return Night();
|
||||
yield return VerseTwo();
|
||||
yield return Works();
|
||||
yield return Slow();
|
||||
yield return Armada();
|
||||
// before the ending, which mows the whole planet
|
||||
yield return Polden();
|
||||
yield return NewThings();
|
||||
yield return Gameplay();
|
||||
yield return Ending();
|
||||
}
|
||||
|
||||
/// <summary>Nothing to do with the film: does everyone fit in every cab?</summary>
|
||||
IEnumerator Seats()
|
||||
{
|
||||
if (_only == null || !_only.Any(o => o.StartsWith("q_"))) yield break;
|
||||
Sky(0.6f);
|
||||
if (Wanted("q_reaper"))
|
||||
{
|
||||
// which way does the Reaper go: its nose must lead
|
||||
var spot = On(300f, -200f);
|
||||
Ts.BuildRpc((byte)PieceId.Reaper, spot, Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(spot)), Planet.Up(spot)), Vector3.zero);
|
||||
Mowbot.Haste = 5f;
|
||||
yield return new WaitForSeconds(4f);
|
||||
var r = Mowbot.All.OfType<Reaper>().FirstOrDefault();
|
||||
if (r) yield return Take("q_reaper", 3f, 60, t => new Lens(r.Shown + new Vector3(5f, 4f, 5f), r.Shown, 50f));
|
||||
Mowbot.Haste = 1f;
|
||||
}
|
||||
int place = 0;
|
||||
foreach (var kind in new[] { VehicleKind.Tractor, VehicleKind.Combine, VehicleKind.Pickup, VehicleKind.Rider })
|
||||
{
|
||||
var at = On(30f + place * 26f, 70f);
|
||||
place++;
|
||||
Vehicle got = null;
|
||||
yield return Machine(kind, at, Vector3.right, s => at, 0, v => got = v);
|
||||
var body = got.seat.GetComponentInChildren<CrewAvatar>();
|
||||
// what the driver sees: the eye sits as high over the seat as PlayerAgent puts it
|
||||
body.gameObject.SetActive(false);
|
||||
yield return Take($"q_eye_{kind}", 0.02f, 60, t => new Lens(got.seat.position + got.transform.up * 0.97f, got.seat.position + got.transform.up * 0.75f + got.transform.forward * 8f, 70f));
|
||||
body.gameObject.SetActive(true);
|
||||
for (int who = 0; who < 8; who++)
|
||||
{
|
||||
body.Dress(who);
|
||||
yield return Take($"q_{kind}_{who}", 0.02f, 60, t => Ride(got.transform, new Vector3(4.4f, 0.75f, 0f), new Vector3(0f, 1f, 0f), 42f));
|
||||
}
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
|
||||
const float Lane = 262f;
|
||||
|
||||
IEnumerator Opening()
|
||||
{
|
||||
if (!Wanted("o_")) yield break;
|
||||
Sky(0.5f, false);
|
||||
var from = Planet.FromBase(-1300f, 400f);
|
||||
yield return Take("o_space", 9f, 60, t =>
|
||||
{
|
||||
float h = Mathf.Lerp(17000f, 6200f, Ease(t));
|
||||
var turn = Quaternion.AngleAxis(-22f + t * 26f, Vector3.Cross(from, Vector3.right).normalized);
|
||||
return new Lens(Planet.Center + turn * from * (Planet.Radius + h), Planet.Center, 34f);
|
||||
});
|
||||
SkyAt = new Vector2(-800f, 100f);
|
||||
Sky(0.34f, false);
|
||||
SkyAt = Vector2.zero;
|
||||
yield return Take("o_dive", 5f, 60, t =>
|
||||
{
|
||||
float h = 3400f * Mathf.Pow(26f / 3400f, Mathf.Pow(t, 1.25f));
|
||||
float x = Mathf.Lerp(-1100f, -560f, t), down = Mathf.Lerp(82f, 7f, Ease(t)) * Mathf.Deg2Rad;
|
||||
return new Lens(On(x, Lane, h), On(x + 100f * Mathf.Cos(down), Lane, h - 100f * Mathf.Sin(down)), 58f);
|
||||
});
|
||||
yield return Take("o_skim", 5f, 60, t =>
|
||||
{
|
||||
float x = -560f + 150f * t, h = Mathf.Lerp(26f, 3f, Ease(Mathf.Clamp01(t * 1.6f)));
|
||||
return new Lens(On(x, Lane + Mathf.Sin(t * 5f) * 5f, h), On(x + 50f, Lane + Mathf.Sin(t * 5f + 0.6f) * 8f, h - 2.2f), 62f, Mathf.Sin(t * 4f) * 7f);
|
||||
});
|
||||
|
||||
// the poster: the crew walking out under the giant
|
||||
Sky(0.22f, false);
|
||||
var o = new Vector2(-90f, 120f);
|
||||
Clear(o.x - 3f, o.y, 4f);
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
float side = (i - 2) * 2f, back = Mathf.Abs(i - 2) * 1.1f;
|
||||
var e = Actor(new[] { 4, 1, 0, 6, 2 }[i], On(o.x + side, o.y + 5.5f - back), Vector3.forward, ToolId.Scythe, false, s => On(o.x + side, o.y + 5.5f - back + s * 1.3f));
|
||||
e.Pitch = -14f;
|
||||
}
|
||||
yield return Take("o_giant", 6f, 60, t => new Lens(On(o.x - 1f, o.y + t * 5f, Mathf.Lerp(0.8f, 1.5f, t)), On(o.x - 8f, o.y + 60f, 24f), 70f));
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator Portraits()
|
||||
{
|
||||
if (!Wanted("p_")) yield break;
|
||||
Sky(0.3f, false);
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
float x = -260f - i * 6f;
|
||||
var e = Actor(i, On(x, 40f), Vector3.back);
|
||||
e.Tool = i % 2 == 0 ? ToolId.Scythe : ToolId.WideScythe;
|
||||
MowMap.Cut(On(x - 2f, 40f), On(x + 2f, 40f), 5f);
|
||||
MowMap.Cut(On(x, 36f), On(x, 41f), 5f);
|
||||
float a = i % 2 == 0 ? -1f : 1f;
|
||||
yield return Take("p_" + i, 2f, 60, t =>
|
||||
{
|
||||
e.Pitch = Mathf.Lerp(30f, -8f, Ease(Mathf.Clamp01(t * 1.5f)));
|
||||
float turn = a * (24f - t * 44f) * Mathf.Deg2Rad;
|
||||
return new Lens(On(x + Mathf.Sin(turn) * (1.75f - t * 0.2f), 40f - Mathf.Cos(turn) * (1.75f - t * 0.2f), 0.92f), On(x, 40f, 0.86f), 36f);
|
||||
}, 0.3f);
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator Hooks()
|
||||
{
|
||||
if (!Wanted("m_")) yield break;
|
||||
Sky(0.2f, false);
|
||||
MowMap.Cut(On(-146f, 56f), On(-146f, 80f), 6.5f);
|
||||
var blade = Actor(0, On(-150f, 60f), Vector3.forward, ToolId.WideScythe, true, s => On(-150f, 60f + s * 0.9f));
|
||||
yield return Take("m_blade", 2.5f, 120, t => Ride(blade.transform, new Vector3(2.5f, 0.4f, 2.2f + t * 0.3f), new Vector3(0f, 0.42f, 0.9f), 34f), 0.5f);
|
||||
Strike();
|
||||
MowMap.Cut(On(-170f, 0f), On(-170f, 70f), 7f);
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float off = i * 1.25f;
|
||||
Actor(i * 2 + 1, On(-170f, off), Vector3.forward, ToolId.Scythe, false, s => On(-170f, off + s * 2.1f));
|
||||
}
|
||||
yield return Take("m_boots", 3f, 60, t => new Lens(On(-167.9f, 2.8f + t * 6.3f, 0.2f), On(-170f, 2.8f + t * 6.3f, 0.3f), 46f), 0.4f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator Chorus()
|
||||
{
|
||||
if (!Wanted("c_")) yield break;
|
||||
Sky(0.55f, false);
|
||||
float x = 160f, z = 90f;
|
||||
var crew = new List<CineExtra>();
|
||||
if (Wanted("c_swing"))
|
||||
{
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
float side = (i - 1) * 3f, back = Mathf.Abs(i - 1) * 2f;
|
||||
crew.Add(Actor(new[] { 6, 0, 3 }[i], On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f)));
|
||||
}
|
||||
yield return Take("c_swing", 3f, 60, t => new Lens(On(x - 0.6f, z + 5.2f + t * 5.1f, 0.7f), On(x, z + 1.2f + t * 5.1f, 1.05f), 44f), 0.5f);
|
||||
yield return Take("c_swing_s", 2.5f, 120, t => new Lens(On(x + 7f, z + 7f + t * 2f, 0.7f), On(x, z + 7f + t * 2f, 0.9f), 34f));
|
||||
Strike();
|
||||
}
|
||||
x = 200f; z = 150f;
|
||||
if (Wanted("c_rider"))
|
||||
{
|
||||
Vehicle r = null;
|
||||
float ax = x, az = z;
|
||||
yield return Machine(VehicleKind.Rider, On(ax, az), Vector3.right, s => On(ax + 9.5f * s, az), 0, v => r = v);
|
||||
Clear(ax + 30f, az + 3.4f, 2.5f);
|
||||
yield return Take("c_rider", 3.2f, 60, t => new Lens(On(ax + 30f, az + 3.4f, 0.55f), r.transform.position + r.transform.up * 0.8f, Mathf.Lerp(24f, 62f, Ease(t))), 0.3f);
|
||||
yield return Take("c_rider_side", 3f, 60, t => Ride(r.transform, new Vector3(2.5f, 0.55f, 1.2f), new Vector3(0f, 0.8f, -0.4f), 46f));
|
||||
Strike();
|
||||
}
|
||||
x = 240f; z = -120f;
|
||||
if (Wanted("c_combine"))
|
||||
{
|
||||
Vehicle c = null;
|
||||
float ax = x, az = z;
|
||||
yield return Machine(VehicleKind.Combine, On(ax, az), Vector3.forward, s => On(ax, az + 7.5f * s), 5, v => c = v);
|
||||
yield return Take("c_combine", 3.5f, 60, t => new Lens(c.transform.position + c.transform.forward * (10.8f - t) + c.transform.right * 1.2f + c.transform.up * 2.6f, c.transform.position + c.transform.up * 1.1f + c.transform.forward * 2f, 60f), 0.4f);
|
||||
yield return Take("c_combine_top", 3f, 60, t => new Lens(c.transform.position - c.transform.forward * 11f - c.transform.right * 4f + c.transform.up * (5f + t * 2f), c.transform.position + c.transform.forward * 7f, 54f));
|
||||
var fixedAt = c.transform.position + c.transform.forward * 24f;
|
||||
var dirt = Planet.Surface(fixedAt);
|
||||
for (int i = -2; i <= 2; i++) MowMap.Cut(dirt + c.transform.right * i * 1.4f - c.transform.forward * 3f, dirt + c.transform.right * i * 1.4f + c.transform.forward * 3f, 2f);
|
||||
yield return Take("c_combine_over", 3.2f, 60, t => new Lens(dirt + Planet.Up(dirt) * 0.3f, c.transform.position + c.transform.up * 2.2f, 66f));
|
||||
Strike();
|
||||
}
|
||||
x = 310f; z = 12f;
|
||||
if (Wanted("c_tractor"))
|
||||
{
|
||||
Vehicle c = null;
|
||||
float ax = x, az = z;
|
||||
yield return Machine(VehicleKind.Tractor, On(ax, az), Vector3.right, s => On(ax + 8f * s, az), 3, v => c = v);
|
||||
Clear(ax + 30f, az + 4.6f, 3.4f);
|
||||
yield return Take("c_tractor", 3.5f, 60, t => new Lens(On(ax + 30f, az + 4.6f, 0.6f), c.transform.position + c.transform.up * 1.1f, Mathf.Lerp(26f, 58f, Ease(t))), 1f);
|
||||
Strike();
|
||||
}
|
||||
x = -30f; z = 230f;
|
||||
if (Wanted("c_line"))
|
||||
{
|
||||
for (int i = 0; i < 8; i++)
|
||||
{
|
||||
float side = (i - 3.5f) * 3.1f, back = Mathf.Abs(i - 3.5f) * 0.9f;
|
||||
Actor(i, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.8f));
|
||||
}
|
||||
yield return Take("c_line", 3.5f, 60, t => new Lens(On(x + 2f, z + 9f + t * 6.3f, Mathf.Lerp(0.9f, 3f, t)), On(x, z + t * 6.3f, 1f), 50f), 0.8f);
|
||||
Strike();
|
||||
}
|
||||
x = 40f; z = 300f;
|
||||
if (Wanted("c_top"))
|
||||
{
|
||||
var all = new List<Vehicle>();
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float ox = x + i * 2.9f, oz = z - i * 3f;
|
||||
yield return Machine(VehicleKind.Rider, On(ox, oz), Vector3.forward, s => On(ox, oz + s * 9f), i, v => all.Add(v));
|
||||
}
|
||||
yield return Take("c_top", 3.5f, 60, t => new Lens(On(x + 4f, z + 2f + t * 31f, 19f), On(x + 4f, z + 2.01f + t * 31f, 0f), 56f), 2f);
|
||||
Strike();
|
||||
}
|
||||
x = -300f; z = -40f;
|
||||
if (Wanted("c_ring"))
|
||||
{
|
||||
Vehicle r = null;
|
||||
float ax = x, az = z;
|
||||
yield return Machine(VehicleKind.Rider, On(ax + 16f, az), Vector3.forward, s => On(ax + Mathf.Cos(s * 0.75f) * 16f, az + Mathf.Sin(s * 0.75f) * 16f), 1, v => r = v);
|
||||
yield return Take("c_ring", 4f, 60, t => new Lens(On(ax, az, Mathf.Lerp(1.6f, 15f, Ease(t))), r.transform.position, 60f, t * 10f), 2.6f);
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator VerseOne()
|
||||
{
|
||||
if (!Wanted("v_")) yield break;
|
||||
Sky(0.4f, false);
|
||||
float x = -210f, z = 180f;
|
||||
if (Wanted("v_touch"))
|
||||
{
|
||||
Clear(x, z - 2f, 7f);
|
||||
var land = new[] { Actor(0, On(x, z), Vector3.back), Actor(4, On(x + 3f, z + 1.4f), Vector3.back), Actor(6, On(x - 3.2f, z + 1.6f), Vector3.back) };
|
||||
land[0].DropAt = 1.1f; land[1].DropAt = 0.75f; land[2].DropAt = 1.45f;
|
||||
foreach (var a in land) a.Pitch = 8f;
|
||||
yield return Take("v_touch", 3f, 60, t => new Lens(On(x + 0.4f, z - 5.2f - t * 0.5f, 0.32f), On(x, z, 1.6f), 58f));
|
||||
yield return Take("v_around", 3.2f, 60, t =>
|
||||
{
|
||||
float a = (Ease(t) * 300f - 40f) * Mathf.Deg2Rad;
|
||||
return new Lens(On(x, z - 9f, 2.3f), On(x + Mathf.Sin(a) * 60f, z - 9f + Mathf.Cos(a) * 60f, 3f), 72f);
|
||||
});
|
||||
Strike();
|
||||
}
|
||||
x = -240f; z = 270f;
|
||||
if (Wanted("v_scissors"))
|
||||
{
|
||||
var e = Actor(1, On(x, z), Vector3.forward, ToolId.NailScissors, true, s => On(x, z + s * 0.3f));
|
||||
e.Width = 0.5f; e.Sweep = 0.15f;
|
||||
yield return Take("v_scissors", 2.5f, 60, t => Ride(e.transform, new Vector3(0.95f, 0.7f, 1.75f), new Vector3(0.12f, 0.8f, 0.2f), 40f), 0.3f);
|
||||
var f = Actor(5, On(x + 8f, z), Vector3.forward, ToolId.GardenShears, true, s => On(x + 8f, z + s * 0.4f));
|
||||
f.Width = 0.6f; f.Sweep = 0.2f;
|
||||
yield return Take("v_snip", 2f, 60, t => Ride(f.transform, new Vector3(-1.05f, 0.62f, 1.7f), new Vector3(0.12f, 0.82f, 0.2f), 40f), 0.3f);
|
||||
Strike();
|
||||
}
|
||||
x = -330f; z = 200f;
|
||||
if (Wanted("v_sixteen"))
|
||||
{
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
float side = (i - 7.5f) * 2.9f, back = Mathf.Abs(i - 7.5f) * 0.55f;
|
||||
Actor(i % 8, On(x + side, z - back), Vector3.forward, i % 3 == 0 ? ToolId.WideScythe : i % 3 == 1 ? ToolId.LongScythe : ToolId.Scythe, true, s => On(x + side, z - back + s * 1.7f), i);
|
||||
}
|
||||
yield return Take("v_sixteen", 4f, 60, t => new Lens(On(x, z + 13f + t * 6.8f, Mathf.Lerp(1.1f, 9f, Ease(t))), On(x, z + t * 6.8f, 0.5f), 62f), 1f);
|
||||
yield return Take("v_sixteen_end", 3f, 60, t => new Lens(On(x - 28f, z + 8f + t * 5.1f, 0.9f), On(x + 12f, z + t * 5.1f, 0.9f), 34f));
|
||||
Strike();
|
||||
}
|
||||
x = 330f; z = -300f;
|
||||
if (Wanted("v_strip"))
|
||||
{
|
||||
// a field in a dozen passes, seen from straight up
|
||||
const float Len = 40f, Row = 4f;
|
||||
const int Rows = 10;
|
||||
Vector3 Lawn(float k)
|
||||
{
|
||||
float d = k * Rows;
|
||||
int row = Mathf.Min(Rows - 1, Mathf.FloorToInt(d));
|
||||
float along = (d - row) * Len;
|
||||
return On(x + row * Row, z + (row % 2 == 0 ? along : Len - along));
|
||||
}
|
||||
Vehicle r = null;
|
||||
yield return Machine(VehicleKind.Rider, Lawn(0f), Vector3.forward, s => Lawn(0f), 0, v => r = v);
|
||||
Destroy(r.GetComponent<CineDriver>());
|
||||
var last = Lawn(0f);
|
||||
yield return Take("v_strip", 8f, 30, t => new Lens(On(x + 18f, z + 20f, 33f), On(x + 18f, z + 20.1f, 0f), 62f), every: k =>
|
||||
{
|
||||
var head = Lawn(k);
|
||||
for (int i = 1; i <= 12; i++)
|
||||
{
|
||||
var a = Lawn(k - (i - 1) / 2400f);
|
||||
var b = Lawn(k - i / 2400f);
|
||||
MowMap.Cut(b, a, 4.2f);
|
||||
}
|
||||
r.ServerPut(head + Planet.Up(head) * 0.5f, Quaternion.LookRotation(Vector3.ProjectOnPlane(head - last, Planet.Up(head)) + Vector3.forward * 0.001f, Planet.Up(head)));
|
||||
last = head;
|
||||
});
|
||||
Strike();
|
||||
}
|
||||
x = -40f; z = 26f;
|
||||
if (Wanted("v_phone"))
|
||||
{
|
||||
var at = On(-34f, -62f);
|
||||
Vehicle r = null;
|
||||
yield return Machine(VehicleKind.Rider, at, Vector3.right, s => at, -1, v => r = v);
|
||||
var e = Actor(2, On(-33f, -60.6f), Vector3.forward, ToolId.Scythe);
|
||||
e.Phone = true;
|
||||
e.Pitch = 20f;
|
||||
Clear(-32.4f, -57.6f, 2.6f);
|
||||
yield return Take("v_phone", 2.6f, 60, t => new Lens(On(-32.4f, -58.2f + t * 0.3f, 0.75f), On(-33f, -60.6f, 0.92f), 38f), 0.8f);
|
||||
Strike();
|
||||
}
|
||||
x = -400f; z = -80f;
|
||||
if (Wanted("v_sunset"))
|
||||
{
|
||||
var run = SkyRun(0.15f, true, -0.06f, true);
|
||||
run(0f);
|
||||
yield return null;
|
||||
Sun.Tick();
|
||||
var up = Planet.Up(On(x, z));
|
||||
var way = Vector3.ProjectOnPlane(Sun.Dir, up).normalized;
|
||||
float wx = way.x, wz = way.z;
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
float side = (i - 2) * 2.4f;
|
||||
Actor(new[] { 7, 3, 0, 6, 1 }[i], On(x + wx * 16f - wz * side, z + wz * 16f + wx * side), way, ToolId.Scythe).Pitch = -10f;
|
||||
}
|
||||
yield return Take("v_sunset", 6f, 30, t => new Lens(On(x, z, 0.7f), On(x + wx * 60f, z + wz * 60f, 7f), 58f), every: run);
|
||||
Strike();
|
||||
}
|
||||
x = 80f; z = 420f;
|
||||
if (Wanted("v_dawn"))
|
||||
{
|
||||
var run = SkyRun(-0.2f, false, 0.3f, false);
|
||||
run(0f);
|
||||
yield return Take("v_dawn", 6f, 30, t => new Lens(On(x, z, 2.2f), On(x + 40f, z + 60f, 12f), 70f), every: run);
|
||||
}
|
||||
// hills and trees: whichever high ground is nearest the base
|
||||
if (Wanted("v_hills"))
|
||||
{
|
||||
Sky(0.3f, false);
|
||||
var top = Grove(1400f);
|
||||
SkyAt = top;
|
||||
Sky(0.34f, false);
|
||||
SkyAt = Vector2.zero;
|
||||
yield return Take("v_hills", 4.5f, 60, t =>
|
||||
{
|
||||
float a = (20f + t * 50f) * Mathf.Deg2Rad;
|
||||
return new Lens(On(top.x - Mathf.Sin(a) * 54f, top.y - Mathf.Cos(a) * 54f, 2.4f + t * 6f), On(top.x, top.y, 9f), 62f);
|
||||
});
|
||||
Sky(0.45f, false);
|
||||
}
|
||||
x = -330f; z = -220f;
|
||||
if (Wanted("v_knees"))
|
||||
{
|
||||
Sky(0.45f, false);
|
||||
MowMap.Cut(On(x + 4.4f, z - 2f), On(x + 4.4f, z + 30f), 5f);
|
||||
var e = Actor(4, On(x, z), Vector3.forward, ToolId.Scythe, false, s => On(x, z + s * 1.6f));
|
||||
yield return Take("v_knees", 3f, 60, t => Ride(e.transform, new Vector3(3.4f, 0.55f, 0.3f), new Vector3(0f, 0.55f, 0.3f), 34f), 0.5f);
|
||||
e.Cutting = true;
|
||||
yield return Take("v_rhythm", 3f, 60, t => Ride(e.transform, new Vector3(-0.8f, 0.95f, -1.7f), new Vector3(0.3f, 0.55f, 1.2f), 58f));
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerator Night()
|
||||
{
|
||||
if (!Wanted("n_")) yield break;
|
||||
Sky(-0.45f, true);
|
||||
float x = -420f, z = 90f;
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
float side = (i - 7.5f) * 3.4f, back = Mathf.Abs(i - 7.5f) * 1f;
|
||||
Actor(i % 8, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f), i);
|
||||
}
|
||||
Vehicle r = null;
|
||||
yield return Machine(VehicleKind.Tractor, On(x + 40f, z - 10f), Vector3.forward, s => On(x + 40f, z - 10f + s * 6f), 0, v => r = v);
|
||||
float go = Time.time;
|
||||
float Near() => z + (Time.time - go) * 1.7f;
|
||||
WorkLight(() => On(x, Near() + 8f, 10f), () => On(x, Near() - 2f, 0.5f));
|
||||
yield return Take("n_line", 4f, 60, t => new Lens(On(x + 4f, z + 15f + t * 6.8f, 1.1f), On(x, z + t * 6.8f, 0.9f), 56f), 0.8f);
|
||||
yield return Take("n_air", 4f, 60, t => new Lens(On(x - 24f, z + 22f + t * 6.8f, 26f - t * 6f), On(x, z + 8f + t * 6.8f, 0f), 60f));
|
||||
yield return Take("n_left", 2f, 60, t => new Lens(On(x - 26f, Near() - 1f, 0.9f), On(x + 20f, Near() - 1f, 1f), 40f));
|
||||
WorkLight(() => r.transform.position + r.transform.forward * 5f + r.transform.up * 6f, () => r.transform.position + r.transform.forward * 3f);
|
||||
yield return Take("n_tractor", 3f, 60, t => Ride(r.transform, new Vector3(3.4f, 3f, 8.5f), new Vector3(0f, 1.2f, 0f), 56f));
|
||||
DayNight.Rig = null;
|
||||
DayNight.SetView(DayNight.Off);
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator VerseTwo()
|
||||
{
|
||||
if (!Wanted("w_")) yield break;
|
||||
Sky(0.5f, false);
|
||||
float x = 60f, z = -300f;
|
||||
if (Wanted("w_wheels") || Wanted("w_trucks"))
|
||||
{
|
||||
Vehicle p = null, t2 = null;
|
||||
float ax = x, az = z;
|
||||
for (int i = -3; i <= 3; i++) MowMap.Cut(On(ax - 30f, az + 1.5f + i * 2f), On(ax + 150f, az + 1.5f + i * 2f), 2.4f);
|
||||
yield return Machine(VehicleKind.Pickup, On(ax, az), Vector3.right, s => On(ax + 12f * s, az), 6, v => p = v);
|
||||
yield return Machine(VehicleKind.Tractor, On(ax - 14f, az + 2.5f), Vector3.right, s => On(ax - 14f + 10f * s, az + 2.5f), 3, v => t2 = v);
|
||||
yield return Take("w_wheels", 2.5f, 60, t => Ride(p.transform, new Vector3(-2.6f, 0.62f, 1.7f), new Vector3(0f, 0.5f, 0.9f), 46f), 1.5f);
|
||||
float sx = ax + 74f;
|
||||
yield return Take("w_trucks", 4f, 60, t => new Lens(On(sx, az + 4f, 1f), p.transform.position + p.transform.forward * -1f + p.transform.up * 0.6f, 50f));
|
||||
Strike();
|
||||
}
|
||||
if (Wanted("w_blades"))
|
||||
{
|
||||
var wall = FindAnyObjectByType<SupplyWall>();
|
||||
if (wall)
|
||||
{
|
||||
var w = wall.transform;
|
||||
yield return Take("w_blades", 3f, 60, t => new Lens(w.TransformPoint(new Vector3(-3.4f + t * 3.6f, 1.5f, 2.3f)), w.TransformPoint(new Vector3(-2.4f + t * 3.6f, 1.5f, 0f)), 44f));
|
||||
}
|
||||
}
|
||||
x = -120f; z = -240f;
|
||||
if (Wanted("w_one"))
|
||||
{
|
||||
Vehicle r = null;
|
||||
float ax = x, az = z;
|
||||
yield return Machine(VehicleKind.Rider, On(ax, az), Vector3.right, s => On(ax + s * 9f, az), 4, v => r = v);
|
||||
yield return Take("w_one", 2.2f, 60, t => Ride(r.transform, new Vector3(-0.2f, 1.25f, 2.7f), new Vector3(0f, 1f, 0f), 50f), 0.4f);
|
||||
Strike();
|
||||
}
|
||||
x = 140f; z = 300f;
|
||||
if (Wanted("w_three"))
|
||||
{
|
||||
Sky(0.25f, false);
|
||||
var top = HighGround(new Vector2(300f, 620f), 200f);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
var e = Actor(new[] { 1, 6, 3 }[i], On(top.x + (i - 1) * 1.7f, top.y), Vector3.back, ToolId.Scythe);
|
||||
e.Laughing = true;
|
||||
e.Lag = i;
|
||||
}
|
||||
yield return Take("w_three", 2.6f, 60, t => new Lens(On(top.x + 1f, top.y - 7.5f + t * 2f, 0.6f), On(top.x, top.y, 0.95f), 40f), 0.4f);
|
||||
Strike();
|
||||
}
|
||||
// fields of gold: the crops by the base, low sun
|
||||
if (Wanted("w_gold"))
|
||||
{
|
||||
Sky(0.1f, true);
|
||||
yield return Take("w_gold", 4f, 60, t => new Lens(On(262f + t * 110f, 18f, 3.2f), On(320f + t * 110f, 14f, 1.2f), 60f, 3f - t * 6f));
|
||||
Sky(0.16f, true);
|
||||
yield return Take("w_mountains", 4f, 60, t => new Lens(On(-500f, 60f + t * 40f, Mathf.Lerp(60f, 520f, Ease(t))), On(-500f, 900f, Mathf.Lerp(10f, 90f, t)), 72f));
|
||||
}
|
||||
}
|
||||
|
||||
Vector2 HighGround(Vector2 near, float reach)
|
||||
{
|
||||
float best = -1e9f;
|
||||
var at = near;
|
||||
for (float a = -reach; a <= reach; a += 40f)
|
||||
for (float b = -reach; b <= reach; b += 40f)
|
||||
{
|
||||
float h = Planet.HeightAt(Planet.FromBase(near.x + a, near.y + b));
|
||||
if (h > best) { best = h; at = new Vector2(near.x + a, near.y + b); }
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
IEnumerator Works()
|
||||
{
|
||||
if (!Wanted("k_")) yield break;
|
||||
Sky(0.42f, false);
|
||||
// the set is dressed where the camera wants it, cut or not
|
||||
BuildRules.AnyGround = true;
|
||||
float x = 60f, z = 480f;
|
||||
for (int i = -20; i <= 20; i += 6) MowMap.Cut(On(x - 34f, z + i * 2f), On(x + 34f, z + i * 2f), 13f);
|
||||
Quaternion Turn(Vector3 p) => Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.forward, Planet.Up(p)), Planet.Up(p));
|
||||
void Put(PieceId id, float dx, float dz)
|
||||
{
|
||||
var at = On(x + dx, z + dz);
|
||||
Ts.BuildRpc((byte)id, at, Turn(at), Vector3.zero);
|
||||
}
|
||||
Vector3 Lay(BuildPiece piece, float metres)
|
||||
{
|
||||
var ports = new List<Port>();
|
||||
piece.Ports(ports);
|
||||
var end = Planet.Surface(ports[0].at + ports[0].dir * metres);
|
||||
end += Planet.Up(end);
|
||||
Ts.BuildRpc((byte)PieceId.Belt, ports[0].at, BuildRules.RunRotation(ports[0].at, end), end);
|
||||
return end;
|
||||
}
|
||||
|
||||
// the factory grows on the beat
|
||||
var order = new (PieceId id, float dx, float dz)[]
|
||||
{
|
||||
(PieceId.Press, 0f, 0f), (PieceId.Dryer, -18f, 8f), (PieceId.Binder, 16f, 10f), (PieceId.SolarL, -20f, -16f), (PieceId.SolarL, -6f, -18f),
|
||||
(PieceId.Garage, 24f, -14f), (PieceId.Pole, 4f, 22f), (PieceId.BatteryL, -12f, 22f), (PieceId.SolarM, 8f, -22f), (PieceId.Press, 28f, 26f),
|
||||
};
|
||||
int put = 0;
|
||||
var hit = new List<CineExtra>
|
||||
{
|
||||
Actor(2, On(x - 7f, z + 4f), Vector3.right, ToolId.Hammer),
|
||||
Actor(5, On(x + 7f, z + 4f), Vector3.left, ToolId.Hammer),
|
||||
};
|
||||
foreach (var h in hit) { h.Cutting = true; h.Width = 0.3f; h.Sweep = 0.2f; }
|
||||
yield return Take("k_grow", 6f, 60, t =>
|
||||
{
|
||||
float a = (205f + t * 36f) * Mathf.Deg2Rad;
|
||||
return new Lens(On(x + Mathf.Sin(a) * 33f, z + Mathf.Cos(a) * 33f, 7f - t * 3f), On(x, z, 3f), 58f);
|
||||
}, every: k =>
|
||||
{
|
||||
while (put < order.Length && k >= put / (float)order.Length)
|
||||
{
|
||||
Put(order[put].id, order[put].dx, order[put].dz);
|
||||
put++;
|
||||
}
|
||||
});
|
||||
// a battery bank comes up where Lin's hammer lands, on a blow
|
||||
bool raised = false;
|
||||
yield return Take("k_hammer", 3.2f, 60, t => new Lens(On(x - 4.4f, z + 9.4f, 1.4f), On(x - 5.2f, z + 4f, 0.8f), 50f), every: k =>
|
||||
{
|
||||
if (raised || k < 0.42f) return;
|
||||
raised = true;
|
||||
Put(PieceId.BatteryL, -3.2f, 4f);
|
||||
});
|
||||
yield return Take("k_build2", 2.6f, 60, t => new Lens(On(x, z + 9.4f - t, 1.3f), On(x, z + 3.6f, 1f), 62f));
|
||||
|
||||
var binder = BuildPiece.All.Find(p => p.piece == PieceId.Binder);
|
||||
if (binder && Wanted("k_belt"))
|
||||
{
|
||||
var ports = new List<Port>();
|
||||
binder.Ports(ports);
|
||||
var start = ports[0].at;
|
||||
var end = Lay(binder, 24f);
|
||||
Log($"belt: {BuildPiece.All.Count(p => p.piece == PieceId.Belt)} laid");
|
||||
yield return null;
|
||||
var bin = binder.GetComponent<Binder>();
|
||||
float gap = 0f;
|
||||
bin.TakeRpc(18f);
|
||||
yield return Take("k_belt", 5f, 60, t =>
|
||||
{
|
||||
var p = Vector3.Lerp(start, end, Mathf.Lerp(0.02f, 0.75f, t));
|
||||
var u = Planet.Up(p);
|
||||
var w = (end - start).normalized;
|
||||
return new Lens(p + u * 0.8f + Vector3.Cross(u, w) * 0.9f - w * 1.8f, p + w * 3f + u * 0.2f, 58f);
|
||||
}, 3f, k => gap = k);
|
||||
}
|
||||
Mowbot.Haste = 5f;
|
||||
x = -420f; z = -120f;
|
||||
if (Wanted("k_robots"))
|
||||
{
|
||||
var made = new List<RobotDock>();
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var at = On(x + i * 34f, z);
|
||||
Ts.BuildRpc((byte)PieceId.RobotII, at, Turn(at), Vector3.zero);
|
||||
}
|
||||
yield return new WaitForSeconds(1f);
|
||||
made = Mowbot.All.OfType<RobotDock>().ToList();
|
||||
foreach (var d in made) Lay(d.GetComponent<BuildPiece>(), 6f);
|
||||
if (made.Count > 0)
|
||||
{
|
||||
var a = made[0];
|
||||
yield return Take("k_robots", 3.5f, 60, t => new Lens(a.Shown + new Vector3(3f, 1.7f, 3f), a.Shown + Planet.Up(a.Shown) * 0.3f, 32f), 7f);
|
||||
var b = made[made.Count - 1];
|
||||
yield return Take("k_robots2", 3f, 60, t => new Lens(b.Shown + new Vector3(-3.5f, 1.8f + t, -3f), b.Shown, 56f));
|
||||
}
|
||||
}
|
||||
Mowbot.Haste = 1f;
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator Slow()
|
||||
{
|
||||
if (!Wanted("b_")) yield break;
|
||||
Sky(0.12f, true);
|
||||
float x = 420f, z = 240f;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float side = (i - 1.5f) * 3.2f;
|
||||
Actor(new[] { 0, 4, 6, 7 }[i], On(x + side, z), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z + s * 1.2f));
|
||||
}
|
||||
yield return Take("b_grass", 3f, 120, t => new Lens(On(x - 12f + t * 2f, z + 16f, 0.75f), On(x - 2f, z + 20f, 0.6f), 30f), 0.2f);
|
||||
yield return Take("b_line", 3.5f, 120, t => new Lens(On(x + 1f, z + 7f + t * 1.5f, 0.7f), On(x, z + 2f + t * 1.5f, 1f), 46f));
|
||||
Strike();
|
||||
Vehicle c = null;
|
||||
float cx = x + 60f, cz = z - 60f;
|
||||
Sky(0.14f, true);
|
||||
yield return Machine(VehicleKind.Combine, On(cx, cz), Vector3.forward, s => On(cx, cz + 8f * s), 0, v => c = v);
|
||||
yield return Take("b_header", 3.5f, 120, t => Ride(c.transform, new Vector3(3.4f, 0.9f, 7.4f), new Vector3(1f, 0.8f, 3.4f), 40f), 1f);
|
||||
yield return Take("b_engine", 3f, 120, t => Ride(c.transform, new Vector3(-2.6f, 0.6f, 0.6f), new Vector3(0f, 0.8f, -0.8f), 44f));
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator Armada()
|
||||
{
|
||||
if (!Wanted("f_")) yield break;
|
||||
Sky(0.5f, false);
|
||||
float x = -200f, z = -330f;
|
||||
const float Pace = 5.5f;
|
||||
var kinds = new List<Vehicle>();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
float side = (i - 1) * 19f;
|
||||
yield return Machine(VehicleKind.Combine, On(x, z + side), Vector3.right, s => On(x + s * Pace, z + side), i * 2, v => kinds.Add(v));
|
||||
}
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float side = (i - 1.5f) * 19f, back = 12f + Mathf.Abs(i - 1.5f) * 4f;
|
||||
yield return Machine(VehicleKind.Tractor, On(x - back, z + side), Vector3.right, s => On(x - back + s * Pace, z + side), 1 + i, v => kinds.Add(v));
|
||||
}
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
float side = (i - 2.5f) * 12f, back = 26f + Mathf.Abs(i - 2.5f) * 3f;
|
||||
yield return Machine(VehicleKind.Rider, On(x - back, z + side), Vector3.right, s => On(x - back + s * Pace, z + side), i + 2, v => kinds.Add(v));
|
||||
}
|
||||
for (int i = 0; i < 16; i++)
|
||||
{
|
||||
float side = (i - 7.5f) * 4f, back = 40f + Mathf.Abs(i - 7.5f);
|
||||
Actor(i % 8, On(x - back, z + side), Vector3.right, ToolId.WideScythe, true, s => On(x - back + s * Pace, z + side), i);
|
||||
}
|
||||
var lead = kinds[1].transform;
|
||||
yield return new WaitForSeconds(1f);
|
||||
yield return Take("f_hero", 4f, 60, t => new Lens(lead.position + lead.forward * (15f - t * 3f) + lead.right * 3f + Planet.Up(lead.position) * 2.4f, lead.position + Planet.Up(lead.position) * 1.6f, 62f), 2f);
|
||||
yield return Take("f_air", 4f, 60, t => new Lens(lead.position + lead.forward * 22f + lead.right * 34f + Planet.Up(lead.position) * (9f + t * 21f), lead.position - lead.forward * 14f, 62f));
|
||||
yield return Take("f_top", 3.5f, 60, t => new Lens(lead.position - lead.forward * 20f + Planet.Up(lead.position) * (30f + t * 4f), lead.position - lead.forward * 20f - Planet.Up(lead.position) * 2f + lead.forward * 0.01f, 78f));
|
||||
yield return Take("f_side", 3.5f, 60, t => new Lens(lead.position - lead.forward * (6f + t * 22f) + lead.right * 44f + Planet.Up(lead.position) * 1.3f, lead.position - lead.forward * (6f + t * 22f), 46f));
|
||||
yield return Take("f_in", 3.5f, 60, t => new Lens(lead.position - lead.forward * (46f - t * 26f) + lead.right * 1.8f + Planet.Up(lead.position) * 1.4f, lead.position + Planet.Up(lead.position) * 1f, 62f));
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator Ending()
|
||||
{
|
||||
if (!Wanted("e_")) yield break;
|
||||
Sky(0.5f, false);
|
||||
// the planet goes, from where the crew started outward, seen from orbit
|
||||
var view = Planet.FromBase(-1300f, 400f);
|
||||
var cells = Enumerable.Range(0, HexGrid.Cells).OrderBy(i => Vector3.Angle(HexGrid.Centre(i), Vector3.up)).ToList();
|
||||
Log($"cells to cut: {cells.Count}");
|
||||
int done = 0;
|
||||
yield return Take("e_cut", 9f, 60, t =>
|
||||
{
|
||||
var turn = Quaternion.AngleAxis(-8f + t * 26f, Vector3.Cross(view, Vector3.right).normalized);
|
||||
return new Lens(Planet.Center + turn * view * (Planet.Radius + Mathf.Lerp(5200f, 6800f, t)), Planet.Center, 40f);
|
||||
}, every: k =>
|
||||
{
|
||||
int to = Mathf.RoundToInt(cells.Count * Mathf.Pow(k, 1.6f));
|
||||
for (; done < to; done++) MowMap.CutSector(cells[done]);
|
||||
});
|
||||
for (; done < cells.Count; done++) MowMap.CutSector(cells[done]);
|
||||
|
||||
Sky(0.16f, true);
|
||||
var o = new Vector2(-90f, 120f);
|
||||
yield return Take("e_bare", 4f, 60, t => new Lens(On(-260f + t * 60f, 60f, 3f + t * 3f), On(0f + t * 60f, 150f, 8f), 68f, 2f - t * 4f));
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
float side = (i - 2) * 2.6f, back = Mathf.Abs(i - 2) * 1.5f;
|
||||
Actor(new[] { 4, 1, 0, 6, 2 }[i], On(o.x + side, o.y + 12f - back), Vector3.forward, ToolId.Scythe).Pitch = -5f;
|
||||
}
|
||||
yield return Take("e_crew", 5f, 60, t => new Lens(On(o.x - 1f, o.y + 3f + t * 3f, 0.8f), On(o.x, o.y + 16f, 1.3f), 50f));
|
||||
foreach (var g in _props)
|
||||
{
|
||||
var e = g.GetComponent<CineExtra>();
|
||||
if (e) e.Pitch = -28f;
|
||||
}
|
||||
yield return Take("e_look", 3f, 60, t => new Lens(On(o.x + 0.8f, o.y + 15.6f - t * 0.6f, 0.62f), On(o.x, o.y + 11.4f, 1f), 40f), 0.3f);
|
||||
yield return Take("e_up", 6f, 60, t => new Lens(On(o.x - 3f, o.y + 3f, 1f), Vector3.Lerp(On(o.x, o.y + 16f, 1.3f), On(o.x - 34f, o.y + 60f, 52f), Ease(t)), Mathf.Lerp(52f, 34f, Ease(t))));
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.Script.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.Script.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 029ac545e81a8844f826cfbd47c640e7
|
||||
404
Assets/Scripts/Core/Trailer.Stills.cs
Normal file
404
Assets/Scripts/Core/Trailer.Stills.cs
Normal file
@ -0,0 +1,404 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// `-demotrailer -stills`: the store page's screenshots, `x_`. Each is a short take of a few frames to pick from, of
|
||||
/// what the game has now: the crew in a row, the machines abreast, the factory with belts and an unload bay, the house
|
||||
/// on stilts with its drone pad by day and by lamplight, the vending machines on the deck, the player's own eyes with
|
||||
/// a boost on, acid rain, a twister, a night shift and the saucer.
|
||||
/// </summary>
|
||||
public partial class Trailer
|
||||
{
|
||||
/// <summary>Set while the music video films the same scenes as moving takes, `y_` instead of `x_`.</summary>
|
||||
bool _clip;
|
||||
|
||||
string X(string name) => _clip ? "y" + name.Substring(1) : name;
|
||||
|
||||
/// <summary>A still is a few frames to pick from; in the video it is three seconds with the lens easing in.</summary>
|
||||
IEnumerator Still(string name, System.Func<float, Lens> lens, float lead = 0.6f, System.Action<float> every = null, bool hud = false)
|
||||
{
|
||||
if (!_clip) return Take(name, 0.3f, 30, lens, lead, every, hud);
|
||||
System.Func<float, Lens> push = t =>
|
||||
{
|
||||
var l = lens(t);
|
||||
l.at = Vector3.Lerp(l.at, l.look, 0.07f * t);
|
||||
return l;
|
||||
};
|
||||
return Take(X(name), 3.2f, 60, push, lead, every, hud);
|
||||
}
|
||||
|
||||
/// <summary>`-demotrailer`: the new things on the planet as moving takes for the music video.</summary>
|
||||
IEnumerator NewThings()
|
||||
{
|
||||
_clip = true;
|
||||
Cheats.Run("ship 60");
|
||||
BuildRules.AnyGround = true;
|
||||
yield return StillFactory();
|
||||
yield return StillHouse();
|
||||
yield return StillVending();
|
||||
yield return StillHands();
|
||||
yield return StillWeather();
|
||||
yield return StillUfo();
|
||||
_clip = false;
|
||||
}
|
||||
|
||||
IEnumerator Stills()
|
||||
{
|
||||
Cheats.Run("ship 60");
|
||||
BuildRules.AnyGround = true;
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
yield return StillCrew();
|
||||
yield return StillMachines();
|
||||
yield return StillFactory();
|
||||
yield return StillHouse();
|
||||
yield return StillVending();
|
||||
yield return StillHands();
|
||||
yield return StillNight();
|
||||
yield return StillWeather();
|
||||
yield return StillUfo();
|
||||
}
|
||||
|
||||
static Quaternion Facing(Vector3 at, Vector3 dir) => Quaternion.LookRotation(Vector3.ProjectOnPlane(dir, Planet.Up(at)), Planet.Up(at));
|
||||
|
||||
/// <summary>A belt from a piece's port straight out for so many metres; returns its far end.</summary>
|
||||
Vector3 LayBelt(BuildPiece piece, int port, float metres)
|
||||
{
|
||||
var ports = new List<Port>();
|
||||
piece.Ports(ports);
|
||||
if (port >= ports.Count) return piece.transform.position;
|
||||
var p = ports[port];
|
||||
var end = Planet.Surface(p.at + p.dir * metres);
|
||||
end += Planet.Up(end);
|
||||
Ts.BuildRpc((byte)PieceId.Belt, p.at, BuildRules.RunRotation(p.at, end), end);
|
||||
return end;
|
||||
}
|
||||
|
||||
// ───────────────────────── by day ─────────────────────────
|
||||
|
||||
IEnumerator StillCrew()
|
||||
{
|
||||
if (!Wanted(X("x_crew"))) yield break;
|
||||
Sky(0.5f, false);
|
||||
float x = -30f, z = 230f;
|
||||
var tools = new[] { ToolId.WideScythe, ToolId.LongScythe, ToolId.LawnMower, ToolId.WideScythe, ToolId.Scythe, ToolId.LongScythe };
|
||||
for (int i = 0; i < 6; i++)
|
||||
{
|
||||
float side = (i - 2.5f) * 3.2f, back = Mathf.Abs(i - 2.5f) * 1.1f;
|
||||
MowMap.Cut(On(x + side, z - back - 30f), On(x + side, z - back), 2.2f);
|
||||
Actor(new[] { 1, 4, 2, 6, 0, 7 }[i], On(x + side, z - back), Vector3.forward, tools[i], true, s => On(x + side, z - back + s * 1.7f));
|
||||
}
|
||||
yield return Still("x_crew", t => new Lens(On(x + 4.5f, z + 8.5f, 1.1f), On(x - 2f, z + 2.6f, 1.05f), 46f), 1.6f);
|
||||
yield return Still("x_crew_back", t => new Lens(On(x - 5f, z - 16f, 5f), On(x + 1f, z + 6f, 0.5f), 55f), 0.4f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator StillMachines()
|
||||
{
|
||||
if (!Wanted(X("x_machines"))) yield break;
|
||||
Sky(0.4f, false);
|
||||
float x = 240f, z = -120f;
|
||||
var row = new (VehicleKind kind, float dx, float dz, int who)[] { (VehicleKind.Combine, 0f, 0f, 5), (VehicleKind.Tractor, 13f, -7f, 3), (VehicleKind.Rider, -10f, -5f, 1), (VehicleKind.Rider, -17f, -10f, 6) };
|
||||
Vehicle lead = null;
|
||||
foreach (var m in row)
|
||||
{
|
||||
float ax = x + m.dx, az = z + m.dz;
|
||||
MowMap.Cut(On(ax, az - 30f), On(ax, az), m.kind == VehicleKind.Combine ? 6f : 3f);
|
||||
yield return Machine(m.kind, On(ax, az), Vector3.forward, s => On(ax, az + 3.2f * s), m.who, v => { if (!lead) lead = v; });
|
||||
}
|
||||
yield return new WaitForSeconds(1.5f);
|
||||
var c = lead.transform;
|
||||
yield return Still("x_machines", t => new Lens(c.position + c.forward * 15f - c.right * 9f + c.up * 1.8f, c.position - c.right * 5f + c.up * 1.4f, 54f), 0.4f);
|
||||
yield return Still("x_machines_air", t => new Lens(c.position - c.forward * 14f - c.right * 14f + c.up * 15f, c.position + c.forward * 3f - c.right * 4f, 56f), 0.2f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
// ───────────────────────── building ─────────────────────────
|
||||
|
||||
IEnumerator StillFactory()
|
||||
{
|
||||
if (!Wanted(X("x_factory")) && !Wanted(X("x_belts"))) yield break;
|
||||
Sky(0.38f, false);
|
||||
// the music video has already built a factory on this spot in Works()
|
||||
float x = _clip ? 160f : 60f, z = _clip ? -300f : 480f;
|
||||
for (int i = -24; i <= 24; i += 6) MowMap.Cut(On(x - 40f, z + i * 2f), On(x + 40f, z + i * 2f), 13f);
|
||||
var at = On(x, z);
|
||||
Ts.BuildRpc((byte)PieceId.UnloadBay, at, Facing(at, Vector3.forward), Vector3.zero);
|
||||
void Put(PieceId id, float dx, float dz)
|
||||
{
|
||||
var p = On(x + dx, z + dz);
|
||||
Ts.BuildRpc((byte)id, p, Facing(p, Vector3.forward), Vector3.zero);
|
||||
}
|
||||
Put(PieceId.Press, -16f, -22f);
|
||||
Put(PieceId.Dryer, 18f, -20f);
|
||||
Put(PieceId.Binder, 22f, 4f);
|
||||
Put(PieceId.SolarL, -22f, 6f);
|
||||
Put(PieceId.SolarL, -22f, 18f);
|
||||
Put(PieceId.BatteryL, -12f, 16f);
|
||||
Put(PieceId.Pole, 10f, 18f);
|
||||
Put(PieceId.Garage, 28f, 22f);
|
||||
yield return new WaitForSeconds(1f);
|
||||
var bay = BuildPiece.All.LastOrDefault(p => p && p.piece == PieceId.UnloadBay);
|
||||
if (!bay) { Log("stills: no unload bay"); yield break; }
|
||||
var ends = new List<Vector3> { LayBelt(bay, 0, 22f), LayBelt(bay, 1, 22f) };
|
||||
yield return null;
|
||||
var silo = bay.GetComponent<UnloadBay>();
|
||||
if (silo) silo.TakeRpc(120f);
|
||||
var b = bay.transform;
|
||||
var up = Planet.Up(b.position);
|
||||
var pad = silo ? silo.PadSpot : b.position + b.forward * 2f;
|
||||
var from = pad + b.forward * 16f;
|
||||
yield return Machine(VehicleKind.Rider, Planet.Surface(from), -b.forward, s => Vector3.Lerp(Planet.Surface(from), Planet.Surface(pad), Mathf.Clamp01(s / 3.5f)), 2, v => { });
|
||||
yield return new WaitForSeconds(2.5f);
|
||||
Log($"stills: {BuildPiece.All.Count(p => p && p.piece == PieceId.Belt)} belts, bay silo {(silo ? silo.Silo.Value : -1f):0}");
|
||||
yield return Still("x_factory", t => new Lens(b.position - b.forward * 11f + b.right * 9f + up * 6f, b.position - b.forward * 2f + up * 0.6f, 54f), 1.5f);
|
||||
yield return Still("x_belts", t =>
|
||||
{
|
||||
var a = ends[0];
|
||||
var w = (a - b.position).normalized;
|
||||
var p = b.position + w * 9f;
|
||||
return new Lens(p + Planet.Up(p) * 1.1f + Vector3.Cross(Planet.Up(p), w) * 1.6f + w * 4f, p - w * 2f + Planet.Up(p) * 0.4f, 52f);
|
||||
}, 0.2f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator StillHouse()
|
||||
{
|
||||
if (!Wanted(X("x_house")) && !Wanted(X("x_drones"))) yield break;
|
||||
Sky(0.14f, true);
|
||||
var c = On(60f, -40f);
|
||||
var up = Planet.Up(c);
|
||||
var east = Vector3.ProjectOnPlane(Vector3.right, up).normalized;
|
||||
var north = Vector3.Cross(east, up);
|
||||
var face = Quaternion.LookRotation(north, up);
|
||||
int built = 0, refused = 0;
|
||||
BuildPiece Put(PieceId id, Vector3 at, Quaternion rot)
|
||||
{
|
||||
var d = GameDefs.Piece(id);
|
||||
if (!BuildRules.CanPlace(d, at, rot, null, out var why)) { refused++; Log($"house: {d.name} refused: {why}"); return null; }
|
||||
built++;
|
||||
return Spawner.Instance.SpawnPiece(id, at, rot, at, true);
|
||||
}
|
||||
void Edge(PieceId id, BuildPiece on, Vector3 toward)
|
||||
{
|
||||
if (!on) return;
|
||||
var top = on.transform.position + on.transform.up * Foundation.Top;
|
||||
if (Snap.Edge(top + toward * 1.4f, on, 0f, out var at, out var rot)) Put(id, at, rot);
|
||||
}
|
||||
var a = Put(PieceId.Square, c + up * 1.5f, face);
|
||||
yield return new WaitForSeconds(0.6f);
|
||||
Foundation.Beside(c + east * 3f + up * 1.8f, PieceId.Square, out var bAt, out var bRot);
|
||||
var b = Put(PieceId.Square, bAt, bRot);
|
||||
yield return new WaitForSeconds(0.8f);
|
||||
Put(PieceId.Steps, Planet.Surface(c - north * 2.7f), face);
|
||||
Edge(PieceId.DoorWall, a, -north);
|
||||
Edge(PieceId.WindowWall, a, -east);
|
||||
Edge(PieceId.Wall, a, north);
|
||||
Edge(PieceId.WindowWall, b, -north);
|
||||
Edge(PieceId.WindowWall, b, east);
|
||||
Edge(PieceId.Wall, b, north);
|
||||
yield return new WaitForSeconds(0.8f);
|
||||
var wallB = BuildPiece.All.FirstOrDefault(p => p && p.piece == PieceId.Wall && b && (p.transform.position - (b.transform.position + north * 1.5f)).magnitude < 1.5f);
|
||||
BuildPiece floor = null;
|
||||
if (wallB && Snap.OnTop(PieceId.Floor, wallB.transform.position + up * 2.9f - north * 0.5f, wallB, null, 0f, out var fAt, out var fRot)) floor = Put(PieceId.Floor, fAt, fRot);
|
||||
var wallA = BuildPiece.All.FirstOrDefault(p => p && p.piece == PieceId.WindowWall && a && (p.transform.position - (a.transform.position - east * 1.5f)).magnitude < 1.5f);
|
||||
if (wallA && Snap.OnTop(PieceId.Roof, wallA.transform.position + up * 2.9f + east * 0.5f, wallA, null, 0f, out var rAt, out var rRot)) Put(PieceId.Roof, rAt, rRot);
|
||||
yield return new WaitForSeconds(0.8f);
|
||||
if (b) Put(PieceId.Stairs, Foundation.Grid(b.transform, b.transform.position + east * 0.5f), b.transform.rotation);
|
||||
if (floor)
|
||||
{
|
||||
var ftop = floor.transform.position;
|
||||
Edge(PieceId.Railing, floor, east);
|
||||
Edge(PieceId.Railing, floor, -north);
|
||||
Edge(PieceId.Railing, floor, north);
|
||||
Put(PieceId.Lamppost, Foundation.Grid(floor.transform, ftop + east * 1f + north * 1f), face);
|
||||
}
|
||||
Put(PieceId.Fence, Planet.Surface(c - north * 5f + east * 6f), face);
|
||||
Put(PieceId.Fence, Planet.Surface(c - north * 5f + east * 9f), face);
|
||||
Put(PieceId.Lamppost, Planet.Surface(c - north * 4f - east * 2.5f), face);
|
||||
Put(PieceId.Lamppost, Planet.Surface(c - north * 5f + east * 11f), face);
|
||||
Put(PieceId.Bench, Planet.Surface(c - north * 4.5f + east * 2f), face);
|
||||
Put(PieceId.Planter, Planet.Surface(c - north * 2.2f + east * 4.2f), face);
|
||||
Put(PieceId.Crates, Planet.Surface(c + east * 6.5f), face);
|
||||
Put(PieceId.Flagpole, Planet.Surface(c - east * 4f + north * 3f), face);
|
||||
// the drone pad beside it, four drones, and bundles lying about for them to fetch
|
||||
var padAt = Planet.Surface(c + east * 14f);
|
||||
var pad = Spawner.Instance.SpawnPiece(PieceId.DronePad, padAt, face, padAt, true);
|
||||
yield return new WaitForSeconds(1.2f);
|
||||
if (pad) pad.Tier.Value = 2;
|
||||
Log($"stills house: {built} built, {refused} refused");
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
float ang = -0.6f + i * 0.17f, r = 14f + (i % 3) * 6f;
|
||||
var p = Planet.Surface(padAt - north * Mathf.Cos(ang) * r + east * Mathf.Sin(ang) * r);
|
||||
Spawner.Instance.SpawnCargo(CargoKind.Grass, p + Planet.Up(p) * 0.5f, Quaternion.Euler(0f, i * 37f, 0f), Vector3.zero);
|
||||
}
|
||||
var mid = c + east * 1.5f + up * 2f;
|
||||
var one = Actor(4, c - north * 4.2f + east * 1.2f, north + east * 0.6f, ToolId.Hammer);
|
||||
var two = Actor(0, c - north * 6.4f - east * 0.6f, north - east * 0.3f, ToolId.Scythe);
|
||||
yield return new WaitForSeconds(2.2f);
|
||||
yield return Still("x_house", t => new Lens(mid - north * 15f + east * 8f + up * 2.6f, mid + east * 3f + up * 0.6f, 52f), 0.5f);
|
||||
yield return Take(X("x_drones"), 3f, _clip ? 60 : 10, t => new Lens(padAt - north * 11f + east * 7f + up * 1.4f, padAt - north * 4f + up * 3.2f, 58f), 0.2f);
|
||||
yield return Still("x_house_wide", t => new Lens(mid - north * 22f - east * 6f + up * 9f, mid + east * 5f, 52f), 0.2f);
|
||||
Sky(-0.3f, true);
|
||||
yield return new WaitForSeconds(1.5f);
|
||||
yield return Still("x_house_night", t => new Lens(mid - north * 15f + east * 8f + up * 2.6f, mid + east * 3f + up * 0.6f, 52f), 0.5f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
// ───────────────────────── the deck ─────────────────────────
|
||||
|
||||
IEnumerator StillVending()
|
||||
{
|
||||
if (!Wanted(X("x_vending"))) yield break;
|
||||
var beer = VendingMachine.All.FirstOrDefault(m => m && m.kind == TreatId.Beer && m.transform.position.magnitude > 0f && (m.transform.position - On(0f, 0f)).magnitude < 40f);
|
||||
var cigar = VendingMachine.All.FirstOrDefault(m => m && m.kind == TreatId.Cigar && beer && (m.transform.position - beer.transform.position).magnitude < 6f);
|
||||
if (!beer || !cigar) { Log($"stills: vending machines {VendingMachine.All.Count}"); yield break; }
|
||||
Sky(0.04f, true);
|
||||
var bt = beer.transform;
|
||||
var up = Planet.Up(bt.position);
|
||||
var mid = (bt.position + cigar.transform.position) * 0.5f;
|
||||
var buyer = Actor(3, bt.position + bt.forward * 1.15f + bt.right * 0.25f, -bt.forward, ToolId.Scythe);
|
||||
var ct = cigar.transform;
|
||||
var smoker = Actor(6, ct.position + ct.forward * 1.5f - ct.right * 0.9f, bt.forward + bt.right * 0.4f, ToolId.Hammer);
|
||||
// Actor stands them on the soil: they belong on the deck the machines stand on
|
||||
buyer.transform.position = bt.position + bt.forward * 1.15f + bt.right * 0.25f;
|
||||
smoker.transform.position = ct.position + ct.forward * 1.5f - ct.right * 0.9f;
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
var hand = buyer.transform.position + up * 1.1f + bt.forward * -0.3f;
|
||||
beer.Play(false, hand);
|
||||
cigar.Play(false, ct.position + ct.forward * 1.1f + up * 1.1f);
|
||||
float puff = 0f;
|
||||
yield return Take(X("x_vending"), _clip ? 2.6f : 1.8f, _clip ? 60 : 10, t => new Lens(mid + bt.forward * 4.6f + bt.right * 1.6f + up * 1.25f, mid + up * 1.05f + bt.forward * 0.4f, 50f), 0.4f, k =>
|
||||
{
|
||||
if (k < puff) return;
|
||||
puff = k + 0.18f;
|
||||
var mouth = smoker.transform.position + up * 1.62f + smoker.transform.forward * 0.18f;
|
||||
Fx.Exhale(mouth, smoker.transform.forward + up * 0.3f, 1f);
|
||||
if (k > 0.4f) Fx.SmokeRing(mouth, smoker.transform.forward + up * 0.2f);
|
||||
});
|
||||
yield return new WaitForSeconds(1.5f);
|
||||
yield return Still("x_vending_wide", t => new Lens(mid + bt.forward * 7.5f - bt.right * 3f + up * 2.4f, mid + up * 1f, 54f), 0.2f);
|
||||
Strike();
|
||||
}
|
||||
|
||||
/// <summary>Through the player's eyes: a can from the machine and down it goes, a cigar from the other, then mowing with both boosts on.</summary>
|
||||
IEnumerator StillHands()
|
||||
{
|
||||
if (!Wanted(X("x_fp"))) yield break;
|
||||
Sky(0.3f, true);
|
||||
Me.Character.Value = 0;
|
||||
Eyes(true);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
foreach (var m in VendingMachine.All.Where(v => v && (v.transform.position - On(0f, 0f)).magnitude < 40f).OrderBy(v => v.kind).ToList())
|
||||
{
|
||||
string name = m.kind == TreatId.Beer ? "x_fp_beer" : "x_fp_cigar";
|
||||
if (!Wanted(X(name))) continue;
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
yield return new WaitForSeconds(0.4f);
|
||||
Me.Tools.CheatFill();
|
||||
var mt = m.transform;
|
||||
var spot = mt.position + mt.forward * 1.5f;
|
||||
Me.Teleport(spot + Planet.Up(spot) * 0.2f);
|
||||
yield return null;
|
||||
Me.LookAt(mt.position + Planet.Up(mt.position) * 1.25f);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
bool bought = false;
|
||||
yield return Take(X(name), 6.2f, _clip ? 60 : 20, null, 0.1f, k =>
|
||||
{
|
||||
if (!bought) { bought = true; m.Interact(); }
|
||||
if (k < 0.3f) Me.LookAt(mt.position + Planet.Up(mt.position) * 1.25f);
|
||||
}, true);
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
}
|
||||
Treats.Begin(TreatId.Beer);
|
||||
Treats.Begin(TreatId.Cigar);
|
||||
Sky(0.45f, false);
|
||||
yield return Mow(X("x_fp_mow"), ToolId.WideScythe, 44f, 8f, 1.5f, 1.4f, 0.5f, 2.8f, 4860);
|
||||
Eyes(false);
|
||||
Treats.Clear();
|
||||
}
|
||||
|
||||
// ───────────────────────── weather and night ─────────────────────────
|
||||
|
||||
IEnumerator StillWeather()
|
||||
{
|
||||
if (Wanted(X("x_acid")))
|
||||
{
|
||||
Sky(0.4f, false);
|
||||
Ts.ServerSetWeather(WeatherKind.AcidRain, 60f);
|
||||
float x = -200f, z = 120f;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
float side = (i - 1.5f) * 3.4f, back = Mathf.Abs(i - 1.5f) * 1.2f;
|
||||
MowMap.Cut(On(x + side, z - back - 20f), On(x + side, z - back), 2.2f);
|
||||
Actor(new[] { 2, 5, 7, 1 }[i], On(x + side, z - back), Vector3.forward, ToolId.LongScythe, true, s => On(x + side, z - back + s * 1.5f));
|
||||
}
|
||||
yield return new WaitForSeconds(3f);
|
||||
yield return Still("x_acid", t => new Lens(On(x + 6f, z + 11f, 1.2f), On(x - 1f, z + 1f, 1.3f), 50f), 1.2f);
|
||||
Strike();
|
||||
}
|
||||
if (Wanted(X("x_twister")))
|
||||
{
|
||||
Ts.ServerSetWeather(WeatherKind.Storm, 40f);
|
||||
Sky(0.3f, false);
|
||||
var cam = On(60f, 26f, 1.4f);
|
||||
var from = On(70f, 92f);
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
float sx = 56f + i * 3.5f, sz = 40f + i * 1.5f;
|
||||
Actor(new[] { 0, 3, 6 }[i], On(sx, sz), Vector3.back, ToolId.Scythe, false, s => On(sx - s * 0.6f, sz - s * 2.6f));
|
||||
}
|
||||
Ts.ServerTwister(from);
|
||||
Ts.TwisterFrom.Value = from;
|
||||
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(cam - from, Planet.Up(from)).normalized;
|
||||
yield return Take(X("x_twister"), _clip ? 4f : 1.5f, _clip ? 60 : 10, t => new Lens(cam, Vector3.Lerp(Ts.TwisterPos(Ts.Now), On(60f, 44f, 1f), 0.45f) + Planet.Up(cam) * 5f, 60f), 3.5f);
|
||||
Ts.TwisterAt.Value = 0d;
|
||||
Strike();
|
||||
}
|
||||
Ts.ServerSetWeather(WeatherKind.Clear, 600f);
|
||||
yield return new WaitForSeconds(1f);
|
||||
}
|
||||
|
||||
IEnumerator StillNight()
|
||||
{
|
||||
if (!Wanted(X("x_night"))) yield break;
|
||||
Ts.ServerSetWeather(WeatherKind.Clear, 600f);
|
||||
Sky(-0.3f, true);
|
||||
float x = -420f, z = 90f;
|
||||
for (int i = 0; i < 12; i++)
|
||||
{
|
||||
float side = (i - 5.5f) * 3.4f, back = Mathf.Abs(i - 5.5f) * 1f;
|
||||
MowMap.Cut(On(x + side, z - back - 25f), On(x + side, z - back), 2.2f);
|
||||
Actor(i % 8, On(x + side, z - back), Vector3.forward, ToolId.WideScythe, true, s => On(x + side, z - back + s * 1.7f), i);
|
||||
}
|
||||
Vehicle r = null;
|
||||
yield return Machine(VehicleKind.Tractor, On(x + 30f, z - 8f), Vector3.forward, s => On(x + 30f, z - 8f + s * 4f), 0, v => r = v);
|
||||
float go = Time.time;
|
||||
float Near() => z + (Time.time - go) * 1.7f;
|
||||
WorkLight(() => On(x, Near() + 8f, 10f), () => On(x, Near() - 2f, 0.5f));
|
||||
yield return Still("x_night", t => new Lens(On(x + 3.5f, Near() + 7.5f, 1.2f), On(x - 1.5f, Near() + 0.8f, 0.95f), 52f), 1.2f);
|
||||
DayNight.Rig = null;
|
||||
DayNight.SetView(DayNight.Off);
|
||||
Strike();
|
||||
}
|
||||
|
||||
IEnumerator StillUfo()
|
||||
{
|
||||
if (!Wanted(X("x_ufo"))) yield break;
|
||||
Sky(0.12f, true);
|
||||
var spot = On(-60f, 70f);
|
||||
for (int i = 0; i < 3; i++)
|
||||
Actor(new[] { 4, 1, 7 }[i], On(-61f + i * 2.4f, 47f + (i % 2) * 1.2f), spot - On(-61f + i * 2.4f, 47f), i == 1 ? ToolId.Hammer : ToolId.Scythe);
|
||||
Ts.ServerUfo(spot);
|
||||
yield return new WaitForSeconds(TeamState.UfoArrive + 4f);
|
||||
yield return Still("x_ufo", t => new Lens(On(-57f, 40f, 1.0f), On(-60f, 70f, 9f), 56f), 0.2f);
|
||||
yield return Still("x_ufo_top", t => new Lens(On(-44f, 54f, 18f), On(-60f, 70f, 2f), 54f), 0.2f);
|
||||
Ts.UfoAt.Value = 0d;
|
||||
Strike();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.Stills.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.Stills.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 370b22f73f7cb4747839cd005c7788e9
|
||||
277
Assets/Scripts/Core/Trailer.Story.cs
Normal file
277
Assets/Scripts/Core/Trailer.Story.cs
Normal file
@ -0,0 +1,277 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering.Universal;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// The story takes, `s_`: the trailer told the way the game opens. The real opening film through the player's eyes with
|
||||
/// the phone and the Director on it, and at the same moments a close-up of him in his studio, filling the frame; his
|
||||
/// assistant in the ear; a twister and a saucer as they come in the game; and his other calls, close up, for the cut.
|
||||
/// Every sound the game asks for while a take rolls goes into the take's sounds.txt (frame, name, volume, pitch, metres
|
||||
/// from the camera), so the edit can lay the voices and effects exactly where they fell.
|
||||
/// </summary>
|
||||
public partial class Trailer
|
||||
{
|
||||
const int CW = 1920, CH = 1080;
|
||||
|
||||
/// <summary>A second camera rolling with a take, into a folder of its own.</summary>
|
||||
class Also
|
||||
{
|
||||
public string Name;
|
||||
public Camera Cam;
|
||||
public RenderTexture Rt;
|
||||
public Renderer Hide, Show;
|
||||
}
|
||||
|
||||
readonly List<Also> _also = new List<Also>();
|
||||
Texture2D _closeRead;
|
||||
/// <summary>The take keeps only its second cameras.</summary>
|
||||
bool _onlyAlso;
|
||||
StreamWriter _sounds;
|
||||
int _frameNow;
|
||||
string _takeName;
|
||||
|
||||
/// <summary>A landscape close-up of a booth's sitter: centred on `centreY` (metres up the sitter), `height` metres tall,
|
||||
/// in front of the wide mission control that the upright booth picture is too narrow for.</summary>
|
||||
Also CloseUp(string name, Booth b, float centreY, float height)
|
||||
{
|
||||
if (b == null || !b.Root) return null;
|
||||
const float fov = 20f;
|
||||
float dist = height * 0.5f / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad);
|
||||
var go = new GameObject("CloseUp " + name);
|
||||
go.transform.SetParent(b.Root, false);
|
||||
go.transform.localPosition = new Vector3(0f, centreY, dist);
|
||||
go.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
|
||||
var cam = go.AddComponent<Camera>();
|
||||
cam.fieldOfView = fov;
|
||||
cam.nearClipPlane = 0.2f;
|
||||
cam.farClipPlane = dist + 10f;
|
||||
cam.cullingMask = 1 << Studio.Layer;
|
||||
cam.clearFlags = CameraClearFlags.SolidColor;
|
||||
cam.backgroundColor = new Color(0.1f, 0.16f, 0.3f);
|
||||
cam.enabled = false;
|
||||
var data = go.AddComponent<UniversalAdditionalCameraData>();
|
||||
data.renderShadows = false;
|
||||
data.renderPostProcessing = false;
|
||||
var rt = new RenderTexture(CW, CH, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { antiAliasing = 8, name = "CloseUp " + name };
|
||||
rt.Create();
|
||||
cam.targetTexture = rt;
|
||||
|
||||
// the wide wall, further back than the booth's own, shown only to this camera
|
||||
var wall = GameObject.CreatePrimitive(PrimitiveType.Quad);
|
||||
Destroy(wall.GetComponent<Collider>());
|
||||
wall.name = "WideBackdrop";
|
||||
wall.layer = Studio.Layer;
|
||||
wall.transform.SetParent(b.Root, false);
|
||||
const float back = 2.6f;
|
||||
float wallH = 2f * (dist + back) * Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad) * 1.06f;
|
||||
var bg = AssetBank.I.Tex("T_Dir_BgWide");
|
||||
float aspect = bg ? bg.width / (float)bg.height : 16f / 9f;
|
||||
float qh = Mathf.Max(wallH, wallH * (CW / (float)CH) / aspect);
|
||||
// the desks at the sitter's waist, as in the upright picture
|
||||
wall.transform.localPosition = new Vector3(0f, centreY + (0.97f - centreY) * 0.6f, -back);
|
||||
wall.transform.localRotation = Quaternion.LookRotation(Vector3.back, Vector3.up);
|
||||
wall.transform.localScale = new Vector3(qh * aspect, qh, 1f);
|
||||
var wm = new Material(AssetBank.I.Mat("M_Studio"));
|
||||
wm.SetFloat("_Lit", 0f);
|
||||
if (bg) wm.SetTexture("_BaseMap", bg);
|
||||
wm.SetColor("_BaseColor", new Color(0.82f, 0.86f, 0.95f));
|
||||
var wr = wall.GetComponent<Renderer>();
|
||||
wr.sharedMaterial = wm;
|
||||
wr.enabled = false;
|
||||
var old = b.Root.Find("Backdrop");
|
||||
_props.Add(go);
|
||||
_props.Add(wall);
|
||||
return new Also { Name = name, Cam = cam, Rt = rt, Hide = old ? old.GetComponent<Renderer>() : null, Show = wr };
|
||||
}
|
||||
|
||||
void RollAlso(int f)
|
||||
{
|
||||
if (_also.Count == 0) return;
|
||||
if (!_closeRead) _closeRead = new Texture2D(CW, CH, TextureFormat.RGB24, false, false);
|
||||
foreach (var a in _also)
|
||||
{
|
||||
if (a == null || !a.Cam) continue;
|
||||
if (a.Hide) a.Hide.enabled = false;
|
||||
if (a.Show) a.Show.enabled = true;
|
||||
a.Cam.Render();
|
||||
if (a.Hide) a.Hide.enabled = true;
|
||||
if (a.Show) a.Show.enabled = false;
|
||||
var was = RenderTexture.active;
|
||||
RenderTexture.active = a.Rt;
|
||||
_closeRead.ReadPixels(new Rect(0, 0, CW, CH), 0, 0, false);
|
||||
RenderTexture.active = was;
|
||||
// each take's close-ups in a folder of their own: take@camera
|
||||
var dir = Path.Combine(Folder, _takeName + "@" + a.Name);
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllBytes(Path.Combine(dir, f.ToString("00000") + ".jpg"), _closeRead.EncodeToJPG(95));
|
||||
}
|
||||
}
|
||||
|
||||
void Listen(string take)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(Folder, take));
|
||||
_sounds = new StreamWriter(Path.Combine(Folder, take, "sounds.txt"));
|
||||
Sfx.Heard = (name, vol, pitch, pos) =>
|
||||
{
|
||||
float d = pos.HasValue && _cam ? Vector3.Distance(pos.Value, _cam.transform.position) : 0f;
|
||||
_sounds?.WriteLine($"{_frameNow}\t{name}\t{vol:0.###}\t{pitch:0.###}\t{d:0.#}");
|
||||
};
|
||||
}
|
||||
|
||||
void StopListening()
|
||||
{
|
||||
Sfx.Heard = null;
|
||||
_sounds?.Close();
|
||||
_sounds = null;
|
||||
}
|
||||
|
||||
void ClearAlso()
|
||||
{
|
||||
_also.Clear();
|
||||
_onlyAlso = false;
|
||||
}
|
||||
|
||||
static Booth BossBooth => Studio.Get("SM_Dir_Boss", 540, 1184, 0.97f, 0.72f);
|
||||
static Booth AsstBooth => Studio.Get("SM_Dir_Assistant", 600, 760, 1.04f, 0.62f);
|
||||
|
||||
IEnumerator Story()
|
||||
{
|
||||
if (!Wanted("s_")) yield break;
|
||||
Sky(0.45f, false);
|
||||
// the meadow furry far out, for the shots from above
|
||||
GrassField.FurReach = 3.5f;
|
||||
Eyes(true);
|
||||
var boss = CloseUp("s_boss", BossBooth, 1.13f, 1.0f);
|
||||
var asst = CloseUp("s_asst", AsstBooth, 1.0f, 0.8f);
|
||||
|
||||
// the opening film, as a new game shows it, and the Director close up beside it
|
||||
if (Wanted("s_intro"))
|
||||
{
|
||||
// a new crew's phone: no money yet
|
||||
Cheats.Run("money set 0");
|
||||
IntroCinematic.NoSkipHint = true;
|
||||
IntroCinematic.Again();
|
||||
float t0 = Time.time;
|
||||
while (!IntroCinematic.Running && Time.time - t0 < 5f) yield return null;
|
||||
_also.Add(boss);
|
||||
yield return Take("s_intro", 57f, 60, null, 0f, null, true);
|
||||
ClearAlso();
|
||||
// her hello as the film lets go, and her close up
|
||||
_also.Add(asst);
|
||||
yield return Take("s_after", 16f, 60, null, 0f, null, true);
|
||||
ClearAlso();
|
||||
}
|
||||
Assistant.Hush();
|
||||
Cheats.Run("money set 90000000");
|
||||
// no beginner's hints talking over the rest
|
||||
Cheats.Run("ship 60");
|
||||
yield return new WaitForSeconds(0.5f);
|
||||
|
||||
// a twister across the meadow under a storm, coming at the lens
|
||||
if (Wanted("s_storm"))
|
||||
{
|
||||
Eyes(false);
|
||||
Cheats.Run("weather storm 6");
|
||||
Sky(0.3f, false);
|
||||
var cam = On(60f, 30f, 1.5f);
|
||||
var from = On(64f, 78f);
|
||||
Ts.ServerTwister(from);
|
||||
Ts.TwisterFrom.Value = from;
|
||||
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(cam - from, Planet.Up(from)).normalized;
|
||||
yield return Take("s_storm", 9f, 60, t => new Lens(cam, Vector3.Lerp(Ts.TwisterPos(Ts.Now), On(62f, 60f, 1f), 0.3f) + Planet.Up(cam) * 6f, 58f), 3f);
|
||||
Ts.TwisterAt.Value = 0d;
|
||||
Assistant.Hush();
|
||||
Eyes(true);
|
||||
}
|
||||
|
||||
// through the eyes: the warning in the ear, the funnel coming, and up you go
|
||||
if (Wanted("s_thrown"))
|
||||
{
|
||||
Assistant.Hush();
|
||||
Assistant.Forget();
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
var from = On(100f, 70f);
|
||||
Ts.ServerTwister(from);
|
||||
Ts.TwisterFrom.Value = from;
|
||||
var meet = On(100f, 40f);
|
||||
Ts.TwisterDir.Value = Vector3.ProjectOnPlane(meet - from, Planet.Up(from)).normalized;
|
||||
// stand where the funnel will be in 7.5 s
|
||||
var spot = Ts.TwisterPos(Ts.TwisterAt.Value + 7.5d);
|
||||
Me.Teleport(spot + Planet.Up(spot) * 0.2f);
|
||||
yield return null;
|
||||
bool flung = false;
|
||||
var p0 = Me.transform.position;
|
||||
_also.Add(asst);
|
||||
yield return Take("s_thrown", 15f, 60, null, 0.2f, k =>
|
||||
{
|
||||
if (!flung && (Me.transform.position - p0).magnitude > 2f) flung = true;
|
||||
if (!flung) Me.LookAt(Ts.TwisterPos(Ts.Now) + Planet.Up(p0) * 3.5f);
|
||||
}, true);
|
||||
ClearAlso();
|
||||
Ts.TwisterAt.Value = 0d;
|
||||
Cheats.Run("weather clear 600");
|
||||
yield return new WaitForSeconds(4f);
|
||||
Assistant.Hush();
|
||||
}
|
||||
|
||||
// the saucer: from the grass as it comes down, from above as it draws
|
||||
if (Wanted("s_ufo"))
|
||||
{
|
||||
Eyes(false);
|
||||
Sky(0.25f, true);
|
||||
var spot = On(-60f, 70f);
|
||||
Ts.ServerUfo(spot);
|
||||
double at = Ts.UfoAt.Value;
|
||||
var low = On(-56f, 42f, 1.1f);
|
||||
yield return Take("s_ufo", 11f, 60, t => new Lens(low, Vector3.Lerp(On(-60f, 70f, 30f), On(-60f, 70f, 6f), Ease(Mathf.Clamp01(t * 1.2f))), 52f), 0f);
|
||||
while (Ts.Now - at < 11d) yield return null;
|
||||
yield return Take("s_ufo_top", 10f, 60, t => new Lens(On(-60f + 16f - t * 3f, 70f - 14f, 20f + t * 3f), On(-60f, 70f, 2f), 52f), 0f);
|
||||
while (Ts.UfoOn) yield return null;
|
||||
Assistant.Hush();
|
||||
Eyes(true);
|
||||
}
|
||||
|
||||
// the Director rings about it while you stand and watch it come down
|
||||
if (Wanted("s_ufocall"))
|
||||
{
|
||||
Me.Tools.Equip(ToolId.Scythe);
|
||||
yield return Stand(-120f, 40f, 8f);
|
||||
var spot = On(-120f, 72f);
|
||||
Ts.ServerUfo(spot);
|
||||
Assistant.Hush();
|
||||
yield return new WaitForSeconds(0.2f);
|
||||
Assistant.Hush();
|
||||
DirectorCall.Quiet = false;
|
||||
DirectorCall.Call("dir_ufo");
|
||||
DirectorCall.Quiet = true;
|
||||
_also.Add(boss);
|
||||
yield return Take("s_ufocall", 17f, 60, null, 0f, k => Me.LookAt(Vector3.Lerp(On(-120f, 72f, 26f), On(-120f, 72f, 6f), Ease(Mathf.Clamp01(k * 1.6f)))), true);
|
||||
ClearAlso();
|
||||
while (Ts.UfoOn) yield return null;
|
||||
Assistant.Hush();
|
||||
}
|
||||
|
||||
// his other calls, close up only
|
||||
foreach (var line in new[] { "dir_belts", "dir_combine", "dir_m1", "dir_m100" })
|
||||
{
|
||||
string take = "s_" + line;
|
||||
if (!Wanted(take)) continue;
|
||||
var c = CloseUp("s_boss", BossBooth, 1.13f, 1.0f);
|
||||
_also.Add(c);
|
||||
_onlyAlso = true;
|
||||
float length = AssetBank.I.Clip(line) ? AssetBank.I.Clip(line).length : 10f;
|
||||
StartCoroutine(DirectorCall.Speak(line, true));
|
||||
yield return Take(take, length + 1.6f, 60, null, 0f, null, false);
|
||||
ClearAlso();
|
||||
while (DirectorCall.Busy) yield return null;
|
||||
}
|
||||
Eyes(false);
|
||||
Sky(0.42f, false);
|
||||
GrassField.FurReach = 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.Story.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.Story.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e500250d684e9b442a420556b4365dbe
|
||||
388
Assets/Scripts/Core/Trailer.cs
Normal file
388
Assets/Scripts/Core/Trailer.cs
Normal file
@ -0,0 +1,388 @@
|
||||
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
|
||||
{
|
||||
const int W = 2560, H = 1440;
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Trailer.cs.meta
Normal file
2
Assets/Scripts/Core/Trailer.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3631ed7bd56fb764c8e679d0cbb8a7ba
|
||||
155
Assets/Scripts/Core/Tween.cs
Normal file
155
Assets/Scripts/Core/Tween.cs
Normal file
@ -0,0 +1,155 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public enum Ease { Linear, OutQuad, InQuad, InOutQuad, OutCubic, InCubic, InOutCubic, OutBack, InBack, OutElastic, OutBounce, OutExpo }
|
||||
|
||||
public static class Easing
|
||||
{
|
||||
public static float Apply(Ease e, float t)
|
||||
{
|
||||
t = Mathf.Clamp01(t);
|
||||
switch (e)
|
||||
{
|
||||
case Ease.OutQuad: return 1f - (1f - t) * (1f - t);
|
||||
case Ease.InQuad: return t * t;
|
||||
case Ease.InOutQuad: return t < 0.5f ? 2f * t * t : 1f - Mathf.Pow(-2f * t + 2f, 2f) / 2f;
|
||||
case Ease.OutCubic: return 1f - Mathf.Pow(1f - t, 3f);
|
||||
case Ease.InCubic: return t * t * t;
|
||||
case Ease.InOutCubic: return t < 0.5f ? 4f * t * t * t : 1f - Mathf.Pow(-2f * t + 2f, 3f) / 2f;
|
||||
case Ease.OutBack: { const float c1 = 1.70158f, c3 = c1 + 1f; return 1f + c3 * Mathf.Pow(t - 1f, 3f) + c1 * Mathf.Pow(t - 1f, 2f); }
|
||||
case Ease.InBack: { const float c1 = 1.70158f, c3 = c1 + 1f; return c3 * t * t * t - c1 * t * t; }
|
||||
case Ease.OutElastic:
|
||||
{
|
||||
if (t <= 0f || t >= 1f) return t;
|
||||
const float c4 = (2f * Mathf.PI) / 3f;
|
||||
return Mathf.Pow(2f, -10f * t) * Mathf.Sin((t * 10f - 0.75f) * c4) + 1f;
|
||||
}
|
||||
case Ease.OutBounce:
|
||||
{
|
||||
const float n1 = 7.5625f, d1 = 2.75f;
|
||||
if (t < 1f / d1) return n1 * t * t;
|
||||
if (t < 2f / d1) { t -= 1.5f / d1; return n1 * t * t + 0.75f; }
|
||||
if (t < 2.5f / d1) { t -= 2.25f / d1; return n1 * t * t + 0.9375f; }
|
||||
t -= 2.625f / d1; return n1 * t * t + 0.984375f;
|
||||
}
|
||||
case Ease.OutExpo: return t >= 1f ? 1f : 1f - Mathf.Pow(2f, -10f * t);
|
||||
default: return t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tiny allocation-light tween runner. Tweens are keyed by an owner object so they can be killed.</summary>
|
||||
public class Tween : MonoBehaviour
|
||||
{
|
||||
class Item
|
||||
{
|
||||
public object owner;
|
||||
public float delay, duration, time;
|
||||
public Ease ease;
|
||||
public bool unscaled;
|
||||
public Action<float> step;
|
||||
public Action done;
|
||||
public bool dead;
|
||||
}
|
||||
|
||||
static Tween _inst;
|
||||
readonly List<Item> _items = new List<Item>(256);
|
||||
readonly List<Item> _adding = new List<Item>(64);
|
||||
|
||||
static Tween Inst
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_inst == null)
|
||||
{
|
||||
var go = new GameObject("[Tween]");
|
||||
DontDestroyOnLoad(go);
|
||||
_inst = go.AddComponent<Tween>();
|
||||
}
|
||||
return _inst;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Runs step(eased01) for duration seconds.</summary>
|
||||
public static void Run(object owner, float duration, Action<float> step, Ease ease = Ease.OutCubic,
|
||||
float delay = 0f, Action done = null, bool unscaled = true)
|
||||
{
|
||||
Inst._adding.Add(new Item { owner = owner, duration = Mathf.Max(0.0001f, duration), delay = delay, ease = ease, step = step, done = done, unscaled = unscaled });
|
||||
}
|
||||
|
||||
public static void Delay(object owner, float delay, Action done, bool unscaled = true)
|
||||
{
|
||||
Run(owner, 0.0001f, null, Ease.Linear, delay, done, unscaled);
|
||||
}
|
||||
|
||||
/// <summary>Whether anything is still tweening for this owner.</summary>
|
||||
public static bool Running(object owner)
|
||||
{
|
||||
if (_inst == null || owner == null) return false;
|
||||
foreach (var i in _inst._items) if (!i.dead && ReferenceEquals(i.owner, owner)) return true;
|
||||
foreach (var i in _inst._adding) if (!i.dead && ReferenceEquals(i.owner, owner)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void Kill(object owner)
|
||||
{
|
||||
if (_inst == null || owner == null) return;
|
||||
foreach (var i in _inst._items) if (ReferenceEquals(i.owner, owner)) i.dead = true;
|
||||
foreach (var i in _inst._adding) if (ReferenceEquals(i.owner, owner)) i.dead = true;
|
||||
}
|
||||
|
||||
public static void Scale(Transform t, Vector3 from, Vector3 to, float dur, Ease ease = Ease.OutBack, float delay = 0f, Action done = null)
|
||||
{
|
||||
Kill(t);
|
||||
PunchRest.Remove(t);
|
||||
t.localScale = from;
|
||||
Run(t, dur, k => { if (t) t.localScale = Vector3.LerpUnclamped(from, to, k); }, ease, delay, done);
|
||||
}
|
||||
|
||||
/// <summary>Quick squash-and-stretch punch on a transform's scale.</summary>
|
||||
public static void Punch(Transform t, float amount = 0.25f, float dur = 0.35f)
|
||||
{
|
||||
if (!t) return;
|
||||
Kill(t);
|
||||
// a punch interrupted mid-wobble must not become the new rest scale, or rapid punches make things drift
|
||||
if (!PunchRest.TryGetValue(t, out var baseScale)) PunchRest[t] = baseScale = t.localScale;
|
||||
Run(t, dur, k =>
|
||||
{
|
||||
if (!t) return;
|
||||
float s = Mathf.Sin(k * Mathf.PI * 3f) * (1f - k) * amount;
|
||||
t.localScale = new Vector3(baseScale.x * (1f + s), baseScale.y * (1f - s * 0.8f), baseScale.z * (1f + s));
|
||||
}, Ease.Linear, 0f, () => { PunchRest.Remove(t); if (t) t.localScale = baseScale; });
|
||||
}
|
||||
|
||||
static readonly Dictionary<Transform, Vector3> PunchRest = new Dictionary<Transform, Vector3>();
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (_adding.Count > 0) { _items.AddRange(_adding); _adding.Clear(); }
|
||||
float dt = Time.deltaTime, udt = Time.unscaledDeltaTime;
|
||||
for (int n = 0; n < _items.Count; n++)
|
||||
{
|
||||
var i = _items[n];
|
||||
if (i.dead) continue;
|
||||
float d = i.unscaled ? udt : dt;
|
||||
if (i.delay > 0f) { i.delay -= d; continue; }
|
||||
i.time += d;
|
||||
float k = Mathf.Clamp01(i.time / i.duration);
|
||||
try
|
||||
{
|
||||
i.step?.Invoke(Easing.Apply(i.ease, k));
|
||||
if (k >= 1f) { i.dead = true; i.done?.Invoke(); }
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
i.dead = true;
|
||||
Debug.LogException(e);
|
||||
}
|
||||
}
|
||||
_items.RemoveAll(x => x.dead);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Core/Tween.cs.meta
Normal file
2
Assets/Scripts/Core/Tween.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8d54b048671cf3a47b6b159c67c6d14c
|
||||
8
Assets/Scripts/Gameplay.meta
Normal file
8
Assets/Scripts/Gameplay.meta
Normal file
@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a80c94b37083e5a47870bcf4e7180a21
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
58
Assets/Scripts/Gameplay/BeltMerger.cs
Normal file
58
Assets/Scripts/Gameplay/BeltMerger.cs
Normal file
@ -0,0 +1,58 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Up to three belts come in, from the left, the right and the back, and one goes out of the front. They take turns, and a
|
||||
/// side with nothing waiting doesn't hold up the others. E gives one of the three the right of way.
|
||||
/// </summary>
|
||||
public class BeltMerger : Conveyor, IJunction
|
||||
{
|
||||
const float Wait = 0.1f;
|
||||
|
||||
int _last = -1;
|
||||
readonly float[] _tried = { -9f, -9f, -9f };
|
||||
|
||||
public int ModeCount => 4;
|
||||
public string ModeName(int mode) => mode == 0 ? Loc.T("the belts take turns") : mode == 1 ? Loc.T("the left belt goes first") : mode == 2 ? Loc.T("the right belt goes first") : Loc.T("the back belt goes first");
|
||||
public Color ModeColor(int mode) => mode == 0 ? Color.white : new Color(0.3f, 0.6f, 0.95f);
|
||||
|
||||
// route 0 = in from the left, route 1 = in from the right, route 2 = in from the back
|
||||
protected override int RouteCount => 3;
|
||||
static float Side(int route) => route == 0 ? -1f : route == 1 ? 1f : 0f;
|
||||
|
||||
protected override Vector2 PathAt(float d, int route) =>
|
||||
d < 0.5f && route != 2 ? new Vector2(Side(route) * (0.5f - d), 0f) : new Vector2(0f, d - 0.5f);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
for (int r = 0; r < 3; r++)
|
||||
into.Add(new Port { at = WorldOnPath(0f, r, 0f), dir = r == 2 ? transform.forward : transform.right * -Side(r), input = true });
|
||||
into.Add(new Port { at = WorldOnPath(1f, 0, 0f), dir = transform.forward });
|
||||
}
|
||||
|
||||
protected override bool Takes(int port)
|
||||
{
|
||||
_tried[port] = Time.time;
|
||||
int first = Mode - 1;
|
||||
if (first >= 0) return port == first || Time.time - _tried[first] > Wait;
|
||||
for (int k = 1; k <= 3; k++)
|
||||
{
|
||||
int other = (_last + 3 + k) % 3;
|
||||
if (other == port) return true;
|
||||
if (Time.time - _tried[other] < Wait) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override int EntryRoute(Cargo c, int port)
|
||||
{
|
||||
_last = port;
|
||||
Sfx.PlayAt("merger_clunk", transform.position + transform.up * 0.4f, 0.35f, 1f, 0.08f, 0.25f);
|
||||
return port;
|
||||
}
|
||||
|
||||
protected override int RouteAt(Vector2 local, Cargo c) => local.x < -0.1f ? 0 : local.x > 0.1f ? 1 : 2;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltMerger.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltMerger.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c330fdcc26d479d418a98a52d4ad19a4
|
||||
647
Assets/Scripts/Gameplay/BeltRun.cs
Normal file
647
Assets/Scripts/Gameplay/BeltRun.cs
Normal file
@ -0,0 +1,647 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// One belt from A to B, up to 30 m, at any height. The piece stands at A with +Z toward B; the bed, the rails and the posts
|
||||
/// down to the ground are generated to fit, so they can only be built once the ends are known. Where it meets another belt
|
||||
/// at an angle the two of them sweep round one arc between them, and where it comes out of (or goes into) a machine's port
|
||||
/// at an angle it leaves the way the port faces and bends round to the run. Cargo rides the same curve the belt is drawn on.
|
||||
/// </summary>
|
||||
public class BeltRun : Conveyor
|
||||
{
|
||||
float _len = 1f;
|
||||
BeltShape _shape;
|
||||
|
||||
protected override float Surface => 0f;
|
||||
protected override bool Sides => true;
|
||||
protected override float Length(int route) => _shape != null ? _shape.PathLength : _len;
|
||||
protected override Vector2 PathAt(float d, int route) => _shape != null ? _shape.PathAt(d) : new Vector2(0f, d);
|
||||
protected override float HeightAt(float d, int route) => _shape != null ? _shape.HeightAt(d) : 0f;
|
||||
|
||||
protected override void Project(Vector2 local, out int route, out float d)
|
||||
{
|
||||
route = 0;
|
||||
d = _shape != null ? _shape.Project(local) : Mathf.Clamp(local.y, 0f, _len);
|
||||
}
|
||||
|
||||
public float Metres => _len;
|
||||
/// <summary>Where the run was laid to. Belts and machines join here, however the belt itself bends round to meet them.</summary>
|
||||
public Vector3 End => transform.position + transform.rotation * new Vector3(0f, 0f, _len);
|
||||
/// <summary>Where the run was laid from.</summary>
|
||||
public Vector3 StartPoint => transform.position;
|
||||
|
||||
protected override Vector3 ExitAt(int route) => End;
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(new Port { at = StartPoint, dir = Tangent(0f, 0), input = true });
|
||||
into.Add(new Port { at = End, dir = Tangent(Length(0), 0) });
|
||||
}
|
||||
|
||||
Vector3 _from, _to;
|
||||
int _seenVersion = -1;
|
||||
float _nextLook;
|
||||
|
||||
/// <summary>
|
||||
/// How each end meets its neighbours, redone whenever something is built or taken down nearby: a belt running on gets
|
||||
/// half of a rounded corner, a machine's port gets a bend out of it and a hood over the end, a free end keeps its drum.
|
||||
/// </summary>
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
if (_shape == null || BuildPiece.Version == _seenVersion || Time.time < _nextLook) return;
|
||||
_seenVersion = BuildPiece.Version;
|
||||
_nextLook = Time.time + 0.25f;
|
||||
_shape.Fit(_from, _to, JointAt(End, true, this, Piece), JointAt(StartPoint, false, this, Piece));
|
||||
}
|
||||
|
||||
/// <summary>What a belt end at <paramref name="at"/> meets (the ghost in the player's hands asks too, with no belt of its own).</summary>
|
||||
public static BeltShape.Joint JointAt(Vector3 at, bool end, BeltRun self, BuildPiece skip)
|
||||
{
|
||||
foreach (var c in All)
|
||||
{
|
||||
if (!(c is BeltRun r) || r == self || r._shape == null) continue;
|
||||
if (((end ? r.StartPoint : r.End) - at).sqrMagnitude < BeltNet.Joined * BeltNet.Joined)
|
||||
return new BeltShape.Joint { kind = BeltShape.JointKind.Belt, dir = r.transform.forward, len = r._len };
|
||||
}
|
||||
// a splitter or merger is a belt too: the end bends round to its port, but keeps its drum instead of a hood
|
||||
if (BeltNet.Nearest(at, end, BeltNet.Joined, skip, out var piece, out _, out var port))
|
||||
return new BeltShape.Joint { kind = BeltShape.JointKind.Port, dir = port.dir, bare = piece.GetComponentInChildren<Conveyor>() };
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>Stretches everything to the run. Every peer does this when the piece spawns.</summary>
|
||||
public void Lay(Vector3 from, Vector3 to)
|
||||
{
|
||||
_len = Vector3.Distance(from, to);
|
||||
_from = from;
|
||||
_to = to;
|
||||
_seenVersion = -1;
|
||||
var root = Piece.transform;
|
||||
if (_shape == null)
|
||||
{
|
||||
_shape = new BeltShape(root, root.gameObject.layer);
|
||||
belts = new[] { _shape.Rubber };
|
||||
}
|
||||
_shape.Fit(from, to);
|
||||
var trigger = GetComponent<BoxCollider>();
|
||||
trigger.center = new Vector3(0f, 0.25f, _len * 0.5f);
|
||||
trigger.size = new Vector3(0.92f, 0.5f, _len);
|
||||
Bar("BeltBase", new Vector3(0f, -0.07f, _len * 0.5f), new Vector3(1f, 0.14f, _len));
|
||||
Bar("RailL", new Vector3(-0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
|
||||
Bar("RailR", new Vector3(0.47f, 0.07f, _len * 0.5f), new Vector3(0.06f, 0.14f, _len));
|
||||
}
|
||||
|
||||
void Bar(string name, Vector3 at, Vector3 size)
|
||||
{
|
||||
var t = Piece.transform.Find(name);
|
||||
if (!t) return;
|
||||
t.localPosition = at;
|
||||
t.GetComponent<BoxCollider>().size = size;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The look of a belt run, shared by the built thing and the ghost in the player's hands, and the path it runs along.</summary>
|
||||
public class BeltShape
|
||||
{
|
||||
const float PostEvery = 6f, BracketEvery = 1.5f, BedTop = -0.02f, BedLow = -0.14f, DrumR = 0.1f, RailX = 0.47f;
|
||||
/// <summary>How wide a bend sweeps round, measured to the middle of the belt.</summary>
|
||||
const float Radius = 1.4f;
|
||||
/// <summary>Degrees of arc per step: small enough that the rails read as one smooth curve.</summary>
|
||||
const float ArcStep = 5f;
|
||||
|
||||
public readonly MeshRenderer Frame, Iron, Rubber;
|
||||
readonly Mesh _frame = new Mesh { name = "BeltFrame" }, _iron = new Mesh { name = "BeltIron" }, _rubber = new Mesh { name = "BeltRubber" };
|
||||
readonly List<Vector3> _v = new List<Vector3>(), _n = new List<Vector3>();
|
||||
readonly List<Vector2> _uv = new List<Vector2>();
|
||||
readonly List<int> _t = new List<int>();
|
||||
/// <summary>The centre line in the run's own space (flat, +Z toward B), how far along it each point is, and its right-hand side at each point (longer than 1 where it turns, so the edges stay parallel).</summary>
|
||||
readonly List<Vector3> _path = new List<Vector3>(), _side = new List<Vector3>();
|
||||
/// <summary>At each point of the path: which way it runs (in 3D, so up and down slopes too), and the belt's own up,
|
||||
/// square to that and to the planet's up. Two belts meeting at a corner work these out the same way at the same spot,
|
||||
/// so their rails and bed meet edge to edge.</summary>
|
||||
readonly List<Vector3> _tan = new List<Vector3>(), _up = new List<Vector3>();
|
||||
readonly List<float> _along = new List<float>();
|
||||
static readonly List<Vector3> s_head = new List<Vector3>(), s_tail = new List<Vector3>(), s_headT = new List<Vector3>(), s_tailT = new List<Vector3>();
|
||||
/// <summary>Where the next parts go: a drum, a hood or a bracket is made square and put down along the path.</summary>
|
||||
Matrix4x4 _xf = Matrix4x4.identity;
|
||||
|
||||
public BeltShape(Transform parent, int layer)
|
||||
{
|
||||
Frame = Part("Frame", parent, layer, _frame, BuildLook.Mat("M_Timber", new Color(0.55f, 0.4f, 0.25f)));
|
||||
Iron = Part("Iron", parent, layer, _iron, BuildLook.Mat("M_Steel", new Color(0.55f, 0.57f, 0.6f)));
|
||||
Rubber = Part("Rubber", parent, layer, _rubber, BuildLook.Mat("M_ConveyorBelt", new Color(0.16f, 0.16f, 0.17f)));
|
||||
}
|
||||
|
||||
static MeshRenderer Part(string name, Transform parent, int layer, Mesh mesh, Material mat)
|
||||
{
|
||||
var go = new GameObject(name) { layer = layer };
|
||||
go.transform.SetParent(parent, false);
|
||||
go.AddComponent<MeshFilter>().sharedMesh = mesh;
|
||||
var r = go.AddComponent<MeshRenderer>();
|
||||
r.sharedMaterial = mat;
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>The ghost is all one see-through material and casts no shadow.</summary>
|
||||
public void Paint(Material m)
|
||||
{
|
||||
foreach (var r in new[] { Frame, Iron, Rubber })
|
||||
{
|
||||
r.sharedMaterial = m;
|
||||
r.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
|
||||
}
|
||||
}
|
||||
|
||||
public void Destroy()
|
||||
{
|
||||
Object.Destroy(_frame);
|
||||
Object.Destroy(_iron);
|
||||
Object.Destroy(_rubber);
|
||||
}
|
||||
|
||||
// ───────────────────────── the path ─────────────────────────
|
||||
|
||||
public float PathLength => _along.Count > 0 ? _along[_along.Count - 1] : 0f;
|
||||
|
||||
/// <summary>The point d metres along the path, in the run's space (x across, y along the run).</summary>
|
||||
public Vector2 PathAt(float d)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0) return new Vector2(0f, d);
|
||||
if (d <= 0f) return Flat(_path[0]);
|
||||
for (int i = 1; i < n; i++)
|
||||
if (d <= _along[i]) return Flat(Vector3.Lerp(_path[i - 1], _path[i], Mathf.InverseLerp(_along[i - 1], _along[i], d)));
|
||||
return Flat(_path[n - 1]);
|
||||
}
|
||||
|
||||
/// <summary>How high the centre line is d metres along, in the run's space (it rounds over a change of slope).</summary>
|
||||
public float HeightAt(float d)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0 || d <= 0f) return n == 0 ? 0f : _path[0].y;
|
||||
for (int i = 1; i < n; i++)
|
||||
if (d <= _along[i]) return Mathf.Lerp(_path[i - 1].y, _path[i].y, Mathf.InverseLerp(_along[i - 1], _along[i], d));
|
||||
return _path[n - 1].y;
|
||||
}
|
||||
|
||||
/// <summary>How far along the path its nearest point to a local point is.</summary>
|
||||
public float Project(Vector2 local)
|
||||
{
|
||||
if (_path.Count < 2) return 0f;
|
||||
float best = float.MaxValue, d = 0f;
|
||||
for (int i = 1; i < _path.Count; i++)
|
||||
{
|
||||
var a = Flat(_path[i - 1]);
|
||||
var ab = Flat(_path[i]) - a;
|
||||
float k = ab.sqrMagnitude > 1e-8f ? Mathf.Clamp01(Vector2.Dot(local - a, ab) / ab.sqrMagnitude) : 0f;
|
||||
float e = (a + ab * k - local).sqrMagnitude;
|
||||
if (e < best) { best = e; d = Mathf.Lerp(_along[i - 1], _along[i], k); }
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static Vector2 Flat(Vector3 p) => new Vector2(p.x, p.z);
|
||||
Vector3 At(float d) { var p = PathAt(d); return new Vector3(p.x, 0f, p.y); }
|
||||
|
||||
Vector3 Fwd(float d)
|
||||
{
|
||||
float L = PathLength;
|
||||
var p = PathAt(Mathf.Clamp(d + 0.03f, 0f, L)) - PathAt(Mathf.Clamp(d - 0.03f, 0f, L));
|
||||
return p.sqrMagnitude > 1e-8f ? new Vector3(p.x, 0f, p.y).normalized : Vector3.forward;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lays out the centre line: a straight run, with half of a corner arc at an end that meets another belt (that belt draws
|
||||
/// the other half, so the two halves meet in the middle of the arc), or a bend out of a port at an end that meets a machine.
|
||||
/// </summary>
|
||||
void Route(float len, Vector3 a, Quaternion rot, Joint atEnd, Joint atStart)
|
||||
{
|
||||
var inv = Quaternion.Inverse(rot);
|
||||
_path.Clear();
|
||||
_tan.Clear();
|
||||
_along.Clear();
|
||||
s_head.Clear();
|
||||
s_tail.Clear();
|
||||
s_headT.Clear();
|
||||
s_tailT.Clear();
|
||||
var b = new Vector3(0f, 0f, len);
|
||||
// a corner with the belt before or after: one arc between the two runs, in 3D, so a change of slope is rounded too
|
||||
if (atStart.kind == JointKind.Belt) Corner(inv * atStart.dir, Vector3.forward, Mathf.Min(len, atStart.len), Vector3.zero, false, s_head, s_headT);
|
||||
if (atEnd.kind == JointKind.Belt) Corner(Vector3.forward, inv * atEnd.dir, Mathf.Min(len, atEnd.len), b, true, s_tail, s_tailT);
|
||||
bool portStart = atStart.kind == JointKind.Port && atStart.dir.sqrMagnitude > 1e-4f;
|
||||
bool portEnd = atEnd.kind == JointKind.Port && atEnd.dir.sqrMagnitude > 1e-4f;
|
||||
// a bend at both ends: each one aims for where the other one leaves off, and they settle in a couple of rounds
|
||||
for (int pass = 0; pass < (portStart && portEnd ? 3 : 1); pass++)
|
||||
{
|
||||
if (portStart)
|
||||
{
|
||||
s_head.Clear();
|
||||
s_headT.Clear();
|
||||
if (!Bow(Vector3.zero, Level(inv * atStart.dir), s_tail.Count > 0 ? s_tail[0] : b, s_head)) s_head.Clear();
|
||||
}
|
||||
if (portEnd)
|
||||
{
|
||||
s_tail.Clear();
|
||||
s_tailT.Clear();
|
||||
if (Bow(b, -Level(inv * atEnd.dir), s_head.Count > 0 ? s_head[s_head.Count - 1] : Vector3.zero, s_tail)) s_tail.Reverse();
|
||||
else s_tail.Clear();
|
||||
}
|
||||
}
|
||||
if (s_head.Count == 0) s_head.Add(Vector3.zero);
|
||||
if (s_tail.Count == 0) s_tail.Add(b);
|
||||
for (int i = 0; i < s_head.Count; i++) Add(s_head[i], i < s_headT.Count ? s_headT[i] : Vector3.zero);
|
||||
for (int i = 0; i < s_tail.Count; i++) Add(s_tail[i], i < s_tailT.Count ? s_tailT[i] : Vector3.zero);
|
||||
Frames(a, rot, inv);
|
||||
}
|
||||
|
||||
static Vector3 Level(Vector3 v) => new Vector3(v.x, 0f, v.z).normalized;
|
||||
|
||||
void Add(Vector3 p, Vector3 tangent)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n > 0 && (p - _path[n - 1]).sqrMagnitude < 1e-6f)
|
||||
{
|
||||
if (tangent.sqrMagnitude > 1e-6f) _tan[n - 1] = tangent;
|
||||
return;
|
||||
}
|
||||
_along.Add(n == 0 ? 0f : _along[n - 1] + Vector3.Distance(p, _path[n - 1]));
|
||||
_path.Add(p);
|
||||
_tan.Add(tangent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Half of the arc round a corner at <paramref name="j"/>, where a run heading <paramref name="d1"/> meets one heading
|
||||
/// <paramref name="d2"/> (in 3D: a turn, a change of slope, or both). The arc lies in the plane of the two directions and
|
||||
/// touches both runs; the end's half runs from where it leaves this run to its middle, the start's half from the middle
|
||||
/// onto this run. Both belts work it out from the same directions, corner and shorter length, so the halves meet exactly.
|
||||
/// </summary>
|
||||
static void Corner(Vector3 d1, Vector3 d2, float shortest, Vector3 j, bool atEnd, List<Vector3> into, List<Vector3> tangents)
|
||||
{
|
||||
d1.Normalize();
|
||||
d2.Normalize();
|
||||
float theta = Mathf.Min(Vector3.Angle(d1, d2), 150f);
|
||||
if (theta < 2f) return;
|
||||
float half = theta * 0.5f * Mathf.Deg2Rad, th = theta * Mathf.Deg2Rad;
|
||||
float tanH = Mathf.Tan(half);
|
||||
float cut = Mathf.Min(Radius * tanH, shortest * 0.5f);
|
||||
float r = cut / tanH;
|
||||
var inward = (d2 - d1 * Vector3.Dot(d1, d2)).normalized;
|
||||
var c = j - d1 * cut + inward * r;
|
||||
int steps = Mathf.Max(2, Mathf.CeilToInt(theta * 0.5f / ArcStep));
|
||||
for (int i = 0; i <= steps; i++)
|
||||
{
|
||||
float k = (float)i / steps;
|
||||
float phi = atEnd ? th * 0.5f * k : th * 0.5f * (1f + k);
|
||||
into.Add(c - inward * r * Mathf.Cos(phi) + d1 * r * Mathf.Sin(phi));
|
||||
tangents.Add((inward * Mathf.Sin(phi) + d1 * Mathf.Cos(phi)).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An arc that leaves <paramref name="at"/> heading <paramref name="heading"/> and turns until it heads straight for
|
||||
/// <paramref name="target"/> (false: no bend needed, or no room for one).
|
||||
/// </summary>
|
||||
static bool Bow(Vector3 at, Vector3 heading, Vector3 target, List<Vector3> into)
|
||||
{
|
||||
var to = target - at;
|
||||
to.y = 0f;
|
||||
if (heading.sqrMagnitude < 1e-4f || to.sqrMagnitude < 0.25f) return false;
|
||||
float turn = Vector3.SignedAngle(heading, to, Vector3.up);
|
||||
if (Mathf.Abs(turn) < 3f || Mathf.Abs(turn) > 165f) return false;
|
||||
float s = Mathf.Sign(turn);
|
||||
float r = Mathf.Min(Radius, to.magnitude * 0.4f);
|
||||
if (r < 0.6f) return false;
|
||||
var c = at + Quaternion.AngleAxis(90f * s, Vector3.up) * heading * r;
|
||||
var w = target - c;
|
||||
w.y = 0f;
|
||||
float dist = w.magnitude;
|
||||
if (dist <= r * 1.05f) return false;
|
||||
float alpha = Mathf.Acos(r / dist) * Mathf.Rad2Deg;
|
||||
var spoke = at - c;
|
||||
var end = Vector3.zero;
|
||||
float fit = -2f;
|
||||
foreach (float sign in new[] { -1f, 1f })
|
||||
{
|
||||
var rt = Quaternion.AngleAxis(alpha * sign, Vector3.up) * (w / dist) * r;
|
||||
// which way the arc is heading where it leaves the circle
|
||||
var h = Quaternion.AngleAxis(90f * s, Vector3.up) * rt.normalized;
|
||||
float f = Vector3.Dot(h, (target - (c + rt)).normalized);
|
||||
if (f > fit) { fit = f; end = rt; }
|
||||
}
|
||||
if (fit < 0.95f) return false;
|
||||
float sweep = Vector3.SignedAngle(spoke, end, Vector3.up);
|
||||
if (sweep * s < 0f) sweep += 360f * s;
|
||||
if (Mathf.Abs(sweep) > 200f) return false;
|
||||
int steps = Mathf.Max(2, Mathf.CeilToInt(Mathf.Abs(sweep) / ArcStep));
|
||||
for (int i = 0; i <= steps; i++) into.Add(c + Quaternion.AngleAxis(sweep * i / steps, Vector3.up) * spoke);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frame at each point of the path: its direction (worked out from the neighbours where the route didn't give one),
|
||||
/// the right-hand side square to it and to the planet's up there, and the belt's own up square to both.
|
||||
/// </summary>
|
||||
void Frames(Vector3 a, Quaternion rot, Quaternion inv)
|
||||
{
|
||||
_side.Clear();
|
||||
_up.Clear();
|
||||
int n = _path.Count;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
var t = _tan[i];
|
||||
if (t.sqrMagnitude < 1e-6f)
|
||||
{
|
||||
var f = n < 2 ? Vector3.forward : _path[Mathf.Min(n - 1, i + 1)] - _path[Mathf.Max(0, i - 1)];
|
||||
t = f.sqrMagnitude > 1e-8f ? f.normalized : Vector3.forward;
|
||||
_tan[i] = t;
|
||||
}
|
||||
var planetUp = inv * Planet.Up(a + rot * _path[i]);
|
||||
var side = Vector3.Cross(planetUp, t);
|
||||
side = side.sqrMagnitude > 1e-6f ? side.normalized : Vector3.right;
|
||||
_side.Add(side);
|
||||
_up.Add(Vector3.Cross(t, side).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── the meshes ─────────────────────────
|
||||
|
||||
void Begin()
|
||||
{
|
||||
_v.Clear(); _n.Clear(); _uv.Clear(); _t.Clear();
|
||||
_xf = Matrix4x4.identity;
|
||||
}
|
||||
|
||||
void Finish(Mesh m)
|
||||
{
|
||||
m.Clear();
|
||||
m.indexFormat = _v.Count > 60000 ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16;
|
||||
m.SetVertices(_v);
|
||||
m.SetNormals(_n);
|
||||
m.SetUVs(0, _uv);
|
||||
m.SetTriangles(_t, 0);
|
||||
m.RecalculateBounds();
|
||||
_xf = Matrix4x4.identity;
|
||||
}
|
||||
|
||||
/// <summary>Square parts that follow go down d metres along the path, turned and tilted with it.</summary>
|
||||
void Along(float d)
|
||||
{
|
||||
Frame3(d, out var at, out var fwd, out var up);
|
||||
_xf = Matrix4x4.TRS(at, Quaternion.LookRotation(fwd, up), Vector3.one);
|
||||
}
|
||||
|
||||
/// <summary>The point d metres along the path in 3D, with its direction and the belt's up there.</summary>
|
||||
void Frame3(float d, out Vector3 at, out Vector3 fwd, out Vector3 up)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n == 0) { at = new Vector3(0f, 0f, d); fwd = Vector3.forward; up = Vector3.up; return; }
|
||||
int i = 1;
|
||||
while (i < n - 1 && _along[i] < d) i++;
|
||||
float k = n < 2 ? 0f : Mathf.Clamp01(Mathf.InverseLerp(_along[i - 1], _along[i], d));
|
||||
int a = n < 2 ? 0 : i - 1, b = n < 2 ? 0 : i;
|
||||
at = Vector3.Lerp(_path[a], _path[b], k);
|
||||
fwd = Vector3.Slerp(_tan[a], _tan[b], k).normalized;
|
||||
up = Vector3.Slerp(_up[a], _up[b], k).normalized;
|
||||
}
|
||||
|
||||
void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 n, Vector2 uv0, Vector2 uv1)
|
||||
{
|
||||
Face(a, b, c, d, n, n, n, n, uv0, new Vector2(uv1.x, uv0.y), uv1, new Vector2(uv0.x, uv1.y));
|
||||
}
|
||||
|
||||
/// <summary>A four-cornered face given round its edge, facing whichever way its normals say.</summary>
|
||||
void Face(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector3 na, Vector3 nb, Vector3 nc, Vector3 nd, Vector2 ua, Vector2 ub, Vector2 uc, Vector2 ud)
|
||||
{
|
||||
int i = _v.Count;
|
||||
_v.Add(_xf.MultiplyPoint3x4(a)); _v.Add(_xf.MultiplyPoint3x4(b)); _v.Add(_xf.MultiplyPoint3x4(c)); _v.Add(_xf.MultiplyPoint3x4(d));
|
||||
_n.Add(_xf.MultiplyVector(na).normalized); _n.Add(_xf.MultiplyVector(nb).normalized);
|
||||
_n.Add(_xf.MultiplyVector(nc).normalized); _n.Add(_xf.MultiplyVector(nd).normalized);
|
||||
_uv.Add(ua); _uv.Add(ub); _uv.Add(uc); _uv.Add(ud);
|
||||
if (Vector3.Dot(Vector3.Cross(b - a, c - a), na + nb + nc + nd) < 0f)
|
||||
{
|
||||
_t.Add(i); _t.Add(i + 2); _t.Add(i + 1);
|
||||
_t.Add(i); _t.Add(i + 3); _t.Add(i + 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
_t.Add(i); _t.Add(i + 1); _t.Add(i + 2);
|
||||
_t.Add(i); _t.Add(i + 2); _t.Add(i + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A bar of square section swept along the whole path, from x0 to x1 across and y0 to y1 up, its ends closed.</summary>
|
||||
bool _capStart = true, _capEnd = true;
|
||||
|
||||
void Sweep(float x0, float x1, float y0, float y1)
|
||||
{
|
||||
int n = _path.Count;
|
||||
if (n < 2) return;
|
||||
float w = (x1 - x0) * 0.8f, h = (y1 - y0) * 0.8f;
|
||||
Vector3 P(int k, float x, float y) => _path[k] + _side[k] * x + _up[k] * y;
|
||||
for (int i = 0; i + 1 < n; i++)
|
||||
{
|
||||
int j = i + 1;
|
||||
float v0 = _along[i] * 0.8f, v1 = _along[j] * 0.8f;
|
||||
var si = _side[i];
|
||||
var sj = _side[j];
|
||||
var ui = _up[i];
|
||||
var uj = _up[j];
|
||||
Face(P(i, x0, y1), P(i, x1, y1), P(j, x1, y1), P(j, x0, y1), ui, ui, uj, uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x0, y0), P(i, x1, y0), P(j, x1, y0), P(j, x0, y0), -ui, -ui, -uj, -uj, new Vector2(0f, v0), new Vector2(w, v0), new Vector2(w, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x1, y0), P(i, x1, y1), P(j, x1, y1), P(j, x1, y0), si, si, sj, sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
|
||||
Face(P(i, x0, y0), P(i, x0, y1), P(j, x0, y1), P(j, x0, y0), -si, -si, -sj, -sj, new Vector2(0f, v0), new Vector2(h, v0), new Vector2(h, v1), new Vector2(0f, v1));
|
||||
}
|
||||
foreach (int k in new[] { 0, n - 1 })
|
||||
{
|
||||
if (k == 0 ? !_capStart : !_capEnd) continue;
|
||||
var f = _tan[k] * (k == 0 ? -1f : 1f);
|
||||
Quad(P(k, x0, y0), P(k, x1, y0), P(k, x1, y1), P(k, x0, y1), f, Vector2.zero, new Vector2(w, h));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The belt itself: one strip along the path, V in metres so the texture runs round the bends with it.</summary>
|
||||
void Strip(float half)
|
||||
{
|
||||
for (int i = 0; i + 1 < _path.Count; i++)
|
||||
{
|
||||
int j = i + 1;
|
||||
Face(_path[i] - _side[i] * half, _path[i] + _side[i] * half, _path[j] + _side[j] * half, _path[j] - _side[j] * half, _up[i], _up[i], _up[j], _up[j],
|
||||
new Vector2(0f, _along[i]), new Vector2(1f, _along[i]), new Vector2(1f, _along[j]), new Vector2(0f, _along[j]));
|
||||
}
|
||||
}
|
||||
|
||||
void Box(Vector3 center, Quaternion rot, Vector3 size)
|
||||
{
|
||||
for (int axis = 0; axis < 3; axis++)
|
||||
for (int sign = -1; sign <= 1; sign += 2)
|
||||
{
|
||||
var n = Vector3.zero; n[axis] = sign;
|
||||
var u = Vector3.zero; u[(axis + 1) % 3] = 1f;
|
||||
var v = Vector3.zero; v[(axis + 2) % 3] = 1f;
|
||||
if (sign > 0) { var w = u; u = v; v = w; }
|
||||
Vector3 P(float a, float b) => center + rot * Vector3.Scale((n + u * a + v * b) * 0.5f, size);
|
||||
// the grain runs the long way and the texture keeps its scale
|
||||
var tile = new Vector2(Vector3.Scale(u, size).magnitude, Vector3.Scale(v, size).magnitude) * 0.8f;
|
||||
Quad(P(-1, -1), P(1, -1), P(1, 1), P(-1, 1), rot * n, Vector2.zero, tile);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An eight-sided roller across the belt.</summary>
|
||||
void Drum(Vector3 center, float r, float width)
|
||||
{
|
||||
const int Sides = 8;
|
||||
for (int k = 0; k < Sides; k++)
|
||||
{
|
||||
float a0 = k * Mathf.PI * 2f / Sides, a1 = (k + 1) * Mathf.PI * 2f / Sides, mid = (a0 + a1) * 0.5f;
|
||||
Vector3 P(float ang, float x) => center + new Vector3(x, Mathf.Sin(ang) * r, Mathf.Cos(ang) * r);
|
||||
Quad(P(a0, -width * 0.5f), P(a0, width * 0.5f), P(a1, width * 0.5f), P(a1, -width * 0.5f), new Vector3(0f, Mathf.Sin(mid), Mathf.Cos(mid)), Vector2.zero, Vector2.one);
|
||||
}
|
||||
}
|
||||
|
||||
public enum JointKind { Free, Belt, Port }
|
||||
|
||||
/// <summary>What an end of the run meets: nothing, another belt (which way it runs, how long it is), or a machine's port (which way things flow through it).</summary>
|
||||
public struct Joint
|
||||
{
|
||||
public JointKind kind;
|
||||
public Vector3 dir;
|
||||
public float len;
|
||||
/// <summary>A port on another belt piece: no hood over the end.</summary>
|
||||
public bool bare;
|
||||
public bool Hooded => kind == JointKind.Port && !bare;
|
||||
public bool Drum => kind == JointKind.Free || (kind == JointKind.Port && bare);
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds the meshes for a run from A to B, with the parent standing at A along the run.</summary>
|
||||
public void Fit(Vector3 a, Vector3 b) => Fit(a, b, default, default);
|
||||
|
||||
/// <summary>
|
||||
/// The same, knowing what each end meets. Bed, rails and belt are swept along one path, so a bend is one smooth piece:
|
||||
/// no wedges, no rails crossing, the belt's arrows running round it. Where it ends at a machine, a hood comes down over
|
||||
/// the end, as if the machine had drawn the belt in; a free end shows its drum.
|
||||
/// </summary>
|
||||
public void Fit(Vector3 a, Vector3 b, Joint atEnd, Joint atStart)
|
||||
{
|
||||
float len = Vector3.Distance(a, b);
|
||||
var rot = BuildRules.RunRotation(a, b);
|
||||
Route(len, a, rot, atEnd, atStart);
|
||||
float total = PathLength;
|
||||
// the belt before this one already stands a post and a bracket at the middle of the corner
|
||||
int first = atStart.kind == JointKind.Belt ? 1 : 0;
|
||||
_capStart = atStart.kind != JointKind.Belt;
|
||||
_capEnd = atEnd.kind != JointKind.Belt;
|
||||
|
||||
Begin();
|
||||
Sweep(-0.45f, 0.45f, BedLow, BedTop);
|
||||
Sweep(-RailX - 0.03f, -RailX + 0.03f, -0.05f, 0.15f);
|
||||
Sweep(RailX - 0.03f, RailX + 0.03f, -0.05f, 0.15f);
|
||||
int posts = Mathf.Max(1, Mathf.RoundToInt(total / PostEvery));
|
||||
for (int i = first; i <= posts; i++)
|
||||
{
|
||||
Frame3(total * i / posts, out var on, out var fwd, out var up);
|
||||
Post(a, rot, on + up * BedLow, fwd);
|
||||
}
|
||||
Finish(_frame);
|
||||
|
||||
Begin();
|
||||
if (atStart.Drum) { Along(0f); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
|
||||
if (atEnd.Drum) { Along(total); Drum(new Vector3(0f, -0.09f, 0f), DrumR, 0.9f); }
|
||||
int brackets = Mathf.Max(1, Mathf.RoundToInt(total / BracketEvery));
|
||||
for (int i = first; i <= brackets; i++)
|
||||
{
|
||||
Along(total * i / brackets);
|
||||
foreach (float x in new[] { -0.51f, 0.51f })
|
||||
Box(new Vector3(x, 0.05f, 0f), Quaternion.identity, new Vector3(0.02f, 0.24f, 0.09f));
|
||||
}
|
||||
if (atEnd.Hooded) { Along(total); Hood(0f, -1f); }
|
||||
if (atStart.Hooded) { Along(0f); Hood(0f, 1f); }
|
||||
Finish(_iron);
|
||||
|
||||
Begin();
|
||||
Strip(0.44f);
|
||||
Finish(_rubber);
|
||||
}
|
||||
|
||||
/// <summary>Degrees the next run turns away from this one, seen from above: + to the right.</summary>
|
||||
static float Turn(Vector3 localDir)
|
||||
{
|
||||
var flat = new Vector3(localDir.x, 0f, localDir.z);
|
||||
if (flat.sqrMagnitude < 1e-4f) return 0f;
|
||||
return Mathf.Clamp(Vector3.SignedAngle(Vector3.forward, flat, Vector3.up), -150f, 150f);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A hood over the end that meets a machine: an arch of iron hoops with a skin over them, open toward the belt, closed
|
||||
/// against the machine. <paramref name="way"/> is +1 when the hood runs on from the start, -1 back from the end.
|
||||
/// </summary>
|
||||
void Hood(float z, float way)
|
||||
{
|
||||
const int Arc = 7;
|
||||
const float R = 0.5f, Long = 0.55f;
|
||||
for (int hoop = 0; hoop <= 2; hoop++)
|
||||
{
|
||||
float hz = z + way * Long * hoop / 2f;
|
||||
for (int k = 0; k < Arc; k++)
|
||||
{
|
||||
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
|
||||
var p0 = new Vector3(Mathf.Cos(a0) * R, Mathf.Sin(a0) * R * 0.7f, hz);
|
||||
var p1 = new Vector3(Mathf.Cos(a1) * R, Mathf.Sin(a1) * R * 0.7f, hz);
|
||||
var d = p1 - p0;
|
||||
Box((p0 + p1) * 0.5f, Quaternion.LookRotation(Vector3.forward, Vector3.Cross(d, Vector3.forward)), new Vector3(d.magnitude + 0.01f, 0.04f, 0.05f));
|
||||
}
|
||||
}
|
||||
// the skin between the first and last hoop
|
||||
for (int k = 0; k < Arc; k++)
|
||||
{
|
||||
float a0 = Mathf.PI * k / Arc, a1 = Mathf.PI * (k + 1) / Arc;
|
||||
Vector3 P(float a, float zz) => new Vector3(Mathf.Cos(a) * (R - 0.02f), Mathf.Sin(a) * (R - 0.02f) * 0.7f, zz);
|
||||
var n = new Vector3(Mathf.Cos((a0 + a1) * 0.5f), Mathf.Sin((a0 + a1) * 0.5f), 0f);
|
||||
float z0 = z, z1 = z + way * Long;
|
||||
if (way > 0f) Quad(P(a0, z0), P(a1, z0), P(a1, z1), P(a0, z1), n, Vector2.zero, Vector2.one);
|
||||
else Quad(P(a1, z0), P(a0, z0), P(a0, z1), P(a1, z1), n, Vector2.zero, Vector2.one);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Two legs spread apart straight down from the bed to whatever is underneath, a low block if there's hardly any room.</summary>
|
||||
void Post(Vector3 a, Quaternion rot, Vector3 on, Vector3 fwd)
|
||||
{
|
||||
var top = a + rot * on;
|
||||
var up = Planet.Up(top);
|
||||
float drop = Planet.Altitude(top);
|
||||
const int Under = (1 << Layers.Default) | (1 << Layers.Build);
|
||||
if (Physics.Raycast(top - up * 0.2f, -up, out var hit, Mathf.Max(0.1f, drop), Under, QueryTriggerInteraction.Ignore)) drop = hit.distance + 0.2f;
|
||||
if (drop < 0.2f) return;
|
||||
var down = Quaternion.Inverse(rot) * -up;
|
||||
// square across the belt where it stands, leaning with the ground
|
||||
var stand = Quaternion.FromToRotation(Vector3.down, down) * Quaternion.LookRotation(fwd, Vector3.up);
|
||||
var at = on;
|
||||
float reach = drop;
|
||||
if (reach < 0.5f)
|
||||
{
|
||||
Box(at + down * reach * 0.5f, stand, new Vector3(0.7f, reach, 0.14f));
|
||||
return;
|
||||
}
|
||||
foreach (float side in new[] { -1f, 1f })
|
||||
{
|
||||
var from = at + stand * Vector3.right * side * 0.34f;
|
||||
var to = at + down * reach + stand * Vector3.right * side * 0.5f;
|
||||
Box((from + to) * 0.5f, Quaternion.FromToRotation(Vector3.up, from - to), new Vector3(0.11f, (from - to).magnitude, 0.11f));
|
||||
Box(to, stand, new Vector3(0.26f, 0.05f, 0.36f));
|
||||
}
|
||||
Box(at + down * reach * 0.55f, stand, new Vector3(0.84f, 0.07f, 0.06f));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Materials for what's generated at run time.</summary>
|
||||
public static class BuildLook
|
||||
{
|
||||
public static Material Mat(string name, Color fallback)
|
||||
{
|
||||
var m = AssetBank.I ? AssetBank.I.Mat(name) : null;
|
||||
return m ? m : new Material(Shader.Find("Universal Render Pipeline/Lit")) { color = fallback };
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltRun.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltRun.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c57a0b3c248f700448b75d76321f7695
|
||||
123
Assets/Scripts/Gameplay/BeltSplitter.cs
Normal file
123
Assets/Scripts/Gameplay/BeltSplitter.cs
Normal file
@ -0,0 +1,123 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A belt comes in at the back and every bundle picks its way in the middle: right, left or straight on, only ways that
|
||||
/// have something joined to them, and never one that's full, so one blocked belt doesn't hold up the others. E turns it into
|
||||
/// a sorter: one kind of cargo goes left and the rest go the other ways. The flap swings toward the way a bundle is taking.
|
||||
/// </summary>
|
||||
public class BeltSplitter : Conveyor, IJunction
|
||||
{
|
||||
const float Middle = 0.5f;
|
||||
|
||||
public Transform paddle;
|
||||
int _next;
|
||||
float _paddleAngle, _paddleTarget;
|
||||
Quaternion _paddleRest;
|
||||
Cargo _lastSeen;
|
||||
|
||||
protected override void Start()
|
||||
{
|
||||
base.Start();
|
||||
if (paddle) _paddleRest = paddle.localRotation;
|
||||
}
|
||||
|
||||
public const int Overflow = 4;
|
||||
public int ModeCount => 5;
|
||||
public string ModeName(int mode) => mode == 0 ? Loc.T("deals bundles out in turn") : mode == Overflow ? Loc.T("straight on, to the sides only when that's full") : (CargoKind)(mode - 1) == CargoKind.Grass ? Loc.T("Grass goes left, the rest the other ways") : (CargoKind)(mode - 1) == CargoKind.Hay ? Loc.T("Hay goes left, the rest the other ways") : Loc.T("Brick goes left, the rest the other ways");
|
||||
public Color ModeColor(int mode) => mode == 1 ? new Color(0.35f, 0.8f, 0.25f) : mode == 2 ? new Color(0.95f, 0.75f, 0.2f) : mode == 3 ? new Color(0.75f, 0.3f, 0.15f) : mode == Overflow ? new Color(0.25f, 0.7f, 0.95f) : Color.white;
|
||||
|
||||
// route 0 = out to the right, route 1 = out to the left, route 2 = straight on
|
||||
const int Left = 1;
|
||||
protected override int RouteCount => 3;
|
||||
protected override float Turn => Middle;
|
||||
static float Side(int route) => route == 0 ? 1f : route == Left ? -1f : 0f;
|
||||
|
||||
protected override Vector2 PathAt(float d, int route) =>
|
||||
d < Middle || route == 2 ? new Vector2(0f, d - Middle) : new Vector2(Side(route) * (d - Middle), 0f);
|
||||
|
||||
protected override int EntryRoute(Cargo c, int port) => 2;
|
||||
|
||||
protected override int RouteAt(Vector2 local, Cargo c) => local.y > -0.1f && Mathf.Abs(local.x) > 0.1f ? (local.x > 0f ? 0 : Left) : 2;
|
||||
|
||||
/// <summary>Bundles on different ways don't queue behind each other once they're past the middle.</summary>
|
||||
protected override bool Apart(Slot ahead, Slot s) => ahead.set && (s.set ? ahead.route != s.route : ahead.d > Middle + 0.1f);
|
||||
|
||||
bool Free(int route)
|
||||
{
|
||||
if (!ExitOpen(route)) return false;
|
||||
foreach (var o in Items) if (o.set && o.route == route && o.d < Middle + Spacing) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Send(Slot s, int route)
|
||||
{
|
||||
if (!Free(route)) return false;
|
||||
s.route = route;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override bool Choose(Slot s)
|
||||
{
|
||||
int mode = Mode;
|
||||
if (mode == Overflow)
|
||||
{
|
||||
// straight on first; only a full or missing way ahead spills to the sides
|
||||
if (Connected(2) && Free(2)) { s.route = 2; return true; }
|
||||
for (int k = 0; k < 2; k++)
|
||||
{
|
||||
int r = (_next + k) % 2;
|
||||
if (Connected(r) && Free(r)) { _next = (r + 1) % 2; s.route = r; return true; }
|
||||
}
|
||||
return !Connected(0) && !Connected(Left) && !Connected(2) && Send(s, 2);
|
||||
}
|
||||
if (mode > 0 && (int)s.c.kind == mode - 1) return Send(s, Left);
|
||||
bool joined = false;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
int r = (_next + k) % 3;
|
||||
if (mode > 0 && r == Left) continue;
|
||||
if (!Connected(r)) continue;
|
||||
joined = true;
|
||||
if (!Free(r)) continue;
|
||||
_next = (r + 1) % 3;
|
||||
s.route = r;
|
||||
return true;
|
||||
}
|
||||
// nothing to send it down: it waits if something is joined, and falls off the end if nothing is
|
||||
return !joined && Send(s, mode > 0 ? 0 : 2);
|
||||
}
|
||||
|
||||
protected override void Update()
|
||||
{
|
||||
base.Update();
|
||||
// every peer: watch the junction and swing the flap toward the item crossing it
|
||||
bool seen = false;
|
||||
Cargo inJunction = null;
|
||||
float side = 0f;
|
||||
foreach (var c in Cargo.All)
|
||||
{
|
||||
if (!c) continue;
|
||||
var l = transform.InverseTransformPoint(c.transform.position);
|
||||
if (Mathf.Abs(l.x) > 0.55f || Mathf.Abs(l.z) > 0.55f || l.y < -0.2f || l.y > 1.4f) continue;
|
||||
if (l.z < -0.2f) continue;
|
||||
inJunction = c;
|
||||
side = Mathf.Abs(l.x) > 0.08f ? Mathf.Sign(l.x) : 0f;
|
||||
seen = Mathf.Abs(l.x) > 0.08f || l.z > 0.08f;
|
||||
if (seen) break;
|
||||
}
|
||||
if (seen && inJunction != _lastSeen)
|
||||
{
|
||||
_lastSeen = inJunction;
|
||||
_paddleTarget = -side * 38f;
|
||||
Sfx.PlayAt("splitter_flip", transform.position + transform.up * 0.4f, 0.55f, 1f, 0.08f);
|
||||
}
|
||||
if (paddle)
|
||||
{
|
||||
_paddleAngle = Mathf.MoveTowards(_paddleAngle, _paddleTarget, Time.deltaTime * 260f);
|
||||
paddle.localRotation = Quaternion.AngleAxis(_paddleAngle, paddle.parent ? paddle.parent.InverseTransformDirection(transform.up) : Vector3.up) * _paddleRest;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BeltSplitter.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BeltSplitter.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b489ca288de487148a6ee9dbffafc403
|
||||
19
Assets/Scripts/Gameplay/Binder.cs
Normal file
19
Assets/Scripts/Gameplay/Binder.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>E hands it what's in your tool; it ties that into bundles and sends them down the belt.</summary>
|
||||
public class Binder : SiloPiece
|
||||
{
|
||||
public override string Prompt => Silo.Value >= 1f ? Loc.F("Binder: hand in your grass ({0} still to tie)", GameDefs.Kilos(Silo.Value)) : Loc.T("Binder: hand in your grass");
|
||||
public override bool CanInteract => PlayerAgent.Local && PlayerAgent.Local.Tank.Value >= 0.005f;
|
||||
|
||||
public override void Interact() => PlayerAgent.Local?.Tools.Feed(this);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Binder.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Binder.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dd2332c594051834ea5b9c29aa0a8f3d
|
||||
255
Assets/Scripts/Gameplay/BuildPiece.cs
Normal file
255
Assets/Scripts/Gameplay/BuildPiece.cs
Normal file
@ -0,0 +1,255 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A placed machine, belt or foundation. It stands wherever it was put on the ball; spawned, moved and removed by the server.</summary>
|
||||
public class BuildPiece : NetworkBehaviour
|
||||
{
|
||||
public static readonly List<BuildPiece> All = new List<BuildPiece>();
|
||||
public static event System.Action PiecesChanged;
|
||||
/// <summary>Goes up whenever something is built, moved or removed: belts look up their links again.</summary>
|
||||
public static int Version { get; private set; }
|
||||
|
||||
public PieceId piece;
|
||||
/// <summary>Belts: where the run ends. It starts at the piece's own position.</summary>
|
||||
public readonly NetworkVariable<Vector3> To = new NetworkVariable<Vector3>();
|
||||
/// <summary>Starter kit: removing it refunds nothing.</summary>
|
||||
public readonly NetworkVariable<bool> Free = new NetworkVariable<bool>();
|
||||
/// <summary>The mode E switches a junction to, saved with the build. 0 if it has none.</summary>
|
||||
public readonly NetworkVariable<int> Mode = new NetworkVariable<int>();
|
||||
/// <summary>Upgrade level, 0 (Mk I) to <see cref="GameDefs.MaxTier"/>.</summary>
|
||||
public readonly NetworkVariable<byte> Tier = new NetworkVariable<byte>();
|
||||
/// <summary>The on/off switch some pieces have: a belt stopped, a machine paused.</summary>
|
||||
public readonly NetworkVariable<byte> Opt = new NetworkVariable<byte>();
|
||||
|
||||
BeltRun _run;
|
||||
IPorts _ports;
|
||||
|
||||
public PieceDef Def => GameDefs.Piece(piece);
|
||||
/// <summary>Stays where it was put: belts lie on top of the grass, a Reaper leaves.</summary>
|
||||
bool Stands => !_run && !GetComponent<Reaper>();
|
||||
public BeltRun Run => _run;
|
||||
|
||||
/// <summary>What it cost, which is what comes back when it's removed.</summary>
|
||||
public double Price => _run ? GameDefs.BeltPrice(_run.Metres) : Def.price;
|
||||
|
||||
/// <summary>Mode, tier and option in one int for the save: the low byte is the mode, as saves from before tiers had it.</summary>
|
||||
public int Setting
|
||||
{
|
||||
get => (Mode.Value & 0xFF) | (Tier.Value << 8) | (Opt.Value << 16);
|
||||
set
|
||||
{
|
||||
Mode.Value = value & 0xFF;
|
||||
Tier.Value = (byte)Mathf.Clamp((value >> 8) & 0xFF, 0, GameDefs.MaxTier);
|
||||
Opt.Value = (byte)((value >> 16) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
public UpgradeKind Upgrades => GameDefs.UpgradeOf(piece);
|
||||
/// <summary>What the tier does to this piece's pace: belts' speed, machines' work, robots' speed and hopper, silos' output.</summary>
|
||||
public float TierMul => GameDefs.TierMul(Upgrades, Tier.Value);
|
||||
public bool Switched => Opt.Value != 0;
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void UpgradeRpc(RpcParams rpc = default)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (!ts || Upgrades == UpgradeKind.None || Tier.Value >= GameDefs.MaxTier) return;
|
||||
double price = GameDefs.UpgradePrice(this, Tier.Value);
|
||||
if (ts.Money.Value < price) { ts.DeniedRpc(RpcTarget.Single(rpc.Receive.SenderClientId, RpcTargetUse.Temp)); return; }
|
||||
ts.Money.Value -= price;
|
||||
Tier.Value++;
|
||||
UpgradedRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void UpgradedRpc()
|
||||
{
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("perk_unlock", transform.position, 0.8f);
|
||||
Tween.Scale(transform, new Vector3(1.12f, 0.85f, 1.12f), Vector3.one, 0.35f, Ease.OutBack, 0f, null);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void SwitchRpc() => Opt.Value = (byte)(Opt.Value == 0 ? 1 : 0);
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
public void NextModeRpc(int count)
|
||||
{
|
||||
if (count > 0) Mode.Value = (Mode.Value + 1) % count;
|
||||
}
|
||||
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
if (_ports == null) _ports = GetComponentInChildren<IPorts>();
|
||||
_ports?.Ports(into);
|
||||
}
|
||||
|
||||
/// <summary>The grass was laid out afresh (the ball changed size): this piece keeps it off its spot again.</summary>
|
||||
public void Reblock()
|
||||
{
|
||||
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
}
|
||||
|
||||
/// <summary>Everything looks at its neighbours again (belts fit their ends anew).</summary>
|
||||
public static void Moved() => Version++;
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
_run = GetComponentInChildren<BeltRun>();
|
||||
if (_run) _run.Lay(transform.position, To.Value);
|
||||
// grass doesn't grow through a machine
|
||||
if (Stands && Planet.Altitude(transform.position) < 1f) MowMap.BlockRound(transform.position, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
if (transform.childCount > 0 && Time.timeSinceLevelLoad > 3f)
|
||||
{
|
||||
// ports read while it bounced were off, so everything looks again once it has settled
|
||||
Tween.Scale(transform, new Vector3(1.2f, 0.4f, 1.2f), Vector3.one, 0.4f, Ease.OutBack, 0f, Touched);
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_place", transform.position, 0.9f);
|
||||
}
|
||||
Touched();
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
Fx.Build(transform.position, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_remove", transform.position, 0.9f);
|
||||
Touched();
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
public void MovedRpc(Vector3 at, Quaternion rot)
|
||||
{
|
||||
transform.SetPositionAndRotation(at, rot);
|
||||
var bot = GetComponent<Mowbot>();
|
||||
if (bot) bot.Moved(at);
|
||||
if (Stands && Planet.Altitude(at) < 1f) MowMap.BlockRound(at, Mathf.Max(Def.sizeX, Def.sizeZ) * 0.72f);
|
||||
Fx.Build(at, new Vector2(Def.sizeX, Def.sizeZ));
|
||||
Sfx.PlayAt("build_place", at, 0.9f);
|
||||
Touched();
|
||||
}
|
||||
|
||||
static void Touched()
|
||||
{
|
||||
Version++;
|
||||
PiecesChanged?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What may stand where, shared by the ghost in the player's hands and the server.</summary>
|
||||
public static class BuildRules
|
||||
{
|
||||
/// <summary>The console's `freebuild` and the test bots: standing grass stops nothing.</summary>
|
||||
public static bool AnyGround;
|
||||
public static string Uncut => Loc.T("Mow the grass here first");
|
||||
// spots under a piece that must be cut, of the 25 looked at: a stray tuft doesn't count
|
||||
const int Enough = 23;
|
||||
|
||||
static readonly Collider[] s_hits = new Collider[16];
|
||||
static readonly List<BuildPiece> s_riders = new List<BuildPiece>();
|
||||
|
||||
/// <summary>Can something start from here, on cut ground?</summary>
|
||||
public static bool CutUnder(Vector3 p) => AnyGround || MowMap.Clear(p);
|
||||
|
||||
public static Quaternion RunRotation(Vector3 a, Vector3 b) => Quaternion.LookRotation(b - a, Planet.Up((a + b) * 0.5f));
|
||||
|
||||
/// <summary>Pieces standing on a foundation: they go along when it moves and keep it from being removed. Belts stay where they are.</summary>
|
||||
public static List<BuildPiece> Riders(BuildPiece foundation)
|
||||
{
|
||||
s_riders.Clear();
|
||||
var t = foundation.transform;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || p == foundation || p.Run || GameDefs.IsFoundation(p.piece)) continue;
|
||||
// the position, not the bouncing scale: a piece just put down is still squashed
|
||||
var l = Quaternion.Inverse(t.rotation) * (p.transform.position - t.position);
|
||||
if (Mathf.Abs(l.x) < 2f && Mathf.Abs(l.z) < 2f && Mathf.Abs(l.y - Foundation.TopOf(foundation.piece)) < 0.4f) s_riders.Add(p);
|
||||
}
|
||||
return s_riders;
|
||||
}
|
||||
|
||||
static bool Reserved(Vector3 p)
|
||||
{
|
||||
foreach (var b in GridBlocker.All) if (b.Covers(p)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool Clear(Vector3 center, Vector3 half, Quaternion rot, BuildPiece moving, out string reason)
|
||||
{
|
||||
const int Mask = (1 << Layers.Default) | (1 << Layers.Vehicle) | (1 << Layers.Build);
|
||||
int n = Physics.OverlapBoxNonAlloc(center, half, s_hits, rot, Mask, QueryTriggerInteraction.Ignore);
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
if (s_hits[i].GetComponentInParent<DeckTileView>()) continue;
|
||||
var p = s_hits[i].GetComponentInParent<BuildPiece>();
|
||||
if (moving && p && (p == moving || Riders(moving).Contains(p))) continue;
|
||||
reason = p ? Loc.F("{0} is in the way", p.Def.name) : s_hits[i].GetComponentInParent<Vehicle>() ? Loc.T("A machine is parked here") : Loc.T("Something is in the way");
|
||||
return false;
|
||||
}
|
||||
reason = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Can a piece stand here? A piece being moved doesn't get in its own way.</summary>
|
||||
public static bool CanPlace(PieceDef d, Vector3 at, Quaternion rot, BuildPiece moving, out string reason)
|
||||
{
|
||||
float hx = d.sizeX * 0.5f, hz = d.sizeZ * 0.5f;
|
||||
var r = rot * Vector3.right * hx;
|
||||
var f = rot * Vector3.forward * hz;
|
||||
if (Reserved(at) || Reserved(at + r + f) || Reserved(at + r - f) || Reserved(at - r + f) || Reserved(at - r - f))
|
||||
{
|
||||
reason = Loc.T("That's where a base building stands");
|
||||
return false;
|
||||
}
|
||||
bool slab = GameDefs.IsFoundation(d.id);
|
||||
// a hair more than half a wall's thickness: what fills a room (stairs end to end) may touch its walls
|
||||
var half = new Vector3(hx - (slab ? 0.3f : 0.12f), slab ? 0.2f : 0.6f, hz - (slab ? 0.3f : 0.12f));
|
||||
if (GameDefs.FitOf(d.id) == Fit.Edge) half = new Vector3(hx - 0.2f, 0.6f, 0.05f);
|
||||
if (!Clear(at + rot * Vector3.up * (half.y + 0.12f), half, rot, moving, out reason)) return false;
|
||||
// what stands on a foundation stands on what's under the foundation
|
||||
if (AnyGround || Planet.Altitude(at) > 0.2f) return true;
|
||||
int cut = 0;
|
||||
for (int x = -2; x <= 2; x++)
|
||||
for (int z = -2; z <= 2; z++)
|
||||
if (MowMap.Clear(at + r * x * 0.45f + f * z * 0.45f)) cut++;
|
||||
if (cut >= Enough) return true;
|
||||
reason = Loc.F("Mow the grass here first: {0}% cut", cut * 4);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Can a belt run from A to B?</summary>
|
||||
public static bool CanRun(Vector3 a, Vector3 b, out string reason)
|
||||
{
|
||||
float len = Vector3.Distance(a, b);
|
||||
if (len < GameDefs.BeltShortest) { reason = Loc.T("Too short"); return false; }
|
||||
if (len > GameDefs.BeltLongest) { reason = Loc.F("Too long: belts are up to {0:0} m", GameDefs.BeltLongest); return false; }
|
||||
var dir = (b - a) / len;
|
||||
var up = Planet.Up((a + b) * 0.5f);
|
||||
if (Mathf.Abs(Vector3.Dot(dir, up)) > Mathf.Sin(GameDefs.BeltSteepest * Mathf.Deg2Rad)) { reason = Loc.T("Too steep"); return false; }
|
||||
if (BeltNet.Taken(b)) { reason = Loc.T("A belt already ends here"); return false; }
|
||||
int spots = 0, uncut = 0;
|
||||
for (float z = 0f; z <= len; z += 1f)
|
||||
{
|
||||
var p = a + dir * z;
|
||||
if (Reserved(p)) { reason = Loc.T("That's where a base building stands"); return false; }
|
||||
if (Planet.Altitude(p) < 0.05f) { reason = Loc.T("The ground is in the way"); return false; }
|
||||
spots++;
|
||||
if (!MowMap.Clear(p)) uncut++;
|
||||
}
|
||||
if (!AnyGround && uncut * 6 > spots) { reason = Loc.T("Mow a path for the belt first"); return false; }
|
||||
if (len < 1.3f) { reason = null; return true; }
|
||||
// the ends may touch what they're joined to
|
||||
return Clear((a + b) * 0.5f, new Vector3(0.42f, 0.2f, len * 0.5f - 0.6f), RunRotation(a, b), null, out reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/BuildPiece.cs.meta
Normal file
2
Assets/Scripts/Gameplay/BuildPiece.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b8baa8ad05bf317418f3c510defc8b7e
|
||||
95
Assets/Scripts/Gameplay/Cargo.cs
Normal file
95
Assets/Scripts/Gameplay/Cargo.cs
Normal file
@ -0,0 +1,95 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A shippable item: grass bundle, hay or pressed brick. Physics + Grabbable carry it around; when it tumbles off the
|
||||
/// deck it lands in the meadow with a puff of clippings. A depot takes it the moment it drops in.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(Grabbable))]
|
||||
public class Cargo : NetworkBehaviour
|
||||
{
|
||||
public static readonly List<Cargo> All = new List<Cargo>();
|
||||
|
||||
public CargoKind kind;
|
||||
/// <summary>Half height (ground contact checks).</summary>
|
||||
public float halfHeight = 0.33f;
|
||||
public readonly NetworkVariable<float> Kg = new NetworkVariable<float>(GameDefs.BundleKg);
|
||||
|
||||
Grabbable _g;
|
||||
bool _wasInGrass;
|
||||
public bool Loaded { get; set; }
|
||||
/// <summary>Server: the belt this item is locked onto (null when loose).</summary>
|
||||
public Conveyor Belt { get; set; }
|
||||
public Grabbable Grab => _g ? _g : (_g = GetComponent<Grabbable>());
|
||||
|
||||
void Awake() { _g = GetComponent<Grabbable>(); }
|
||||
|
||||
/// <summary>Server: unlock from the belt and become a loose physics body again.</summary>
|
||||
public void ServerLeaveBelt(Vector3 velocity)
|
||||
{
|
||||
if (Belt) Belt.ServerRemove(this, velocity);
|
||||
}
|
||||
|
||||
/// <summary>E at the depot or a machine with this bundle in your arms.</summary>
|
||||
[Rpc(SendTo.Server)]
|
||||
public void HandInRpc(ulong piece, RpcParams rpc = default)
|
||||
{
|
||||
if (Grab.Holder.Value != rpc.Receive.SenderClientId || Grab.Consumed) return;
|
||||
if (!NetworkManager.SpawnManager.SpawnedObjects.TryGetValue(piece, out var no)) return;
|
||||
var sink = no.GetComponentInChildren<ICargoSink>();
|
||||
if (sink == null || (transform.position - no.transform.position).sqrMagnitude > 49f) return;
|
||||
Grab.ServerForceRelease();
|
||||
sink.ServerAccept(this, transform.position, Vector3.down);
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
if (Time.timeSinceLevelLoad > 3f) Tween.Scale(transform, Vector3.one * 0.3f, Vector3.one, 0.35f, Ease.OutBack);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (Belt) { Belt.ServerRemove(this, Vector3.zero); Belt = null; }
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
float _fallV;
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
var rb = _g.Body;
|
||||
var p = transform.position;
|
||||
|
||||
// tossed into a depot
|
||||
if (IsServer && !_g.IsHeld && !_g.Consumed && !Belt)
|
||||
foreach (var d in Depot.All)
|
||||
if (d && (p - d.Mouth).sqrMagnitude < 1.1f) { d.ServerAccept(this, p, Vector3.down); return; }
|
||||
|
||||
var up = Planet.Up(p);
|
||||
bool inGrass = Planet.Altitude(p) - halfHeight < 0.25f;
|
||||
// thump into the meadow: a puff of clippings
|
||||
if (inGrass && !_wasInGrass && _fallV < -2.5f)
|
||||
{
|
||||
Fx.Splash(Planet.Surface(p), Mathf.Clamp01(-_fallV / 10f) + 0.3f);
|
||||
Sfx.PlayAt(_fallV < -6f ? "splash_big" : "splash_small", p, 0.8f, 1.1f, 0.1f);
|
||||
}
|
||||
_wasInGrass = inGrass;
|
||||
_fallV = rb.isKinematic ? 0f : Vector3.Dot(rb.linearVelocity, up);
|
||||
if (!IsOwner || rb.isKinematic || _g.IsHeld || !inGrass) return;
|
||||
// the thick grass brakes rolling cargo
|
||||
rb.AddForce(-Vector3.ProjectOnPlane(rb.linearVelocity, up) * 2.2f, ForceMode.Acceleration);
|
||||
rb.angularVelocity *= 0.96f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Cargo.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Cargo.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 674efdadb118e3e45bd8298e372b4789
|
||||
50
Assets/Scripts/Gameplay/Catcher.cs
Normal file
50
Assets/Scripts/Gameplay/Catcher.cs
Normal file
@ -0,0 +1,50 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Catches what a Reaper shoots from anywhere on the planet and puts it on the belt.</summary>
|
||||
public class Catcher : SiloPiece
|
||||
{
|
||||
const float Room = 100f;
|
||||
|
||||
static readonly List<Catcher> s_all = new List<Catcher>();
|
||||
|
||||
public override string Prompt => Loc.F("Bundle Catcher: {0} of {1}", GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room));
|
||||
|
||||
public override void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public override void OnNetworkSpawn() => s_all.Add(this);
|
||||
public override void OnNetworkDespawn() => s_all.Remove(this);
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
s_all.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
/// <summary>The emptiest catcher that still has room.</summary>
|
||||
public static Catcher WithRoom()
|
||||
{
|
||||
Catcher best = null;
|
||||
foreach (var c in s_all)
|
||||
if (c && c.Silo.Value + GameDefs.BundleKg <= Room && (!best || c.Silo.Value < best.Silo.Value)) best = c;
|
||||
return best;
|
||||
}
|
||||
|
||||
public void ServerCatch(float kg)
|
||||
{
|
||||
Silo.Value += kg;
|
||||
CaughtRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void CaughtRpc() => Sfx.PlayAt("cargo_load", transform.position, 0.5f, 1f, 0.1f, 0.4f);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Catcher.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Catcher.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bd7c57c2d64397347bdd44709fca3a70
|
||||
536
Assets/Scripts/Gameplay/Conveyor.cs
Normal file
536
Assets/Scripts/Gameplay/Conveyor.cs
Normal file
@ -0,0 +1,536 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>Where cargo enters or leaves a piece, in world space.</summary>
|
||||
public struct Port
|
||||
{
|
||||
public Vector3 at, dir;
|
||||
public bool input;
|
||||
}
|
||||
|
||||
/// <summary>Anything with ports a belt can be joined to.</summary>
|
||||
public interface IPorts
|
||||
{
|
||||
void Ports(List<Port> into);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A belt with a real queue. Cargo that lands on it locks onto the centre line (server-owned, kinematic) and rides along
|
||||
/// a fixed path at belt speed, keeping <see cref="Spacing"/> to the item ahead. At the end it is handed to whatever stands
|
||||
/// at the exit: the next belt, a machine's port, a belt it runs into from the side, or dropped off onto the ground. If
|
||||
/// none of those can take it right now it simply waits at the end and the line behind it queues up. No piles, no jams.
|
||||
/// </summary>
|
||||
public class Conveyor : MonoBehaviour, IPorts
|
||||
{
|
||||
public float speed = 1.6f;
|
||||
/// <summary>Built belts follow the team's Fast Belts perk instead of a fixed speed.</summary>
|
||||
public bool usePerkSpeed;
|
||||
/// <summary>Belt texture repeats per metre of belt (matches the material's V tiling).</summary>
|
||||
public float uvPerMetre = 2f;
|
||||
public Renderer[] belts;
|
||||
|
||||
/// <summary>Gap between item centres along the belt.</summary>
|
||||
public const float Spacing = 0.58f;
|
||||
/// <summary>Height of a junction's surface above what it stands on.</summary>
|
||||
public const float Top = 0.35f;
|
||||
|
||||
protected class Slot
|
||||
{
|
||||
public Cargo c;
|
||||
public float d;
|
||||
public int route;
|
||||
public Vector3 from;
|
||||
public float blend;
|
||||
/// <summary>Has it settled which way it's going?</summary>
|
||||
public bool set;
|
||||
}
|
||||
|
||||
struct Link
|
||||
{
|
||||
public Conveyor belt;
|
||||
public int port;
|
||||
public bool side;
|
||||
public float at;
|
||||
public ICargoSink sink;
|
||||
}
|
||||
|
||||
public static readonly List<Conveyor> All = new List<Conveyor>();
|
||||
|
||||
/// <summary>Front of the belt first (largest d).</summary>
|
||||
protected readonly List<Slot> Items = new List<Slot>();
|
||||
MaterialPropertyBlock _mpb;
|
||||
float _offset;
|
||||
BuildPiece _piece;
|
||||
Link[] _links;
|
||||
int _found, _linkVersion = -1;
|
||||
static readonly int BaseMapST = Shader.PropertyToID("_BaseMap_ST");
|
||||
static readonly List<Port> s_out = new List<Port>();
|
||||
static readonly Collider[] s_hits = new Collider[8];
|
||||
|
||||
public float Speed => Piece && Piece.Switched ? 0f : (usePerkSpeed && TeamState.Instance ? GameDefs.BeltSpeed : speed) * (Piece ? Piece.TierMul : 1f);
|
||||
public BuildPiece Piece => _piece ? _piece : (_piece = GetComponentInParent<BuildPiece>());
|
||||
public int Count => Items.Count;
|
||||
protected int Mode => Piece ? Piece.Mode.Value : 0;
|
||||
/// <summary>Could something come in through a port right now?</summary>
|
||||
public bool HasRoom => MinD >= Spacing;
|
||||
protected static bool Server => NetworkManager.Singleton && NetworkManager.Singleton.IsServer;
|
||||
|
||||
protected virtual void Start() { _mpb = new MaterialPropertyBlock(); }
|
||||
void OnEnable() { All.Add(this); }
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
All.Remove(this);
|
||||
// the piece is going away: whatever rides on it falls off where it is
|
||||
if (Server) for (int i = Items.Count - 1; i >= 0; i--) Release(Items[i], transform.up * 0.5f);
|
||||
Items.Clear();
|
||||
}
|
||||
|
||||
protected virtual void Update()
|
||||
{
|
||||
if (belts == null || belts.Length == 0 || _mpb == null) return;
|
||||
// belt meshes carry V in metres and run +V along the flow
|
||||
_offset = Mathf.Repeat(_offset - Speed * Time.deltaTime * uvPerMetre, 1f);
|
||||
foreach (var b in belts)
|
||||
{
|
||||
if (!b) continue;
|
||||
b.GetPropertyBlock(_mpb);
|
||||
_mpb.SetVector(BaseMapST, new Vector4(1, uvPerMetre, 0, _offset));
|
||||
b.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── path (local XZ, +Z = flow) ─────────────────────────
|
||||
|
||||
protected virtual int RouteCount => 1;
|
||||
|
||||
/// <summary>Height of the moving surface in local space.</summary>
|
||||
protected virtual float Surface => Top;
|
||||
|
||||
/// <summary>Does this belt take items from the side?</summary>
|
||||
protected virtual bool Sides => false;
|
||||
|
||||
protected virtual float Length(int route) => 1f;
|
||||
|
||||
/// <summary>Point on the centre line, d metres from where items come in.</summary>
|
||||
protected virtual Vector2 PathAt(float d, int route) => new Vector2(0f, d - 0.5f);
|
||||
|
||||
/// <summary>How far the centre line rises above the piece's own level d metres along (a belt that rounds over a crest).</summary>
|
||||
protected virtual float HeightAt(float d, int route) => 0f;
|
||||
|
||||
/// <summary>Server: route for an item that comes in through a port.</summary>
|
||||
protected virtual int EntryRoute(Cargo c, int port) => 0;
|
||||
|
||||
/// <summary>Server: route for an item dropped onto the belt at a local point.</summary>
|
||||
protected virtual int RouteAt(Vector2 local, Cargo c) => EntryRoute(c, 0);
|
||||
|
||||
/// <summary>Server: is it this port's turn to send something in?</summary>
|
||||
protected virtual bool Takes(int port) => true;
|
||||
|
||||
/// <summary>How far along an item goes before it has to settle on a route.</summary>
|
||||
protected virtual float Turn => 0f;
|
||||
|
||||
/// <summary>Server: an item at the turn settles on a route, or waits there (false).</summary>
|
||||
protected virtual bool Choose(Slot s) => true;
|
||||
|
||||
/// <summary>Items on separate ways don't keep their distance.</summary>
|
||||
protected virtual bool Apart(Slot ahead, Slot s) => false;
|
||||
|
||||
/// <summary>Is anything joined to the end of this route?</summary>
|
||||
protected bool Connected(int route)
|
||||
{
|
||||
var l = LinkOf(route);
|
||||
return l.belt || l.sink != null;
|
||||
}
|
||||
|
||||
/// <summary>The point of the path nearest to somewhere in the world, for the sound.</summary>
|
||||
public Vector3 NearestPoint(Vector3 world)
|
||||
{
|
||||
var p = ToLocal(world);
|
||||
Project(new Vector2(p.x, p.z), out int route, out float d);
|
||||
return WorldOnPath(d, route, 0f);
|
||||
}
|
||||
|
||||
public virtual void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(new Port { at = WorldOnPath(0f, 0, 0f), dir = Tangent(0f, 0), input = true });
|
||||
for (int r = 0; r < RouteCount; r++)
|
||||
{
|
||||
float L = Length(r);
|
||||
into.Add(new Port { at = WorldOnPath(L, r, 0f), dir = Tangent(L, r) });
|
||||
}
|
||||
}
|
||||
|
||||
protected Vector3 WorldOnPath(float d, int route, float lift)
|
||||
{
|
||||
var l = PathAt(d, route);
|
||||
return transform.position + transform.rotation * new Vector3(l.x, Surface + lift + HeightAt(d, route), l.y);
|
||||
}
|
||||
|
||||
/// <summary>Where the other end of a route meets whatever it hands over to.</summary>
|
||||
protected virtual Vector3 ExitAt(int route) => WorldOnPath(Length(route), route, 0f);
|
||||
|
||||
// a piece that has just landed is still bouncing: its scale says nothing about where the path runs
|
||||
Vector3 ToLocal(Vector3 world) => Quaternion.Inverse(transform.rotation) * (world - transform.position);
|
||||
|
||||
protected Vector3 Tangent(float d, int route)
|
||||
{
|
||||
float L = Length(route);
|
||||
float d0 = Mathf.Clamp(d - 0.02f, 0f, L), d1 = Mathf.Clamp(d + 0.02f, 0f, L);
|
||||
var a = PathAt(d0, route);
|
||||
var b = PathAt(d1, route);
|
||||
var t = transform.TransformDirection(new Vector3(b.x - a.x, HeightAt(d1, route) - HeightAt(d0, route), b.y - a.y));
|
||||
return t.sqrMagnitude > 1e-6f ? t.normalized : transform.forward;
|
||||
}
|
||||
|
||||
/// <summary>Nearest point on any route to a local point.</summary>
|
||||
protected virtual void Project(Vector2 local, out int route, out float d)
|
||||
{
|
||||
route = 0; d = 0f;
|
||||
float best = float.MaxValue;
|
||||
for (int r = 0; r < RouteCount; r++)
|
||||
{
|
||||
float L = Length(r);
|
||||
for (int k = 0; k <= 16; k++)
|
||||
{
|
||||
float dd = L * k / 16f;
|
||||
float e = (PathAt(dd, r) - local).sqrMagnitude;
|
||||
if (e < best) { best = e; route = r; d = dd; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool FreeAt(float d)
|
||||
{
|
||||
foreach (var s in Items) if (Mathf.Abs(s.d - d) < Spacing) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
float MinD => Items.Count > 0 ? Items[Items.Count - 1].d : float.MaxValue;
|
||||
|
||||
// ───────────────────────── what stands at the exit ─────────────────────────
|
||||
|
||||
/// <summary>Links are looked up the first time they're needed after anything was built, moved or removed.</summary>
|
||||
Link LinkOf(int route)
|
||||
{
|
||||
if (_links == null) _links = new Link[RouteCount];
|
||||
if (_linkVersion != BuildPiece.Version)
|
||||
{
|
||||
_linkVersion = BuildPiece.Version;
|
||||
_found = 0;
|
||||
}
|
||||
if ((_found >> route & 1) == 0)
|
||||
{
|
||||
_links[route] = Find(route);
|
||||
_found |= 1 << route;
|
||||
}
|
||||
return _links[route];
|
||||
}
|
||||
|
||||
Link Find(int route)
|
||||
{
|
||||
var end = ExitAt(route);
|
||||
if (BeltNet.Nearest(end, true, BeltNet.Joined, Piece, out var piece, out int port, out _))
|
||||
{
|
||||
var conv = piece.GetComponentInChildren<Conveyor>();
|
||||
if (conv) return new Link { belt = conv, port = port };
|
||||
var sink = piece.GetComponentInChildren<ICargoSink>();
|
||||
if (sink != null) return new Link { sink = sink };
|
||||
}
|
||||
foreach (var b in All)
|
||||
{
|
||||
if (b == this || !b.Sides) continue;
|
||||
var l = b.ToLocal(end);
|
||||
if (Mathf.Abs(l.x) < 0.6f && Mathf.Abs(l.y) < 0.6f && l.z > 0.3f && l.z < b.Length(0) - 0.3f) return new Link { belt = b, side = true, at = l.z };
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
/// <summary>Could the exit of this route take an item right now?</summary>
|
||||
protected bool ExitOpen(int route)
|
||||
{
|
||||
var l = LinkOf(route);
|
||||
return !l.belt || (l.side ? l.belt.FreeAt(l.at) : l.belt.MinD >= Spacing);
|
||||
}
|
||||
|
||||
// ───────────────────────── server API ─────────────────────────
|
||||
|
||||
/// <summary>Could an item be put on this belt at a world point right now?</summary>
|
||||
public bool CanInsert(Vector3 world)
|
||||
{
|
||||
var p = ToLocal(world);
|
||||
Project(new Vector2(p.x, p.z), out _, out float d);
|
||||
return FreeAt(d);
|
||||
}
|
||||
|
||||
/// <summary>Server: lock an item onto the belt at the nearest point of its path (false: no room there yet).</summary>
|
||||
public bool ServerTryInsert(Cargo c, Vector3 world)
|
||||
{
|
||||
if (!Server || !c || !c.IsSpawned || c.Belt) return false;
|
||||
var p = ToLocal(world);
|
||||
var local = new Vector2(p.x, p.z);
|
||||
Project(local, out int route, out float d);
|
||||
if (!FreeAt(d)) return false;
|
||||
route = RouteCount > 1 ? RouteAt(local, c) : route;
|
||||
Insert(c, d, route);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Server: accept an item handed over through a port.</summary>
|
||||
public bool ServerAcceptPort(Cargo c, int port)
|
||||
{
|
||||
bool turn = Takes(port);
|
||||
if (!turn || MinD < Spacing) return false;
|
||||
Insert(c, 0f, EntryRoute(c, port));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Server: accept an item from a belt that runs into this one's side.</summary>
|
||||
bool ServerSideLoad(Cargo c, float d)
|
||||
{
|
||||
if (!FreeAt(d)) return false;
|
||||
Insert(c, d, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Insert(Cargo c, float d, int route)
|
||||
{
|
||||
var g = c.Grab;
|
||||
if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId);
|
||||
g.Body.linearVelocity = Vector3.zero;
|
||||
g.Body.isKinematic = true;
|
||||
c.Belt = this;
|
||||
var s = new Slot { c = c, d = d, route = route, from = c.transform.position, blend = 0f, set = d > Turn };
|
||||
int i = 0;
|
||||
while (i < Items.Count && Items[i].d > d) i++;
|
||||
Items.Insert(i, s);
|
||||
}
|
||||
|
||||
/// <summary>Server: take an item off this belt (a player grabbed it, it got despawned).</summary>
|
||||
public void ServerRemove(Cargo c, Vector3 velocity)
|
||||
{
|
||||
for (int i = 0; i < Items.Count; i++)
|
||||
if (Items[i].c == c) { var s = Items[i]; Items.RemoveAt(i); Release(s, velocity); return; }
|
||||
if (c && c.Belt == this) c.Belt = null;
|
||||
}
|
||||
|
||||
void Release(Slot s, Vector3 velocity)
|
||||
{
|
||||
var c = s.c;
|
||||
if (!c) return;
|
||||
if (c.Belt == this) c.Belt = null;
|
||||
if (!c.IsSpawned) return;
|
||||
var rb = c.Grab.Body;
|
||||
rb.isKinematic = false;
|
||||
rb.linearVelocity = velocity;
|
||||
rb.angularVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
// ───────────────────────── simulation (server) ─────────────────────────
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!Server || !Piece || !Piece.IsSpawned || Items.Count == 0) return;
|
||||
float dt = Time.fixedDeltaTime;
|
||||
float step = Speed * dt;
|
||||
for (int i = 0; i < Items.Count; i++)
|
||||
{
|
||||
var s = Items[i];
|
||||
if (!s.c || !s.c.IsSpawned || s.c.Loaded || s.c.Belt != this || s.c.Grab.IsHeld)
|
||||
{
|
||||
Items.RemoveAt(i--);
|
||||
if (s.c && s.c.Belt == this) s.c.Belt = null;
|
||||
continue;
|
||||
}
|
||||
float L = Length(s.route);
|
||||
float limit = Room(i, ref L);
|
||||
if (s.d < limit) s.d = Mathf.Min(s.d + step, limit);
|
||||
if ((i == 0 || RouteCount > 1) && s.d >= L - 1e-4f && HandOff(s))
|
||||
{
|
||||
Items.RemoveAt(i--);
|
||||
continue;
|
||||
}
|
||||
Place(s, dt);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var s = Items[i];
|
||||
float limit = L;
|
||||
if (!s.set)
|
||||
{
|
||||
if (s.d < Turn - 1e-4f || !Choose(s)) limit = Turn;
|
||||
else
|
||||
{
|
||||
s.set = true;
|
||||
L = limit = Length(s.route);
|
||||
}
|
||||
}
|
||||
for (int k = i - 1; k >= 0; k--)
|
||||
{
|
||||
if (Apart(Items[k], s)) continue;
|
||||
return Mathf.Min(limit, Items[k].d - Spacing);
|
||||
}
|
||||
return limit;
|
||||
}
|
||||
|
||||
void Place(Slot s, float dt)
|
||||
{
|
||||
var c = s.c;
|
||||
var rb = c.Grab.Body;
|
||||
var target = WorldOnPath(s.d, s.route, c.halfHeight);
|
||||
s.blend = Mathf.MoveTowards(s.blend, 1f, dt * 6f);
|
||||
var pos = s.blend < 1f ? Vector3.Lerp(s.from, target, Easing.Apply(Ease.OutCubic, s.blend)) : target;
|
||||
// square the item up with the flow
|
||||
var want = Quaternion.LookRotation(Tangent(s.d, s.route), transform.up);
|
||||
var rot = Quaternion.RotateTowards(rb.rotation, want, 540f * dt);
|
||||
rb.MovePosition(pos);
|
||||
rb.MoveRotation(rot);
|
||||
}
|
||||
|
||||
/// <summary>The front item reached the end of its route: pass it on if anything can take it.</summary>
|
||||
bool HandOff(Slot s)
|
||||
{
|
||||
var c = s.c;
|
||||
float L = Length(s.route);
|
||||
var link = LinkOf(s.route);
|
||||
var dir = Tangent(L, s.route);
|
||||
if (link.belt)
|
||||
{
|
||||
c.Belt = null;
|
||||
if (link.side ? link.belt.ServerSideLoad(c, link.at) : link.belt.ServerAcceptPort(c, link.port)) return true;
|
||||
c.Belt = this;
|
||||
return false;
|
||||
}
|
||||
if (link.sink != null)
|
||||
{
|
||||
c.Belt = null;
|
||||
var rb = c.Grab.Body;
|
||||
if (link.sink.ServerAccept(c, WorldOnPath(L, s.route, c.halfHeight), dir)) return true;
|
||||
c.Belt = this;
|
||||
rb.isKinematic = true;
|
||||
return false;
|
||||
}
|
||||
// nothing there: drop it off the end, but only onto a free spot (one item waits there at a time)
|
||||
var land = WorldOnPath(L, s.route, 0f) + dir * 0.45f;
|
||||
int n = Physics.OverlapSphereNonAlloc(land, 0.3f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore);
|
||||
for (int k = 0; k < n; k++)
|
||||
{
|
||||
var other = s_hits[k].GetComponentInParent<Cargo>();
|
||||
if (other && other != c) return false;
|
||||
}
|
||||
Release(s, dir * Mathf.Max(1.2f, Speed) + transform.up * 0.4f);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ───────────────────────── catching loose cargo ─────────────────────────
|
||||
|
||||
protected void OnTriggerStay(Collider other)
|
||||
{
|
||||
if (!Server) return;
|
||||
var rb = other.attachedRigidbody;
|
||||
if (!rb) return;
|
||||
var c = rb.GetComponent<Cargo>();
|
||||
if (!c || !c.IsSpawned || c.Belt || c.Loaded || c.Grab.IsHeld || c.Grab.Consumed) return;
|
||||
// still flying up from a throw: let it come down first
|
||||
if (Vector3.Dot(rb.linearVelocity, transform.up) > 1.5f) return;
|
||||
if (transform.InverseTransformPoint(c.transform.position).y - c.halfHeight > Surface + 0.8f) return;
|
||||
ServerTryInsert(c, c.transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A piece that swallows cargo handed to it by a belt or a machine.</summary>
|
||||
public interface ICargoSink
|
||||
{
|
||||
/// <summary>Server: take the item (true) or refuse it for now (false: it waits).</summary>
|
||||
bool ServerAccept(Cargo c, Vector3 from, Vector3 dir);
|
||||
}
|
||||
|
||||
/// <summary>Finding ports among everything that's built.</summary>
|
||||
public static class BeltNet
|
||||
{
|
||||
/// <summary>A belt end this close to a port feeds it. Laying one snaps it exactly, so this only forgives rounding.</summary>
|
||||
public const float Joined = 0.4f;
|
||||
/// <summary>How close to a port you have to aim for a belt to snap onto it.</summary>
|
||||
public const float Snap = 1.2f;
|
||||
|
||||
static readonly List<Port> s_list = new List<Port>();
|
||||
static readonly List<Port> s_out = new List<Port>();
|
||||
static readonly Collider[] s_hits = new Collider[8];
|
||||
|
||||
public static bool Nearest(Vector3 near, bool input, float within, BuildPiece skip, out BuildPiece piece, out int index, out Port port)
|
||||
{
|
||||
piece = null; index = -1; port = default;
|
||||
float best = within * within;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || p == skip || !p.IsSpawned) continue;
|
||||
s_list.Clear();
|
||||
p.Ports(s_list);
|
||||
for (int i = 0; i < s_list.Count; i++)
|
||||
{
|
||||
if (s_list[i].input != input) continue;
|
||||
float d = (s_list[i].at - near).sqrMagnitude;
|
||||
if (d >= best) continue;
|
||||
best = d; piece = p; index = i; port = s_list[i];
|
||||
}
|
||||
}
|
||||
return piece;
|
||||
}
|
||||
|
||||
/// <summary>Server: one kilo leaves a machine through a port, onto the belt there or, with no belt, onto clear ground.</summary>
|
||||
public static bool Send(BuildPiece from, Port way, CargoKind kind)
|
||||
{
|
||||
Conveyor belt = null;
|
||||
int port = 0;
|
||||
if (Nearest(way.at, true, Joined, from, out var next, out int index, out _))
|
||||
{
|
||||
belt = next.GetComponentInChildren<Conveyor>();
|
||||
port = index;
|
||||
if (belt && !belt.HasRoom) return false;
|
||||
}
|
||||
else if (Physics.OverlapSphereNonAlloc(way.at + way.dir * 0.5f, 0.45f, s_hits, 1 << Layers.Prop, QueryTriggerInteraction.Ignore) > 0) return false;
|
||||
var made = Spawner.Instance.SpawnCargo(kind, way.at + way.dir * 0.2f + from.transform.up * 0.35f, from.transform.rotation, way.dir * 1.6f);
|
||||
if (!made) return false;
|
||||
if (belt) belt.ServerAcceptPort(made, port);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A port at the front of a piece, just clear of its solid box.</summary>
|
||||
public static Port Front(Transform piece)
|
||||
{
|
||||
var box = piece.Find("Solid")?.GetComponent<BoxCollider>();
|
||||
float reach = box ? box.transform.localPosition.z + box.size.z * 0.5f + 0.25f : 1.7f;
|
||||
return new Port { at = piece.position + piece.up * GameDefs.BeltLowest + piece.forward * reach, dir = piece.forward };
|
||||
}
|
||||
|
||||
/// <summary>Server: one kilo out of a silo, through whichever port has room. Ports take turns.</summary>
|
||||
public static bool Drain(BuildPiece from, NetworkVariable<float> silo, ref int turn)
|
||||
{
|
||||
if (silo.Value < 1f) return false;
|
||||
s_out.Clear();
|
||||
from.Ports(s_out);
|
||||
for (int i = 0; i < s_out.Count; i++)
|
||||
{
|
||||
turn = (turn + 1) % s_out.Count;
|
||||
if (s_out[turn].input || !Send(from, s_out[turn], CargoKind.Grass)) continue;
|
||||
silo.Value -= 1f;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Does a belt already end here?</summary>
|
||||
public static bool Taken(Vector3 at)
|
||||
{
|
||||
foreach (var c in Conveyor.All)
|
||||
if (c is BeltRun r && (r.End - at).sqrMagnitude < Joined * Joined) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Conveyor.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Conveyor.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 934f648461a295a448cd209fc420d5b9
|
||||
62
Assets/Scripts/Gameplay/Depot.cs
Normal file
62
Assets/Scripts/Gameplay/Depot.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Where grass leaves for Earth: E empties the tool in your hands at once or takes the bundle in your arms, thrown
|
||||
/// bundles and bundles arriving on a belt are paid for the moment they drop in. The HUD writes out a receipt.
|
||||
/// </summary>
|
||||
public class Depot : MonoBehaviour, IInteractable, ICargoSink, IPorts
|
||||
{
|
||||
public static readonly List<Depot> All = new List<Depot>();
|
||||
|
||||
public Transform mouth;
|
||||
/// <summary>Half the footprint across and along; a base intake has its back to the deck and takes no belt there.</summary>
|
||||
public float halfX = 1.05f, halfZ = 1.05f;
|
||||
public bool backToDeck;
|
||||
public Vector3 Mouth => mouth ? mouth.position : transform.position + Vector3.up * 1.1f;
|
||||
|
||||
void OnEnable() => All.Add(this);
|
||||
void OnDisable() => All.Remove(this);
|
||||
|
||||
/// <summary>Three belts on each side, twelve in all.</summary>
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
for (int side = 0; side < 4; side++)
|
||||
{
|
||||
if (backToDeck && side == 2) continue;
|
||||
var inward = Quaternion.AngleAxis(side * 90f, transform.up) * -transform.forward;
|
||||
var across = Vector3.Cross(transform.up, inward);
|
||||
float reach = side % 2 == 0 ? halfZ : halfX, room = side % 2 == 0 ? halfX : halfZ;
|
||||
float step = Mathf.Min(0.6f, room * 0.45f);
|
||||
for (int k = -1; k <= 1; k++)
|
||||
into.Add(new Port { at = transform.position - inward * reach + across * (k * step) + transform.up * GameDefs.BeltLowest, dir = inward, input = true });
|
||||
}
|
||||
}
|
||||
|
||||
public string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
var p = PlayerAgent.Local;
|
||||
if (!p) return null;
|
||||
return p.Tank.Value < 0.005f ? (backToDeck ? Loc.T("Base Intake — nothing to hand in") : Loc.T("Grass Depot — nothing to hand in")) : Loc.F("Hand in {0}", GameDefs.Kilos(p.Tank.Value));
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanInteract => PlayerAgent.Local && PlayerAgent.Local.Tank.Value >= 0.005f;
|
||||
|
||||
public void Interact() => PlayerAgent.Local?.Tools.Deposit(this);
|
||||
|
||||
public bool ServerAccept(Cargo c, Vector3 from, Vector3 dir)
|
||||
{
|
||||
var ts = TeamState.Instance;
|
||||
if (!ts || !c || !c.IsSpawned) return false;
|
||||
ts.ServerDeposit(c.Kg.Value, c.kind, Mouth);
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Depot.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Depot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1a9223629109a94428a30bda982066d6
|
||||
293
Assets/Scripts/Gameplay/DronePad.cs
Normal file
293
Assets/Scripts/Gameplay/DronePad.cs
Normal file
@ -0,0 +1,293 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A pad of fetching drones. Bundles of grass lying loose within <see cref="Range"/> of it (thrown down, dropped off the
|
||||
/// end of a belt, flung by a twister) are flown in, one per drone per trip, and go into the pad's silo, which puts them
|
||||
/// on the belts like any other silo. A trip is one synced value per drone (where to, when it left), and every peer flies
|
||||
/// the drone along the same plan from it: up, across, down, grab, up, back, down onto the pad.
|
||||
/// </summary>
|
||||
public class DronePad : SiloPiece
|
||||
{
|
||||
public const float Range = 40f;
|
||||
const float Room = 60f, Cruise = 7f, Climb = 3f, Speed = 6f, Hover = 1.35f, GrabTime = 0.8f, Carry = 1f, Look = 0.5f;
|
||||
const int Most = 4;
|
||||
/// <summary>A drone at rest on the pad.</summary>
|
||||
static readonly Vector4 Parked = new Vector4(0f, 0f, 0f, -1f);
|
||||
/// <summary>Where each drone sits on the pad, in the piece's space (the perch post is at the back left).</summary>
|
||||
static readonly Vector3[] Slots = { new Vector3(0.75f, 0.68f, 0.75f), new Vector3(-0.75f, 0.68f, 0.75f), new Vector3(0.75f, 0.68f, -0.75f), new Vector3(-0.75f, 0.68f, -0.75f) };
|
||||
/// <summary>Bundles some drone is on its way to, so no two go for the same one.</summary>
|
||||
static readonly HashSet<Cargo> s_claimed = new HashSet<Cargo>();
|
||||
|
||||
public Transform drone;
|
||||
|
||||
readonly NetworkVariable<Vector4> _trip0 = new NetworkVariable<Vector4>(Parked), _trip1 = new NetworkVariable<Vector4>(Parked);
|
||||
readonly NetworkVariable<Vector4> _trip2 = new NetworkVariable<Vector4>(Parked), _trip3 = new NetworkVariable<Vector4>(Parked);
|
||||
readonly Transform[] _drones = new Transform[Most];
|
||||
readonly Transform[][] _rotors = new Transform[Most][];
|
||||
readonly AudioSource[] _hum = new AudioSource[Most];
|
||||
readonly Cargo[] _for = new Cargo[Most];
|
||||
readonly bool[] _holding = new bool[Most];
|
||||
float _nextLook;
|
||||
/// <summary>Server: bundles brought in since it was built (for the demo's log).</summary>
|
||||
public int Delivered { get; private set; }
|
||||
BuildPiece _piece;
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
NetworkVariable<Vector4> Trip(int i) => i == 0 ? _trip0 : i == 1 ? _trip1 : i == 2 ? _trip2 : _trip3;
|
||||
/// <summary>Two drones at Mk I, one more per upgrade, four at most.</summary>
|
||||
int Count => Mathf.Min(Most, 2 + (Piece ? Piece.Tier.Value : 0));
|
||||
float Fly => Speed * Mathf.Sqrt(Piece ? Piece.TierMul : 1f);
|
||||
double Now => NetworkManager ? NetworkManager.ServerTime.Time : Time.timeAsDouble;
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
int out_ = 0;
|
||||
for (int i = 0; i < Count; i++) if (Trip(i).Value.w >= 0f) out_++;
|
||||
return Loc.F("Drone Pad: {0} drones, {1} out · {2} of {3}", Count, out_, GameDefs.Kilos(Silo.Value), GameDefs.Kilos(Room));
|
||||
}
|
||||
}
|
||||
|
||||
public override void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
if (!drone) return;
|
||||
_drones[0] = drone;
|
||||
for (int i = 1; i < Most; i++) _drones[i] = Instantiate(drone, drone.parent);
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var spin = new List<Transform>();
|
||||
foreach (var t in _drones[i].GetComponentsInChildren<Transform>(true))
|
||||
if (t.name.StartsWith("Rotor")) spin.Add(t);
|
||||
_rotors[i] = spin.ToArray();
|
||||
_hum[i] = Sfx.Loop("drone_loop", _drones[i], 0f);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
// whatever was in the air falls where it is
|
||||
for (int i = 0; i < Most; i++) Let(i);
|
||||
base.OnNetworkDespawn();
|
||||
}
|
||||
|
||||
// ───────────────────────── the flight plan ─────────────────────────
|
||||
|
||||
Vector3 Home(int i) => transform.TransformPoint(Slots[i]);
|
||||
|
||||
static float Ease(float k) => k * k * (3f - 2f * k);
|
||||
|
||||
/// <summary>Where drone i is on its trip right now, which stage it's at (7: back on the pad) and how far through it.</summary>
|
||||
Vector3 Where(int i, Vector4 trip, double now, out int leg, out float k, out Vector3 heading)
|
||||
{
|
||||
var home = Home(i);
|
||||
leg = 7; k = 1f; heading = transform.forward;
|
||||
if (trip.w < 0f) return home;
|
||||
var target = new Vector3(trip.x, trip.y, trip.z);
|
||||
var a = home + Planet.Up(home) * Cruise;
|
||||
var b = target + Planet.Up(target) * Cruise;
|
||||
var low = target + Planet.Up(target) * Hover;
|
||||
float across = Vector3.Distance(a, b) / Fly, rise = Cruise / Climb, drop = (Cruise - Hover) / Climb;
|
||||
float t = (float)(now - trip.w);
|
||||
leg = 0;
|
||||
float span = rise;
|
||||
while (leg < 7)
|
||||
{
|
||||
span = leg == 0 || leg == 6 ? rise : leg == 1 || leg == 5 ? across : leg == 3 ? GrabTime : drop;
|
||||
if (t < span) break;
|
||||
t -= span;
|
||||
leg++;
|
||||
}
|
||||
if (leg == 7) return home;
|
||||
k = Mathf.Clamp01(t / Mathf.Max(0.01f, span));
|
||||
float e = Ease(k);
|
||||
var go = b - a;
|
||||
heading = leg <= 3 ? go : -go;
|
||||
switch (leg)
|
||||
{
|
||||
case 0: return Vector3.Lerp(home, a, e);
|
||||
case 1: return Vector3.Lerp(a, b, e);
|
||||
case 2: return Vector3.Lerp(b, low, e);
|
||||
case 3: return low;
|
||||
case 4: return Vector3.Lerp(low, b, e);
|
||||
case 5: return Vector3.Lerp(b, a, e);
|
||||
default: return Vector3.Lerp(a, home, e);
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── every peer: fly them ─────────────────────────
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (_drones[0] == null) return;
|
||||
double now = Now;
|
||||
int count = Count;
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var d = _drones[i];
|
||||
if (!d) continue;
|
||||
bool shown = i < count;
|
||||
if (d.gameObject.activeSelf != shown) d.gameObject.SetActive(shown);
|
||||
if (!shown) continue;
|
||||
var trip = Trip(i).Value;
|
||||
var at = Where(i, trip, now, out int leg, out float k, out var heading);
|
||||
var up = Planet.Up(at);
|
||||
heading = Vector3.ProjectOnPlane(heading, up);
|
||||
var face = heading.sqrMagnitude > 0.01f ? Quaternion.LookRotation(heading, up) : transform.rotation;
|
||||
// nose down while it picks up speed across, a little sway in the hover
|
||||
float lean = leg == 1 || leg == 5 ? Mathf.Sin(k * Mathf.PI) * 14f : 0f;
|
||||
float sway = trip.w >= 0f ? Mathf.Sin(Time.time * 2.1f + i) * 2.5f : 0f;
|
||||
d.SetPositionAndRotation(at, face * Quaternion.Euler(lean, 0f, sway));
|
||||
float spin = trip.w >= 0f ? 1900f : 0f;
|
||||
foreach (var r in _rotors[i]) if (r) r.Rotate(up, spin * Time.deltaTime, Space.World);
|
||||
if (_hum[i]) _hum[i].volume = trip.w >= 0f ? 0.3f * Sfx.SfxVolume : 0f;
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────────────────── server: send them out, bring the bundles in ─────────────────────────
|
||||
|
||||
protected override void Update()
|
||||
{
|
||||
if (Belted()) base.Update();
|
||||
if (!IsServer || !IsSpawned) return;
|
||||
double now = Now;
|
||||
bool look = Time.time >= _nextLook;
|
||||
if (look) _nextLook = Time.time + Look;
|
||||
int count = Count;
|
||||
for (int i = 0; i < Most; i++)
|
||||
{
|
||||
var trip = Trip(i).Value;
|
||||
if (trip.w < 0f)
|
||||
{
|
||||
if (look && i < count && !(Piece && Piece.Switched)) Send(i, now);
|
||||
continue;
|
||||
}
|
||||
var at = Where(i, trip, now, out int leg, out float k, out _);
|
||||
var c = _for[i];
|
||||
if (c && (!c.IsSpawned || c.Grab.IsHeld || c.Grab.Consumed || (!_holding[i] && (c.Belt || c.Loaded)))) { Let(i); c = null; }
|
||||
if (c && !_holding[i] && leg >= 3 && leg < 7)
|
||||
{
|
||||
// still where it was when the drone set off? then hook it
|
||||
if ((c.transform.position - new Vector3(trip.x, trip.y, trip.z)).sqrMagnitude < 2.5f * 2.5f) Hook(i, c);
|
||||
else { Let(i); c = null; }
|
||||
}
|
||||
if (c && _holding[i])
|
||||
{
|
||||
var rb = c.Grab.Body;
|
||||
rb.MovePosition(at - Planet.Up(at) * Carry);
|
||||
// down on the pad: into the silo
|
||||
if (leg == 7 || (leg == 6 && k > 0.75f))
|
||||
{
|
||||
Silo.Value += c.Kg.Value;
|
||||
Delivered++;
|
||||
s_claimed.Remove(c);
|
||||
_for[i] = null;
|
||||
_holding[i] = false;
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
DeliveredRpc();
|
||||
}
|
||||
}
|
||||
if (leg == 7)
|
||||
{
|
||||
if (_for[i]) Let(i);
|
||||
Trip(i).Value = Parked;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static readonly List<Port> s_ports = new List<Port>();
|
||||
|
||||
/// <summary>Is a belt joined to the hatch?</summary>
|
||||
bool Belted()
|
||||
{
|
||||
s_ports.Clear();
|
||||
Ports(s_ports);
|
||||
return s_ports.Count > 0 && BeltNet.Nearest(s_ports[0].at, true, BeltNet.Joined, Piece, out var next, out _, out _) && next.GetComponentInChildren<Conveyor>();
|
||||
}
|
||||
|
||||
/// <summary>The nearest loose bundle of grass in reach that nobody is after, if the silo has room for it.</summary>
|
||||
void Send(int i, double now)
|
||||
{
|
||||
int out_ = 0;
|
||||
for (int k = 0; k < Most; k++) if (Trip(k).Value.w >= 0f) out_++;
|
||||
if (Silo.Value + (out_ + 1) * GameDefs.BundleKg > Room) return;
|
||||
Cargo best = null;
|
||||
float bestD = Range * Range;
|
||||
var here = transform.position;
|
||||
foreach (var c in Cargo.All)
|
||||
{
|
||||
if (!c || !c.IsSpawned || c.kind != CargoKind.Grass || c.Belt || c.Loaded || s_claimed.Contains(c)) continue;
|
||||
var g = c.Grab;
|
||||
if (!g || g.IsHeld || g.Consumed || !g.Body || g.Body.isKinematic || g.Body.linearVelocity.sqrMagnitude > 0.25f) continue;
|
||||
float d = (c.transform.position - here).sqrMagnitude;
|
||||
// right by the pad: just put out of the hatch, or about to be
|
||||
if (d < 3f * 3f) continue;
|
||||
// dropped off the free end of a belt: that's where someone wants it, and it may be this pad's own
|
||||
if (AtBeltEnd(c.transform.position)) continue;
|
||||
if (d < bestD) { bestD = d; best = c; }
|
||||
}
|
||||
if (!best) return;
|
||||
s_claimed.Add(best);
|
||||
_for[i] = best;
|
||||
_holding[i] = false;
|
||||
var p = best.transform.position;
|
||||
Trip(i).Value = new Vector4(p.x, p.y, p.z, (float)now);
|
||||
}
|
||||
|
||||
static bool AtBeltEnd(Vector3 p)
|
||||
{
|
||||
foreach (var b in Conveyor.All)
|
||||
if (b is BeltRun r && (r.End - p).sqrMagnitude < 2.5f * 2.5f) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
void Hook(int i, Cargo c)
|
||||
{
|
||||
if (c.OwnerClientId != NetworkManager.ServerClientId) c.NetworkObject.ChangeOwnership(NetworkManager.ServerClientId);
|
||||
var rb = c.Grab.Body;
|
||||
rb.linearVelocity = Vector3.zero;
|
||||
rb.angularVelocity = Vector3.zero;
|
||||
rb.isKinematic = true;
|
||||
c.Loaded = true;
|
||||
_holding[i] = true;
|
||||
HookRpc(i);
|
||||
}
|
||||
|
||||
/// <summary>Drone i lets go of its bundle (or of the claim on it): it drops where it is.</summary>
|
||||
void Let(int i)
|
||||
{
|
||||
var c = _for[i];
|
||||
_for[i] = null;
|
||||
if (!c) { _holding[i] = false; return; }
|
||||
s_claimed.Remove(c);
|
||||
if (_holding[i] && c.IsSpawned && !c.Grab.Consumed)
|
||||
{
|
||||
c.Loaded = false;
|
||||
var rb = c.Grab.Body;
|
||||
if (rb) rb.isKinematic = false;
|
||||
}
|
||||
_holding[i] = false;
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void HookRpc(int i)
|
||||
{
|
||||
if (_drones[i]) Sfx.PlayAt("drone_grab", _drones[i].position, 0.5f, 1f, 0.1f, 0.2f);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void DeliveredRpc() => Sfx.PlayAt("cargo_load", transform.position, 0.5f, 1f, 0.1f, 0.4f);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/DronePad.cs.meta
Normal file
2
Assets/Scripts/Gameplay/DronePad.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 93d302c9b3132c94ca2833cf8e1cf9d6
|
||||
314
Assets/Scripts/Gameplay/Foundation.cs
Normal file
314
Assets/Scripts/Gameplay/Foundation.cs
Normal file
@ -0,0 +1,314 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A deck to build on. On the ground: a timber slab, square or hexagonal, 3 m across, its footing sunk into the ground so it
|
||||
/// stays level on a slope; lifted (Ctrl+wheel while placing) it stands on timber stilts down to the soil instead. A storey up:
|
||||
/// a floor or a flat roof resting on walls. What stands on a deck sits on a half-metre grid and turns with it, walls go on its
|
||||
/// edges, and neighbouring decks of a kind line up edge to edge at the same height.
|
||||
/// </summary>
|
||||
public class Foundation : MonoBehaviour
|
||||
{
|
||||
public const float Across = 3f, Top = 0.3f, Sunk = 1.5f;
|
||||
/// <summary>A slab lifted more than this stands on stilts; a raised deck is this deep.</summary>
|
||||
public const float Stilts = 0.25f, DeckDepth = 0.4f;
|
||||
/// <summary>How high a foundation can be lifted off the ground.</summary>
|
||||
public const float MaxRaise = 6f;
|
||||
|
||||
/// <summary>Height of a deck's walking surface above its origin: foundations stand on the ground, floors hang from their top.</summary>
|
||||
public static float TopOf(PieceId id) => GameDefs.IsFoundation(id) ? Top : 0f;
|
||||
|
||||
static Mesh s_square, s_hex, s_squareDeck, s_hexDeck, s_floor;
|
||||
|
||||
static float SquareR => Across * Mathf.Sqrt(0.5f);
|
||||
static float HexR => Across * 0.5f / Mathf.Cos(30f * Mathf.Deg2Rad);
|
||||
|
||||
public static Mesh Shape(PieceId id, bool raised = false)
|
||||
{
|
||||
if (id == PieceId.Floor || id == PieceId.FlatRoof) return s_floor ? s_floor : (s_floor = Slab(4, SquareR, 45f, 0f, -0.3f));
|
||||
if (id == PieceId.Hex)
|
||||
{
|
||||
if (raised) return s_hexDeck ? s_hexDeck : (s_hexDeck = Slab(6, HexR, 30f, Top, Top - DeckDepth));
|
||||
return s_hex ? s_hex : (s_hex = Slab(6, HexR, 30f, Top, -Sunk));
|
||||
}
|
||||
if (raised) return s_squareDeck ? s_squareDeck : (s_squareDeck = Slab(4, SquareR, 45f, Top, Top - DeckDepth));
|
||||
return s_square ? s_square : (s_square = Slab(4, SquareR, 45f, Top, -Sunk));
|
||||
}
|
||||
|
||||
/// <summary>A flat-topped prism with the corners on a circle.</summary>
|
||||
static Mesh Slab(int sides, float radius, float turn, float top, float bottom)
|
||||
{
|
||||
var v = new List<Vector3>();
|
||||
var n = new List<Vector3>();
|
||||
var uv = new List<Vector2>();
|
||||
var t = new List<int>();
|
||||
Vector3 Corner(int i, float y)
|
||||
{
|
||||
float a = (turn + i * 360f / sides) * Mathf.Deg2Rad;
|
||||
return new Vector3(Mathf.Sin(a) * radius, y, Mathf.Cos(a) * radius);
|
||||
}
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
v.Add(Corner(i, top));
|
||||
n.Add(Vector3.up);
|
||||
uv.Add(new Vector2(v[i].x, v[i].z));
|
||||
}
|
||||
for (int i = 1; i < sides - 1; i++) { t.Add(0); t.Add(i); t.Add(i + 1); }
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
int b = v.Count;
|
||||
Vector3 p = Corner(i, top), q = Corner(i + 1, top), r = Corner(i + 1, bottom), s = Corner(i, bottom);
|
||||
var face = Vector3.Cross(r - p, q - p).normalized;
|
||||
v.Add(p); v.Add(q); v.Add(r); v.Add(s);
|
||||
n.Add(face); n.Add(face); n.Add(face); n.Add(face);
|
||||
uv.Add(new Vector2(0f, top)); uv.Add(new Vector2(Across, top)); uv.Add(new Vector2(Across, bottom)); uv.Add(new Vector2(0f, bottom));
|
||||
t.Add(b); t.Add(b + 2); t.Add(b + 1);
|
||||
t.Add(b); t.Add(b + 3); t.Add(b + 2);
|
||||
}
|
||||
// the underside, so a raised deck isn't hollow from below
|
||||
int u = v.Count;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
v.Add(Corner(i, bottom));
|
||||
n.Add(Vector3.down);
|
||||
uv.Add(new Vector2(v[u + i].x, v[u + i].z));
|
||||
}
|
||||
for (int i = 1; i < sides - 1; i++) { t.Add(u); t.Add(u + i + 1); t.Add(u + i); }
|
||||
var m = new Mesh { name = "Slab" + sides };
|
||||
m.SetVertices(v);
|
||||
m.SetNormals(n);
|
||||
m.SetUVs(0, uv);
|
||||
m.SetTriangles(t, 0);
|
||||
m.RecalculateBounds();
|
||||
return m;
|
||||
}
|
||||
|
||||
BuildPiece _piece;
|
||||
MeshCollider _collider;
|
||||
Transform _slab, _model, _stilts;
|
||||
bool _raised;
|
||||
Vector3 _fitAt = new Vector3(float.NaN, 0f, 0f);
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_piece = GetComponent<BuildPiece>();
|
||||
var slab = new GameObject("Slab") { layer = gameObject.layer };
|
||||
slab.transform.SetParent(transform, false);
|
||||
_slab = slab.transform;
|
||||
_collider = slab.AddComponent<MeshCollider>();
|
||||
_collider.sharedMesh = Shape(_piece.piece);
|
||||
_collider.convex = true;
|
||||
Dress(_piece.Def.model);
|
||||
}
|
||||
|
||||
void Start() => Fit();
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if ((transform.position - _fitAt).sqrMagnitude > 1e-4f) Fit();
|
||||
}
|
||||
|
||||
void Dress(string name)
|
||||
{
|
||||
if (_model) Destroy(_model.gameObject);
|
||||
_model = null;
|
||||
var model = AssetBank.I ? AssetBank.I.Model(name) : null;
|
||||
if (!model) return;
|
||||
var deck = Instantiate(model, _slab);
|
||||
foreach (var other in deck.GetComponentsInChildren<Collider>(true)) Destroy(other);
|
||||
_model = deck.transform;
|
||||
}
|
||||
|
||||
/// <summary>Lifted off the ground: the deck alone on stilts down to the soil; on the ground, the slab with its footing.</summary>
|
||||
void Fit()
|
||||
{
|
||||
_fitAt = transform.position;
|
||||
if (!GameDefs.IsFoundation(_piece.piece)) return;
|
||||
bool raised = Planet.Altitude(transform.position) > Stilts;
|
||||
if (raised != _raised)
|
||||
{
|
||||
_raised = raised;
|
||||
_collider.sharedMesh = Shape(_piece.piece, raised);
|
||||
string deck = _piece.piece == PieceId.Hex ? "SM_Deck_Hex" : "SM_Deck_Square";
|
||||
Dress(raised && AssetBank.I && AssetBank.I.Model(deck) ? deck : _piece.Def.model);
|
||||
}
|
||||
if (_stilts) Destroy(_stilts.gameObject);
|
||||
_stilts = null;
|
||||
if (raised) Stand();
|
||||
}
|
||||
|
||||
/// <summary>Timber legs from under the deck to the soil, braced where they're tall.</summary>
|
||||
void Stand()
|
||||
{
|
||||
_stilts = new GameObject("Stilts") { layer = gameObject.layer }.transform;
|
||||
_stilts.SetParent(transform, false);
|
||||
var wood = BuildLook.Mat("M_Timber", new Color(0.55f, 0.4f, 0.25f));
|
||||
int sides = _piece.piece == PieceId.Hex ? 6 : 4;
|
||||
float reach = (sides == 6 ? HexR : SquareR) - 0.32f, turn = sides == 6 ? 30f : 45f;
|
||||
float under = Top - DeckDepth;
|
||||
var feet = new Vector3[sides];
|
||||
var lengths = new float[sides];
|
||||
// the turn alone, not the bounce the piece lands with: the ground is measured in metres
|
||||
var rot = transform.rotation;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
float a = (turn + i * 360f / sides) * Mathf.Deg2Rad;
|
||||
var foot = new Vector3(Mathf.Sin(a) * reach, under, Mathf.Cos(a) * reach);
|
||||
float drop = Mathf.Max(0.2f, Planet.Altitude(transform.position + rot * foot)) + 0.35f;
|
||||
feet[i] = foot;
|
||||
lengths[i] = drop;
|
||||
Beam(wood, foot + Vector3.down * drop * 0.5f, Quaternion.identity, new Vector3(0.22f, drop, 0.22f));
|
||||
// a stone pad where it meets the soil
|
||||
Beam(BuildLook.Mat("M_Stone", new Color(0.55f, 0.54f, 0.5f)), foot + Vector3.down * (drop - 0.3f), Quaternion.identity, new Vector3(0.42f, 0.16f, 0.42f));
|
||||
}
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
int j = (i + 1) % sides;
|
||||
float tall = Mathf.Min(lengths[i], lengths[j]) - 0.35f;
|
||||
if (tall < 0.9f) continue;
|
||||
// a rail under the deck and a diagonal brace on each side
|
||||
var a = feet[i] + Vector3.down * 0.25f;
|
||||
var b = feet[j] + Vector3.down * Mathf.Min(tall * 0.8f, 2.6f);
|
||||
Strut(wood, feet[i] + Vector3.down * 0.18f, feet[j] + Vector3.down * 0.18f, 0.12f);
|
||||
Strut(wood, a, b, 0.1f);
|
||||
}
|
||||
}
|
||||
|
||||
void Strut(Material m, Vector3 a, Vector3 b, float w)
|
||||
{
|
||||
var d = b - a;
|
||||
Beam(m, (a + b) * 0.5f, Quaternion.LookRotation(d), new Vector3(w, w * 1.2f, d.magnitude));
|
||||
}
|
||||
|
||||
void Beam(Material m, Vector3 at, Quaternion rot, Vector3 size)
|
||||
{
|
||||
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
go.name = "Stilt";
|
||||
go.layer = gameObject.layer;
|
||||
go.transform.SetParent(_stilts, false);
|
||||
go.transform.localPosition = at;
|
||||
go.transform.localRotation = rot;
|
||||
go.transform.localScale = size;
|
||||
go.GetComponent<Renderer>().sharedMaterial = m;
|
||||
}
|
||||
|
||||
/// <summary>Half-metre grid on a deck, level with its top.</summary>
|
||||
public static Vector3 Grid(Transform slab, Vector3 point)
|
||||
{
|
||||
var piece = slab.GetComponent<BuildPiece>();
|
||||
var l = Quaternion.Inverse(slab.rotation) * (point - slab.position);
|
||||
l.x = Mathf.Round(l.x * 2f) * 0.5f;
|
||||
l.z = Mathf.Round(l.z * 2f) * 0.5f;
|
||||
l.y = piece ? TopOf(piece.piece) : Top;
|
||||
return slab.position + slab.rotation * l;
|
||||
}
|
||||
|
||||
/// <summary>The spot next to a deck of the same kind nearest to a point, edge to edge with it and at its height.</summary>
|
||||
public static bool Beside(Vector3 point, PieceId id, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
BuildPiece near = null;
|
||||
float best = 36f;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || !GameDefs.IsDeck(p.piece)) continue;
|
||||
float d = (p.transform.position + p.transform.rotation * Vector3.up * TopOf(p.piece) - point).sqrMagnitude;
|
||||
if (d < best) { best = d; near = p; }
|
||||
}
|
||||
if (!near || near.piece != id) return false;
|
||||
int sides = id == PieceId.Hex ? 6 : 4;
|
||||
var t = near.transform;
|
||||
rot = t.rotation;
|
||||
best = float.MaxValue;
|
||||
for (int i = 0; i < sides; i++)
|
||||
{
|
||||
var c = t.position + t.rotation * (Quaternion.Euler(0f, i * 360f / sides, 0f) * Vector3.forward) * Across;
|
||||
float d = (c - point).sqrMagnitude;
|
||||
if (d < best) { best = d; at = c; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Where walls, floors and roofs go: walls on the edges of a square deck, floors and roofs on top of the walls.</summary>
|
||||
public static class Snap
|
||||
{
|
||||
/// <summary>The edge of the square deck nearest to the point, facing out (or in, every other turn of R).</summary>
|
||||
public static bool Edge(Vector3 point, BuildPiece on, float yaw, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
var deck = on && GameDefs.IsSquareDeck(on.piece) ? on : null;
|
||||
if (!deck)
|
||||
{
|
||||
float near = 4.5f * 4.5f;
|
||||
foreach (var p in BuildPiece.All)
|
||||
{
|
||||
if (!p || !GameDefs.IsSquareDeck(p.piece)) continue;
|
||||
float d = (Top(p) - point).sqrMagnitude;
|
||||
if (d < near) { near = d; deck = p; }
|
||||
}
|
||||
}
|
||||
if (!deck) return false;
|
||||
var t = deck.transform;
|
||||
var c = Top(deck);
|
||||
float best = float.MaxValue;
|
||||
var outward = t.rotation * Vector3.forward;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var dir = t.rotation * (Quaternion.Euler(0f, i * 90f, 0f) * Vector3.forward);
|
||||
var e = c + dir * Foundation.Across * 0.5f;
|
||||
float d = (e - point).sqrMagnitude;
|
||||
if (d < best) { best = d; at = e; outward = dir; }
|
||||
}
|
||||
if (Mathf.Repeat(yaw, 360f) >= 180f) outward = -outward;
|
||||
rot = Quaternion.LookRotation(outward, t.rotation * Vector3.up);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A storey up: aimed at a wall (or a pillar), the 3 m cell beside it on the side you're looking from, level with its top;
|
||||
/// a pitched roof's eave goes along that wall. Standing on a floor, a pitched roof goes on the floor itself.
|
||||
/// </summary>
|
||||
public static bool OnTop(PieceId id, Vector3 point, BuildPiece target, BuildPiece on, float yaw, out Vector3 at, out Quaternion rot)
|
||||
{
|
||||
at = point; rot = Quaternion.identity;
|
||||
var spin = Quaternion.Euler(0f, Mathf.Round(yaw / 90f) * 90f, 0f);
|
||||
if (target && GameDefs.Holds(target.piece))
|
||||
{
|
||||
var t = target.transform;
|
||||
var up = t.rotation * Vector3.up;
|
||||
var top = t.position + up * GameDefs.Storey;
|
||||
Vector3 cell;
|
||||
if (target.piece == PieceId.Pillar)
|
||||
{
|
||||
var l = Quaternion.Inverse(t.rotation) * (point - top);
|
||||
cell = top + t.rotation * new Vector3(Mathf.Sign(l.x) * 1.5f, 0f, Mathf.Sign(l.z) * 1.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
var f = t.rotation * Vector3.forward;
|
||||
var inside = top - f * 1.5f;
|
||||
var outside = top + f * 1.5f;
|
||||
cell = (inside - point).sqrMagnitude <= (outside - point).sqrMagnitude ? inside : outside;
|
||||
}
|
||||
var toWall = top - cell;
|
||||
toWall = Vector3.ProjectOnPlane(toWall, up);
|
||||
if (toWall.sqrMagnitude < 0.01f) toWall = t.rotation * Vector3.forward;
|
||||
at = cell;
|
||||
rot = Quaternion.LookRotation(toWall.normalized, up) * spin;
|
||||
return true;
|
||||
}
|
||||
if (id == PieceId.Roof && on && GameDefs.IsSquareDeck(on.piece))
|
||||
{
|
||||
at = Top(on);
|
||||
rot = on.transform.rotation * spin;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static Vector3 Top(BuildPiece deck) => deck.transform.position + deck.transform.rotation * Vector3.up * Foundation.TopOf(deck.piece);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Foundation.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Foundation.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3ef451b3573bec4c8c45723012d2023
|
||||
564
Assets/Scripts/Gameplay/GameDefs.cs
Normal file
564
Assets/Scripts/Gameplay/GameDefs.cs
Normal file
@ -0,0 +1,564 @@
|
||||
using System;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>What a player can hold: six hand tools from nail scissors to the two-handed scythe, each with its own
|
||||
/// grass container, and the hammer that opens the build menu.</summary>
|
||||
public enum ToolId : byte { NailScissors = 0, GardenShears = 1, Sickle = 2, Scythe = 3, LongScythe = 4, WideScythe = 5, Hammer = 6, LawnMower = 7, None = 255 }
|
||||
|
||||
/// <summary>Personal gear on the supply wall; shares the owned mask with the tools.</summary>
|
||||
public enum GearId : byte { Jetpack = 8, Boots = 9, NightVision = 10 }
|
||||
|
||||
public enum CargoKind : byte { Grass = 0, Hay = 1, Brick = 2 }
|
||||
|
||||
public enum VehicleKind : byte { Push, Rider, Pickup, Tractor, Combine, Hauler, Mulcher, Baler, Count }
|
||||
|
||||
public enum TuneId : byte { Motors, Hopper, Turbo, Cruise, Cutter, Release, Lights, Count }
|
||||
|
||||
public enum PerkTree : byte { Containers = 0, Cutting = 1, Suit = 2, Logistics = 3, Economy = 4 }
|
||||
|
||||
public enum PerkId : byte
|
||||
{
|
||||
// CONTAINERS
|
||||
BinScissors, BinShears, BinSickle, BinScythe, BinLongScythe, BinWideScythe, Compactor, AutoBaler,
|
||||
// CUTTING
|
||||
WiderBlades, LongHandles, DeepSwath, WhetSteel,
|
||||
// SUIT
|
||||
ServoBoots, SpringStep, FieldFrame,
|
||||
// LOGISTICS
|
||||
QuickTwine, BundleLine, ThrowArm, ExpressDepot,
|
||||
// ECONOMY
|
||||
EarthPrices, RegionBonus, SupplyDeals, GreenExchange,
|
||||
Count
|
||||
}
|
||||
|
||||
public enum PieceCat : byte { Services, Logistics, Production, Power, Structures, Decor, Count }
|
||||
|
||||
public enum PieceId : byte { Depot, Belt, Splitter, Merger, Square, Hex, Dryer, Press, SolarS, SolarM, SolarL, Garage, Binder, RobotI, RobotII, Reaper, Catcher, Pole, BatteryS, BatteryL, UnloadBay, DronePad, Intake,
|
||||
Wall, WindowWall, DoorWall, Railing, Fence, Floor, FlatRoof, Roof, Stairs, Steps, Pillar, Planter, Lamppost, Bench, Crates, Flagpole, Count }
|
||||
|
||||
/// <summary>How a structure finds its place: anywhere, on the edge of a deck, or on top of the walls (a storey up).</summary>
|
||||
public enum Fit : byte { Free, Edge, Top }
|
||||
|
||||
public class ToolDef
|
||||
{
|
||||
public ToolId id;
|
||||
public string nameEn, descEn, icon, model;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public float width; // metres
|
||||
public float capacity; // kilos
|
||||
public long price;
|
||||
}
|
||||
|
||||
public class PerkDef
|
||||
{
|
||||
public PerkId id;
|
||||
public PerkTree tree;
|
||||
public string nameEn, descEn, icon;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public int col, row;
|
||||
/// <summary>Price of each level, in order.</summary>
|
||||
public long[] prices = { 0 };
|
||||
public bool big; // a big step: drawn bigger
|
||||
public PerkId[] requires = new PerkId[0];
|
||||
public int requireLevel = 1;
|
||||
public System.Func<int, string> effect;
|
||||
|
||||
public int maxLevel => prices.Length;
|
||||
public long PriceFor(int currentLevel) => prices[Mathf.Clamp(currentLevel, 0, prices.Length - 1)];
|
||||
public string EffectFor(int level) => effect != null ? effect(level) : desc;
|
||||
}
|
||||
|
||||
public class PieceDef
|
||||
{
|
||||
public PieceId id;
|
||||
public PieceCat cat;
|
||||
public string nameEn, descEn, icon, model, prefab;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public double price;
|
||||
public int sizeX = 1, sizeZ = 1;
|
||||
/// <summary>How much bigger than its file the model is built.</summary>
|
||||
public float scale = 1f;
|
||||
/// <summary>Kilowatts a machine draws while it works.</summary>
|
||||
public float kw;
|
||||
/// <summary>Company equipment: never in the build menu.</summary>
|
||||
public bool company;
|
||||
}
|
||||
|
||||
/// <summary>What a machine turns into what, batch by batch.</summary>
|
||||
public class RecipeDef
|
||||
{
|
||||
public float grass, hay, seconds, makes;
|
||||
public CargoKind product;
|
||||
}
|
||||
|
||||
public class VehicleDef
|
||||
{
|
||||
public VehicleKind kind;
|
||||
public string nameEn, descEn, icon;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public string desc { get => Loc.T(descEn); set => descEn = value; }
|
||||
public double price;
|
||||
/// <summary>Strip it cuts, kilos it holds, bundles on the bed. A pickup cuts nothing.</summary>
|
||||
public float width, hopper;
|
||||
public int bed;
|
||||
public float speed, accel, turn;
|
||||
/// <summary>The crew are tall in the head: how far the seat sits below where the model has it, to keep them under the roof.</summary>
|
||||
public float seatDrop;
|
||||
public float seatAhead;
|
||||
/// <summary>Feeds its hopper onto a belt as bundles from a chute on its right, wherever a belt starts beside it.</summary>
|
||||
public bool bales;
|
||||
}
|
||||
|
||||
/// <summary>One upgrade a machine can take, level by level.</summary>
|
||||
public class TuneDef
|
||||
{
|
||||
public TuneId id;
|
||||
public string nameEn;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public long[] prices;
|
||||
public System.Func<int, string> effect;
|
||||
}
|
||||
|
||||
/// <summary>What drives itself: rings of sectors it works (0 = all of them), strip, walking speed, hopper.</summary>
|
||||
/// <summary>What a piece's upgrade levels change.</summary>
|
||||
public enum UpgradeKind { None, Belt, Machine, Robot, Silo }
|
||||
|
||||
public class RobotDef
|
||||
{
|
||||
public PieceId piece;
|
||||
public string nameEn;
|
||||
public string name { get => Loc.T(nameEn); set => nameEn = value; }
|
||||
public int reach;
|
||||
public float width, speed, hopper;
|
||||
}
|
||||
|
||||
public class PanelDef
|
||||
{
|
||||
public float kw, radius;
|
||||
public bool tracker;
|
||||
}
|
||||
|
||||
public class BatteryDef
|
||||
{
|
||||
public float kwh, kw, radius;
|
||||
}
|
||||
|
||||
public static class GameDefs
|
||||
{
|
||||
// ───────────────────────── world ─────────────────────────
|
||||
|
||||
/// <summary>The soil around the base (the deck top is y = 0; the deck stands on stilts above the meadow).</summary>
|
||||
public const float WaterY = -1.2f;
|
||||
/// <summary>The whole of Herbaria-7: 163 842 sectors of about 600 m² each. Easier games play on a smaller ball (<see cref="Planet.Radius"/>).</summary>
|
||||
public const float PlanetRadius = 2797f;
|
||||
public const float TileSize = 6f;
|
||||
/// <summary>The meadow is this tall, everywhere, until it is cut.</summary>
|
||||
public const float GrassHeight = 0.42f;
|
||||
|
||||
/// <summary>Kilos of grass on a square metre of meadow.</summary>
|
||||
public const float GrassDensity = 0.25f;
|
||||
/// <summary>Herbaria-7: 163 830 hex sectors of about 600 m² (the base and the planet size live here).</summary>
|
||||
public const int Sectors = 163830;
|
||||
/// <summary>About 600 m² on the whole planet, a quarter of that on half of it, a ninth on a third.</summary>
|
||||
public static float SectorArea => 4f * Mathf.PI * Planet.Radius * Planet.Radius / HexGrid.Cells;
|
||||
public static double PlanetKg => Sectors * (double)SectorArea * GrassDensity;
|
||||
public static double PlanetArea => Sectors * (double)SectorArea;
|
||||
/// <summary>A sector mown clean pays on top of its grass.</summary>
|
||||
public static double SectorBonus(int bounty) => 10d + bounty * 15d;
|
||||
public const double StakePay = 100d, PointPay = 250d;
|
||||
|
||||
// ───────────────────────── tools ─────────────────────────
|
||||
|
||||
public static readonly ToolDef[] Tools =
|
||||
{
|
||||
new ToolDef { id = ToolId.NailScissors, name = Loc.N("Nail Scissors"), icon = "icon_tool_scissors", model = "SM_Tool_NailScissors", width = 0.12f, capacity = 0.5f, price = 0,
|
||||
desc = Loc.N("Company issue. For a whole planet. Earth is counting on you.") },
|
||||
new ToolDef { id = ToolId.GardenShears, name = Loc.N("Garden Shears"), icon = "icon_tool_shears", model = "SM_Tool_GardenShears", width = 0.18f, capacity = 0.75f, price = 5,
|
||||
desc = Loc.N("A proper pair of shears. Your wrist says thank you.") },
|
||||
new ToolDef { id = ToolId.Sickle, name = Loc.N("Sickle"), icon = "icon_tool_sickle", model = "SM_Tool_Sickle", width = 0.24f, capacity = 1f, price = 10,
|
||||
desc = Loc.N("A one-handed hooked blade with a small grass sack.") },
|
||||
new ToolDef { id = ToolId.Scythe, name = Loc.N("Scythe"), icon = "icon_tool_scythe", model = "SM_Tool_Scythe", width = 0.43f, capacity = 3f, price = 25,
|
||||
desc = Loc.N("The real thing: long strokes and a proper basket on the back.") },
|
||||
new ToolDef { id = ToolId.LongScythe, name = Loc.N("Long Scythe"), icon = "icon_tool_longscythe", model = "SM_Tool_LongScythe", width = 0.65f, capacity = 6f, price = 75,
|
||||
desc = Loc.N("A longer blade, a wider strip, a bigger basket.") },
|
||||
new ToolDef { id = ToolId.WideScythe, name = Loc.N("Two-Handed Scythe"), icon = "icon_tool_widescythe", model = "SM_Tool_WideScythe", width = 0.988f, capacity = 12f, price = 150,
|
||||
desc = Loc.N("Almost a metre of steel. Earth will be green by Christmas.") },
|
||||
new ToolDef { id = ToolId.Hammer, name = Loc.N("Build Hammer"), icon = "icon_tool_hammer", model = "SM_Tool_Hammer", price = 50,
|
||||
desc = Loc.N("Opens the build menu. Q category, wheel piece, R rotate, RMB remove.") },
|
||||
new ToolDef { id = ToolId.LawnMower, name = Loc.N("Lawn Mower"), icon = "icon_tool_lawnmower", model = "SM_Tool_LawnMower", width = 1.1f, capacity = 30f, price = 400,
|
||||
desc = Loc.N("A wide-deck push mower. Hold the mouse and walk: it cuts the strip under it as you go.") },
|
||||
};
|
||||
|
||||
/// <summary>How many tool ids there are, and the order the supply wall and the belt list them: blades by size, then the hammer.</summary>
|
||||
public const int ToolCount = 8;
|
||||
public static readonly ToolId[] ToolOrder = { ToolId.NailScissors, ToolId.GardenShears, ToolId.Sickle, ToolId.Scythe, ToolId.LongScythe, ToolId.WideScythe, ToolId.LawnMower, ToolId.Hammer };
|
||||
|
||||
public static ToolDef Tool(ToolId id) => Tools[(int)id];
|
||||
public static bool IsBlade(ToolId t) => t <= ToolId.WideScythe || t == ToolId.LawnMower;
|
||||
/// <summary>Pushed along the ground instead of swung: cuts under its deck while you walk.</summary>
|
||||
public static bool IsMower(ToolId t) => t == ToolId.LawnMower;
|
||||
/// <summary>Scythes and shears have a basket perk each; the mower's bag only grows with the compactor.</summary>
|
||||
public static bool HasBinPerk(ToolId t) => t <= ToolId.WideScythe;
|
||||
public static PerkId BinPerk(ToolId t) => (PerkId)((int)PerkId.BinScissors + (int)t);
|
||||
|
||||
public const int MaxBeltSlots = 6;
|
||||
/// <summary>Price of the next belt slot when you already have this many.</summary>
|
||||
public static long BeltSlotPrice(int have) => 15L << Mathf.Clamp(have - 1, 0, MaxBeltSlots);
|
||||
public const long JetpackPrice = 300, BootsPrice = 250, NightVisionPrice = 350;
|
||||
public static long GearPrice(GearId g) => g == GearId.Boots ? BootsPrice : g == GearId.NightVision ? NightVisionPrice : JetpackPrice;
|
||||
public const float JetDash = 11f, JetCooldown = 2.5f;
|
||||
/// <summary>Herbaria-7 pulls weakly: this is how fast the crew and loose bundles fall, and how hard you jump.
|
||||
/// The gravity boots bring back Earth's pull (the player's own gravity and jump).</summary>
|
||||
public const float LowGravity = 7.6f, LowJump = 5.4f;
|
||||
|
||||
// ───────────────────────── upgrade matrix ─────────────────────────
|
||||
|
||||
static PerkDef Bin(PerkId id, string name, string desc, int col, params long[] prices) => new PerkDef
|
||||
{
|
||||
id = id, tree = PerkTree.Containers, name = name, icon = "icon_perk_backpack", col = col, row = 0, prices = prices,
|
||||
desc = desc,
|
||||
effect = l => Loc.F("Container x{0:0}", BinMul(l)),
|
||||
};
|
||||
|
||||
public static readonly PerkDef[] Perks =
|
||||
{
|
||||
// ── CONTAINERS ──
|
||||
Bin(PerkId.BinScissors, Loc.N("Nail Scissors Basket"), Loc.N("A bigger basket for the Nail Scissors."), 0, 10, 25, 60),
|
||||
Bin(PerkId.BinShears, Loc.N("Garden Shears Basket"), Loc.N("A bigger basket for the Garden Shears."), 1, 15, 40, 100),
|
||||
Bin(PerkId.BinSickle, Loc.N("Sickle Basket"), Loc.N("A bigger basket for the Sickle."), 2, 20, 50, 120),
|
||||
Bin(PerkId.BinScythe, Loc.N("Scythe Basket"), Loc.N("A bigger basket for the Scythe."), 3, 30, 80, 190),
|
||||
Bin(PerkId.BinLongScythe, Loc.N("Long Scythe Basket"), Loc.N("A bigger basket for the Long Scythe."), 4, 45, 110, 260),
|
||||
Bin(PerkId.BinWideScythe, Loc.N("Two-Handed Scythe Basket"), Loc.N("A bigger basket for the Two-Handed Scythe."), 5, 55, 140, 320),
|
||||
new PerkDef { id = PerkId.Compactor, tree = PerkTree.Containers, name = Loc.N("Grass Compactor"), icon = "icon_perk_pressure", col = 2, row = 1, prices = new long[] { 150, 450, 1200 },
|
||||
desc = Loc.N("Tread it down harder. Every tool holds more."), effect = l => Loc.F("All tools +{0}%", l * 15) },
|
||||
new PerkDef { id = PerkId.AutoBaler, tree = PerkTree.Containers, name = Loc.N("Auto-Binder"), icon = "icon_piece_filler", col = 3, row = 2, prices = new long[] { 2000 }, big = true, requires = new[] { PerkId.Compactor }, requireLevel = 2,
|
||||
desc = Loc.N("A full basket ties itself into a bundle and drops it at your feet.") },
|
||||
|
||||
// ── CUTTING ──
|
||||
new PerkDef { id = PerkId.WiderBlades, tree = PerkTree.Cutting, name = Loc.N("Wider Blades"), icon = "icon_perk_suction", col = 0, row = 0, prices = new long[] { 40, 140, 400 },
|
||||
desc = Loc.N("A wider strip with every tool."), effect = l => Loc.F("Strip width +{0:0}%", WidthBonus(l) * 100f) },
|
||||
new PerkDef { id = PerkId.LongHandles, tree = PerkTree.Cutting, name = Loc.N("Long Handles"), icon = "icon_perk_nozzle", col = 1, row = 0, prices = new long[] { 70, 220 },
|
||||
desc = Loc.N("Reach further without taking a step."), effect = l => Loc.F("Reach +{0:0.##} m", l * 0.75f) },
|
||||
new PerkDef { id = PerkId.DeepSwath, tree = PerkTree.Cutting, name = Loc.N("Deep Swath"), icon = "icon_perk_flow", col = 2, row = 0, prices = new long[] { 90, 280 },
|
||||
desc = Loc.N("The blade bites deeper into the grass."), effect = l => Loc.F("Strip width +{0:0}%", l * 6) },
|
||||
new PerkDef { id = PerkId.WhetSteel, tree = PerkTree.Cutting, name = Loc.N("Whetstone Steel"), icon = "icon_perk_blast", col = 1, row = 1, prices = new long[] { 1500 }, big = true, requires = new[] { PerkId.WiderBlades, PerkId.LongHandles, PerkId.DeepSwath }, requireLevel = 2,
|
||||
desc = Loc.N("A razor edge: +10% width and depth, +0.5 m reach.") },
|
||||
|
||||
// ── SUIT ──
|
||||
new PerkDef { id = PerkId.ServoBoots, tree = PerkTree.Suit, name = Loc.N("Servo Boots"), icon = "icon_perk_sneakers", col = 0, row = 0, prices = new long[] { 50, 160, 450 },
|
||||
desc = Loc.N("Move faster."), effect = l => Loc.F("Speed +{0}%", l * 7) },
|
||||
new PerkDef { id = PerkId.SpringStep, tree = PerkTree.Suit, name = Loc.N("Spring Step"), icon = "icon_perk_boots", col = 2, row = 0, prices = new long[] { 80, 250 },
|
||||
desc = Loc.N("Jump higher."), effect = l => Loc.F("Jump +{0}%", l * 20) },
|
||||
new PerkDef { id = PerkId.FieldFrame, tree = PerkTree.Suit, name = Loc.N("Field Frame"), icon = "icon_perk_fins", col = 1, row = 1, prices = new long[] { 1200 }, big = true, requires = new[] { PerkId.ServoBoots, PerkId.SpringStep }, requireLevel = 2,
|
||||
desc = Loc.N("A light exoskeleton: +8% speed, +15% jump.") },
|
||||
|
||||
// ── LOGISTICS ──
|
||||
new PerkDef { id = PerkId.QuickTwine, tree = PerkTree.Logistics, name = Loc.N("Quick Twine"), icon = "icon_perk_release", col = 0, row = 0, prices = new long[] { 30, 100, 300 },
|
||||
desc = Loc.N("Tie bundles faster."), effect = l => Loc.F("Bundle time -{0}%", l switch { 1 => 25, 2 => 44, _ => 58 }) },
|
||||
new PerkDef { id = PerkId.BundleLine, tree = PerkTree.Logistics, name = Loc.N("Bundle Line"), icon = "icon_perk_remote", col = 1, row = 0, prices = new long[] { 60, 200 },
|
||||
desc = Loc.N("Grab bundles from further away."), effect = l => Loc.F("Pick-up reach +{0:0.#} m", l * 1.5f) },
|
||||
new PerkDef { id = PerkId.ThrowArm, tree = PerkTree.Logistics, name = Loc.N("Throwing Arm"), icon = "icon_perk_beltspeed", col = 2, row = 0, prices = new long[] { 80, 240 },
|
||||
desc = Loc.N("Throw bundles further."), effect = l => Loc.F("Throw +{0}%", l * 25) },
|
||||
new PerkDef { id = PerkId.ExpressDepot, tree = PerkTree.Logistics, name = Loc.N("Express Depot"), icon = "icon_perk_dockpump", col = 1, row = 1, prices = new long[] { 900 }, big = true, requires = new[] { PerkId.QuickTwine }, requireLevel = 2,
|
||||
desc = Loc.N("Bundles tie twice as fast and machines unload at the depot twice as fast.") },
|
||||
|
||||
// ── ECONOMY ──
|
||||
new PerkDef { id = PerkId.EarthPrices, tree = PerkTree.Economy, name = Loc.N("Earth Prices"), icon = "icon_perk_contracts", col = 0, row = 0, prices = new long[] { 120, 400, 1100 },
|
||||
desc = Loc.N("Earth is desperate for grass. Make it pay."), effect = l => Loc.F("Payout +{0}%", l * 6) },
|
||||
new PerkDef { id = PerkId.RegionBonus, tree = PerkTree.Economy, name = Loc.N("Sector Bounty"), icon = "icon_perk_purity", col = 2, row = 0, prices = new long[] { 200, 600 },
|
||||
desc = Loc.N("More cash for every sector mown clean."), effect = l => Loc.F("+{0} per sector", UIK.Money(l * 15d)) },
|
||||
new PerkDef { id = PerkId.SupplyDeals, tree = PerkTree.Economy, name = Loc.N("Supply Deals"), icon = "icon_perk_overclock", col = 0, row = 1, prices = new long[] { 250, 700 },
|
||||
desc = Loc.N("Tools at the supply wall get cheaper."), effect = l => Loc.F("Tools -{0}%", l * 5) },
|
||||
new PerkDef { id = PerkId.GreenExchange, tree = PerkTree.Economy, name = Loc.N("Green Exchange"), icon = "icon_star", col = 1, row = 2, prices = new long[] { 2500 }, big = true, requires = new[] { PerkId.EarthPrices }, requireLevel = 2,
|
||||
desc = Loc.N("A seat on the Earth grass exchange: +10% on every payout.") },
|
||||
};
|
||||
|
||||
public static PerkDef Perk(PerkId id) => Perks[(int)id];
|
||||
|
||||
// ───────────────────────── build pieces ─────────────────────────
|
||||
|
||||
public static readonly PieceDef[] Pieces =
|
||||
{
|
||||
new PieceDef { id = PieceId.Depot, cat = PieceCat.Services, company = true, name = Loc.N("Grass Depot"), icon = "icon_piece_hopper", model = "SM_Hopper", prefab = "Piece_Depot", sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Everything that goes in here is paid for and shipped to Earth.") },
|
||||
new PieceDef { id = PieceId.Belt, cat = PieceCat.Logistics, name = Loc.N("Belt"), icon = "icon_piece_belt", model = "SM_Belt", prefab = "Piece_Belt", price = 0.5,
|
||||
desc = Loc.N("A straight run: click where it starts, click where it ends.") },
|
||||
new PieceDef { id = PieceId.Splitter, cat = PieceCat.Logistics, name = Loc.N("Splitter"), icon = "icon_piece_splitter", model = "SM_BeltSplitter", prefab = "Piece_Splitter", price = 5,
|
||||
desc = Loc.N("Deals bundles to the belts joined to it, left, right and straight on. E makes it a sorter: one kind goes left.") },
|
||||
new PieceDef { id = PieceId.Merger, cat = PieceCat.Logistics, name = Loc.N("Merger"), icon = "icon_piece_merger", model = "SM_BeltMerger", prefab = "Piece_Merger", price = 5,
|
||||
desc = Loc.N("Brings up to three belts into one, in turn. E gives one of them the right of way.") },
|
||||
new PieceDef { id = PieceId.Square, cat = PieceCat.Structures, name = Loc.N("Square Foundation"), icon = "icon_piece_foundation", model = "SM_Foundation_Square", prefab = "Piece_Square", price = 10, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A level timber deck on mown ground. What stands on it goes along when you move it.") },
|
||||
new PieceDef { id = PieceId.Hex, cat = PieceCat.Structures, name = Loc.N("Hex Foundation"), icon = "icon_piece_hexfoundation", model = "SM_Foundation_Hex", prefab = "Piece_Hex", price = 10, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A level timber deck on mown ground, turns in steps of 30 degrees.") },
|
||||
new PieceDef { id = PieceId.Dryer, cat = PieceCat.Production, name = Loc.N("Windmill"), icon = "icon_piece_vaporizer", model = "SM_Windmill", prefab = "Piece_Dryer", price = 500, sizeX = 2, sizeZ = 2, kw = 10f,
|
||||
desc = Loc.N("Five kilos of grass become five of hay in 12 seconds. Hay pays three times as much.") },
|
||||
new PieceDef { id = PieceId.Press, cat = PieceCat.Production, name = Loc.N("Brick Press"), icon = "icon_piece_cryo", model = "SM_CryoPress", prefab = "Piece_Press", price = 1000, sizeX = 2, sizeZ = 2, kw = 18f,
|
||||
desc = Loc.N("A kilo of grass and a kilo of hay become two kilos of brick in 6 seconds. Brick pays seven times as much.") },
|
||||
new PieceDef { id = PieceId.SolarS, cat = PieceCat.Power, name = Loc.N("Solar Post"), icon = "icon_piece_solars", prefab = "Piece_SolarS", price = 75,
|
||||
desc = Loc.N("3 kW within 16 m, less when the sun is low, nothing at night.") },
|
||||
new PieceDef { id = PieceId.SolarM, cat = PieceCat.Power, name = Loc.N("Solar Pair"), icon = "icon_piece_solarm", prefab = "Piece_SolarM", price = 150, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("7.5 kW within 24 m, less when the sun is low, nothing at night.") },
|
||||
new PieceDef { id = PieceId.SolarL, cat = PieceCat.Power, name = Loc.N("Solar Tracker"), icon = "icon_piece_solarl", prefab = "Piece_SolarL", price = 300, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("16 kW within 34 m. Follows the sun, so it gives its full power all day.") },
|
||||
new PieceDef { id = PieceId.Garage, cat = PieceCat.Services, name = Loc.N("Garage"), icon = "icon_perk_fleet", model = "SM_Bld_Garage_01", prefab = "Piece_Garage", price = 200, sizeX = 9, sizeZ = 4, scale = 0.6f,
|
||||
desc = Loc.N("Sells and calls machines. What they unload on the pad goes into a silo, two ports at the back send it out as bundles.") },
|
||||
new PieceDef { id = PieceId.Binder, cat = PieceCat.Logistics, name = Loc.N("Binder"), icon = "icon_piece_binder", model = "SM_Binder", prefab = "Piece_Binder", price = 100, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("E hands it what's in your tool. It ties the grass into bundles and puts them on the belt at its front.") },
|
||||
new PieceDef { id = PieceId.RobotI, cat = PieceCat.Services, name = Loc.N("Robot Mk I"), icon = "icon_piece_robot", model = "SM_RobotDock", prefab = "Piece_RobotI", price = 250, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Mows the 19 sectors around its dock. The dock ties what it brings into bundles for the belt.") },
|
||||
new PieceDef { id = PieceId.RobotII, cat = PieceCat.Services, name = Loc.N("Robot Mk II"), icon = "icon_piece_robot2", model = "SM_RobotDock", prefab = "Piece_RobotII", price = 500, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("37 sectors, a wider cut and a bigger hopper.") },
|
||||
new PieceDef { id = PieceId.Reaper, cat = PieceCat.Services, name = Loc.N("Reaper"), icon = "icon_piece_reaper", model = "SM_Reaper", prefab = "Piece_Reaper", price = 20000, sizeX = 3, sizeZ = 4,
|
||||
desc = Loc.N("Goes from sector to sector on its own and shoots every bundle into a Bundle Catcher, from anywhere on the planet.") },
|
||||
new PieceDef { id = PieceId.Catcher, cat = PieceCat.Services, name = Loc.N("Bundle Catcher"), icon = "icon_piece_catcher", model = "SM_BundleCatcher", prefab = "Piece_Catcher", price = 1500, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Holds 100 kg of what Reapers shoot and puts it on the belt.") },
|
||||
new PieceDef { id = PieceId.Pole, cat = PieceCat.Power, name = Loc.N("Power Pole"), icon = "icon_piece_pole", model = "SM_Prop_Power_Pole_01", prefab = "Piece_Pole", price = 25, scale = 0.62f,
|
||||
desc = Loc.N("Carries the network 30 m further. Poles reach each other and everything around them.") },
|
||||
new PieceDef { id = PieceId.BatteryS, cat = PieceCat.Power, name = Loc.N("Battery Rack"), icon = "icon_piece_battery", model = "SM_BatteryRack", prefab = "Piece_BatteryS", price = 250, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Stores 5 kWh of spare sun and gives it back at up to 10 kW when the panels fall short, within 12 m.") },
|
||||
new PieceDef { id = PieceId.BatteryL, cat = PieceCat.Power, name = Loc.N("Battery Bank"), icon = "icon_piece_batteryl", model = "SM_BatteryBank", prefab = "Piece_BatteryL", price = 1000, sizeX = 3, sizeZ = 2,
|
||||
desc = Loc.N("Stores 25 kWh and gives back up to 40 kW, within 16 m. A windmill and a press run all night on one.") },
|
||||
new PieceDef { id = PieceId.UnloadBay, cat = PieceCat.Logistics, name = Loc.N("Unload Bay"), icon = "icon_piece_unloadbay", model = "SM_UnloadBay", prefab = "Piece_UnloadBay", price = 150, sizeX = 4, sizeZ = 7,
|
||||
desc = Loc.N("Drive a mower onto the grate and it empties into the bin. Two hatches at the back put it on belts as bundles.") },
|
||||
new PieceDef { id = PieceId.DronePad, cat = PieceCat.Logistics, name = Loc.N("Drone Pad"), icon = "icon_piece_dronepad", model = "SM_DronePad", prefab = "Piece_DronePad", price = 600, sizeX = 3, sizeZ = 3, scale = 3.2f,
|
||||
desc = Loc.N("Its drones fly out to bundles of grass lying loose within 40 m and bring them in. The front hatch puts them on a belt. Two drones, one more per upgrade.") },
|
||||
new PieceDef { id = PieceId.Intake, cat = PieceCat.Services, company = true, name = Loc.N("Base Intake"), icon = "icon_piece_hopper", model = "SM_BaseIntake", prefab = "Piece_Intake", sizeX = 3, sizeZ = 2,
|
||||
desc = Loc.N("A low hopper against the side of the base: drop grass in or run a belt to it, and it's paid and on its way to Earth.") },
|
||||
|
||||
// structures: a 3 m grid, walls on the edges of a deck, floors and roofs on top of the walls
|
||||
new PieceDef { id = PieceId.Wall, cat = PieceCat.Structures, name = Loc.N("Wall"), icon = "icon_piece_wall", model = "SM_Wall", prefab = "Piece_Wall", price = 4, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A 3 m timber wall. It goes on the edge of a foundation or a floor; R turns it round.") },
|
||||
new PieceDef { id = PieceId.WindowWall, cat = PieceCat.Structures, name = Loc.N("Window Wall"), icon = "icon_piece_windowwall", model = "SM_WallWindow", prefab = "Piece_WindowWall", price = 6, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A wall with a glazed window and a flower box under it.") },
|
||||
new PieceDef { id = PieceId.DoorWall, cat = PieceCat.Structures, name = Loc.N("Door Wall"), icon = "icon_piece_doorwall", model = "SM_WallDoor", prefab = "Piece_DoorWall", price = 6, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("A wall with a doorway you can walk through, and a lantern over it.") },
|
||||
new PieceDef { id = PieceId.Railing, cat = PieceCat.Structures, name = Loc.N("Railing"), icon = "icon_piece_railing", model = "SM_Railing", prefab = "Piece_Railing", price = 2, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("Waist-high rails for the edge of a raised deck or a floor upstairs.") },
|
||||
new PieceDef { id = PieceId.Fence, cat = PieceCat.Decor, name = Loc.N("Picket Fence"), icon = "icon_piece_fence", model = "SM_Fence", prefab = "Piece_Fence", price = 1, sizeX = 3, sizeZ = 1,
|
||||
desc = Loc.N("Three metres of cream pickets, on the ground or on the edge of a deck.") },
|
||||
new PieceDef { id = PieceId.Floor, cat = PieceCat.Structures, name = Loc.N("Floor"), icon = "icon_piece_floor", model = "SM_Floor", prefab = "Piece_Floor", price = 6, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A storey up: it rests on the walls below. Walls and machines stand on it like on a foundation.") },
|
||||
new PieceDef { id = PieceId.FlatRoof, cat = PieceCat.Structures, name = Loc.N("Flat Roof"), icon = "icon_piece_flatroof", model = "SM_FlatRoof", prefab = "Piece_FlatRoof", price = 5, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("A tin roof on top of the walls. You can stand on it, and build on it too.") },
|
||||
new PieceDef { id = PieceId.Roof, cat = PieceCat.Structures, name = Loc.N("Pitched Roof"), icon = "icon_piece_roof", model = "SM_Roof", prefab = "Piece_Roof", price = 5, sizeX = 3, sizeZ = 3,
|
||||
desc = Loc.N("Half of a gable roof on top of the walls, the eave on the wall you aim at. Two back to back make a whole roof.") },
|
||||
new PieceDef { id = PieceId.Stairs, cat = PieceCat.Structures, name = Loc.N("Stairs"), icon = "icon_piece_stairs", model = "SM_Stairs", prefab = "Piece_Stairs", price = 8, sizeX = 1, sizeZ = 3,
|
||||
desc = Loc.N("A flight up one storey, 3 m. It climbs the way the arrow points.") },
|
||||
new PieceDef { id = PieceId.Steps, cat = PieceCat.Structures, name = Loc.N("Steps"), icon = "icon_piece_steps", model = "SM_Steps", prefab = "Piece_Steps", price = 4, sizeX = 2, sizeZ = 2,
|
||||
desc = Loc.N("Six wide steps up to a raised foundation, 1.5 m high.") },
|
||||
new PieceDef { id = PieceId.Pillar, cat = PieceCat.Structures, name = Loc.N("Pillar"), icon = "icon_piece_pillar", model = "SM_Pillar", prefab = "Piece_Pillar", price = 2, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("A 3 m timber post on a stone base: it holds up a floor where there's no wall.") },
|
||||
new PieceDef { id = PieceId.Planter, cat = PieceCat.Decor, name = Loc.N("Flower Box"), icon = "icon_piece_planter", model = "SM_Planter", prefab = "Piece_Planter", price = 3, sizeX = 2, sizeZ = 1,
|
||||
desc = Loc.N("Flowers in a timber box. They don't pay, they just look nice.") },
|
||||
new PieceDef { id = PieceId.Lamppost, cat = PieceCat.Decor, name = Loc.N("Lamp Post"), icon = "icon_piece_lamppost", model = "SM_Lamppost", prefab = "Piece_Lamppost", price = 4, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("A farm lamp that comes on at dusk.") },
|
||||
new PieceDef { id = PieceId.Bench, cat = PieceCat.Decor, name = Loc.N("Bench"), icon = "icon_piece_bench", model = "SM_Bench", prefab = "Piece_Bench", price = 3, sizeX = 2, sizeZ = 1,
|
||||
desc = Loc.N("Somewhere to sit and watch the robots work.") },
|
||||
new PieceDef { id = PieceId.Crates, cat = PieceCat.Decor, name = Loc.N("Crates"), icon = "icon_piece_crates", model = "SM_Crate", prefab = "Piece_Crates", price = 2, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("Company crates, stacked two high.") },
|
||||
new PieceDef { id = PieceId.Flagpole, cat = PieceCat.Decor, name = Loc.N("Flagpole"), icon = "icon_piece_flagpole", model = "SM_Flagpole", prefab = "Piece_Flagpole", price = 5, sizeX = 1, sizeZ = 1,
|
||||
desc = Loc.N("The crew's own flag, four metres up.") },
|
||||
};
|
||||
|
||||
public static PieceDef Piece(PieceId id) => Pieces[(int)id];
|
||||
|
||||
// ───────────────────────── piece upgrades ─────────────────────────
|
||||
|
||||
public const int MaxTier = 3;
|
||||
public static string TierName(int t) => Loc.F("Mk {0}", t == 0 ? "I" : t == 1 ? "II" : t == 2 ? "III" : "IV");
|
||||
|
||||
public static UpgradeKind UpgradeOf(PieceId id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case PieceId.Belt: case PieceId.Splitter: case PieceId.Merger: return UpgradeKind.Belt;
|
||||
case PieceId.Dryer: case PieceId.Press: case PieceId.Binder: return UpgradeKind.Machine;
|
||||
case PieceId.RobotI: case PieceId.RobotII: case PieceId.Reaper: return UpgradeKind.Robot;
|
||||
case PieceId.Garage: case PieceId.UnloadBay: case PieceId.Catcher: case PieceId.DronePad: return UpgradeKind.Silo;
|
||||
default: return UpgradeKind.None;
|
||||
}
|
||||
}
|
||||
|
||||
static readonly float[] BeltTiers = { 1f, 1.5f, 2f, 3f }, MachineTiers = { 1f, 1.5f, 2f, 2.5f }, RobotTiers = { 1f, 1.3f, 1.6f, 1.9f }, SiloTiers = { 1f, 2f, 3f, 4f };
|
||||
|
||||
public static float TierMul(UpgradeKind k, int tier)
|
||||
{
|
||||
tier = Mathf.Clamp(tier, 0, MaxTier);
|
||||
switch (k)
|
||||
{
|
||||
case UpgradeKind.Belt: return BeltTiers[tier];
|
||||
case UpgradeKind.Machine: return MachineTiers[tier];
|
||||
case UpgradeKind.Robot: return RobotTiers[tier];
|
||||
case UpgradeKind.Silo: return SiloTiers[tier];
|
||||
default: return 1f;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A machine at a higher tier also draws more power.</summary>
|
||||
public static float TierPower(int tier) => 1f + 0.25f * Mathf.Clamp(tier, 0, MaxTier);
|
||||
|
||||
public static string TierEffect(UpgradeKind k, int tier)
|
||||
{
|
||||
float m = TierMul(k, tier);
|
||||
switch (k)
|
||||
{
|
||||
case UpgradeKind.Belt: return Loc.F("runs at x{0:0.#} speed", m);
|
||||
case UpgradeKind.Machine: return Loc.F("works x{0:0.#} as fast, draws x{1:0.##} power", m, TierPower(tier));
|
||||
case UpgradeKind.Robot: return Loc.F("x{0:0.#} speed and hopper", m);
|
||||
case UpgradeKind.Silo: return Loc.F("sends out x{0:0} the bundles", m);
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
public static double UpgradePrice(BuildPiece p, int tier)
|
||||
{
|
||||
double basis = p.Run ? Math.Max(20d, p.Run.Metres * 4d) : Math.Max(20d, p.Def.price);
|
||||
return Math.Round(basis * (tier == 0 ? 0.5 : tier == 1 ? 1.2 : 2.5));
|
||||
}
|
||||
public static bool IsFoundation(PieceId id) => id == PieceId.Square || id == PieceId.Hex;
|
||||
/// <summary>Something to stand and build on: a foundation on the ground, or a floor or flat roof a storey up.</summary>
|
||||
public static bool IsDeck(PieceId id) => IsFoundation(id) || id == PieceId.Floor || id == PieceId.FlatRoof;
|
||||
/// <summary>A deck with four 3 m edges, where walls go.</summary>
|
||||
public static bool IsSquareDeck(PieceId id) => id == PieceId.Square || id == PieceId.Floor || id == PieceId.FlatRoof;
|
||||
/// <summary>A storey: walls are this tall, and a floor on them is this far above the deck they stand on.</summary>
|
||||
public const float Storey = 3f;
|
||||
|
||||
public static Fit FitOf(PieceId id)
|
||||
{
|
||||
switch (id)
|
||||
{
|
||||
case PieceId.Wall: case PieceId.WindowWall: case PieceId.DoorWall: case PieceId.Railing: case PieceId.Fence: return Fit.Edge;
|
||||
case PieceId.Floor: case PieceId.FlatRoof: case PieceId.Roof: return Fit.Top;
|
||||
default: return Fit.Free;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A wall-high piece: a floor or a roof can rest on it.</summary>
|
||||
public static bool Holds(PieceId id) => id == PieceId.Wall || id == PieceId.WindowWall || id == PieceId.DoorWall || id == PieceId.Pillar;
|
||||
public static bool IsPanel(PieceId id) => id >= PieceId.SolarS && id <= PieceId.SolarL;
|
||||
|
||||
static readonly RecipeDef Drying = new RecipeDef { grass = 5f, seconds = 12f, makes = 5f, product = CargoKind.Hay };
|
||||
static readonly RecipeDef Pressing = new RecipeDef { grass = 1f, hay = 1f, seconds = 6f, makes = 2f, product = CargoKind.Brick };
|
||||
public static RecipeDef Recipe(PieceId id) => id == PieceId.Press ? Pressing : Drying;
|
||||
|
||||
static readonly PanelDef Post = new PanelDef { kw = 3f, radius = 16f };
|
||||
static readonly PanelDef Pair = new PanelDef { kw = 7.5f, radius = 24f };
|
||||
static readonly PanelDef Tracker = new PanelDef { kw = 16f, radius = 34f, tracker = true };
|
||||
public static PanelDef Panel(PieceId id) => id == PieceId.SolarL ? Tracker : id == PieceId.SolarM ? Pair : Post;
|
||||
|
||||
static readonly BatteryDef Rack = new BatteryDef { kwh = 5f, kw = 10f, radius = 12f };
|
||||
static readonly BatteryDef Bank = new BatteryDef { kwh = 25f, kw = 40f, radius = 16f };
|
||||
public static BatteryDef Battery(PieceId id) => id == PieceId.BatteryL ? Bank : Rack;
|
||||
public static bool IsBattery(PieceId id) => id == PieceId.BatteryS || id == PieceId.BatteryL;
|
||||
|
||||
public const float PoleReach = 30f, PoleHeight = 3.05f, PoleArm = 0.62f;
|
||||
|
||||
/// <summary>How far a power piece reaches, 0 for anything else.</summary>
|
||||
public static float Reach(PieceId id) => IsPanel(id) ? Panel(id).radius : IsBattery(id) ? Battery(id).radius : id == PieceId.Pole ? PoleReach : 0f;
|
||||
|
||||
/// <summary>Seconds from noon to noon. The original's figure isn't known.</summary>
|
||||
public const float DayLength = 1800f;
|
||||
|
||||
// ───────────────────────── economy (shared by server & client prediction) ─────────────────────────
|
||||
|
||||
public static float BinMul(int level) => 1 << Mathf.Clamp(level, 0, 3);
|
||||
public static float CompactorMul(int level) => 1f + level * 0.15f;
|
||||
public static float ToolCap(ToolId t, int binLevel, int compactor) => Tool(t).capacity * BinMul(binLevel) * CompactorMul(compactor);
|
||||
|
||||
public static float WidthBonus(int level) => level * 0.08f;
|
||||
public const float ToolReach = 2.6f;
|
||||
public const float BundleKg = 1f;
|
||||
public static float BundleSeconds(int quick, int express) =>
|
||||
0.6f * (quick switch { 0 => 1f, 1 => 0.75f, 2 => 0.56f, _ => 0.42f }) * (express > 0 ? 0.5f : 1f);
|
||||
|
||||
public static float MoveMul(int stride, int frame) => (1f + stride * 0.07f) * (frame > 0 ? 1.08f : 1f);
|
||||
public static float JumpMul(int leap, int frame) => (1f + leap * 0.2f) * (frame > 0 ? 1.15f : 1f);
|
||||
public static float ThrowMul(int level) => 1f + level * 0.25f;
|
||||
public static float PayoutMul(int prices, int exchange) => (1f + prices * 0.06f) * (exchange > 0 ? 1.1f : 1f);
|
||||
public static float ToolPriceMul(int deals) => 1f - deals * 0.05f;
|
||||
|
||||
// cargo
|
||||
public static string CargoName(CargoKind k) => k switch { CargoKind.Hay => Loc.T("Hay"), CargoKind.Brick => Loc.T("Pressed Brick"), _ => Loc.T("Grass Bundle") };
|
||||
/// <summary>What Earth pays per kilo for each form (before market bonuses).</summary>
|
||||
public static float PerKg(CargoKind k) => k switch { CargoKind.Hay => 3f, CargoKind.Brick => 7f, _ => 1f };
|
||||
|
||||
// belts
|
||||
public const float BeltSpeed = 2.2f;
|
||||
public const float BeltShortest = 0.8f, BeltLongest = 30f, BeltLowest = 0.4f, BeltHighest = 6f, BeltSteepest = 40f;
|
||||
public static double BeltPrice(float metres) => System.Math.Round(metres * Piece(PieceId.Belt).price, 2);
|
||||
|
||||
// vehicles
|
||||
public const double TravelPrice = 50d;
|
||||
|
||||
public static readonly RobotDef[] Robots =
|
||||
{
|
||||
new RobotDef { piece = PieceId.RobotI, name = Loc.N("Robot Mk I"), reach = 2, width = 0.9f, speed = 1.6f, hopper = 20f },
|
||||
new RobotDef { piece = PieceId.RobotII, name = Loc.N("Robot Mk II"), reach = 3, width = 1.2f, speed = 2.2f, hopper = 50f },
|
||||
new RobotDef { piece = PieceId.Reaper, name = Loc.N("Reaper"), width = 1.8f, speed = 3f, hopper = 40f },
|
||||
};
|
||||
|
||||
public static RobotDef Robot(PieceId id)
|
||||
{
|
||||
foreach (var r in Robots) if (r.piece == id) return r;
|
||||
return Robots[0];
|
||||
}
|
||||
|
||||
public static readonly VehicleDef[] Vehicles =
|
||||
{
|
||||
new VehicleDef { kind = VehicleKind.Push, name = Loc.N("Push Mower"), icon = "icon_vehicle_push", price = 300, width = 1.35f, hopper = 100f, speed = 5f, accel = 7f, turn = 3f,
|
||||
desc = Loc.N("The first step up from a scythe: a wide strip at walking pace.") },
|
||||
new VehicleDef { kind = VehicleKind.Rider, name = Loc.N("Garden Rider"), icon = "icon_vehicle_ski", price = 1000, width = 2f, hopper = 500f, speed = 9.7f, accel = 11f, turn = 2.2f,
|
||||
desc = Loc.N("Sit down, drive, mow. Unloads at a garage pad.") },
|
||||
new VehicleDef { kind = VehicleKind.Pickup, name = Loc.N("Pickup"), icon = "icon_vehicle_hover", price = 2000, speed = 14f, accel = 10f, turn = 1.8f, bed = 4, seatDrop = 0.56f, seatAhead = 0.12f,
|
||||
desc = Loc.N("Doesn't mow. Fast, and carries four bundles: E loads the one in your arms, T tips them out.") },
|
||||
new VehicleDef { kind = VehicleKind.Tractor, name = Loc.N("Mowing Tractor"), icon = "icon_vehicle_tug", price = 2500, width = 2.8f, hopper = 1200f, speed = 9f, accel = 8f, turn = 1.5f, seatDrop = 0.42f,
|
||||
desc = Loc.N("A proper machine for proper fields.") },
|
||||
new VehicleDef { kind = VehicleKind.Combine, name = Loc.N("Combine"), icon = "icon_vehicle_combine", price = 6000, width = 3.7f, hopper = 3000f, speed = 8f, accel = 5f, turn = 1.3f, seatDrop = 0.45f,
|
||||
desc = Loc.N("Slow to turn, and nothing else cuts as wide or carries as much.") },
|
||||
new VehicleDef { kind = VehicleKind.Hauler, name = Loc.N("Haul Tractor"), icon = "icon_vehicle_hauler", price = 4000, width = 1.6f, hopper = 4000f, speed = 12f, accel = 8f, turn = 1.4f, seatDrop = 0.18f,
|
||||
desc = Loc.N("A narrow cutter and a huge tank on a trailer: mow far out, come back once.") },
|
||||
new VehicleDef { kind = VehicleKind.Mulcher, name = Loc.N("Wide Mulcher"), icon = "icon_vehicle_mulcher", price = 8000, width = 5.5f, hopper = 900f, speed = 7f, accel = 5f, turn = 1.1f, seatDrop = 0.18f,
|
||||
desc = Loc.N("Wings out to five and a half metres. Fills fast: put an Unload Bay near the field.") },
|
||||
new VehicleDef { kind = VehicleKind.Baler, name = Loc.N("Baler Tractor"), icon = "icon_vehicle_baler", price = 3500, width = 2.2f, hopper = 600f, speed = 9f, accel = 8f, turn = 1.5f, bales = true,
|
||||
desc = Loc.N("Bales as it goes: pull up beside the start of any belt and its chute feeds the belt, five bundles a second.") },
|
||||
};
|
||||
|
||||
public static VehicleDef Vehicle(VehicleKind k) => Vehicles[(int)k];
|
||||
|
||||
public static readonly TuneDef[] Tunes =
|
||||
{
|
||||
new TuneDef { id = TuneId.Motors, name = Loc.N("Tuned Motors"), prices = new long[] { 250, 600, 1500 }, effect = l => Loc.F("+{0}% speed and pull", l * 10) },
|
||||
new TuneDef { id = TuneId.Hopper, name = Loc.N("Big Hopper"), prices = new long[] { 200, 500, 1200 }, effect = l => Loc.F("+{0}% hopper", l * 30) },
|
||||
new TuneDef { id = TuneId.Turbo, name = Loc.N("Turbo Kit"), prices = new long[] { 400, 1200 }, effect = l => Loc.F("SHIFT boost {0:0}%", BoostMul(l) * 100f) },
|
||||
new TuneDef { id = TuneId.Cruise, name = Loc.N("Cruise Control"), prices = new long[] { 500 }, effect = l => Loc.T("C holds your speed") },
|
||||
new TuneDef { id = TuneId.Cutter, name = Loc.N("Cutter Control"), prices = new long[] { 400, 900, 2000 }, effect = l => Loc.F("Strip +{0}% at {1:0}% speed", l * 25, CutterSpeed(l) * 100f) },
|
||||
new TuneDef { id = TuneId.Release, name = Loc.N("Quick Release"), prices = new long[] { 150, 400 }, effect = l => Loc.F("+{0}% unloading", l * 50) },
|
||||
new TuneDef { id = TuneId.Lights, name = Loc.N("Floodlights"), prices = new long[] { 100, 300 }, effect = l => Loc.F("+{0}% light at night", l * 60) },
|
||||
};
|
||||
|
||||
public static TuneDef Tune(TuneId t) => Tunes[(int)t];
|
||||
/// <summary>Upgrades cost more on dearer machines, from half to three times the listed price.</summary>
|
||||
public static double TunePrice(VehicleKind k, TuneId t, int level) => System.Math.Round(Tune(t).prices[level] * System.Math.Min(3d, System.Math.Max(0.5d, Vehicle(k).price / 1000d)), 2);
|
||||
public static bool TuneFits(VehicleKind k, TuneId t) => Vehicle(k).bed == 0 || (t != TuneId.Hopper && t != TuneId.Cutter && t != TuneId.Release);
|
||||
public static float BoostMul(int level) => level >= 2 ? 1.65f : level == 1 ? 1.5f : 1.25f;
|
||||
public static float CutterSpeed(int level) => level >= 3 ? 0.6f : level == 2 ? 0.72f : level == 1 ? 0.85f : 1f;
|
||||
public static float VehicleTankMul(int level) => 1f + level * 0.3f;
|
||||
public static float VehicleSpeedMul(int level) => 1f + level * 0.1f;
|
||||
public static float DockRate(int level) => 120f * (1f + level * 0.5f);
|
||||
|
||||
public static string ToRoman(int n) => n switch { 1 => "I", 2 => "II", 3 => "III", 4 => "IV", 5 => "V", _ => n.ToString() };
|
||||
|
||||
public static string Kilos(double kg)
|
||||
{
|
||||
if (kg >= 1_000_000) return Loc.F("{0} t", Loc.Num(kg / 1000d, "N0"));
|
||||
if (kg >= 10_000) return Loc.F("{0} t", Loc.Num(kg / 1000d, "0.#"));
|
||||
return Loc.F("{0} kg", Loc.Num(kg, kg < 100d ? "0.##" : "N0"));
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/GameDefs.cs.meta
Normal file
2
Assets/Scripts/Gameplay/GameDefs.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0cbdb0f35d4c2984fa886594181b5501
|
||||
60
Assets/Scripts/Gameplay/Garage.cs
Normal file
60
Assets/Scripts/Gameplay/Garage.cs
Normal file
@ -0,0 +1,60 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A garage you build yourself: sells and calls machines like the one at the base, and whatever a machine unloads on the pad
|
||||
/// in front goes into its silo. Two ports at the back turn the silo into bundles for the belts.
|
||||
/// </summary>
|
||||
public class Garage : SiloPiece
|
||||
{
|
||||
public static readonly List<Garage> All = new List<Garage>();
|
||||
|
||||
// the garage stands at 0.6 times the pack model (half what it was: it towered over the base): its front is 1.9 m out,
|
||||
// its back wall 1.9 m back. The pad is still sized for the machines.
|
||||
const float PadFront = 2.4f, PadLong = 11f, PadWide = 6.5f, PortBack = 2.24f;
|
||||
|
||||
public override string Prompt => Loc.F("Garage — buy, call & upgrade machines (silo {0})", GameDefs.Kilos(Silo.Value));
|
||||
|
||||
public override void Interact()
|
||||
{
|
||||
Sfx.Play("ui_open");
|
||||
UIRoot.I?.OpenGarage(this);
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() { All.Add(this); base.OnNetworkSpawn(); }
|
||||
public override void OnNetworkDespawn() { All.Remove(this); base.OnNetworkDespawn(); }
|
||||
|
||||
public override string PadName => Loc.T("Garage pad");
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public override void Ports(List<Port> into)
|
||||
{
|
||||
var back = -transform.forward;
|
||||
var at = transform.position + transform.up * GameDefs.BeltLowest + back * PortBack;
|
||||
into.Add(new Port { at = at - transform.right * 0.8f, dir = back });
|
||||
into.Add(new Port { at = at + transform.right * 0.8f, dir = back });
|
||||
}
|
||||
|
||||
/// <summary>Where a called machine appears: the middle of the pad.</summary>
|
||||
public override Vector3 PadSpot => transform.position + transform.forward * (PadFront + PadLong * 0.5f) + transform.up * 0.6f;
|
||||
|
||||
public override bool OnPad(Vector3 p)
|
||||
{
|
||||
var l = transform.InverseTransformPoint(p);
|
||||
return Mathf.Abs(l.x) < PadWide && l.z > PadFront - 1f && l.z < PadFront + PadLong && Mathf.Abs(l.y) < 4f;
|
||||
}
|
||||
|
||||
public static Garage Under(Vector3 p)
|
||||
{
|
||||
foreach (var g in All) if (g && g.OnPad(p)) return g;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Garage.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Garage.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0ac65e3a49c10724ea8bdcaf15a12b76
|
||||
210
Assets/Scripts/Gameplay/Grabbable.cs
Normal file
210
Assets/Scripts/Gameplay/Grabbable.cs
Normal file
@ -0,0 +1,210 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using Unity.Netcode.Components;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A physics prop that players can pick up, carry and throw. Ownership moves to whoever grabs it so the
|
||||
/// holder simulates it locally (no lag); NetworkTransform runs in owner-authority mode.
|
||||
/// </summary>
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class Grabbable : NetworkBehaviour
|
||||
{
|
||||
public static readonly List<Grabbable> All = new List<Grabbable>();
|
||||
public const ulong Nobody = ulong.MaxValue;
|
||||
|
||||
public string displayName = "Thing";
|
||||
public bool trash;
|
||||
public bool trashIsBox;
|
||||
public float holdDistance = 1.4f;
|
||||
/// <summary>Recycler payout multiplier (pallets are worth more than a wrap ball).</summary>
|
||||
public float valueMul = 1f;
|
||||
|
||||
public readonly NetworkVariable<ulong> Holder = new NetworkVariable<ulong>(Nobody);
|
||||
public readonly NetworkVariable<bool> IsTrashNet = new NetworkVariable<bool>();
|
||||
public readonly NetworkVariable<float> Scale = new NetworkVariable<float>(1f);
|
||||
|
||||
public Rigidbody Body { get; private set; }
|
||||
public bool IsTrash => trash || IsTrashNet.Value;
|
||||
public bool IsHeld => Holder.Value != Nobody;
|
||||
public bool Consumed { get; set; }
|
||||
|
||||
int _baseLayer;
|
||||
Vector3 _baseScale;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
Body = GetComponent<Rigidbody>();
|
||||
Body.useGravity = false;
|
||||
_baseLayer = gameObject.layer;
|
||||
_baseScale = transform.localScale;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
Holder.OnValueChanged += (_, h) => ApplyHeldLayer(h != Nobody);
|
||||
Scale.OnValueChanged += (_, s) => transform.localScale = _baseScale * s;
|
||||
transform.localScale = _baseScale * Scale.Value;
|
||||
ApplyHeldLayer(IsHeld);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn() { All.Remove(this); }
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
void ApplyHeldLayer(bool held)
|
||||
{
|
||||
int layer = held ? Layers.Held : _baseLayer;
|
||||
foreach (var t in GetComponentsInChildren<Transform>(true)) t.gameObject.layer = layer;
|
||||
}
|
||||
|
||||
// ───────────────────────── grabbing ─────────────────────────
|
||||
|
||||
public void RequestGrab()
|
||||
{
|
||||
if (IsHeld) return;
|
||||
GrabRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
void GrabRpc(RpcParams rpc = default)
|
||||
{
|
||||
if (IsHeld || Consumed) return;
|
||||
// grabbing something off a belt unlocks it from the queue
|
||||
var cargo = GetComponent<Cargo>();
|
||||
if (cargo && cargo.Belt) cargo.ServerLeaveBelt(Vector3.zero);
|
||||
ulong who = rpc.Receive.SenderClientId;
|
||||
Holder.Value = who;
|
||||
if (OwnerClientId != who) NetworkObject.ChangeOwnership(who);
|
||||
GrabbedRpc(who);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void GrabbedRpc(ulong who)
|
||||
{
|
||||
Sfx.PlayAt(GrabClip, transform.position, 0.7f, 1.1f);
|
||||
if (who == NetworkManager.LocalClientId) PlayerAgent.Local?.Grab.OnGrantedGrab(this);
|
||||
}
|
||||
|
||||
/// <summary>Called by the holder (owner) to let go; velocity is applied locally since the holder owns the body.</summary>
|
||||
public void Release(Vector3 velocity, Vector3 angular)
|
||||
{
|
||||
if (IsOwner && Body && !Body.isKinematic)
|
||||
{
|
||||
Body.linearVelocity = velocity;
|
||||
Body.angularVelocity = angular;
|
||||
}
|
||||
ReleaseRpc();
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Server)]
|
||||
void ReleaseRpc(RpcParams rpc = default)
|
||||
{
|
||||
if (Holder.Value == rpc.Receive.SenderClientId) Holder.Value = Nobody;
|
||||
}
|
||||
|
||||
/// <summary>Server: forcibly drop (e.g. the holder disconnected or the item got recycled).</summary>
|
||||
public void ServerForceRelease()
|
||||
{
|
||||
if (IsServer) Holder.Value = Nobody;
|
||||
}
|
||||
|
||||
/// <summary>Ask the owner to apply an impulse (used by the recycler to spit out non-trash).</summary>
|
||||
public void ServerKick(Vector3 velocity)
|
||||
{
|
||||
KickRpc(velocity, RpcTarget.Single(OwnerClientId, RpcTargetUse.Temp));
|
||||
}
|
||||
|
||||
[Rpc(SendTo.SpecifiedInParams)]
|
||||
void KickRpc(Vector3 velocity, RpcParams p = default)
|
||||
{
|
||||
if (Body && !Body.isKinematic) { Body.linearVelocity = velocity; Body.angularVelocity = Random.insideUnitSphere * 6f; }
|
||||
}
|
||||
|
||||
string GrabClip
|
||||
{
|
||||
get
|
||||
{
|
||||
var c = GetComponent<Cargo>();
|
||||
if (!c) return "plastic_grab";
|
||||
return c.kind == CargoKind.Brick ? "ice_clink" : "barrel_clunk";
|
||||
}
|
||||
}
|
||||
|
||||
float _lastPush;
|
||||
|
||||
/// <summary>Nudge from a walking player. Applied directly when we simulate the body, otherwise forwarded to the owner.</summary>
|
||||
public void Push(Vector3 velocity)
|
||||
{
|
||||
if (Time.time - _lastPush < 0.12f || !IsSpawned) return;
|
||||
_lastPush = Time.time;
|
||||
if (IsOwner) { if (Body && !Body.isKinematic) Body.AddForce(velocity, ForceMode.VelocityChange); }
|
||||
else PushRpc(velocity);
|
||||
}
|
||||
|
||||
[Rpc(SendTo.Owner)]
|
||||
void PushRpc(Vector3 velocity)
|
||||
{
|
||||
if (Body && !Body.isKinematic && !IsHeld) Body.AddForce(velocity, ForceMode.VelocityChange);
|
||||
}
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!IsSpawned || !IsOwner || !Body || Body.isKinematic) return;
|
||||
var p = Body.position;
|
||||
var up = Planet.Up(p);
|
||||
if (!IsHeld) Body.AddForce(-up * GameDefs.LowGravity, ForceMode.Acceleration);
|
||||
// there is no collider under the grass: the soil is a number
|
||||
var c = GetComponent<Cargo>();
|
||||
float below = Planet.Altitude(p) - (c ? c.halfHeight : 0.3f);
|
||||
if (below >= 0f) return;
|
||||
Body.position = p - up * below;
|
||||
var v = Body.linearVelocity;
|
||||
float fall = Vector3.Dot(v, up);
|
||||
if (fall < 0f) v -= up * fall;
|
||||
Body.linearVelocity = v * 0.9f;
|
||||
Body.angularVelocity *= 0.9f;
|
||||
}
|
||||
|
||||
void OnCollisionEnter(Collision c)
|
||||
{
|
||||
float v = c.relativeVelocity.magnitude;
|
||||
if (v < 2.2f || !IsSpawned) return;
|
||||
string clip = GrabClip;
|
||||
Sfx.PlayAt(clip, transform.position, Mathf.Clamp01(v / 8f) * 0.8f, 1f, 0.1f, 0.05f);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Layers
|
||||
{
|
||||
public const int Default = 0;
|
||||
public const int Player = 6;
|
||||
public const int Wrap = 7;
|
||||
public const int Prop = 8;
|
||||
public const int Vehicle = 9;
|
||||
public const int Held = 10;
|
||||
public const int ViewModel = 11;
|
||||
public const int LocalPlayer = 12;
|
||||
public const int Build = 13;
|
||||
|
||||
public static void SetupCollisions()
|
||||
{
|
||||
Physics.IgnoreLayerCollision(Held, Player);
|
||||
Physics.IgnoreLayerCollision(Held, LocalPlayer);
|
||||
Physics.IgnoreLayerCollision(Held, Held);
|
||||
Physics.IgnoreLayerCollision(Wrap, Vehicle);
|
||||
Physics.IgnoreLayerCollision(ViewModel, Default);
|
||||
for (int i = 0; i < 32; i++) Physics.IgnoreLayerCollision(ViewModel, i);
|
||||
}
|
||||
|
||||
/// <summary>Things the player's interaction ray can hit.</summary>
|
||||
public static readonly int InteractMask = (1 << Default) | (1 << Wrap) | (1 << Prop) | (1 << Vehicle) | (1 << Player) | (1 << Build);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Grabbable.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Grabbable.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 50acd62fb7dd3264c9789ce552d296d9
|
||||
13
Assets/Scripts/Gameplay/IInteractable.cs
Normal file
13
Assets/Scripts/Gameplay/IInteractable.cs
Normal file
@ -0,0 +1,13 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public interface IInteractable
|
||||
{
|
||||
string Prompt { get; }
|
||||
bool CanInteract { get; }
|
||||
void Interact();
|
||||
}
|
||||
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/IInteractable.cs.meta
Normal file
2
Assets/Scripts/Gameplay/IInteractable.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 877ba4cdd9f1ba343a81ec12b5dbb728
|
||||
47
Assets/Scripts/Gameplay/Junction.cs
Normal file
47
Assets/Scripts/Gameplay/Junction.cs
Normal file
@ -0,0 +1,47 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A belt piece with a choice to make: the modes it can switch between.</summary>
|
||||
public interface IJunction
|
||||
{
|
||||
int ModeCount { get; }
|
||||
string ModeName(int mode);
|
||||
Color ModeColor(int mode);
|
||||
}
|
||||
|
||||
/// <summary>E on a splitter or a merger switches what it does, and the little sign on it shows which.</summary>
|
||||
public class Junction : MonoBehaviour, IInteractable
|
||||
{
|
||||
public Renderer sign;
|
||||
|
||||
BuildPiece _piece;
|
||||
IJunction _junction;
|
||||
MaterialPropertyBlock _mpb;
|
||||
int _shown = -1;
|
||||
static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
IJunction Parts => _junction ?? (_junction = GetComponentInChildren<IJunction>());
|
||||
|
||||
public string Prompt => Loc.F("{0}: {1} (E changes it)", Piece.Def.name, Parts.ModeName(Piece.Mode.Value));
|
||||
public bool CanInteract => true;
|
||||
|
||||
public void Interact()
|
||||
{
|
||||
Piece.NextModeRpc(Parts.ModeCount);
|
||||
Sfx.Play("ui_click", 0.7f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
int mode = Piece.Mode.Value;
|
||||
if (mode == _shown || !sign) return;
|
||||
_shown = mode;
|
||||
if (_mpb == null) _mpb = new MaterialPropertyBlock();
|
||||
sign.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(BaseColor, Parts.ModeColor(mode));
|
||||
sign.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Junction.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Junction.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b8dce3ea7ba192843a6c27a35253cdb1
|
||||
43
Assets/Scripts/Gameplay/Lamppost.cs
Normal file
43
Assets/Scripts/Gameplay/Lamppost.cs
Normal file
@ -0,0 +1,43 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A lamp post that comes on as the light goes: its glass glows and it throws a warm pool round its foot.</summary>
|
||||
public class Lamppost : MonoBehaviour
|
||||
{
|
||||
public Renderer glow;
|
||||
Light _light;
|
||||
MaterialPropertyBlock _mpb;
|
||||
float _on = -1f;
|
||||
static readonly int EmissionId = Shader.PropertyToID("_EmissionColor"), BaseId = Shader.PropertyToID("_BaseColor");
|
||||
static readonly Color Warm = new Color(1f, 0.78f, 0.45f);
|
||||
|
||||
void Start()
|
||||
{
|
||||
var go = new GameObject("Light");
|
||||
go.transform.SetParent(transform, false);
|
||||
go.transform.localPosition = new Vector3(0f, 2.35f, 0f);
|
||||
_light = go.AddComponent<Light>();
|
||||
_light.type = LightType.Point;
|
||||
_light.color = Warm;
|
||||
_light.range = 9f;
|
||||
_light.shadows = LightShadows.None;
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
// lit a little before it's properly dark, out a little after the sun is up
|
||||
float on = Mathf.Clamp01(DayNight.Dark * 1.6f + DayNight.Dusk * 0.6f);
|
||||
if (Mathf.Abs(on - _on) < 0.02f) return;
|
||||
_on = on;
|
||||
_light.enabled = on > 0.05f;
|
||||
_light.intensity = on * 2.2f;
|
||||
if (!glow) return;
|
||||
glow.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(EmissionId, Warm * (0.2f + on * 3f));
|
||||
_mpb.SetColor(BaseId, Color.Lerp(new Color(0.85f, 0.82f, 0.7f), Warm, on));
|
||||
glow.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Lamppost.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Lamppost.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6558f3088100a79438c30d74e7912470
|
||||
194
Assets/Scripts/Gameplay/Machine.cs
Normal file
194
Assets/Scripts/Gameplay/Machine.cs
Normal file
@ -0,0 +1,194 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A built thing that remembers more than where it stands: what's inside, how full its battery is.</summary>
|
||||
public interface IPieceState
|
||||
{
|
||||
float[] State { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The dryer and the brick press: cargo comes in by belt or by hand and turns into the product all the time, not in
|
||||
/// batches, at the speed the power allows: 100% power is full speed, 30% is a third of it. What's made goes onto the belt at
|
||||
/// the front, or onto the ground if there's none.
|
||||
/// </summary>
|
||||
public class Machine : NetworkBehaviour, ICargoSink, IPorts, IInteractable, IPieceState
|
||||
{
|
||||
public static readonly List<Machine> All = new List<Machine>();
|
||||
|
||||
/// <summary>A hopper holds this many kilos of each thing.</summary>
|
||||
const float Hold = 10f;
|
||||
const float PortOut = 1.05f;
|
||||
|
||||
public readonly NetworkVariable<float> Grass = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Hay = new NetworkVariable<float>();
|
||||
/// <summary>Kilos made and waiting to leave.</summary>
|
||||
public readonly NetworkVariable<float> Made = new NetworkVariable<float>();
|
||||
/// <summary>Share of the power it asks for that it's getting, 0..1: that's how fast it runs.</summary>
|
||||
public readonly NetworkVariable<float> Power = new NetworkVariable<float>();
|
||||
|
||||
public Renderer lamp;
|
||||
public Transform spin;
|
||||
|
||||
BuildPiece _piece;
|
||||
float _done, _nextEject, _pace, _spun, _nextThump;
|
||||
bool _short;
|
||||
int _spinAxis = -1;
|
||||
AudioSource _hum;
|
||||
MaterialPropertyBlock _mpb;
|
||||
static readonly int Emission = Shader.PropertyToID("_EmissionColor");
|
||||
readonly List<Port> _ports = new List<Port>();
|
||||
|
||||
BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
RecipeDef Recipe => GameDefs.Recipe(Piece.piece);
|
||||
public float Kw => Piece.Def.kw * GameDefs.TierPower(Piece.Tier.Value);
|
||||
|
||||
const float Crumb = 0.001f;
|
||||
|
||||
bool Stocked => Grass.Value > Crumb && (Recipe.hay <= 0f || Hay.Value > Crumb);
|
||||
/// <summary>Does it want power right now?</summary>
|
||||
public bool Busy => Stocked && Made.Value < Hold;
|
||||
/// <summary>Kilos a minute it's turning out right now.</summary>
|
||||
public float PerMinute => Busy ? 60f * Recipe.makes / Recipe.seconds * Power.Value : 0f;
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
_hum = Sfx.Loop("machine_hum_loop", transform, 0f);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
if (_hum) Destroy(_hum.gameObject);
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public float[] State
|
||||
{
|
||||
get => new[] { Grass.Value, Hay.Value, Made.Value };
|
||||
set
|
||||
{
|
||||
if (value == null || value.Length < 3) return;
|
||||
Grass.Value = value[0];
|
||||
Hay.Value = value[1];
|
||||
Made.Value = value[2];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>In at the back, out at the front. The press has two ways in and either takes either.</summary>
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
var f = transform.forward;
|
||||
var r = transform.right;
|
||||
var at = transform.position + transform.up * GameDefs.BeltLowest;
|
||||
if (Recipe.hay > 0f)
|
||||
{
|
||||
into.Add(new Port { at = at - f * PortOut - r * 0.5f, dir = f, input = true });
|
||||
into.Add(new Port { at = at - f * PortOut + r * 0.5f, dir = f, input = true });
|
||||
}
|
||||
else into.Add(new Port { at = at - f * PortOut, dir = f, input = true });
|
||||
into.Add(new Port { at = at + f * PortOut, dir = f });
|
||||
}
|
||||
|
||||
public string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
var r = Recipe;
|
||||
string have = r.hay > 0f ? Loc.F("{0} grass, {1} hay", GameDefs.Kilos(Grass.Value), GameDefs.Kilos(Hay.Value)) : Loc.F("{0} grass", GameDefs.Kilos(Grass.Value));
|
||||
string state = !Busy ? (Made.Value >= Hold ? Loc.T("the way out is blocked") : Loc.T("waiting for grass")) : Power.Value <= 0f ? Loc.T("no power") : Loc.F("running at {0:0}% speed, {1:0.#} kg a minute", Power.Value * 100f, PerMinute);
|
||||
return Loc.F("{0}: {1}, {2}", Piece.Def.name, have, state);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanInteract => false;
|
||||
public void Interact() { }
|
||||
|
||||
public bool ServerAccept(Cargo c, Vector3 from, Vector3 dir)
|
||||
{
|
||||
if (!c || !c.IsSpawned) return false;
|
||||
float kg = c.Kg.Value;
|
||||
var r = Recipe;
|
||||
if (c.kind == CargoKind.Grass && r.grass > 0f && Grass.Value + kg <= Hold) Grass.Value += kg;
|
||||
else if (c.kind == CargoKind.Hay && r.hay > 0f && Hay.Value + kg <= Hold) Hay.Value += kg;
|
||||
else return false;
|
||||
c.Grab.Consumed = true;
|
||||
c.NetworkObject.Despawn(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
Visuals();
|
||||
if (!IsServer) return;
|
||||
Eject();
|
||||
if (!Busy) return;
|
||||
var r = Recipe;
|
||||
// it adds up for a moment so the network isn't written to every frame
|
||||
if (Piece.Switched) return;
|
||||
_done += Time.deltaTime * Power.Value * Piece.TierMul / r.seconds;
|
||||
if (_done < 0.02f) return;
|
||||
float take = Mathf.Min(_done, Grass.Value / r.grass, (Hold - Made.Value) / r.makes);
|
||||
if (r.hay > 0f) take = Mathf.Min(take, Hay.Value / r.hay);
|
||||
_done = 0f;
|
||||
Grass.Value = Mathf.Max(0f, Grass.Value - r.grass * take);
|
||||
Hay.Value = Mathf.Max(0f, Hay.Value - r.hay * take);
|
||||
Made.Value += r.makes * take;
|
||||
}
|
||||
|
||||
/// <summary>On every peer: the lamp, the moving part and the sound all follow the speed it's running at.</summary>
|
||||
void Visuals()
|
||||
{
|
||||
_pace = Mathf.MoveTowards(_pace, Busy ? Power.Value : 0f, Time.deltaTime * 1.5f);
|
||||
if (_hum)
|
||||
{
|
||||
_hum.volume = _pace * 0.32f * Sfx.SfxVolume;
|
||||
_hum.pitch = Mathf.Lerp(0.6f, 1.1f, _pace);
|
||||
}
|
||||
// the press comes down slower the less power it gets
|
||||
if (Piece.piece == PieceId.Press && _pace > 0.05f && Time.time >= _nextThump)
|
||||
{
|
||||
_nextThump = Time.time + 2.2f / _pace;
|
||||
Sfx.PlayAt("press_thump", transform.position + transform.up, 0.45f);
|
||||
}
|
||||
bool slow = Busy && Power.Value < 0.5f;
|
||||
if (slow && !_short) Sfx.PlayAt("power_low", transform.position + transform.up, 0.4f, 1f, 0f, 20f);
|
||||
_short = slow;
|
||||
if (spin)
|
||||
{
|
||||
if (_spinAxis < 0) _spinAxis = BaseRot.LocalAxisFor(spin, transform.forward);
|
||||
_spun += _pace * 300f * Time.deltaTime;
|
||||
var axis = _spinAxis == 0 ? Vector3.right : _spinAxis == 1 ? Vector3.up : Vector3.forward;
|
||||
spin.localRotation = BaseRot.Of(spin) * Quaternion.Euler(axis * _spun);
|
||||
}
|
||||
if (lamp)
|
||||
{
|
||||
var c = !Busy ? new Color(0.12f, 0.2f, 0.12f) : Power.Value <= 0f ? new Color(1f, 0.1f, 0.08f) : Power.Value < 0.99f ? new Color(1f, 0.7f, 0.1f) : new Color(0.2f, 1f, 0.3f);
|
||||
lamp.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(Emission, c * 2.2f);
|
||||
lamp.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One kilo at a time through the front, onto whatever takes it.</summary>
|
||||
void Eject()
|
||||
{
|
||||
if (Made.Value < 1f || Time.time < _nextEject) return;
|
||||
_nextEject = Time.time + 0.3f;
|
||||
_ports.Clear();
|
||||
Ports(_ports);
|
||||
if (BeltNet.Send(Piece, _ports[_ports.Count - 1], Recipe.product)) Made.Value -= 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Machine.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Machine.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0c4e72debb52c37409daabb7f5983fc0
|
||||
394
Assets/Scripts/Gameplay/Mowbot.cs
Normal file
394
Assets/Scripts/Gameplay/Mowbot.cs
Normal file
@ -0,0 +1,394 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
public enum RobotMood : byte { Mowing, Travelling, Unloading, Waiting, Finished, NoCatcher }
|
||||
|
||||
/// <summary>
|
||||
/// A mower that drives itself. Only the server decides where it goes: it takes the nearest sector it may work and nobody else
|
||||
/// has, walks it row by row and says where it is five times a second. Every peer cuts what it hears, so the grass goes for all.
|
||||
/// </summary>
|
||||
public abstract class Mowbot : NetworkBehaviour, IInteractable, IPieceState
|
||||
{
|
||||
public static readonly List<Mowbot> All = new List<Mowbot>();
|
||||
/// <summary>The demo's fast forward, on the server.</summary>
|
||||
public static float Haste = 1f;
|
||||
|
||||
const float Tick = 0.2f, Overrun = 0.6f, IdleWait = 5f;
|
||||
const float EngineVolume = 0.16f;
|
||||
const int SearchLimit = 4000;
|
||||
|
||||
public readonly NetworkVariable<Vector3> At = new NetworkVariable<Vector3>();
|
||||
public readonly NetworkVariable<bool> Mowing = new NetworkVariable<bool>();
|
||||
public readonly NetworkVariable<float> Hopper = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<byte> Mood = new NetworkVariable<byte>();
|
||||
|
||||
static readonly Dictionary<int, Mowbot> s_held = new Dictionary<int, Mowbot>();
|
||||
static readonly Queue<(int id, int ring)> s_queue = new Queue<(int, int)>();
|
||||
static readonly HashSet<int> s_seen = new HashSet<int>();
|
||||
static readonly List<Vector3> s_rows = new List<Vector3>();
|
||||
|
||||
readonly List<Vector3> _way = new List<Vector3>();
|
||||
readonly HashSet<int> _empty = new HashSet<int>();
|
||||
int _next, _sector = -1;
|
||||
bool _travel;
|
||||
float _clock, _idleUntil;
|
||||
// the body runs from where it was to the latest tick's spot at an even pace over one tick
|
||||
Vector3 _shown, _from, _to;
|
||||
float _leg = 1f;
|
||||
RobotDef _def;
|
||||
|
||||
/// <summary>Where the body is drawn, smooth between the ticks that move At.</summary>
|
||||
public Vector3 Shown => _shown;
|
||||
/// <summary>For the test bots: how the body stands, as the eye sees it.</summary>
|
||||
public Transform ShownBody => Body;
|
||||
AudioSource _engine;
|
||||
|
||||
protected Vector3 Dir;
|
||||
protected bool Homing;
|
||||
|
||||
public RobotDef Def => _def ?? (_def = GameDefs.Robot(GetComponent<BuildPiece>().piece));
|
||||
BuildPiece _bp;
|
||||
/// <summary>The dock's upgrade level makes the robot faster and its hopper bigger.</summary>
|
||||
protected float Boost => (_bp ? _bp : (_bp = GetComponent<BuildPiece>())) ? _bp.TierMul : 1f;
|
||||
public float HopperCap => Def.hopper * Boost;
|
||||
public RobotMood Doing => (RobotMood)Mood.Value;
|
||||
|
||||
protected abstract Transform Body { get; }
|
||||
|
||||
/// <summary>The body's model has its nose on local -Z, so it is turned the other way round to go nose first.</summary>
|
||||
protected virtual bool NoseOnBack => false;
|
||||
protected abstract Vector3 Origin { get; }
|
||||
protected abstract int Reach { get; }
|
||||
protected virtual Vector3 HomeDir => Dir;
|
||||
/// <summary>Unloading, or out of room: true keeps it where it is for this tick.</summary>
|
||||
protected abstract bool Stay(float dt);
|
||||
protected virtual void Arrived() { }
|
||||
protected abstract void NoWork();
|
||||
|
||||
public abstract string Prompt { get; }
|
||||
public bool CanInteract => true;
|
||||
public void Interact() => Sfx.Play("ui_click", 0.6f);
|
||||
|
||||
public virtual float[] State
|
||||
{
|
||||
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z };
|
||||
set
|
||||
{
|
||||
if (value == null || value.Length < 4) return;
|
||||
Hopper.Value = value[0];
|
||||
Seat(new Vector3(value[1], value[2], value[3]).normalized);
|
||||
}
|
||||
}
|
||||
|
||||
protected string MoodText
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (Doing)
|
||||
{
|
||||
case RobotMood.Mowing: return Loc.T("mowing");
|
||||
case RobotMood.Unloading: return Loc.T("unloading");
|
||||
case RobotMood.Waiting: return Loc.T("waiting for room, connect a belt");
|
||||
case RobotMood.Finished: return Loc.T("everything in reach is mown");
|
||||
case RobotMood.NoCatcher: return Loc.T("hopper full, needs a catcher with room");
|
||||
default: return Loc.T("on the move");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
All.Add(this);
|
||||
if (IsServer) Seat(Planet.Up(transform.position));
|
||||
_shown = _from = _to = At.Value;
|
||||
At.OnValueChanged += Heard;
|
||||
_engine = Sfx.Loop("robot_mower_loop", Body, 0f);
|
||||
}
|
||||
|
||||
public override void OnNetworkDespawn()
|
||||
{
|
||||
All.Remove(this);
|
||||
At.OnValueChanged -= Heard;
|
||||
Release();
|
||||
if (_engine) Destroy(_engine.gameObject);
|
||||
}
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
Release();
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
void Seat(Vector3 dir)
|
||||
{
|
||||
Dir = dir;
|
||||
At.Value = Planet.OnSurface(dir);
|
||||
}
|
||||
|
||||
/// <summary>The hammer put it somewhere else: everything it had planned is off.</summary>
|
||||
public virtual void Moved(Vector3 at)
|
||||
{
|
||||
_empty.Clear();
|
||||
_way.Clear();
|
||||
_next = 0;
|
||||
if (IsServer) Release();
|
||||
}
|
||||
|
||||
protected void Teleported(Vector3 at)
|
||||
{
|
||||
_shown = _from = _to = at;
|
||||
_leg = 1f;
|
||||
if (IsServer) Seat(Planet.Up(at));
|
||||
}
|
||||
|
||||
void Release()
|
||||
{
|
||||
if (_sector >= 0 && s_held.TryGetValue(_sector, out var who) && who == this) s_held.Remove(_sector);
|
||||
_sector = -1;
|
||||
}
|
||||
|
||||
/// <summary>The host cuts for real as it goes: the rest of the crew repeat the stroke they hear about.</summary>
|
||||
void Heard(Vector3 was, Vector3 now)
|
||||
{
|
||||
// a jump of more than a few ticks' walk is a teleport: no running there
|
||||
bool far = (now - _shown).sqrMagnitude > 400f;
|
||||
_from = far ? now : _shown;
|
||||
_to = now;
|
||||
_leg = far ? 1f : 0f;
|
||||
if (!IsServer && Mowing.Value && (now - was).sqrMagnitude < 400f) MowMap.Cut(was, now, Def.width, 0f, MowMap.PaintFeather);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
if (!IsSpawned) return;
|
||||
if (IsServer)
|
||||
{
|
||||
_clock += Time.deltaTime;
|
||||
if (_clock >= Tick)
|
||||
{
|
||||
_clock -= Tick;
|
||||
float dt = Tick * Haste;
|
||||
// stopped from its settings: it waits where it is
|
||||
if ((_bp ? _bp : (_bp = GetComponent<BuildPiece>())) && _bp.Switched) { Mowing.Value = false; Mood.Value = (byte)RobotMood.Waiting; }
|
||||
else if (!Stay(dt)) Walk(dt);
|
||||
}
|
||||
}
|
||||
Show();
|
||||
if (_engine)
|
||||
{
|
||||
_engine.volume = Mathf.MoveTowards(_engine.volume, (Doing == RobotMood.Mowing ? EngineVolume : Doing == RobotMood.Travelling ? EngineVolume * 0.6f : 0f) * Sfx.SfxVolume, Time.deltaTime * 0.5f);
|
||||
_engine.pitch = Mathf.Lerp(1.5f, 1.1f, Def.width / 2f);
|
||||
}
|
||||
}
|
||||
|
||||
void Show()
|
||||
{
|
||||
var body = Body;
|
||||
if (!body) return;
|
||||
var aim = _to;
|
||||
var up = Planet.Up(aim);
|
||||
var flat = Vector3.ProjectOnPlane(aim - _from, up);
|
||||
_leg = Mathf.Min(1f, _leg + Time.deltaTime / Tick);
|
||||
_shown = Vector3.Lerp(_from, _to, _leg);
|
||||
// the nose, where the cutter is, goes first
|
||||
float nose = NoseOnBack ? -1f : 1f;
|
||||
if (flat.sqrMagnitude < 0.01f) flat = Vector3.ProjectOnPlane(body.forward * nose, up);
|
||||
if (flat.sqrMagnitude < 1e-4f) return;
|
||||
var was = body.rotation;
|
||||
var turn = Quaternion.Slerp(was, Quaternion.LookRotation(flat * nose, up), 1f - Mathf.Exp(-6f * Time.deltaTime));
|
||||
// it glides: no shake, no bob, the moving parts do the living
|
||||
bool going = _leg < 1f && (_to - _from).sqrMagnitude > 1e-4f;
|
||||
body.SetPositionAndRotation(_shown, turn);
|
||||
Animate(body, Vector3.SignedAngle(was * Vector3.forward, turn * Vector3.forward, up) / Mathf.Max(1e-3f, Time.deltaTime), going);
|
||||
}
|
||||
|
||||
// ───────────────────────── looks ─────────────────────────
|
||||
|
||||
// parts named for it by the model: Spin* turns while it mows, Blink* shuts now and then, Sway* springs about on its base
|
||||
readonly List<(Transform t, int axis)> _spin = new List<(Transform, int)>();
|
||||
readonly List<(Transform t, int axis, Vector3 size)> _blink = new List<(Transform, int, Vector3)>();
|
||||
readonly List<Transform> _sway = new List<Transform>();
|
||||
readonly List<(Transform t, int axis, float radius)> _wheels = new List<(Transform, int, float)>();
|
||||
Transform _fill;
|
||||
int _fillAxis = 1;
|
||||
float _roll, _level;
|
||||
bool _parts;
|
||||
float _spun, _nextBlink = 2f, _blinkAt = -1f, _swayX, _swayV, _wasGoing, _go;
|
||||
|
||||
void Animate(Transform body, float turnRate, bool going)
|
||||
{
|
||||
if (!_parts)
|
||||
{
|
||||
_parts = true;
|
||||
foreach (var c in body.GetComponentsInChildren<Transform>(true))
|
||||
{
|
||||
if (c.name.StartsWith("Spin")) _spin.Add((c, BaseRot.LocalAxisFor(c, body.up)));
|
||||
else if (c.name.StartsWith("Blink")) _blink.Add((c, BaseRot.LocalAxisFor(c, body.up), c.localScale));
|
||||
else if (c.name.StartsWith("Sway")) _sway.Add(c);
|
||||
else if (c.name.StartsWith("Wheel_"))
|
||||
{
|
||||
var r = c.GetComponent<Renderer>();
|
||||
_wheels.Add((c, BaseRot.LocalAxisFor(c, body.right), r ? Mathf.Max(0.05f, r.bounds.extents.y) : 0.2f));
|
||||
}
|
||||
else if (c.name == "Fill") { _fill = c; _fillAxis = BaseRot.LocalAxisFor(c, body.up); }
|
||||
if (c != body) BaseRot.Of(c);
|
||||
}
|
||||
}
|
||||
_spun += Time.deltaTime * (Mowing.Value ? 1400f : 0f);
|
||||
foreach (var (t, axis) in _spin)
|
||||
t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_spun, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward);
|
||||
// the wheels roll with the ground going by, the clippings rise in the hopper
|
||||
// eased, so the frame between two steps doesn't read as a stop and a start
|
||||
_go = Mathf.MoveTowards(_go, going ? 1f : 0f, Time.deltaTime * 2.5f);
|
||||
float speed = (_to - _from).magnitude / Tick * _go;
|
||||
_roll += speed * Time.deltaTime * Mathf.Rad2Deg;
|
||||
foreach (var (t, axis, radius) in _wheels)
|
||||
t.localRotation = BaseRot.Of(t) * Quaternion.AngleAxis(_roll / radius, axis == 0 ? Vector3.right : axis == 1 ? Vector3.up : Vector3.forward);
|
||||
if (_fill)
|
||||
{
|
||||
_level = Mathf.Lerp(_level, Mathf.Clamp01(Hopper.Value / Mathf.Max(1f, HopperCap)), Time.deltaTime * 3f);
|
||||
var f = _fill.localScale;
|
||||
f[_fillAxis] = Mathf.Max(0.001f, _level);
|
||||
_fill.localScale = f;
|
||||
}
|
||||
// blink: shut over a tenth of a second, open again, every two to six seconds
|
||||
if (Time.time > _nextBlink) { _blinkAt = Time.time; _nextBlink = Time.time + Random.Range(2f, 6f); }
|
||||
float b = _blinkAt < 0f ? 1f : Mathf.Clamp01(Mathf.Abs(Time.time - _blinkAt - 0.08f) / 0.08f);
|
||||
foreach (var (t, axis, size) in _blink)
|
||||
{
|
||||
var s = size;
|
||||
s[axis] *= Mathf.Max(0.05f, b);
|
||||
t.localScale = s;
|
||||
}
|
||||
// the antenna whips back when it sets off or stops, and leans out of the turns
|
||||
float kick = _go - _wasGoing;
|
||||
_wasGoing = _go;
|
||||
_swayV += (-90f * _swayX - 5f * _swayV) * Time.deltaTime - kick * 2.5f + Mathf.Clamp(turnRate, -200f, 200f) * 0.0004f;
|
||||
_swayX += _swayV * Time.deltaTime;
|
||||
foreach (var t in _sway)
|
||||
t.localRotation = Quaternion.AngleAxis(_swayX * 40f, t.parent.InverseTransformDirection(body.right)) * BaseRot.Of(t);
|
||||
}
|
||||
|
||||
// ───────────────────────── walking ─────────────────────────
|
||||
|
||||
void Walk(float dt)
|
||||
{
|
||||
if (!Homing && _next >= _way.Count)
|
||||
{
|
||||
if (Time.time < _idleUntil) return;
|
||||
if (!FindWork())
|
||||
{
|
||||
_idleUntil = Time.time + IdleWait;
|
||||
NoWork();
|
||||
if (!Homing) return;
|
||||
}
|
||||
}
|
||||
var goal = Homing ? HomeDir : _way[_next];
|
||||
var from = Planet.OnSurface(Dir);
|
||||
// not RotateTowards: it calls anything under a tenth of a degree "there already", and that is 4 m on this ball
|
||||
var gap = goal - Dir;
|
||||
float step = Def.speed * Boost * dt / Planet.Radius;
|
||||
if (gap.magnitude > step) Dir = (Dir + gap.normalized * step).normalized;
|
||||
else
|
||||
{
|
||||
Dir = goal;
|
||||
if (Homing)
|
||||
{
|
||||
Homing = false;
|
||||
Arrived();
|
||||
}
|
||||
else
|
||||
{
|
||||
_next++;
|
||||
_travel = false;
|
||||
}
|
||||
}
|
||||
var to = Planet.OnSurface(Dir);
|
||||
if (Mowing.Value) Hopper.Value += MowMap.Cut(from, to, Def.width, 0f, MowMap.PaintFeather) * GameDefs.GrassDensity;
|
||||
Mowing.Value = !Homing && !_travel && _next < _way.Count;
|
||||
Mood.Value = (byte)(Mowing.Value ? RobotMood.Mowing : RobotMood.Travelling);
|
||||
At.Value = to;
|
||||
}
|
||||
|
||||
/// <summary>Off to unload, then back to the very spot it left.</summary>
|
||||
protected void GoHome()
|
||||
{
|
||||
if (_next < _way.Count) _way.Insert(_next, Dir);
|
||||
_travel = true;
|
||||
Homing = true;
|
||||
}
|
||||
|
||||
// ───────────────────────── planning ─────────────────────────
|
||||
|
||||
/// <summary>Sectors around where it started, rings out to its reach.</summary>
|
||||
public int Area()
|
||||
{
|
||||
Spread(HexGrid.SectorAt(Planet.Up(Origin)), id => false);
|
||||
return s_seen.Count;
|
||||
}
|
||||
|
||||
bool FindWork()
|
||||
{
|
||||
Release();
|
||||
return Spread(HexGrid.SectorAt(Planet.Up(Origin)), TryPlan);
|
||||
}
|
||||
|
||||
bool TryPlan(int id)
|
||||
{
|
||||
if (_empty.Contains(id) || MowMap.Cleared(id) >= 1f) return false;
|
||||
if (s_held.TryGetValue(id, out var who) && who) return false;
|
||||
Plan(id);
|
||||
if (_way.Count == 0)
|
||||
{
|
||||
_empty.Add(id);
|
||||
return false;
|
||||
}
|
||||
_sector = id;
|
||||
s_held[id] = this;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Spread(int start, System.Func<int, bool> take)
|
||||
{
|
||||
s_seen.Clear();
|
||||
s_queue.Clear();
|
||||
s_seen.Add(start);
|
||||
s_queue.Enqueue((start, 0));
|
||||
while (s_queue.Count > 0 && s_seen.Count < SearchLimit)
|
||||
{
|
||||
var (id, ring) = s_queue.Dequeue();
|
||||
if (take(id)) return true;
|
||||
if (ring >= Reach) continue;
|
||||
foreach (int n in HexGrid.Get(id).neighbours)
|
||||
if (s_seen.Add(n)) s_queue.Enqueue((n, ring + 1));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Rows across the sector, edge to edge, and only where there is something to cut.</summary>
|
||||
void Plan(int id)
|
||||
{
|
||||
_way.Clear();
|
||||
_next = 0;
|
||||
_travel = true;
|
||||
var s = HexGrid.Get(id);
|
||||
MowMap.Rows(id, Def.width, s_rows);
|
||||
bool flip = false;
|
||||
foreach (var r in s_rows)
|
||||
{
|
||||
var a = Flat(s, r.y - Overrun, r.x);
|
||||
var b = Flat(s, r.z + Overrun, r.x);
|
||||
_way.Add(flip ? b : a);
|
||||
_way.Add(flip ? a : b);
|
||||
flip = !flip;
|
||||
}
|
||||
if (_way.Count > 1 && Vector3.Dot(_way[_way.Count - 1], Dir) > Vector3.Dot(_way[0], Dir)) _way.Reverse();
|
||||
}
|
||||
|
||||
static Vector3 Flat(HexGrid.Sector s, float u, float v) => (s.c * Planet.Radius + s.e1 * u + s.e2 * v).normalized;
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Mowbot.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Mowbot.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9b918cdea2cadd346b46a3bad08a1963
|
||||
91
Assets/Scripts/Gameplay/PowerBattery.cs
Normal file
91
Assets/Scripts/Gameplay/PowerBattery.cs
Normal file
@ -0,0 +1,91 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A battery takes what the panels have to spare and gives it back when they fall short, so machines keep running through
|
||||
/// the night at whatever the battery can deliver. It charges and empties over time, at no more than its rated power.
|
||||
/// </summary>
|
||||
public class PowerBattery : PowerNode, IPieceState
|
||||
{
|
||||
public Transform gauge;
|
||||
public Renderer lamp;
|
||||
|
||||
public readonly NetworkVariable<float> Stored = new NetworkVariable<float>();
|
||||
/// <summary>Kilowatts going in, or out if below zero.</summary>
|
||||
public readonly NetworkVariable<float> Flow = new NetworkVariable<float>();
|
||||
|
||||
MaterialPropertyBlock _mpb;
|
||||
Vector3 _gaugeScale = Vector3.one;
|
||||
AudioSource _hum;
|
||||
bool _wasFull;
|
||||
static readonly int Emission = Shader.PropertyToID("_EmissionColor");
|
||||
|
||||
BatteryDef Def => GameDefs.Battery(Piece.piece);
|
||||
public override float Radius => Def.radius;
|
||||
public float Capacity => Def.kwh;
|
||||
public float Rate => Def.kw;
|
||||
/// <summary>How many times its output rating a battery may charge at.</summary>
|
||||
public const float ChargeBoost = 6f;
|
||||
public bool Full => Stored.Value >= Capacity - 0.001f;
|
||||
|
||||
public float[] State
|
||||
{
|
||||
get => new[] { Stored.Value };
|
||||
set { if (value != null && value.Length > 0) Stored.Value = Mathf.Min(value[0], Capacity); }
|
||||
}
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
string doing = Flow.Value > 0.01f ? Loc.F("charging at {0:0.#} kW", Flow.Value) : Flow.Value < -0.01f ? Loc.F("giving {0:0.#} kW, {1:0} min left at this rate", -Flow.Value, Stored.Value / -Flow.Value * 60f) : Full ? Loc.T("full") : Loc.T("resting");
|
||||
return Loc.F("{0}: {1:0.0} of {2:0} kWh, {3}. {4}", Piece.Def.name, Stored.Value, Capacity, doing, Network);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Server: moves kilowatts for dt seconds, in or out if below zero. Returns what really moved. Kilowatt-hours are real hours.</summary>
|
||||
public float Charge(float kw, float dt)
|
||||
{
|
||||
float can = kw >= 0f ? (Capacity - Stored.Value) * 3600f / dt : Stored.Value * 3600f / dt;
|
||||
// they take charge much faster than they give it: a rack fills from spare sun in a few minutes, not half an hour
|
||||
float done = Mathf.Sign(kw) * Mathf.Min(Mathf.Abs(kw), kw >= 0f ? Rate * ChargeBoost : Rate, can);
|
||||
if (done != 0f) Stored.Value = Mathf.Clamp(Stored.Value + done * dt / 3600f, 0f, Capacity);
|
||||
Write(Flow, done);
|
||||
return done;
|
||||
}
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_mpb = new MaterialPropertyBlock();
|
||||
if (gauge) _gaugeScale = gauge.localScale;
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn()
|
||||
{
|
||||
base.OnNetworkSpawn();
|
||||
_hum = Sfx.Loop("battery_hum_loop", transform, 0f);
|
||||
_wasFull = Full;
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
float full = Capacity > 0f ? Stored.Value / Capacity : 0f;
|
||||
if (_hum) _hum.volume = Mathf.MoveTowards(_hum.volume, Mathf.Abs(Flow.Value) > 0.01f ? 0.3f * Sfx.SfxVolume : 0f, Time.deltaTime * 0.6f);
|
||||
if (Full && !_wasFull) Sfx.PlayAt("battery_full", transform.position + transform.up, 0.5f);
|
||||
_wasFull = Full;
|
||||
if (gauge)
|
||||
{
|
||||
var s = _gaugeScale;
|
||||
s.y *= Mathf.Max(0.02f, full);
|
||||
gauge.localScale = s;
|
||||
}
|
||||
if (!lamp) return;
|
||||
var c = Flow.Value > 0.01f ? new Color(0.2f, 1f, 0.35f) : Flow.Value < -0.01f ? new Color(1f, 0.7f, 0.15f) : full > 0.02f ? new Color(0.2f, 0.5f, 1f) : new Color(1f, 0.15f, 0.1f);
|
||||
lamp.GetPropertyBlock(_mpb);
|
||||
_mpb.SetColor(Emission, c * 2.2f);
|
||||
lamp.SetPropertyBlock(_mpb);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerBattery.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerBattery.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0f7a32d3f065345488fb8707d4d4c99a
|
||||
112
Assets/Scripts/Gameplay/PowerGrid.cs
Normal file
112
Assets/Scripts/Gameplay/PowerGrid.cs
Normal file
@ -0,0 +1,112 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// Server: who powers whom. Nodes and machines that reach each other make one network. The sun goes to the machines first,
|
||||
/// batteries make up what's missing, and whatever is left over charges them. A machine gets the share of its power that the
|
||||
/// network can give, and that share is how fast it runs.
|
||||
/// </summary>
|
||||
public static class PowerGrid
|
||||
{
|
||||
class Net
|
||||
{
|
||||
public readonly List<PowerNode> nodes = new List<PowerNode>();
|
||||
public readonly List<Machine> machines = new List<Machine>();
|
||||
public readonly List<PowerBattery> batteries = new List<PowerBattery>();
|
||||
}
|
||||
|
||||
static readonly List<Net> s_nets = new List<Net>();
|
||||
static readonly HashSet<Machine> s_seenM = new HashSet<Machine>();
|
||||
static readonly HashSet<PowerNode> s_seenN = new HashSet<PowerNode>();
|
||||
static int s_version = -1, s_nodes, s_machines;
|
||||
|
||||
public static bool Reaches(PowerNode n, Vector3 at) => (n.transform.position - at).sqrMagnitude <= n.Radius * n.Radius;
|
||||
|
||||
public static bool Joined(PowerNode a, PowerNode b)
|
||||
{
|
||||
float r = Mathf.Max(a.Radius, b.Radius);
|
||||
return (a.transform.position - b.transform.position).sqrMagnitude <= r * r;
|
||||
}
|
||||
|
||||
/// <summary>Is there power reaching this spot?</summary>
|
||||
public static bool Covers(Vector3 at)
|
||||
{
|
||||
foreach (var n in PowerNode.All) if (n && Reaches(n, at)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public static void Tick(float dt)
|
||||
{
|
||||
if (s_version != BuildPiece.Version || s_nodes != PowerNode.All.Count || s_machines != Machine.All.Count) Rebuild();
|
||||
foreach (var net in s_nets) Balance(net, dt);
|
||||
}
|
||||
|
||||
static void Rebuild()
|
||||
{
|
||||
s_version = BuildPiece.Version;
|
||||
s_nodes = PowerNode.All.Count;
|
||||
s_machines = Machine.All.Count;
|
||||
s_nets.Clear();
|
||||
s_seenM.Clear();
|
||||
s_seenN.Clear();
|
||||
foreach (var m in Machine.All)
|
||||
{
|
||||
if (!m || s_seenM.Contains(m)) continue;
|
||||
var net = new Net();
|
||||
Walk(m, net);
|
||||
s_nets.Add(net);
|
||||
}
|
||||
foreach (var n in PowerNode.All)
|
||||
{
|
||||
if (!n || s_seenN.Contains(n)) continue;
|
||||
var net = new Net();
|
||||
Walk(n, net);
|
||||
s_nets.Add(net);
|
||||
}
|
||||
}
|
||||
|
||||
static void Walk(Machine m, Net net)
|
||||
{
|
||||
s_seenM.Add(m);
|
||||
net.machines.Add(m);
|
||||
foreach (var n in PowerNode.All)
|
||||
if (n && !s_seenN.Contains(n) && Reaches(n, m.transform.position)) Walk(n, net);
|
||||
}
|
||||
|
||||
static void Walk(PowerNode n, Net net)
|
||||
{
|
||||
s_seenN.Add(n);
|
||||
net.nodes.Add(n);
|
||||
if (n is PowerBattery b) net.batteries.Add(b);
|
||||
foreach (var other in PowerNode.All)
|
||||
if (other && !s_seenN.Contains(other) && Joined(n, other)) Walk(other, net);
|
||||
foreach (var m in Machine.All)
|
||||
if (m && !s_seenM.Contains(m) && Reaches(n, m.transform.position)) Walk(m, net);
|
||||
}
|
||||
|
||||
static void Balance(Net net, float dt)
|
||||
{
|
||||
float sun = 0f, asked = 0f, held = 0f, cap = 0f;
|
||||
foreach (var n in net.nodes) if (n) sun += n.Sunlight;
|
||||
foreach (var m in net.machines) if (m && m.Busy) asked += m.Kw;
|
||||
|
||||
// short of sun the batteries top it up, with sun to spare they fill, shared out evenly among them
|
||||
float want = asked - sun, given = 0f;
|
||||
for (int i = 0; i < net.batteries.Count; i++)
|
||||
{
|
||||
var b = net.batteries[i];
|
||||
if (!b) continue;
|
||||
float out_ = b.Charge(-(want - given) / (net.batteries.Count - i), dt);
|
||||
given -= out_;
|
||||
held += b.Stored.Value;
|
||||
cap += b.Capacity;
|
||||
}
|
||||
float supply = sun + Mathf.Max(0f, given);
|
||||
float pace = net.nodes.Count == 0 ? 0f : asked > 0f ? Mathf.Clamp01(supply / asked) : supply > 0f || held > 0f ? 1f : 0f;
|
||||
foreach (var m in net.machines) if (m && !Mathf.Approximately(m.Power.Value, pace)) m.Power.Value = pace;
|
||||
foreach (var n in net.nodes) if (n) n.Report(supply, asked, held, cap);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerGrid.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerGrid.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: db2db15fad6db7c4ab2510b6d7efb8c6
|
||||
69
Assets/Scripts/Gameplay/PowerNode.cs
Normal file
69
Assets/Scripts/Gameplay/PowerNode.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>
|
||||
/// A piece of the power network: a panel, a battery or a pole. Nodes join up with whatever lies inside the longer of
|
||||
/// their radii, machines with any node that reaches them, and everything joined shares one supply.
|
||||
/// </summary>
|
||||
public abstract class PowerNode : NetworkBehaviour, IInteractable
|
||||
{
|
||||
public static readonly List<PowerNode> All = new List<PowerNode>();
|
||||
|
||||
/// <summary>What the whole network this node is on is doing, in kilowatts and kilowatt-hours.</summary>
|
||||
public readonly NetworkVariable<float> Supply = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Asked = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Held = new NetworkVariable<float>();
|
||||
public readonly NetworkVariable<float> Cap = new NetworkVariable<float>();
|
||||
|
||||
BuildPiece _piece;
|
||||
|
||||
protected BuildPiece Piece => _piece ? _piece : (_piece = GetComponent<BuildPiece>());
|
||||
public abstract float Radius { get; }
|
||||
/// <summary>Where a wire ties on.</summary>
|
||||
public virtual float WireHeight => 1.6f;
|
||||
/// <summary>Kilowatts the sun gives it right now.</summary>
|
||||
public virtual float Sunlight => 0f;
|
||||
|
||||
public abstract string Prompt { get; }
|
||||
public bool CanInteract => false;
|
||||
public void Interact() { }
|
||||
|
||||
/// <summary>The network in a few words, for the prompt.</summary>
|
||||
protected string Network
|
||||
{
|
||||
get
|
||||
{
|
||||
bool batteries = Cap.Value > 0f;
|
||||
if (Asked.Value <= 0f)
|
||||
return batteries ? Loc.F("nothing to run, {0:0.#} kW free, batteries {1:0.0} of {2:0} kWh", Supply.Value, Held.Value, Cap.Value) : Loc.F("nothing to run, {0:0.#} kW free", Supply.Value);
|
||||
float at = Mathf.Clamp01(Supply.Value / Asked.Value) * 100f;
|
||||
return batteries ? Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW, batteries {3:0.0} of {4:0} kWh", at, Supply.Value, Asked.Value, Held.Value, Cap.Value) : Loc.F("machines at {0:0}%, {1:0.#} of {2:0.#} kW", at, Supply.Value, Asked.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnNetworkSpawn() => All.Add(this);
|
||||
public override void OnNetworkDespawn() => All.Remove(this);
|
||||
|
||||
public override void OnDestroy()
|
||||
{
|
||||
All.Remove(this);
|
||||
base.OnDestroy();
|
||||
}
|
||||
|
||||
public void Report(float supply, float asked, float held, float cap)
|
||||
{
|
||||
Write(Supply, supply);
|
||||
Write(Asked, asked);
|
||||
Write(Held, held);
|
||||
Write(Cap, cap);
|
||||
}
|
||||
|
||||
protected static void Write(NetworkVariable<float> v, float value)
|
||||
{
|
||||
if (Mathf.Abs(v.Value - value) > 0.01f || (value == 0f && v.Value != 0f)) v.Value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerNode.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerNode.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 513b7b26d9018284488e552fbcfcee44
|
||||
10
Assets/Scripts/Gameplay/PowerPole.cs
Normal file
10
Assets/Scripts/Gameplay/PowerPole.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A pole carries the network further: it makes nothing and stores nothing, but it reaches a long way and shows its wires.</summary>
|
||||
public class PowerPole : PowerNode
|
||||
{
|
||||
public override float Radius => GameDefs.PoleReach;
|
||||
public override float WireHeight => GameDefs.PoleHeight;
|
||||
public override string Prompt => Loc.F("{0}: reaches {1:0} m, {2}", Piece.Def.name, Radius, Network);
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/PowerPole.cs.meta
Normal file
2
Assets/Scripts/Gameplay/PowerPole.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ae848234fa7ef4648b31d0d8897b67ae
|
||||
101
Assets/Scripts/Gameplay/Reaper.cs
Normal file
101
Assets/Scripts/Gameplay/Reaper.cs
Normal file
@ -0,0 +1,101 @@
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>The Reaper belongs to no dock: it goes from sector to sector over the whole planet and shoots its bundles into a catcher, however far.</summary>
|
||||
public class Reaper : Mowbot
|
||||
{
|
||||
const float ShotEvery = 0.5f, ShowEvery = 0.4f, ReelSpeed = 420f;
|
||||
|
||||
public Transform muzzle, reel;
|
||||
|
||||
float _nextShow, _spun;
|
||||
int _reelAxis = -1;
|
||||
|
||||
protected override Transform Body => transform;
|
||||
protected override Vector3 Origin => At.Value;
|
||||
protected override int Reach => 100000;
|
||||
|
||||
public override string Prompt => Loc.F("{0}: {1}, {2} of {3}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap));
|
||||
|
||||
public override void Moved(Vector3 at)
|
||||
{
|
||||
base.Moved(at);
|
||||
Teleported(at);
|
||||
}
|
||||
|
||||
protected override bool Stay(float dt)
|
||||
{
|
||||
int shots = Mathf.CeilToInt(dt / ShotEvery);
|
||||
while (Hopper.Value >= GameDefs.BundleKg && shots-- > 0)
|
||||
{
|
||||
var c = Catcher.WithRoom();
|
||||
if (!c) break;
|
||||
c.ServerCatch(GameDefs.BundleKg);
|
||||
Hopper.Value -= GameDefs.BundleKg;
|
||||
if (Time.time >= _nextShow)
|
||||
{
|
||||
_nextShow = Time.time + ShowEvery;
|
||||
ShotRpc(c.transform.position + c.transform.up * 2f);
|
||||
}
|
||||
}
|
||||
if (Hopper.Value < HopperCap) return false;
|
||||
Mowing.Value = false;
|
||||
Mood.Value = (byte)RobotMood.NoCatcher;
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void NoWork() => Mood.Value = (byte)RobotMood.Finished;
|
||||
|
||||
[Rpc(SendTo.Everyone)]
|
||||
void ShotRpc(Vector3 to)
|
||||
{
|
||||
BundleShot.Fly(muzzle ? muzzle.position : At.Value + transform.up * 1.5f, to);
|
||||
Sfx.PlayAt("launcher_fire", At.Value, 0.5f, 1.2f);
|
||||
}
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
if (!reel || !Mowing.Value) return;
|
||||
if (_reelAxis < 0) _reelAxis = BaseRot.LocalAxisFor(reel, transform.right);
|
||||
_spun += ReelSpeed * Time.deltaTime;
|
||||
var axis = _reelAxis == 0 ? Vector3.right : _reelAxis == 1 ? Vector3.up : Vector3.forward;
|
||||
reel.localRotation = BaseRot.Of(reel) * Quaternion.Euler(axis * _spun);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A bundle in the air. Only for the eyes: the catcher has it already.</summary>
|
||||
public class BundleShot : MonoBehaviour
|
||||
{
|
||||
const float Near = 600f;
|
||||
|
||||
Vector3 _from, _to;
|
||||
float _t, _time, _arc;
|
||||
|
||||
public static void Fly(Vector3 from, Vector3 to)
|
||||
{
|
||||
var cam = Camera.main;
|
||||
if (!cam || (Vector3.Distance(cam.transform.position, from) > Near && Vector3.Distance(cam.transform.position, to) > Near)) return;
|
||||
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
|
||||
Destroy(go.GetComponent<Collider>());
|
||||
go.transform.localScale = Vector3.one * 0.5f;
|
||||
go.GetComponent<Renderer>().sharedMaterial = BuildLook.Mat("M_Bundle", new Color(0.62f, 0.78f, 0.28f));
|
||||
var shot = go.AddComponent<BundleShot>();
|
||||
float far = Vector3.Distance(from, to);
|
||||
shot._from = Planet.Up(from);
|
||||
shot._to = Planet.Up(to);
|
||||
shot._time = Mathf.Clamp(1f + far / 150f, 1f, 8f);
|
||||
shot._arc = Mathf.Min(8f + far * 0.25f, 200f);
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
_t += Time.deltaTime / _time;
|
||||
if (_t >= 1f) { Destroy(gameObject); return; }
|
||||
var d = Vector3.Slerp(_from, _to, _t);
|
||||
transform.position = Planet.OnSurface(d) + d * (1.5f + Mathf.Sin(_t * Mathf.PI) * _arc);
|
||||
transform.Rotate(180f * Time.deltaTime, 90f * Time.deltaTime, 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/Reaper.cs.meta
Normal file
2
Assets/Scripts/Gameplay/Reaper.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b2c8b41ca64137f41ade2157da18f05a
|
||||
79
Assets/Scripts/Gameplay/RobotDock.cs
Normal file
79
Assets/Scripts/Gameplay/RobotDock.cs
Normal file
@ -0,0 +1,79 @@
|
||||
using System.Collections.Generic;
|
||||
using Unity.Netcode;
|
||||
using UnityEngine;
|
||||
|
||||
namespace GrassCutter
|
||||
{
|
||||
/// <summary>A robot mower and its dock: it works the rings of sectors around the dock, and the dock ties what it brings into bundles for the belt.</summary>
|
||||
public class RobotDock : Mowbot, IPorts
|
||||
{
|
||||
const float SiloRoom = 100f, UnloadRate = 5f;
|
||||
|
||||
public Transform bot;
|
||||
public readonly NetworkVariable<float> Silo = new NetworkVariable<float>();
|
||||
|
||||
bool _unloading;
|
||||
int _turn, _area;
|
||||
|
||||
protected override Transform Body => bot;
|
||||
protected override bool NoseOnBack => true;
|
||||
protected override Vector3 Origin => transform.position;
|
||||
protected override int Reach => Def.reach;
|
||||
protected override Vector3 HomeDir => Planet.Up(transform.position);
|
||||
|
||||
public override string Prompt
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_area == 0) _area = Area();
|
||||
return Loc.F("{0}: {1}, {2} of {3}, {4} sectors, dock holds {5}", Def.name, MoodText, GameDefs.Kilos(Hopper.Value), GameDefs.Kilos(HopperCap), _area, GameDefs.Kilos(Silo.Value));
|
||||
}
|
||||
}
|
||||
|
||||
public override float[] State
|
||||
{
|
||||
get => new[] { Hopper.Value, Dir.x, Dir.y, Dir.z, Silo.Value };
|
||||
set
|
||||
{
|
||||
base.State = value;
|
||||
if (value != null && value.Length > 4) Silo.Value = value[4];
|
||||
}
|
||||
}
|
||||
|
||||
public void Ports(List<Port> into)
|
||||
{
|
||||
into.Add(BeltNet.Front(transform));
|
||||
}
|
||||
|
||||
protected override bool Stay(float dt)
|
||||
{
|
||||
BeltNet.Drain(GetComponent<BuildPiece>(), Silo, ref _turn);
|
||||
if (_unloading)
|
||||
{
|
||||
float give = Mathf.Min(Hopper.Value, UnloadRate * dt, SiloRoom - Silo.Value);
|
||||
if (give > 0f)
|
||||
{
|
||||
Hopper.Value -= give;
|
||||
Silo.Value += give;
|
||||
}
|
||||
if (Hopper.Value >= 0.01f)
|
||||
{
|
||||
Mood.Value = (byte)(give > 0f ? RobotMood.Unloading : RobotMood.Waiting);
|
||||
return true;
|
||||
}
|
||||
Hopper.Value = 0f;
|
||||
_unloading = false;
|
||||
}
|
||||
if (!Homing && Hopper.Value >= HopperCap) GoHome();
|
||||
return false;
|
||||
}
|
||||
|
||||
protected override void Arrived() => _unloading = true;
|
||||
|
||||
protected override void NoWork()
|
||||
{
|
||||
if (Vector3.Dot(Dir, HomeDir) < 0.9999999f || Hopper.Value > 0f) GoHome();
|
||||
else Mood.Value = (byte)RobotMood.Finished;
|
||||
}
|
||||
}
|
||||
}
|
||||
2
Assets/Scripts/Gameplay/RobotDock.cs.meta
Normal file
2
Assets/Scripts/Gameplay/RobotDock.cs.meta
Normal file
@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7bf64db802ef6514b9f51564dfd066a2
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user