- 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>
213 lines
8.7 KiB
C#
213 lines
8.7 KiB
C#
using System;
|
|
using Steamworks;
|
|
using UnityEngine;
|
|
|
|
namespace GrassCutter
|
|
{
|
|
/// <summary>Owns the Steam API lifetime (AppID 5551720, Grass Cutters Together), pumps callbacks, tracks the overlay.</summary>
|
|
[DefaultExecutionOrder(-1000)]
|
|
public class SteamManager : MonoBehaviour
|
|
{
|
|
public const uint AppId = 5551720;
|
|
|
|
public static SteamManager Instance { get; private set; }
|
|
public static bool Initialized { get; private set; }
|
|
public static bool OverlayActive { get; private set; }
|
|
public static event Action<bool> OverlayChanged;
|
|
|
|
Callback<GameOverlayActivated_t> _overlayCb;
|
|
SteamAPIWarningMessageHook_t _warningHook;
|
|
|
|
public static CSteamID MySteamId => Initialized ? SteamUser.GetSteamID() : CSteamID.Nil;
|
|
|
|
public static string MyName
|
|
{
|
|
get
|
|
{
|
|
if (Initialized) return SteamFriends.GetPersonaName();
|
|
return string.IsNullOrEmpty(Environment.UserName) ? "Popper" : Environment.UserName;
|
|
}
|
|
}
|
|
|
|
void Awake()
|
|
{
|
|
if (Instance != null) { Destroy(gameObject); return; }
|
|
Instance = this;
|
|
DontDestroyOnLoad(gameObject);
|
|
|
|
Debug.Log("[Steam] initializing…");
|
|
// Only our own builds carry steam_appid.txt; a player's copy must run through Steam, which checks it's theirs.
|
|
bool devAppId = Application.isEditor || System.IO.File.Exists(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.dataPath) ?? ".", "steam_appid.txt"));
|
|
if (CommandLine.Has("-nosteam") && devAppId) { Debug.Log("[Steam] disabled by -nosteam"); return; }
|
|
|
|
if (!Packsize.Test()) Debug.LogError("[Steam] Packsize test failed — wrong Steamworks.NET platform binaries.");
|
|
if (!DllCheck.Test()) Debug.LogError("[Steam] DllCheck failed — steam_api64.dll mismatch.");
|
|
|
|
try
|
|
{
|
|
#if !UNITY_EDITOR
|
|
// When launched outside Steam without steam_appid.txt this relaunches through Steam.
|
|
// Dev builds ship steam_appid.txt next to the exe, so skip the check entirely there.
|
|
if (!devAppId && SteamAPI.RestartAppIfNecessary(new AppId_t(AppId)))
|
|
{
|
|
Debug.Log("[Steam] Relaunching through Steam");
|
|
Application.Quit();
|
|
return;
|
|
}
|
|
#endif
|
|
var res = SteamAPI.InitEx(out string err);
|
|
Initialized = res == ESteamAPIInitResult.k_ESteamAPIInitResult_OK;
|
|
if (!Initialized)
|
|
{
|
|
Debug.LogWarning($"[Steam] Init failed ({res}): {err}. Is Steam running? Falling back to offline mode.");
|
|
if (!devAppId) NeedSteam();
|
|
return;
|
|
}
|
|
}
|
|
catch (DllNotFoundException e)
|
|
{
|
|
Debug.LogError("[Steam] steam_api64.dll not found: " + e.Message);
|
|
if (!devAppId) NeedSteam();
|
|
return;
|
|
}
|
|
|
|
_warningHook = (severity, text) => Debug.LogWarning("[Steam] " + text);
|
|
SteamClient.SetWarningMessageHook(_warningHook);
|
|
_overlayCb = Callback<GameOverlayActivated_t>.Create(OnOverlay);
|
|
|
|
// Warm up the relay network so P2P connects fast when the player hosts/joins.
|
|
SteamNetworkingUtils.InitRelayNetworkAccess();
|
|
Debug.Log($"[Steam] OK as {SteamFriends.GetPersonaName()} ({SteamUser.GetSteamID()}), AppID {SteamUtils.GetAppID()}");
|
|
Invoke(nameof(LogOverlay), 3f);
|
|
}
|
|
|
|
/// <summary>Player.log line that tells whether Shift+Tab can work in this run (overlay hooked + graphics API).</summary>
|
|
void LogOverlay()
|
|
{
|
|
if (!Initialized) return;
|
|
bool hooked = false;
|
|
try
|
|
{
|
|
foreach (System.Diagnostics.ProcessModule m in System.Diagnostics.Process.GetCurrentProcess().Modules)
|
|
if (m.ModuleName.StartsWith("GameOverlayRenderer", StringComparison.OrdinalIgnoreCase)) { hooked = true; break; }
|
|
}
|
|
catch (Exception e) { Debug.LogWarning("[Steam] module scan failed: " + e.Message); }
|
|
Debug.Log($"[Steam] overlay: enabled={SteamUtils.IsOverlayEnabled()} rendererLoaded={hooked} gfx={SystemInfo.graphicsDeviceType}");
|
|
}
|
|
|
|
void OnOverlay(GameOverlayActivated_t e)
|
|
{
|
|
OverlayActive = e.m_bActive != 0;
|
|
OverlayChanged?.Invoke(OverlayActive);
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
if (Initialized) SteamAPI.RunCallbacks();
|
|
}
|
|
|
|
public static string StoreUrl => $"https://store.steampowered.com/app/{AppId}/";
|
|
public static string FeedbackUrl => $"https://steamcommunity.com/app/{AppId}/discussions/";
|
|
|
|
/// <summary>The game's store page (wishlist, follow, review): in the Steam overlay, else the browser.</summary>
|
|
public static void OpenStore()
|
|
{
|
|
try
|
|
{
|
|
if (Initialized && SteamUtils.IsOverlayEnabled()) { SteamFriends.ActivateGameOverlayToStore(new AppId_t(AppId), EOverlayToStoreFlag.k_EOverlayToStoreFlag_None); return; }
|
|
}
|
|
catch (Exception) { }
|
|
Application.OpenURL(StoreUrl);
|
|
}
|
|
|
|
/// <summary>A page in the Steam overlay's browser, else the system's.</summary>
|
|
public static void OpenWeb(string url)
|
|
{
|
|
try
|
|
{
|
|
if (Initialized && SteamUtils.IsOverlayEnabled()) { SteamFriends.ActivateGameOverlayToWebPage(url); return; }
|
|
}
|
|
catch (Exception) { }
|
|
Application.OpenURL(url);
|
|
}
|
|
|
|
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
|
|
static extern int MessageBoxW(IntPtr hWnd, string text, string caption, uint type);
|
|
|
|
/// <summary>The game isn't running through Steam (or Steam can't vouch for it): say so and close.</summary>
|
|
static void NeedSteam()
|
|
{
|
|
Debug.LogError("[Steam] not started through Steam: quitting");
|
|
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
|
|
try { MessageBoxW(IntPtr.Zero, Loc.T("Grass Cutters Together needs Steam. Start Steam, sign in to the account that owns the game, and launch it from your library."), "Grass Cutters Together", 0x30); }
|
|
catch (Exception) { }
|
|
#endif
|
|
Application.Quit();
|
|
}
|
|
|
|
void OnApplicationQuit()
|
|
{
|
|
Shutdown();
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
if (Instance == this) Shutdown();
|
|
}
|
|
|
|
static void Shutdown()
|
|
{
|
|
if (!Initialized) return;
|
|
Initialized = false;
|
|
SteamAPI.Shutdown();
|
|
}
|
|
|
|
public static void SetRichPresence(string status, string connect = null)
|
|
{
|
|
if (!Initialized) return;
|
|
SteamFriends.SetRichPresence("status", status);
|
|
SteamFriends.SetRichPresence("steam_display", "#Status");
|
|
SteamFriends.SetRichPresence("connect", connect ?? "");
|
|
}
|
|
|
|
/// <summary>Returns the Steam avatar for a user as a texture (may be null until Steam has downloaded it).</summary>
|
|
public static Texture2D GetAvatar(CSteamID id)
|
|
{
|
|
if (!Initialized) return null;
|
|
int handle = SteamFriends.GetLargeFriendAvatar(id);
|
|
if (handle <= 0) return null;
|
|
if (!SteamUtils.GetImageSize(handle, out uint w, out uint h) || w == 0) return null;
|
|
var data = new byte[w * h * 4];
|
|
if (!SteamUtils.GetImageRGBA(handle, data, data.Length)) return null;
|
|
var tex = new Texture2D((int)w, (int)h, TextureFormat.RGBA32, false);
|
|
// Steam images are top-down; flip rows for Unity.
|
|
var flipped = new byte[data.Length];
|
|
int row = (int)w * 4;
|
|
for (int y = 0; y < h; y++) Buffer.BlockCopy(data, y * row, flipped, ((int)h - 1 - y) * row, row);
|
|
tex.LoadRawTextureData(flipped);
|
|
tex.Apply();
|
|
return tex;
|
|
}
|
|
}
|
|
|
|
public static class CommandLine
|
|
{
|
|
static string[] _args;
|
|
static string[] Args => _args ??= Environment.GetCommandLineArgs();
|
|
|
|
public static bool Has(string flag)
|
|
{
|
|
foreach (var a in Args) if (string.Equals(a, flag, StringComparison.OrdinalIgnoreCase)) return true;
|
|
return false;
|
|
}
|
|
|
|
public static string Get(string flag, string fallback = null)
|
|
{
|
|
var a = Args;
|
|
for (int i = 0; i < a.Length - 1; i++)
|
|
if (string.Equals(a[i], flag, StringComparison.OrdinalIgnoreCase)) return a[i + 1];
|
|
return fallback;
|
|
}
|
|
}
|
|
}
|