- The cheat console opens only in the editor, a development build, or with -gcdev - Without steam_appid.txt next to the exe, a failed Steam start says so and quits instead of running offline; -nosteam only works in our own builds - A language picked in the game's Steam properties overrides the one saved in the game, if it changed since - Main menu: language button, Steam page (overlay, else browser), feedback (Steam discussions); "early build" and the AppID gone from the footer - Settings > Game: head bob on/off - The cursor stays inside the window while it's free - -resetsettings puts every setting back as it comes out of the box Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
259 lines
15 KiB
C#
259 lines
15 KiB
C#
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
|
||
{
|
||
/// <summary>The console is for the team: the editor, a development build, or a build started with -gcdev.</summary>
|
||
public static readonly bool Allowed = Application.isEditor || Debug.isDebugBuild || CommandLine.Has("-gcdev");
|
||
|
||
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) | Layers.CargoMask, 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.##}";
|
||
}
|
||
}
|
||
}
|